HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/libsystemd-network/sd-dhcp-client.c

49,261 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: df6b704e17fb7da976dc16c92382f13927a9bda3

Lines 1001–1446 of 1,446

                return r;
 
        /* RFC2131 section 4.4.5:
         * Times T1 and T2 SHOULD be chosen with some random "fuzz".
         * Since the RFC doesn't specify here the exact 'fuzz' to use,
         * we use the range from section 4.1: -1 to +1 sec. */
        client->t1_time = usec_sub_signed(client->t1_time, RFC2131_RANDOM_FUZZ);
        client->t2_time = usec_sub_signed(client->t2_time, RFC2131_RANDOM_FUZZ);
 
        /* after fuzzing, ensure t2 is still >= t1 */
        client->t2_time = MAX(client->t1_time, client->t2_time);
 
        /* arm lifetime timeout */
        r = event_reset_time(client->event, &client->timeout_expire,
                             CLOCK_BOOTTIME,
                             client->expire_time, 10 * USEC_PER_MSEC,
                             client_timeout_expire, client,
                             client->event_priority, "dhcp4-lifetime", true);
        if (r < 0)
                return r;
 
        /* don't arm earlier timeouts if this has already expired */
        if (client->expire_time <= time_now)
                return 0;
 
        log_dhcp_client(client, "lease expires in %s",
                        FORMAT_TIMESPAN(client->expire_time - time_now, USEC_PER_SEC));
 
        /* arm T2 timeout */
        r = event_reset_time(client->event, &client->timeout_t2,
                             CLOCK_BOOTTIME,
                             client->t2_time, 10 * USEC_PER_MSEC,
                             client_timeout_t2, client,
                             client->event_priority, "dhcp4-t2-timeout", true);
        if (r < 0)
                return r;
 
        /* don't arm earlier timeout if this has already expired */
        if (client->t2_time <= time_now)
                return 0;
 
        log_dhcp_client(client, "T2 expires in %s",
                        FORMAT_TIMESPAN(client->t2_time - time_now, USEC_PER_SEC));
 
        /* arm T1 timeout */
        r = event_reset_time(client->event, &client->timeout_t1,
                             CLOCK_BOOTTIME,
                             client->t1_time, 10 * USEC_PER_MSEC,
                             client_timeout_t1, client,
                             client->event_priority, "dhcp4-t1-timer", true);
        if (r < 0)
                return r;
 
        if (client->t1_time > time_now)
                log_dhcp_client(client, "T1 expires in %s",
                                FORMAT_TIMESPAN(client->t1_time - time_now, USEC_PER_SEC));
 
        return 0;
}
 
static int client_enter_bound(sd_dhcp_client *client, sd_dhcp_lease *lease) {
        int r;
 
        assert(client);
        assert(lease);
 
        int notify_event;
        switch (client->state) {
        case DHCP_STATE_SELECTING:
        case DHCP_STATE_REQUESTING:
        case DHCP_STATE_REBOOTING:
                notify_event = SD_DHCP_CLIENT_EVENT_IP_ACQUIRE;
                break;
        case DHCP_STATE_RENEWING:
        case DHCP_STATE_REBINDING:
                assert(client->lease);
                if (lease_equal(client->lease, lease))
                        notify_event = SD_DHCP_CLIENT_EVENT_RENEW;
                else
                        notify_event = SD_DHCP_CLIENT_EVENT_IP_CHANGE;
                break;
        default:
                assert_not_reached();
        }
 
        unref_and_replace_new_ref(client->lease, lease, sd_dhcp_lease_ref, sd_dhcp_lease_unref);
 
        client_disable_event_sources(client);
 
        client->start_delay = 0;
 
        client_set_state(client, DHCP_STATE_BOUND);
 
        client->last_addr = client->lease->address;
 
        r = client_set_lease_timeouts(client);
        if (r < 0)
                return log_dhcp_client_errno(client, r, "Failed to set lease timeouts: %m");
 
        client_notify(client, notify_event);
        return 0;
}
 
static int client_handle_message(sd_dhcp_client *client, const struct iovec *iov, const triple_timestamp *timestamp) {
        DHCP_CLIENT_DONT_DESTROY(client);
        int r;
 
        assert(client);
        assert(iov);
 
        _cleanup_(sd_dhcp_lease_unrefp) sd_dhcp_lease *lease = NULL;
        r = dhcp_client_parse_message(client, iov, &lease);
        if (ERRNO_IS_NEG_RESOURCE(r))
                return r;
        if (r < 0)
                return 0; /* Ignore all parse errors. */
 
        switch (r) {
 
        case DHCP_OFFER:
                dhcp_lease_set_timestamp(lease, timestamp);
 
                unref_and_replace_new_ref(client->lease, lease, sd_dhcp_lease_ref, sd_dhcp_lease_unref);
                if (client_notify(client, SD_DHCP_CLIENT_EVENT_SELECTING) < 0)
                        return 0; /* networkd refused the server, ignoring the message. */
                if (client->state == DHCP_STATE_STOPPED)
                        return 0; /* The notify callback stopped the client. */
                return client_enter_requesting(client);
 
        case DHCP_ACK:
                dhcp_lease_set_timestamp(lease, timestamp);
                return client_enter_bound(client, lease);
 
        case DHCP_NAK:
                return client_restart(client);
 
        default:
                assert_not_reached();
        }
}
 
static int client_receive_message(sd_dhcp_client *client, int fd, bool raw) {
        int r;
 
        assert(client);
        assert(fd >= 0);
 
        ssize_t buflen = next_datagram_size_fd(fd);
        if (ERRNO_IS_NEG_TRANSIENT(buflen) || ERRNO_IS_NEG_DISCONNECT(buflen))
                return 0;
        if (buflen < 0) {
                log_dhcp_client_errno(client, buflen, "Failed to determine datagram size to read, ignoring: %m");
                return 0;
        }
 
        _cleanup_free_ void *buf = malloc0(buflen);
        if (!buf)
                return -ENOMEM;
 
        /* This needs to be initialized with zero. See #20741.
         * The issue is fixed on glibc-2.35 (8fba672472ae0055387e9315fc2eddfa6775ca79). */
        CMSG_BUFFER_TYPE(CMSG_SPACE_TIMEVAL +
                         CMSG_SPACE(sizeof(struct tpacket_auxdata))) control = {};
        struct msghdr msg = {
                .msg_iov = &IOVEC_MAKE(buf, buflen),
                .msg_iovlen = 1,
                .msg_control = &control,
                .msg_controllen = sizeof(control),
        };
 
        ssize_t len = recvmsg_safe(fd, &msg, MSG_DONTWAIT);
        if (ERRNO_IS_NEG_TRANSIENT(len) || ERRNO_IS_NEG_DISCONNECT(len))
                return 0;
        if (len < 0) {
                log_dhcp_client_errno(client, len,
                                      "Could not receive message from %s socket, ignoring: %m",
                                      raw ? "RAW" : "UDP");
                return 0;
        }
 
        struct iovec payload = IOVEC_MAKE(buf, len);
        if (raw) {
                struct tpacket_auxdata *aux = CMSG_FIND_DATA(&msg, SOL_PACKET, PACKET_AUXDATA, struct tpacket_auxdata);
                bool checksum = !aux || !(aux->tp_status & TP_STATUS_CSUMNOTREADY);
 
                if (udp_packet_verify(&payload, client->port, checksum, &payload) < 0)
                        return 0;
        }
 
        log_dhcp_client(client, "Received message from %s socket, processing.", raw ? "RAW" : "UDP");
        r = client_handle_message(client, &payload, TRIPLE_TIMESTAMP_FROM_CMSG(&msg));
        if (r < 0)
                client_stop(client, r);
 
        return 0;
}
 
int client_receive_message_udp(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
        return client_receive_message(userdata, fd, /* raw= */ false);
}
 
int client_receive_message_raw(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
        return client_receive_message(userdata, fd, /* raw= */ true);
}
 
int sd_dhcp_client_send_renew(sd_dhcp_client *client) {
        if (!sd_dhcp_client_is_running(client) || client->state != DHCP_STATE_BOUND || client->bootp)
                return 0; /* do nothing */
 
        client_set_state(client, DHCP_STATE_RENEWING);
 
        client->start_delay = 0;
        return client_initialize_time_events(client);
}
 
int sd_dhcp_client_is_running(sd_dhcp_client *client) {
        if (!client)
                return 0;
 
        return client->state != DHCP_STATE_STOPPED;
}
 
int sd_dhcp_client_start(sd_dhcp_client *client) {
        int r;
 
        assert_return(client, -EINVAL);
        assert_return(client->event, -EINVAL);
        assert_return(client->ifindex > 0, -EINVAL);
        assert_return(!hw_addr_is_null(&client->bcast_addr), -EINVAL);
 
        /* If no client identifier exists, construct an RFC 4361-compliant one */
        if (!sd_dhcp_client_id_is_set(&client->client_id)) {
                r = sd_dhcp_client_set_iaid_duid_en(client, /* iaid_set= */ false, /* iaid= */ 0);
                if (r < 0)
                        return r;
        }
 
        /* RFC7844 section 3.3:
           SHOULD perform a complete four-way handshake, starting with a
           DHCPDISCOVER, to obtain a new address lease.  If the client can
           ascertain that this is exactly the same network to which it was
           previously connected, and if the link-layer address did not change,
           the client MAY issue a DHCPREQUEST to try to reclaim the current
           address. */
        if (client->last_addr && !client->anonymize && !client->bootp)
                client_set_state(client, DHCP_STATE_INIT_REBOOT);
 
        /* We currently ignore:
         * The client SHOULD wait a random time between one and ten seconds to desynchronize the use of
         * DHCP at startup. */
        r = client_start(client);
        if (r >= 0)
                log_dhcp_client(client, "STARTED on ifindex %i", client->ifindex);
 
        return r;
}
 
int sd_dhcp_client_send_decline(sd_dhcp_client *client) {
        int r;
 
        if (!sd_dhcp_client_is_running(client) || !client->lease || client->bootp)
                return 0; /* there is nothing to decline */
 
        r = dhcp_client_send_message(client, DHCP_DECLINE);
        if (r < 0)
                return r;
 
        /* This function is mostly called when the acquired address conflicts with another host.
         * Restarting the daemon to acquire another address. */
        return client_restart(client);
}
 
static int client_send_release(sd_dhcp_client *client) {
        assert(client);
 
        if (!client->send_release)
                return 0;
 
        if (!sd_dhcp_client_is_running(client) || !client->lease || client->bootp)
                return 0; /* there is nothing to release */
 
        return dhcp_client_send_message(client, DHCP_RELEASE);
}
 
int sd_dhcp_client_stop(sd_dhcp_client *client) {
        if (!client)
                return 0;
 
        DHCP_CLIENT_DONT_DESTROY(client);
 
        (void) client_send_release(client);
 
        client_stop(client, SD_DHCP_CLIENT_EVENT_STOP);
        return 0;
}
 
int sd_dhcp_client_is_waiting_for_ipv6_connectivity(sd_dhcp_client *client) {
        /* Note that we intentionally do not implement the following behavior:
         *
         * RFC 8925, section 3.2:
         *   If the client is in the INIT-REBOOT state, it SHOULD stop the DHCPv4 configuration process or
         *   disable the IPv4 stack completely for V6ONLY_WAIT seconds or until the next network attachment
         *   event, whichever occurs first.
         *
         * Delaying the application of an acquired IPv4 address after DHCPACK introduces several issues:
         *
         * - If T1 is reached before the address is assigned to the interface, the client cannot send a
         *   unicast DHCPREQUEST during RENEWING.
         *
         * - If the client is stopped before the address is configured, it cannot send a DHCPRELEASE message,
         *   which also requires a valid source address.
         *
         * While these issues could be worked around, doing so would significantly complicate the
         * implementation and violate assumptions in the DHCP state machine as defined in RFC 2131.
         *
         * Instead, we only honor the IPv6-Only Preferred delay (Option 108) in the REQUESTING state, i.e.
         * before any DHCPREQUEST has been sent. */
 
        return
                client &&
                client->state == DHCP_STATE_REQUESTING &&
                client->request_attempt == 0 &&
                client->lease &&
                client->lease->ipv6_only_preferred_usec > 0;
}
 
int sd_dhcp_client_set_ipv6_connectivity(sd_dhcp_client *client, int have) {
        if (!client)
                return 0;
 
        client->ipv6_acquired = have;
 
        if (have && sd_dhcp_client_is_waiting_for_ipv6_connectivity(client)) {
                log_dhcp_client(client,
                                "Acquired IPv6 connectivity before sending REQUEST, stopping DHCPv4 client.");
                return sd_dhcp_client_stop(client);
        }
 
        return 0;
}
 
int sd_dhcp_client_attach_event(sd_dhcp_client *client, sd_event *event, int64_t priority) {
        int r;
 
        assert_return(client, -EINVAL);
        assert_return(!client->event, -EBUSY);
        assert_return(!sd_dhcp_client_is_running(client), -EBUSY);
 
        if (event)
                client->event = sd_event_ref(event);
        else {
                r = sd_event_default(&client->event);
                if (r < 0)
                        return r;
        }
 
        client->event_priority = priority;
 
        return 0;
}
 
int sd_dhcp_client_detach_event(sd_dhcp_client *client) {
        assert_return(client, -EINVAL);
        assert_return(!sd_dhcp_client_is_running(client), -EBUSY);
 
        client->event = sd_event_unref(client->event);
 
        return 0;
}
 
sd_event* sd_dhcp_client_get_event(sd_dhcp_client *client) {
        assert_return(client, NULL);
 
        return client->event;
}
 
int sd_dhcp_client_attach_device(sd_dhcp_client *client, sd_device *dev) {
        assert_return(client, -EINVAL);
 
        return device_unref_and_replace_new_ref(client->dev, dev);
}
 
static sd_dhcp_client* dhcp_client_free(sd_dhcp_client *client) {
        if (!client)
                return NULL;
 
        log_dhcp_client(client, "FREE");
 
        client_initialize(client);
 
        safe_close(client->socket_fd);
 
        sd_event_source_unref(client->timeout_resend);
        sd_event_source_unref(client->timeout_t1);
        sd_event_source_unref(client->timeout_t2);
        sd_event_source_unref(client->timeout_expire);
 
        sd_dhcp_client_detach_event(client);
 
        sd_device_unref(client->dev);
 
        set_free(client->req_opts);
        free(client->hostname);
        free(client->vendor_class_identifier);
        free(client->mudurl);
        iovw_done_free(&client->user_class);
        tlv_unref(client->extra_options);
        tlv_unref(client->vendor_options);
        free(client->ifname);
        return mfree(client);
}
 
DEFINE_TRIVIAL_REF_UNREF_FUNC(sd_dhcp_client, sd_dhcp_client, dhcp_client_free);
 
int sd_dhcp_client_new(sd_dhcp_client **ret) {
        int r;
 
        assert_return(ret, -EINVAL);
 
        _cleanup_(sd_dhcp_client_unrefp) sd_dhcp_client *client = new(sd_dhcp_client, 1);
        if (!client)
                return -ENOMEM;
 
        *client = (sd_dhcp_client) {
                .n_ref = 1,
                .socket_fd = -EBADF,
                .state = DHCP_STATE_STOPPED,
                .ifindex = -1,
                .port = DHCP_PORT_CLIENT,
                .server_port = DHCP_PORT_SERVER,
                .max_discover_attempts = UINT64_MAX,
                .ip_service_type = IPTOS_CLASS_CS6, /* Defaults to CS6 (Internetwork Control). */
                .socket_priority = tos_to_priority(IPTOS_CLASS_CS6),
        };
 
        FOREACH_ELEMENT(opt, default_req_opts) {
                r = sd_dhcp_client_set_request_option(client, *opt);
                if (r < 0)
                        return r;
        }
 
        *ret = TAKE_PTR(client);
 
        return 0;
}