patches and low-level development discussion
 help / color / mirror / code / Atom feed
blob f36866d8e5c71c4aece53b460d3e0431dd9a7d0a 5455 bytes (raw)
name: tools/router/src/router.rs 	 # note: path name is non-authoritative(*)

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
 
// SPDX-License-Identifier: EUPL-1.2+
// SPDX-FileCopyrightText: 2025 Yureka Lilian <yureka@cyberchaos.dev>

use std::collections::HashMap;
use std::io::{self, Cursor};
use std::net::Ipv6Addr;
use std::pin::Pin;
use std::time::Duration;

use crate::packet::*;
use crate::protocol::*;

use futures_util::{FutureExt, Sink, SinkExt, Stream, StreamExt};
use log::{debug, info, trace, warn};
use tokio_stream::StreamMap;
use vhost_device_net::IncomingPacket;
use vm_memory::GuestMemory;

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum InterfaceId {
    Upstream,
    App(usize),
    Broadcast,
}

pub type PacketStream<M> = Pin<Box<dyn Stream<Item = io::Result<Packet<IncomingPacket<M>>>>>>;
pub type PacketSink<M> = Pin<Box<dyn Sink<Packet<IncomingPacket<M>>, Error = io::Error>>>;

pub struct Router<M: GuestMemory> {
    streams: StreamMap<InterfaceId, PacketStream<M>>,
    sinks: HashMap<InterfaceId, PacketSink<M>>,
    fib: HashMap<Ipv6Addr, (MacAddr, InterfaceId)>,
    default_out: InterfaceId,
}

impl<M: GuestMemory> Router<M> {
    pub fn new(default_out: InterfaceId) -> Self {
        Self {
            streams: Default::default(),
            sinks: Default::default(),
            fib: Default::default(),
            default_out,
        }
    }

    pub fn add_iface(&mut self, id: InterfaceId, stream: PacketStream<M>, sink: PacketSink<M>) {
        self.streams.insert(id.clone(), stream);
        self.sinks.insert(id.clone(), sink);
    }

    pub async fn run(&mut self) -> io::Result<()> {
        loop {
            let next_res = self.streams.next().await;
            let Some((in_iface, Ok(mut packet))) = next_res else {
                info!("incoming err");
                continue;
            };

            let PacketHeaders {
                ether_frame,
                ipv6_hdr,
                ..
            } = packet.headers()?;

            let Some(ipv6_hdr) = ipv6_hdr else {
                continue;
            };
            let src_addr = Ipv6Addr::from(ipv6_hdr.src_addr);
            let dst_addr = Ipv6Addr::from(ipv6_hdr.dst_addr);

            let out_iface = if is_multicast(&ether_frame.dst_addr) {
                InterfaceId::Broadcast
            } else if let Some((dst_mac, if_idx)) = self.fib.get(&dst_addr) {
                ether_frame.dst_addr = *dst_mac;
                if_idx.clone()
            } else if in_iface != self.default_out {
                self.default_out.clone()
            } else {
                warn!("no fib match for {}, dropping packet", dst_addr);
                continue;
            };

            if in_iface != self.default_out
                && !src_addr.is_unspecified()
                && !src_addr.is_multicast()
                && !self.fib.contains_key(&src_addr)
            {
                debug!(
                    "adding fib entry for {} -> {:x?} {:?}",
                    src_addr, ether_frame.src_addr, in_iface
                );
                self.fib
                    .insert(src_addr, (ether_frame.src_addr, in_iface.clone()));
            }

            match out_iface {
                InterfaceId::Broadcast => {
                    let Packet::Peek {
                        peek,
                        mut buf,
                        decap_vlan,
                    } = packet
                    else {
                        unreachable!()
                    };
                    let buf = Box::<[u8]>::from(buf.full_packet());
                    futures_util::future::try_join_all(
                        self.sinks
                            .iter_mut()
                            .filter(|(id, _)| **id != in_iface)
                            .map(|(id, sink)| {
                                let packet = Packet::Peek {
                                    peek: peek.clone(),
                                    buf: PacketData::Bytes(Cursor::new(buf.clone())),
                                    decap_vlan,
                                };
                                let fut = sink.send(packet);
                                tokio::time::timeout(Duration::from_secs(1), fut).map(move |res| match res {
                                    Err(_) => {
                                        warn!("interface {:?} has been blocked for 1 sec, dropping packet", id);
                                        Ok(())
                                    },
                                    Ok(Err(e)) => Err(e),
                                    Ok(Ok(())) => Ok(()),
                                })
                            }),
                    )
                    .await?;
                }
                ref unicast => {
                    trace!("got unicast packet {:?} -> {:?}", in_iface, out_iface);
                    let Some(sink) = self.sinks.get_mut(unicast) else {
                        warn!("dropped packet because interface is not ready");
                        continue;
                    };
                    match tokio::time::timeout(Duration::from_secs(1), sink.send(packet)).await {
                        Err(_) => warn!(
                            "interface {:?} has been blocked for 1 sec, dropping packet",
                            unicast
                        ),
                        Ok(Err(e)) => return Err(e),
                        Ok(Ok(())) => {}
                    }
                }
            }
        }
    }
}

debug log:

solving f36866d8 ...
found f36866d8 in https://inbox.spectrum-os.org/spectrum-devel/20260619130940.273236-1-hi@alyssa.is/
retrying a91e4155 as a91e415
found a91e415 in https://inbox.spectrum-os.org/spectrum-devel/20251129194404.37773-7-yureka@cyberchaos.dev/ ||
	https://inbox.spectrum-os.org/spectrum-devel/20251129181514.20296-7-yureka@cyberchaos.dev/

applying [1/2] https://inbox.spectrum-os.org/spectrum-devel/20251129194404.37773-7-yureka@cyberchaos.dev/
diff --git a/tools/router/src/router.rs b/tools/router/src/router.rs
new file mode 100644
index 0000000..a91e415

Checking patch tools/router/src/router.rs...
Applied patch tools/router/src/router.rs cleanly.

skipping https://inbox.spectrum-os.org/spectrum-devel/20251129181514.20296-7-yureka@cyberchaos.dev/ for a91e415
index at:
100644 a91e4155c9dbfdbaec5395dc3c7c12505e6e08b5	tools/router/src/router.rs

applying [2/2] https://inbox.spectrum-os.org/spectrum-devel/20260619130940.273236-1-hi@alyssa.is/
diff --git a/tools/router/src/router.rs b/tools/router/src/router.rs
index a91e4155..f36866d8 100644

Checking patch tools/router/src/router.rs...
Applied patch tools/router/src/router.rs cleanly.

index at:
100644 f36866d8e5c71c4aece53b460d3e0431dd9a7d0a	tools/router/src/router.rs

(*) Git path names are given by the tree(s) the blob belongs to.
    Blobs themselves have no identifier aside from the hash of its contents.^

Code repositories for project(s) associated with this public inbox

	https://spectrum-os.org/git/crosvm
	https://spectrum-os.org/git/doc
	https://spectrum-os.org/git/mktuntap
	https://spectrum-os.org/git/nixpkgs
	https://spectrum-os.org/git/spectrum
	https://spectrum-os.org/git/ucspi-vsock
	https://spectrum-os.org/git/www

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).