Repository: firecracker-microvm/firecracker
File: src/vmm/src/devices/virtio/net/device.rs (Rust)

Code before:
            }
        }

        // This frame goes to the TAP.

        // Check for guest MAC spoofing.
        if let Some(guest_mac) = guest_mac {
            let _ = EthernetFrame::from_bytes(headers).map(|eth_frame| {
                if guest_mac != eth_frame.src_mac() {
                    net_metrics.tx_spoofed_mac_count.inc();
                }
            });
        }

        let _metric = net_metrics.tap_write_agg.record_latency_metrics();
        match Self::write_tap(tap, frame_iovec) {
            Ok(_) => {
                let len = u64::from(frame_iovec.len());
                net_metrics.tx_bytes_count.add(len);
                net_metrics.tx_packets_count.inc();
                net_metrics.tx_count.inc();
            }
            Err(err) => {
                error!("Failed to write to tap: {:?}", err);
                net_metrics.tap_write_fails.inc();
            }
        };
        Ok(false)
    }

    // We currently prioritize packets from the MMDS over regular network packets.
    fn read_from_mmds_or_tap(&mut self) -> Result<Option<NonZeroU32>, NetError> {
        // We only want to read from TAP (or mmds) if we have at least 64K of available capacity as
        // this is the max size of 1 packet.
        // SAFETY:
        // * MAX_BUFFER_SIZE is constant and fits into u32
        #[allow(clippy::cast_possible_truncation)]
        if self.rx_buffer.capacity() < MAX_BUFFER_SIZE as u32 {
            self.parse_rx_descriptors();

            // If after parsing the RX queue we still don't have enough capacity, stop processing RX
            // frames.
            if self.rx_buffer.capacity() < MAX_BUFFER_SIZE as u32 {
                return Ok(None);
            }
        }

        if let Some(ns) = self.mmds_ns.as_mut() {
            if let Some(len) =
                ns.write_next_frame(frame_bytes_from_buf_mut(&mut self.rx_frame_buf)?)
            {

Review comment (suggestion):
I really dislike `try_into().unwrap()` (after Patrick brainwashing me :P) but I dislike this more :) I know that there are places that the truncation cannot happen today (like this one) but 1. you use them all over the place and 2. I'm afraid of what might happen when/if the code changes in a way that makes it possible to actually truncate. This is like leaving an Easter egg for someone in the future.

Code after:
            });
        }

        let _metric = net_metrics.tap_write_agg.record_latency_metrics();
        match Self::write_tap(tap, frame_iovec) {
            Ok(_) => {
                let len = u64::from(frame_iovec.len());
                net_metrics.tx_bytes_count.add(len);
                net_metrics.tx_packets_count.inc();
                net_metrics.tx_count.inc();
            }
            Err(err) => {
                error!("Failed to write to tap: {:?}", err);
                net_metrics.tap_write_fails.inc();
            }
        };
        Ok(false)
    }

    // We currently prioritize packets from the MMDS over regular network packets.
    fn read_from_mmds_or_tap(&mut self) -> Result<Option<u32>, NetError> {
        // We only want to read from TAP (or mmds) if we have at least 64K of available capacity as
        // this is the max size of 1 packet.
        // SAFETY:
        // * MAX_BUFFER_SIZE is constant and fits into u32
        #[allow(clippy::cast_possible_truncation)]
        if self.rx_buffer.capacity() < MAX_BUFFER_SIZE as u32 {
            self.parse_rx_descriptors();

            // If after parsing the RX queue we still don't have enough capacity, stop processing RX
            // frames.
            if self.rx_buffer.capacity() < MAX_BUFFER_SIZE as u32 {
                return Ok(None);
            }
        }

        if let Some(ns) = self.mmds_ns.as_mut() {
            if let Some(len) =
                ns.write_next_frame(frame_bytes_from_buf_mut(&mut self.rx_frame_buf)?)
            {
                let len = len.get();
                METRICS.mmds.tx_frames.inc();
                METRICS.mmds.tx_bytes.add(len as u64);
                init_vnet_hdr(&mut self.rx_frame_buf);
                self.rx_buffer
                    .iovec
                    .write_all_volatile_at(&self.rx_frame_buf[..vnet_hdr_len() + len], 0)?;
                // SAFETY:
                // * len will never be bigger that u32::MAX because mmds is bound
                // by the size of `self.rx_frame_buf` which is MAX_BUFFER_SIZE size.
                let len: u32 = (vnet_hdr_len() + len).try_into().unwrap();