/* * Copyright (c) 2017 SUSE LLC. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include #include #include #include /** * Flush tx frame populated by retransmits and timer pops */ void sctp_flush_frame_to_output (vlib_main_t * vm, u8 thread_index, u8 is_ip4) { if (sctp_main.tx_frames[!is_ip4][thread_index]) { u32 next_index; next_index = is_ip4 ? sctp4_output_node.index : sctp6_output_node.index; vlib_put_frame_to_node (vm, next_index, sctp_main.tx_frames[!is_ip4][thread_index]); sctp_main.tx_frames[!is_ip4][thread_index] = 0; } } /** * Flush ip lookup tx frames populated by timer pops */ always_inline void sctp_flush_frame_to_ip_lookup (vlib_main_t * vm, u8 thread_index, u8 is_ip4) { if (sctp_main.ip_lookup_tx_frames[!is_ip4][thread_index]) { u32 next_index; next_index = is_ip4 ? ip4_lookup_node.index : ip6_lookup_node.index; vlib_put_frame_to_node (vm, next_index, sctp_main.ip_lookup_tx_frames[!is_ip4] [thread_index]); sctp_main.ip_lookup_tx_frames[!is_ip4][thread_index] = 0; } } /** * Flush v4 and v6 sctp and ip-lookup tx frames for thread index */ void sctp_flush_frames_to_output (u8 thread_index) { vlib_main_t *vm = vlib_get_main (); sctp_flush_frame_to_output (vm, thread_index, 1); sctp_flush_frame_to_output (vm, thread_index, 0); sctp_flush_frame_to_ip_lookup (vm, thread_index, 1); sctp_flush_frame_to_ip_lookup (vm, thread_index, 0); } u32 ip4_sctp_compute_checksum (vlib_main_t * vm, vlib_buffer_t * p0, ip4_header_t * ip0) { ip_csum_t checksum; u32 ip_header_length, payload_length_host_byte_order; u32 n_this_buffer, n_bytes_left, n_ip_bytes_this_buffer; void *data_this_buffer; /* Initialize checksum with ip header. */ ip_header_length = ip4_header_bytes (ip0); payload_length_host_byte_order = clib_net_to_host_u16 (ip0->length) - ip_header_length; checksum = clib_host_to_net_u32 (payload_length_host_byte_order + (ip0->protocol << 16)); if (BITS (uword) == 32) { checksum = ip_csum_with_carry (checksum, clib_mem_unaligned (&ip0->src_address, u32)); checksum = ip_csum_with_carry (checksum, clib_mem_unaligned (&ip0->dst_address, u32)); } else checksum = ip_csum_with_carry (checksum, clib_mem_unaligned (&ip0->src_address, u64)); n_bytes_left = n_this_buffer = payload_length_host_byte_order; data_this_buffer = (void *) ip0 + ip_header_length; n_ip_bytes_this_buffer = p0->current_length - (((u8 *) ip0 - p0->data) - p0->current_data); if (n_this_buffer + ip_header_length > n_ip_bytes_this_buffer) { n_this_buffer = n_ip_bytes_this_buffer > ip_header_length ? n_ip_bytes_this_buffer - ip_header_length : 0; } while (1) { checksum = ip_incremental_checksum (checksum, data_this_buffer, n_this_buffer); n_bytes_left -= n_this_buffer; if (n_bytes_left == 0) break; ASSERT (p0->flags & VLIB_BUFFER_NEXT_PRESENT); p0 = vlib_get_buffer (vm, p0->next_buffer); data_this_buffer = vlib_buffer_get_current (p0); n_this_buffer = p0->current_length; } return checksum; } u32 ip6_sctp_compute_checksum (vlib_main_t * vm, vlib_buffer_t * p0, ip6_header_t * ip0, int *bogus_lengthp) { ip_csum_t checksum; u16 payload_length_host_byte_order; u32 i, n_this_buffer, n_bytes_left; u32 headers_size = sizeof (ip0[0]); void *data_this_buffer; ASSERT (bogus_lengthp); *bogus_lengthp = 0; /* Initialize checksum with ip header. */ checksum = ip0->payload_length + clib_host_to_net_u16 (ip0->protocol); payload_length_host_byte_order = clib_net_to_host_u16 (ip0->payload_length); data_this_buffer = (void *) (ip0 + 1); for (i = 0; i < ARRAY_LEN (ip0->src_address.as_uword); i++) { checksum = ip_csum_with_carry (checksum, clib_mem_unaligned (&ip0-> src_address.as_uword [i], uword)); checksum = ip_csum_with_carry (checksum, clib_mem_unaligned (&ip0->dst_address.as_uword[i], uword)); } /* some icmp packets may come with a "router alert" hop-by-hop extension header (e.g., mldv2 packets) * or UDP-Ping packets */ if (PREDICT_FALSE (ip0->protocol == IP_PROTOCOL_IP6_HOP_BY_HOP_OPTIONS)) { u32 skip_bytes; ip6_hop_by_hop_ext_t *ext_hdr = (ip6_hop_by_hop_ext_t *) data_this_buffer; /* validate really icmp6 next */ ASSERT ((ext_hdr->next_hdr == IP_PROTOCOL_SCTP)); skip_bytes = 8 * (1 + ext_hdr->n_data_u64s); data_this_buffer = (void *) ((u8 *) data_this_buffer + skip_bytes); payload_length_host_byte_order -= skip_bytes; headers_size += skip_bytes; } n_bytes_left = n_this_buffer = payload_length_host_byte_order; if (p0 && n_this_buffer + headers_size > p0->current_length) n_this_buffer = p0->current_length > headers_size ? p0->current_length - headers_size : 0; while (1) { checksum = ip_incremental_checksum (checksum, data_this_buffer, n_this_buffer); n_bytes_left -= n_this_buffer; if (n_bytes_left == 0) break; if (!(p0->flags & VLIB_BUFFER_NEXT_PRESENT)) { *bogus_lengthp = 1; return 0xfefe; } p0 = vlib_get_buffer (vm, p0->next_buffer); data_this_buffer = vlib_buffer_get_current (p0); n_this_buffer = p0->current_length; } return checksum; } void sctp_push_ip_hdr (sctp_main_t * tm, sctp_sub_connection_t * sctp_sub_conn, vlib_buffer_t * b) { sctp_header_t *th = vlib_buffer_get_current (b); vlib_main_t *vm = vlib_get_main (); if (sctp_sub_conn->c_is_ip4) { ip4_header_t *ih; ih = vlib_buffer_push_ip4 (vm, b, &sctp_sub_conn->c_lcl_ip4, &sctp_sub_conn->c_rmt_ip4, IP_PROTOCOL_SCTP, 1); th->checksum = ip4_sctp_compute_checksum (vm, b, ih); } else { ip6_header_t *ih; int bogus = ~0; ih = vlib_buffer_push_ip6 (vm, b, &sctp_sub_conn->c_lcl_ip6, &sctp_sub_conn->c_rmt_ip6, IP_PROTOCOL_SCTP); th->checksum = ip6_sctp_compute_checksum (vm, b, ih, &bogus); ASSERT (!bogus); } } always_inline void * sctp_reuse_buffer (vlib_main_t * vm, vlib_buffer_t * b) { if (b->flags & VLIB_BUFFER_NEXT_PRESENT) vlib_buffer_free_one (vm, b->next_buffer); /* Zero all flags but free list index and trace flag */ b->flags &= VLIB_BUFFER_NEXT_PRESENT - 1; b->current_data = 0; b->current_length = 0; b->total_length_not_including_first_buffer = 0; vnet_buffer (b)->sctp.flags = 0; vnet_buffer (b)->sctp.subconn_idx = MAX_SCTP_CONNECTIONS; /* Leave enough space for headers */ return vlib_buffer_make_headroom (b, TRANSPORT_MAX_HDRS_LEN); } always_inline void * sctp_init_buffer (vlib_main_t * vm, vlib_buffer_t * b) { ASSERT ((b->flags & VLIB_BUFFER_NEXT_PRESENT) == 0); b->flags |= VNET_BUFFER_F_LOCALLY_ORIGINATED; b->total_length_not_including_first_buffer = 0; vnet_buffer (b)->sctp.flags = 0; vnet_buffer (b)->sctp.subconn_idx = MAX_SCTP_CONNECTIONS; VLIB_BUFFER_TRACE_TRAJECTORY_INIT (b); /* Leave enough space for headers */ return vlib_buffer_make_headroom (b, TRANSPORT_MAX_HDRS_LEN); } always_inline int sctp_alloc_tx_buffers (sctp_main_t * tm, u8 thread_index, u32 n_free_buffers) { vlib_main_t *vm = vlib_get_main (); u32 current_length = vec_len (tm->tx_buffers[thread_index]); u32 n_allocated; vec_validate (tm->tx_buffers[thread_index], current_length + n_free_buffers - 1); n_allocated = vlib_buffer_alloc (vm, &tm->tx_buffers[thread_index][current_length], n_free_buffers); _vec_len (tm->tx_buffers[thread_index]) = current_length + n_allocated; /* buffer shortage, report failure */ if (vec_len (tm->tx_buffers[thread_index]) == 0) { clib_warning ("out of buffers"); return -1; } return 0; } always_inline int sctp_get_free_buffer_index (sctp_main_t * tm, u32 * bidx) { u32 *my_tx_buffers; u32 thread_index = vlib_get_thread_index (); if (PREDICT_FALSE (vec_len (tm->tx_buffers[thread_index]) == 0)) { if (sctp_alloc_tx_buffers (tm, thread_index, VLIB_FRAME_SIZE)) return -1; } my_tx_buffers = tm->tx_buffers[thread_index]; *bidx = my_tx_buffers[vec_len (my_tx_buffers) - 1]; _vec_len (my_tx_buffers) -= 1; return 0; } always_inline void sctp_enqueue_to_output_i (vlib_main_t * vm, vlib_buffer_t * b, u32 bi, u8 is_ip4, u8 flush) { sctp_main_t *tm = vnet_get_sctp_main (); u32 thread_index = vlib_get_thread_index (); u32 *to_next, next_index; vlib_frame_t *f; b->flags |= VNET_BUFFER_F_LOCALLY_ORIGINATED; b->error = 0; /* Decide where to send the packet */ next_index = is_ip4 ? sctp4_output_node.index : sctp6_output_node.index; sctp_trajectory_add_start (b, 2); /* Get frame to v4/6 output node */ f = tm->tx_frames[!is_ip4][thread_index]; if (!f) { f = vlib_get_frame_to_node (vm, next_index); ASSERT (f); tm->tx_frames[!is_ip4][thread_index] = f; } to_next = vlib_frame_vector_args (f); to_next[f->n_vectors] = bi; f->n_vectors += 1; if (flush || f->n_vectors == VLIB_FRAME_SIZE) { vlib_put_frame_to_node (vm, next_index, f); tm->tx_frames[!is_ip4][thread_index] = 0; } } always_inline void sctp_enqueue_to_output_now (vlib_main_t * vm, vlib_buffer_t * b, u32 bi, u8 is_ip4) { sctp_enqueue_to_output_i (vm, b, bi, is_ip4, 1); } always_inline void sctp_enqueue_to_ip_lookup_i (vlib_main_t * vm, vlib_buffer_t * b, u32 bi, u8 is_ip4, u32 fib_index, u8 flush) { sctp_main_t *tm = vnet_get_sctp_main (); u32 thread_index = vlib_get_thread_index (); u32 *to_next, next_index; vlib_frame_t *f; b->flags |= VNET_BUFFER_F_LOCALLY_ORIGINATED; b->error = 0; vnet_buffer (b)->sw_if_index[VLIB_TX] = fib_index; vnet_buffer (b)->sw_if_index[VLIB_RX] = 0; /* Send to IP lookup */ next_index = is_ip4 ? ip4_lookup_node.index : ip6_lookup_node.index; if (VLIB_BUFFER_TRACE_TRAJECTORY > 0) { b->pre_data[0] = 2; b->pre_data[1] = next_index; } f = tm->ip_lookup_tx_frames[!is_ip4][thread_index]; if (!f) { f = vlib_get_frame_to_node (vm, next_index); ASSERT (f); tm->ip_lookup_tx_frames[!is_ip4][thread_index] = f; } to_next = vlib_frame_vector_args (f); to_next[f->n_vectors] = bi; f->n_vectors += 1; if (flush || f->n_vectors == VLIB_FRAME_SIZE) { vlib_put_frame_to_node (vm, next_index, f); tm->ip_lookup_tx_frames[!is_ip4][thread_index] = 0; } } always_inline void sctp_enqueue_to_ip_lookup (vlib_main_t * vm, vlib_buffer_t * b, u32 bi, u8 is_ip4, u32 fib_index) { sctp_enqueue_to_ip_lookup_i (vm, b, bi, is_ip4, fib_index, 0); if (vm->thread_index == 0 && vlib_num_workers ()) session_flush_frames_main_thread (vm); } /** * Convert buffer to INIT */ void sctp_prepare_init_chunk (sctp_connection_t * sctp_conn, u8 idx, vlib_buffer_t * b) { u32 random_seed = random_default_seed (); u16 alloc_bytes = sizeof (sctp_init_chunk_t); sctp_sub_connection_t *sub_conn = &sctp_conn->sub_conn[idx]; sctp_ipv4_addr_param_t *ip4_param = 0; sctp_ipv6_addr_param_t *ip6_param = 0; if (sub_conn->c_is_ip4) alloc_bytes += sizeof (sctp_ipv4_addr_param_t); else alloc_bytes += sizeof (sctp_ipv6_addr_param_t); /* As per RFC 4960 the chunk_length value does NOT contemplate * the size of the first header (see sctp_header_t) and any padding */ u16 chunk_len = alloc_bytes - sizeof (sctp_header_t); alloc_bytes += vnet_sctp_calculate_padding (alloc_bytes); sctp_init_chunk_t *init_chunk = vlib_buffer_push_uninit (b, alloc_bytes); u16 pointer_offset = sizeof (init_chunk); if (sub_conn->c_is_ip4) { ip4_param = (sctp_ipv4_addr_param_t *) init_chunk + pointer_offset; ip4_param->address.as_u32 = sub_conn->c_lcl_ip.ip4.as_u32; pointer_offset += sizeof (sctp_ipv4_addr_param_t); } else { ip6_param = (sctp_ipv6_addr_param_t *) init_chunk + pointer_offset; ip6_param->address.as_u64[0] = sub_conn->c_lcl_ip.ip6.as_u64[0]; ip6_param->address.as_u64[1] = sub_conn->c_lcl_ip.ip6.as_u64[1]; pointer_offset += sizeof (sctp_ipv6_addr_param_t); } init_chunk->sctp_hdr.src_port = sub_conn->c_lcl_port; /* No need of host_to_net conversion, already in net-byte order */ init_chunk->sctp_hdr.dst_port = sub_conn->c_rmt_port; /* No need of host_to_net conversion, already in net-byte order */ init_chunk->sctp_hdr.checksum = 0; /* The sender of an INIT must set the VERIFICATION_TAG to 0 as per RFC 4960 Section 8.5.1 */ init_chunk->sctp_hdr.verification_tag = 0x0; vnet_sctp_set_chunk_type (&init_chunk->chunk_hdr, INIT); vnet_sctp_set_chunk_length (&init_chunk->chunk_hdr, chunk_len); vnet_sctp_common_hdr_params_host_to_net (&init_chunk->chunk_hdr); sctp_init_cwnd (sctp_conn); init_chunk->a_rwnd = clib_host_to_net_u32 (sctp_conn->sub_conn[idx].cwnd); init_chunk->initiate_tag = clib_host_to_net_u32 (random_u32 (&random_seed)); init_chunk->inboud_streams_count = clib_host_to_net_u16 (INBOUND_STREAMS_COUNT); init_chunk->outbound_streams_count = clib_host_to_net_u16 (OUTBOUND_STREAMS_COUNT); init_chunk->initial_tsn = clib_host_to_net_u32 (sctp_conn->local_initial_tsn); SCTP_CONN_TRACKING_DBG ("sctp_conn->local_initial_tsn = %u", sctp_conn->local_initial_tsn); sctp_conn->local_tag = init_chunk->initiate_tag; vnet_buffer (b)->sctp.connection_index = sub_conn->c_c_index; vnet_buffer (b)->sctp.subconn_idx = idx; SCTP_DBG_STATE_MACHINE ("CONN_INDEX = %u, CURR_CONN_STATE = %u (%s), " "CHUNK_TYPE = %s, " "SRC_PORT = %u, DST_PORT = %u", sub_conn->connection.c_index, sctp_conn->state, sctp_state_to_string (sctp_conn->state), sctp_chunk_to_string (INIT), init_chunk->sctp_hdr.src_port, init_chunk->sctp_hdr.dst_port); } void sctp_compute_mac (sctp_connection_t * sctp_conn, sctp_state_cookie_param_t * state_cookie) { #if OPENSSL_VERSION_NUMBER >= 0x10100000L HMAC_CTX *ctx; #else HMAC_CTX ctx; #endif unsigned int len = 0; const EVP_MD *md = EVP_sha1 (); #if OPENSSL_VERSION_NUMBER >= 0x10100000L ctx = HMAC_CTX_new (); HMAC_Init_ex (ctx, &state_cookie->creation_time, sizeof (state_cookie->creation_time), md, NULL); HMAC_Update (ctx, (const unsigned char *) &sctp_conn, sizeof (sctp_conn)); HMAC_Final (ctx, state_cookie->mac, &len); #else HMAC_CTX_init (&ctx); HMAC_Init_ex (&ctx, &state_cookie->creation_time, sizeof (state_cookie->creation_time), md, NULL); HMAC_Update (&ctx, (const unsigned char *) &sctp_conn, sizeof (sctp_conn)); HMAC_Final (&ctx, state_cookie->mac, &len); HMAC_CTX_cleanup (&ctx); #endif ENDIANESS_SWAP (state_cookie->mac); } void sctp_prepare_cookie_ack_chunk (sctp_connection_t * sctp_conn, u8 idx, vlib_buffer_t * b) { vlib_main_t *vm = vlib_get_main (); sctp_reuse_buffer (vm, b); u16 alloc_bytes = sizeof (sctp_cookie_ack_chunk_t); /* As per RFC 4960 the chunk_length value does NOT contemplate * the size of the first header (see sctp_header_t) and any padding */ u16 chunk_len = alloc_bytes - sizeof (sctp_header_t); alloc_bytes += vnet_sctp_calculate_padding (alloc_bytes); sctp_cookie_ack_chunk_t *cookie_ack_chunk = vlib_buffer_push_uninit (b, alloc_bytes); cookie_ack_chunk->sctp_hdr.checksum = 0; cookie_ack_chunk->sctp_hdr.src_port = sctp_conn->sub_conn[idx].connection.lcl_port; cookie_ack_chunk->sctp_hdr.dst_port = sctp_conn->sub_conn[idx].connection.rmt_port; cookie_ack_chunk->sctp_hdr.verification_tag = sctp_conn->remote_tag; vnet_sctp_set_chunk_type (&cookie_ack_chunk->chunk_hdr, COOKIE_ACK); vnet_sctp_set_chunk_length (&cookie_ack_chunk->chunk_hdr, chunk_len); vnet_buffer (b)->sctp.connection_index = sctp_conn->sub_conn[idx].connection.c_index; vnet_buffer (b)->sctp.subconn_idx = idx; } void sctp_prepare_cookie_echo_chunk (sctp_connection_t * sctp_conn, u8 idx, vlib_buffer_t * b, u8 reuse_buffer) { vlib_main_t *vm = vlib_get_main (); if (reuse_buffer) sctp_reuse_buffer (vm, b); /* The minimum size of the message is given by the sctp_init_ack_chunk_t */ u16 alloc_bytes = sizeof (sctp_cookie_echo_chunk_t); /* As per RFC 4960 the chunk_length value does NOT contemplate * the size of the first header (see sctp_header_t) and any padding */ u16 chunk_len = alloc_bytes - sizeof (sctp_header_t); alloc_bytes += vnet_sctp_calculate_padding (alloc_bytes); sctp_cookie_echo_chunk_t *cookie_echo_chunk = vlib_buffer_push_uninit (b, alloc_bytes); cookie_echo_chunk->sctp_hdr.checksum = 0; cookie_echo_chunk->sctp_hdr.src_port = sctp_conn->sub_conn[idx].connection.lcl_port; cookie_echo_chunk->sctp_hdr.dst_port = sctp_conn->sub_conn[idx].connection.rmt_port; cookie_echo_chunk->sctp_hdr.verification_tag = sctp_conn->remote_tag; vnet_sctp_set_chunk_type (&cookie_echo_chunk->chunk_hdr, COOKIE_ECHO); vnet_sctp_set_chunk_length (&cookie_echo_chunk->chunk_hdr, chunk_len); clib_memcpy_fast (&(cookie_echo_chunk->cookie), &sctp_conn->cookie_param, sizeof (sctp_state_cookie_param_t)); vnet_buffer (b)->sctp.connection_index = sctp_conn->sub_conn[idx].connection.c_index; vnet_buffer (b)->sctp.subconn_idx = idx; } /* * Send COOKIE_ECHO */ void sctp_send_cookie_echo (sctp_connection_t * sctp_conn) { vlib_buffer_t *b; u32 bi; sctp_main_t *tm = vnet_get_sctp_main (); vlib_main_t *vm = vlib_get_main (); if (PREDICT_FALSE (sctp_conn->init_retransmit_err > SCTP_MAX_INIT_RETRANS)) { clib_warning ("Reached MAX_INIT_RETRANS times. Aborting connection."); session_stream_connect_notify (&sctp_conn->sub_conn [SCTP_PRIMARY_PATH_IDX].connection, 1); sctp_connection_timers_reset (sctp_conn); sctp_connection_cleanup (sctp_conn); } if (PREDICT_FALSE (sctp_get_free_buffer_index (tm, &bi))) return; b = vlib_get_buffer (vm, bi); u8 idx = SCTP_PRIMARY_PATH_IDX; sctp_init_buffer (vm, b); sctp_prepare_cookie_echo_chunk (sctp_conn, idx, b, 0); sctp_enqueue_to_output_now (vm, b, bi, sctp_conn->sub_conn[idx].c_is_ip4); /* Start the T1_INIT timer */ sctp_timer_set (sctp_conn, idx, SCTP_TIMER_T1_INIT, sctp_conn->sub_conn[idx].RTO); /* Change state to COOKIE_WAIT */ sctp_conn->state = SCTP_STATE_COOKIE_WAIT; /* Measure RTT with this */ sctp_conn->su
# Copyright (c) 2021 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Vhost-user interfaces library."""

from enum import IntEnum

from robot.api import logger

from resources.libraries.python.CpuUtils import CpuUtils
from resources.libraries.python.PapiExecutor import PapiSocketExecutor
from resources.libraries.python.topology import NodeType, Topology
from resources.libraries.python.InterfaceUtil import InterfaceUtil
from resources.libraries.python.ssh import exec_cmd_no_error


class VirtioFeaturesFlags(IntEnum):
    """Virtio Features Flags."""
    VIRTIO_NET_F_API_CSUM = 0
    VIRTIO_NET_F_API_GUEST_CSUM = 1
    VIRTIO_NET_F_API_GSO = 6
    VIRTIO_NET_F_API_GUEST_TSO4 = 7
    VIRTIO_NET_F_API_GUEST_TSO6 = 8
    VIRTIO_NET_F_API_GUEST_UFO = 10
    VIRTIO_NET_F_API_HOST_TSO4 = 11
    VIRTIO_NET_F_API_HOST_TSO6 = 12
    VIRTIO_NET_F_API_HOST_UFO = 14
    VIRTIO_NET_F_API_MRG_RXBUF = 15
    VIRTIO_NET_F_API_CTRL_VQ = 17
    VIRTIO_NET_F_API_GUEST_ANNOUNCE = 21
    VIRTIO_NET_F_API_MQ = 22
    VIRTIO_F_API_ANY_LAYOUT = 27
    VIRTIO_F_API_INDIRECT_DESC = 28


class VhostUser:
    """Vhost-user interfaces L1 library."""

    @staticmethod
    def vpp_create_vhost_user_interface(
            node, socket, is_server=False, virtio_feature_mask=None):
        """Create Vhost-user interface on VPP node.

        :param node: Node to create Vhost-user interface on.
        :param socket: Vhost-user interface socket path.
        :param is_server: Server side of connection. Default: False
        :param virtio_feature_mask: Mask of virtio features to be enabled.
        :type node: dict
        :type socket: str
        :type is_server: bool
        :type virtio_feature_mask: int
        :returns: SW interface index.
        :rtype: int
        """
        cmd = u"create_vhost_user_if"
        err_msg = f"Failed to create Vhost-user interface " \
            f"on host {node[u'host']}"
        if virtio_feature_mask is None:
            enable_gso = False
        else:
            enable_gso = VirtioFeatureMask.is_feature_enabled(
                virtio_feature_mask, VirtioFeaturesFlags.VIRTIO_NET_F_API_GSO
            )
        args = dict(
            is_server=bool(is_server),
            sock_filename=str(socket),
            enable_gso=bool(enable_gso)
        )

        with PapiSocketExecutor(node) as papi_exec:
            sw_if_index = papi_exec.add(cmd, **args).get_sw_if_index(err_msg)

        # Update the Topology:
        if_key = Topology.add_new_port(node, u"vhost")
        Topology.update_interface_sw_if_index(node, if_key, sw_if_index)

        ifc_name = InterfaceUtil.vpp_get_interface_name(node, sw_if_index)
        Topology.update_interface_name(node, if_key, ifc_name)

        ifc_mac = InterfaceUtil.vpp_get_interface_mac(node, sw_if_index)
        Topology.update_interface_mac_address(node, if_key, ifc_mac)

        Topology.update_interface_vhost_socket(node, if_key, socket)

        return sw_if_index

    @staticmethod
    def get_vhost_user_if_name_by_sock(node, socket):
        """Get Vhost-user interface name by socket.

        :param node: Node to get Vhost-user interface name on.
        :param socket: Vhost-user interface socket path.
        :type node: dict
        :type socket: str
        :returns: Interface name or None if not found.
        :rtype: str
        """
        for interface in node[u"interfaces"].values():
            if interface.get(u"socket") == socket:
                return interface.get(u"name")
        return None

    @staticmethod
    def get_vhost_user_mac_by_sw_index(node, sw_if_index):
        """Get Vhost-user l2_address for the given interface from actual
        interface dump.

        :param node: VPP node to get interface data from.
        :param sw_if_index: SW index of the specific interface.
        :type node: dict
        :type sw_if_index: str
        :returns: l2_address of the given interface.
        :rtype: str
        """
        return InterfaceUtil.vpp_get_interface_mac(node, sw_if_index)

    @staticmethod
    def show_vpp_vhost_on_all_duts(nodes):
        """Show Vhost-user on all DUTs.

        :param nodes: VPP nodes.
        :type nodes: dict
        """
        for node in nodes.values():
            if node[u"type"] == NodeType.DUT:
                VhostUser.vhost_user_dump(node)

    @staticmethod
    def vhost_user_dump(node):
        """Get vhost-user data for the given node.

        :param node: VPP node to get interface data from.
        :type node: dict
        :returns: List of dictionaries with all vhost-user interfaces.
        :rtype: list
        """
        cmd = u"sw_interface_vhost_user_dump"
        err_msg = f"Failed to get vhost-user dump on host {node['host']}"

        with PapiSocketExecutor(node) as papi_exec:
            details = papi_exec.add(cmd).get_details(err_msg)

        logger.debug(f"Vhost-user details:\n{details}")
        return details

    @staticmethod
    def vhost_user_affinity(node, pf_key, skip_cnt=0):
        """Set vhost-user affinity for the given node.

        :param node: Topology node.
        :param pf_key: Interface key to compute numa location.
        :param skip_cnt: Skip first "skip_cnt" CPUs.
        :type node: dict
        :type pf_key: str
        :type skip_cnt: int
        """
        pids, _ = exec_cmd_no_error(
            node, f"grep -h vhost /proc/*/comm | uniq | xargs pidof")

        affinity = CpuUtils.get_affinity_vhost(
            node, pf_key, skip_cnt=skip_cnt, cpu_cnt=len(pids.split(" ")))

        for cpu, pid in zip(affinity, pids.split(" ")):
            exec_cmd_no_error(node, f"taskset -pc {cpu} {pid}", sudo=True)


class VirtioFeatureMask:
    """Virtio features utilities"""

    @staticmethod
    def create_virtio_feature_mask(**kwargs):
        """Create virtio feature mask with feature bits set according to kwargs.
        :param kwargs: Key-value pairs of feature names and it's state
        :type kwargs: dict
        """
        virtio_feature_mask = 0

        if u"all" in kwargs and kwargs[u"all"] is True:
            for virtio_feature_flag in VirtioFeaturesFlags:
                virtio_feature_mask |= 1 << virtio_feature_flag.value
        else:
            for feature_name, enabled in kwargs.items():
                virtio_feature_name = \
                    u"VIRTIO_NET_F_API_" + feature_name.upper()
                if virtio_feature_name not in VirtioFeaturesFlags.__members__:
                    raise ValueError(u"Unsupported virtio feature flag name")
                if enabled:
                    virtio_feature_mask |= \
                        1