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
use std::collections::BTreeMap;

use twizzler_net::{addr::ServiceAddr, PacketData, TxCompletion, TxCompletionError};

use crate::{endpoint::EndPointKey, link::IncomingPacketInfo, HandleRef};

pub mod icmp;
pub mod tcp;
pub mod udp;

#[allow(dead_code)]
enum RawSupport {
    NoRaw,
    RawAllowed,
    OnlyRaw,
}

#[async_trait::async_trait]
trait TransportProto: Sync + Send {
    async fn send_packet(
        &self,
        handle: &HandleRef,
        endpoint_info: EndPointKey,
        packet_data: PacketData,
    ) -> TxCompletion;

    async fn handle_packet(&self, info: IncomingPacketInfo);

    fn raw_support(&self) -> RawSupport;
}

lazy_static::lazy_static! {
    static ref PROTOS: BTreeMap<ServiceAddr, Box<dyn TransportProto>> = {
        let mut map: BTreeMap<ServiceAddr, Box<dyn TransportProto>> = BTreeMap::new();
       // let (key, value) = tcp::init();
      //  map.insert(key, value);
       // let (key, value) = udp::init();
      //  map.insert(key, value);
        let (key, value) = icmp::init();
        map.insert(key, Box::new(value));
        map
    };
}

pub async fn send_packet(
    handle: &HandleRef,
    endpoint_info: EndPointKey,
    packet_data: PacketData,
) -> TxCompletion {
    let dest_service_any = endpoint_info.dest_address().1.any();
    if let Some(proto) = PROTOS.get(&dest_service_any) {
        proto.send_packet(handle, endpoint_info, packet_data).await
    } else {
        TxCompletion::Error(TxCompletionError::InvalidArgument)
    }
}

pub async fn handle_packet(addr: ServiceAddr, info: IncomingPacketInfo) {
    if let Some(proto) = PROTOS.get(&addr) {
        let _ = proto.handle_packet(info);
    }
}