use alloc::fmt::Debug;
use core::marker::PhantomData;
use log::debug;
use net_types::ip::{Ipv4, Ipv6};
use netstack3_base::{
AnyDevice, ContextPair, CoreTimerContext, Device, DeviceIdAnyCompatContext, DeviceIdContext,
Inspector, RecvFrameContext, ReferenceNotifiers, ReferenceNotifiersExt as _,
RemoveResourceResultWithContext, ResourceCounterContext, TimerContext,
};
use netstack3_ip::device::{
IpAddressIdSpecContext, IpDeviceBindingsContext, IpDeviceConfigurationContext, IpDeviceTimerId,
Ipv6DeviceConfigurationContext,
};
use netstack3_ip::{self as ip, RawMetric};
use packet::BufferMut;
use crate::internal::base::{
DeviceCollectionContext, DeviceCounters, DeviceLayerStateTypes, DeviceLayerTypes,
DeviceReceiveFrameSpec, OriginTrackerContext,
};
use crate::internal::config::{
ArpConfiguration, ArpConfigurationUpdate, DeviceConfiguration, DeviceConfigurationContext,
DeviceConfigurationUpdate, DeviceConfigurationUpdateError, NdpConfiguration,
NdpConfigurationUpdate,
};
use crate::internal::ethernet::EthernetLinkDevice;
use crate::internal::id::{
for_any_device_id, BaseDeviceId, BasePrimaryDeviceId, BaseWeakDeviceId, DeviceId,
DeviceProvider,
};
use crate::internal::loopback::LoopbackDevice;
use crate::internal::pure_ip::PureIpDevice;
use crate::internal::state::{BaseDeviceState, DeviceStateSpec, IpLinkDeviceStateInner};
pub struct PendingDeviceConfigurationUpdate<'a, D>(DeviceConfigurationUpdate, &'a D);
pub struct DeviceApi<D, C>(C, PhantomData<D>);
impl<D, C> DeviceApi<D, C> {
pub fn new(ctx: C) -> Self {
Self(ctx, PhantomData)
}
}
impl<D, C> DeviceApi<D, C>
where
D: Device + DeviceStateSpec + DeviceReceiveFrameSpec,
C: ContextPair,
C::CoreContext: DeviceApiCoreContext<D, C::BindingsContext>,
C::BindingsContext: DeviceApiBindingsContext,
{
pub(crate) fn contexts(&mut self) -> (&mut C::CoreContext, &mut C::BindingsContext) {
let Self(pair, PhantomData) = self;
pair.contexts()
}
pub(crate) fn core_ctx(&mut self) -> &mut C::CoreContext {
let Self(pair, PhantomData) = self;
pair.core_ctx()
}
pub fn add_device(
&mut self,
bindings_id: <C::BindingsContext as DeviceLayerStateTypes>::DeviceIdentifier,
properties: D::CreationProperties,
metric: RawMetric,
external_state: D::External<C::BindingsContext>,
) -> <C::CoreContext as DeviceIdContext<D>>::DeviceId
where
C::CoreContext: DeviceApiIpLayerCoreContext<D, C::BindingsContext>,
{
debug!("adding {} device with {:?} metric:{metric}", D::DEBUG_TYPE, properties);
let (core_ctx, bindings_ctx) = self.contexts();
let origin = core_ctx.origin_tracker();
let primary = BasePrimaryDeviceId::new(
|weak_ref| {
let link = D::new_link_state::<C::CoreContext, _>(
bindings_ctx,
weak_ref.clone(),
properties,
);
IpLinkDeviceStateInner::new::<_, _, C::CoreContext>(
bindings_ctx,
weak_ref.into(),
link,
metric,
origin,
)
},
external_state,
bindings_id,
);
let id = primary.clone_strong();
core_ctx.insert(primary);
id
}
#[cfg(any(test, feature = "testutils"))]
pub fn add_device_with_default_state(
&mut self,
properties: D::CreationProperties,
metric: RawMetric,
) -> <C::CoreContext as DeviceIdContext<D>>::DeviceId
where
<C::BindingsContext as DeviceLayerStateTypes>::DeviceIdentifier: Default,
D::External<C::BindingsContext>: Default,
C::CoreContext: DeviceApiIpLayerCoreContext<D, C::BindingsContext>,
{
self.add_device(Default::default(), properties, metric, Default::default())
}
pub fn remove_device(
&mut self,
device: BaseDeviceId<D, C::BindingsContext>,
) -> RemoveResourceResultWithContext<D::External<C::BindingsContext>, C::BindingsContext>
where
BaseDeviceId<D, C::BindingsContext>: Into<DeviceId<C::BindingsContext>>,
C::CoreContext: IpDeviceConfigurationContext<Ipv4, C::BindingsContext>
+ Ipv6DeviceConfigurationContext<C::BindingsContext>
+ DeviceIdContext<AnyDevice, DeviceId = DeviceId<C::BindingsContext>>,
C::BindingsContext: IpDeviceBindingsContext<Ipv4, <C::CoreContext as DeviceIdContext<AnyDevice>>::DeviceId>
+ IpDeviceBindingsContext<Ipv6, <C::CoreContext as DeviceIdContext<AnyDevice>>::DeviceId>,
{
let (core_ctx, bindings_ctx) = self.contexts();
{
let device = device.clone().into();
ip::device::clear_ipv4_device_state(core_ctx, bindings_ctx, &device);
ip::device::clear_ipv6_device_state(core_ctx, bindings_ctx, &device);
};
debug!("removing {device:?}");
let primary = core_ctx.remove(&device).expect("tried to remove device not in stack");
assert_eq!(device, primary);
core::mem::drop(device);
C::BindingsContext::unwrap_or_notify_with_new_reference_notifier(
primary.into_inner(),
|state: BaseDeviceState<_, _>| state.external_state,
)
}
pub fn receive_frame<B: BufferMut + Debug>(
&mut self,
meta: D::FrameMetadata<BaseDeviceId<D, C::BindingsContext>>,
frame: B,
) {
let (core_ctx, bindings_ctx) = self.contexts();
core_ctx.receive_frame(bindings_ctx, meta, frame)
}
pub fn apply_configuration(
&mut self,
pending: PendingDeviceConfigurationUpdate<'_, BaseDeviceId<D, C::BindingsContext>>,
) -> DeviceConfigurationUpdate {
let PendingDeviceConfigurationUpdate(DeviceConfigurationUpdate { arp, ndp }, device_id) =
pending;
let core_ctx = self.core_ctx();
let arp = core_ctx.with_nud_config_mut::<Ipv4, _, _>(device_id, move |device_config| {
let device_config = match device_config {
Some(c) => c,
None => {
assert!(arp.is_none());
return None;
}
};
arp.map(|ArpConfigurationUpdate { nud }| {
let nud = nud.map(|config| config.apply_and_take_previous(device_config));
ArpConfigurationUpdate { nud }
})
});
let ndp = core_ctx.with_nud_config_mut::<Ipv6, _, _>(device_id, move |device_config| {
let device_config = match device_config {
Some(c) => c,
None => {
assert!(ndp.is_none());
return None;
}
};
ndp.map(|NdpConfigurationUpdate { nud }| {
let nud = nud.map(|config| config.apply_and_take_previous(device_config));
NdpConfigurationUpdate { nud }
})
});
DeviceConfigurationUpdate { arp, ndp }
}
pub fn new_configuration_update<'a>(
&mut self,
device: &'a BaseDeviceId<D, C::BindingsContext>,
config: DeviceConfigurationUpdate,
) -> Result<
PendingDeviceConfigurationUpdate<'a, BaseDeviceId<D, C::BindingsContext>>,
DeviceConfigurationUpdateError,
> {
let core_ctx = self.core_ctx();
let DeviceConfigurationUpdate { arp, ndp } = &config;
if arp.is_some() && core_ctx.with_nud_config::<Ipv4, _, _>(device, |c| c.is_none()) {
return Err(DeviceConfigurationUpdateError::ArpNotSupported);
}
if ndp.is_some() && core_ctx.with_nud_config::<Ipv6, _, _>(device, |c| c.is_none()) {
return Err(DeviceConfigurationUpdateError::NdpNotSupported);
}
Ok(PendingDeviceConfigurationUpdate(config, device))
}
pub fn get_configuration(
&mut self,
device: &BaseDeviceId<D, C::BindingsContext>,
) -> DeviceConfiguration {
let core_ctx = self.core_ctx();
let arp = core_ctx
.with_nud_config::<Ipv4, _, _>(device, |config| config.cloned())
.map(|nud| ArpConfiguration { nud });
let ndp = core_ctx
.with_nud_config::<Ipv6, _, _>(device, |config| config.cloned())
.map(|nud| NdpConfiguration { nud });
DeviceConfiguration { arp, ndp }
}
pub fn inspect<N: Inspector>(
&mut self,
device: &BaseDeviceId<D, C::BindingsContext>,
inspector: &mut N,
) {
inspector.record_child("Counters", |inspector| {
self.core_ctx().with_per_resource_counters(device, |counters: &DeviceCounters| {
inspector.delegate_inspectable(counters)
});
self.core_ctx().with_per_resource_counters(device, |counters: &D::Counters| {
inspector.delegate_inspectable(counters)
});
});
}
}
pub struct DeviceAnyApi<C>(C);
impl<C> DeviceAnyApi<C> {
pub fn new(ctx: C) -> Self {
Self(ctx)
}
}
impl<C> DeviceAnyApi<C>
where
C: ContextPair,
C::CoreContext: DeviceApiCoreContext<EthernetLinkDevice, C::BindingsContext>
+ DeviceApiCoreContext<LoopbackDevice, C::BindingsContext>
+ DeviceApiCoreContext<PureIpDevice, C::BindingsContext>,
C::BindingsContext: DeviceApiBindingsContext,
{
fn device<D>(&mut self) -> DeviceApi<D, &mut C> {
let Self(pair) = self;
DeviceApi::new(pair)
}
pub fn apply_configuration(
&mut self,
pending: PendingDeviceConfigurationUpdate<'_, DeviceId<C::BindingsContext>>,
) -> DeviceConfigurationUpdate {
let PendingDeviceConfigurationUpdate(config, device) = pending;
for_any_device_id!(DeviceId, device,
device => {
self.device().apply_configuration(PendingDeviceConfigurationUpdate(config, device))
}
)
}
pub fn new_configuration_update<'a>(
&mut self,
device: &'a DeviceId<C::BindingsContext>,
config: DeviceConfigurationUpdate,
) -> Result<
PendingDeviceConfigurationUpdate<'a, DeviceId<C::BindingsContext>>,
DeviceConfigurationUpdateError,
> {
for_any_device_id!(DeviceId, device,
inner => {
self.device()
.new_configuration_update(inner, config)
.map(|PendingDeviceConfigurationUpdate(config, _)| {
PendingDeviceConfigurationUpdate(config, device)
})
}
)
}
pub fn get_configuration(
&mut self,
device: &DeviceId<C::BindingsContext>,
) -> DeviceConfiguration {
for_any_device_id!(DeviceId, device,
device => self.device().get_configuration(device))
}
pub fn inspect<N: Inspector>(
&mut self,
device: &DeviceId<C::BindingsContext>,
inspector: &mut N,
) {
for_any_device_id!(DeviceId, DeviceProvider, D, device,
device => self.device::<D>().inspect(device, inspector))
}
}
pub trait DeviceApiCoreContext<
D: Device + DeviceStateSpec + DeviceReceiveFrameSpec,
BC: DeviceApiBindingsContext,
>:
DeviceIdContext<D, DeviceId = BaseDeviceId<D, BC>, WeakDeviceId = BaseWeakDeviceId<D, BC>>
+ OriginTrackerContext
+ DeviceCollectionContext<D, BC>
+ DeviceConfigurationContext<D>
+ RecvFrameContext<D::FrameMetadata<BaseDeviceId<D, BC>>, BC>
+ ResourceCounterContext<Self::DeviceId, DeviceCounters>
+ ResourceCounterContext<Self::DeviceId, D::Counters>
+ CoreTimerContext<D::TimerId<Self::WeakDeviceId>, BC>
{
}
impl<O, D, BC> DeviceApiCoreContext<D, BC> for O
where
D: Device + DeviceStateSpec + DeviceReceiveFrameSpec,
BC: DeviceApiBindingsContext,
O: DeviceIdContext<D, DeviceId = BaseDeviceId<D, BC>, WeakDeviceId = BaseWeakDeviceId<D, BC>>
+ OriginTrackerContext
+ DeviceCollectionContext<D, BC>
+ DeviceConfigurationContext<D>
+ RecvFrameContext<D::FrameMetadata<BaseDeviceId<D, BC>>, BC>
+ ResourceCounterContext<Self::DeviceId, DeviceCounters>
+ ResourceCounterContext<Self::DeviceId, D::Counters>
+ CoreTimerContext<D::TimerId<Self::WeakDeviceId>, BC>,
{
}
pub trait DeviceApiBindingsContext: DeviceLayerTypes + ReferenceNotifiers + TimerContext {}
impl<O> DeviceApiBindingsContext for O where O: DeviceLayerTypes + ReferenceNotifiers + TimerContext {}
pub trait DeviceApiIpLayerCoreContext<D: Device, BC: DeviceLayerTypes>:
DeviceIdAnyCompatContext<D>
+ IpAddressIdSpecContext
+ CoreTimerContext<
IpDeviceTimerId<
Ipv6,
<Self as DeviceIdContext<AnyDevice>>::WeakDeviceId,
Self::AddressIdSpec,
>,
BC,
> + CoreTimerContext<
IpDeviceTimerId<
Ipv4,
<Self as DeviceIdContext<AnyDevice>>::WeakDeviceId,
Self::AddressIdSpec,
>,
BC,
>
{
}
impl<O, D, BC> DeviceApiIpLayerCoreContext<D, BC> for O
where
D: Device,
BC: DeviceLayerTypes,
O: DeviceIdAnyCompatContext<D>
+ IpAddressIdSpecContext
+ CoreTimerContext<
IpDeviceTimerId<
Ipv6,
<Self as DeviceIdContext<AnyDevice>>::WeakDeviceId,
Self::AddressIdSpec,
>,
BC,
> + CoreTimerContext<
IpDeviceTimerId<
Ipv4,
<Self as DeviceIdContext<AnyDevice>>::WeakDeviceId,
Self::AddressIdSpec,
>,
BC,
>,
{
}