patches and low-level development discussion
 help / color / mirror / code / Atom feed
blob 8676e4a844a88d7913d76652b7773229643bf408 4468 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
 
// 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 crate::packet::*;
use crate::protocol::*;

use futures_util::{Sink, SinkExt, Stream, StreamExt};
use log::{debug, info, 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!(
                    "dropped incoming message to {} because no fib match",
                    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(|(_, sink)| {
                                sink.send(Packet::Peek {
                                    peek: peek.clone(),
                                    buf: PacketData::Bytes(Cursor::new(buf.clone())),
                                    decap_vlan,
                                })
                            }),
                    )
                    .await?;
                }
                ref unicast => {
                    let Some(sink) = self.sinks.get_mut(unicast) else {
                        warn!("dropped message because interface is not ready");
                        continue;
                    };
                    sink.send(packet).await?;
                }
            }
        }
    }
}

debug log:

solving 8676e4a ...
found 8676e4a in https://inbox.spectrum-os.org/spectrum-devel/20251128223038.97536-5-yureka@cyberchaos.dev/

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

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

index at:
100644 8676e4a844a88d7913d76652b7773229643bf408	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).