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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
// Copyright 2022 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

//! The loopback device.

use alloc::vec::Vec;
use core::convert::Infallible as Never;
use core::fmt::Debug;
use derivative::Derivative;

use lock_order::lock::{OrderedLockAccess, OrderedLockRef};
use log::trace;
use net_types::ethernet::Mac;
use net_types::ip::{Ipv4, Ipv6, Mtu};
use netstack3_base::sync::Mutex;
use netstack3_base::{
    AnyDevice, BroadcastIpExt, CoreTimerContext, Device, DeviceIdAnyCompatContext, DeviceIdContext,
    FrameDestination, RecvFrameContext, RecvIpFrameMeta, ResourceCounterContext, SendFrameError,
    SendFrameErrorReason, SendableFrameMeta, StrongDeviceIdentifier, TimerContext,
    WeakDeviceIdentifier,
};
use netstack3_ip::{DeviceIpLayerMetadata, IpPacketDestination};
use packet::{Buf, Buffer as _, BufferMut, Serializer};
use packet_formats::ethernet::{
    EtherType, EthernetFrame, EthernetFrameBuilder, EthernetFrameLengthCheck, EthernetIpExt,
};

use crate::internal::base::{
    DeviceCounters, DeviceLayerTypes, DeviceReceiveFrameSpec, EthernetDeviceCounters,
};
use crate::internal::id::{BaseDeviceId, BasePrimaryDeviceId, BaseWeakDeviceId, WeakDeviceId};
use crate::internal::queue::rx::{
    ReceiveDequeFrameContext, ReceiveQueue, ReceiveQueueState, ReceiveQueueTypes,
};
use crate::internal::queue::tx::{
    BufVecU8Allocator, TransmitQueue, TransmitQueueHandler, TransmitQueueState,
};
use crate::internal::queue::{DequeueState, TransmitQueueFrameError};
use crate::internal::socket::{
    DeviceSocketHandler, DeviceSocketMetadata, DeviceSocketSendTypes, EthernetHeaderParams,
    ReceivedFrame,
};
use crate::internal::state::{DeviceStateSpec, IpLinkDeviceState};

/// The MAC address corresponding to the loopback interface.
const LOOPBACK_MAC: Mac = Mac::UNSPECIFIED;

/// A weak device ID identifying a loopback device.
///
/// This device ID is like [`WeakDeviceId`] but specifically for loopback
/// devices.
///
/// [`WeakDeviceId`]: crate::device::WeakDeviceId
pub type LoopbackWeakDeviceId<BT> = BaseWeakDeviceId<LoopbackDevice, BT>;

/// A strong device ID identifying a loopback device.
///
/// This device ID is like [`DeviceId`] but specifically for loopback devices.
///
/// [`DeviceId`]: crate::device::DeviceId
pub type LoopbackDeviceId<BT> = BaseDeviceId<LoopbackDevice, BT>;

/// The primary reference for a loopback device.
pub type LoopbackPrimaryDeviceId<BT> = BasePrimaryDeviceId<LoopbackDevice, BT>;

/// Loopback device domain.
#[derive(Copy, Clone)]
pub enum LoopbackDevice {}

impl Device for LoopbackDevice {}

impl DeviceStateSpec for LoopbackDevice {
    type Link<BT: DeviceLayerTypes> = LoopbackDeviceState<WeakDeviceId<BT>>;
    type External<BT: DeviceLayerTypes> = BT::LoopbackDeviceState;
    type CreationProperties = LoopbackCreationProperties;
    type Counters = EthernetDeviceCounters;
    type TimerId<D: WeakDeviceIdentifier> = Never;

    fn new_link_state<
        CC: CoreTimerContext<Self::TimerId<CC::WeakDeviceId>, BC> + DeviceIdContext<Self>,
        BC: DeviceLayerTypes + TimerContext,
    >(
        _bindings_ctx: &mut BC,
        _self_id: CC::WeakDeviceId,
        LoopbackCreationProperties { mtu }: Self::CreationProperties,
    ) -> Self::Link<BC> {
        LoopbackDeviceState {
            counters: Default::default(),
            mtu,
            rx_queue: Default::default(),
            tx_queue: Default::default(),
        }
    }

    const IS_LOOPBACK: bool = true;
    const DEBUG_TYPE: &'static str = "Loopback";
}

/// Properties used to create a loopback device.
#[derive(Debug)]
pub struct LoopbackCreationProperties {
    /// The device's MTU.
    pub mtu: Mtu,
}

/// State for a loopback device.
pub struct LoopbackDeviceState<D: WeakDeviceIdentifier> {
    /// Loopback device counters.
    pub counters: EthernetDeviceCounters,
    /// The MTU this device was created with (immutable).
    pub mtu: Mtu,
    /// Loopback device receive queue.
    pub rx_queue: ReceiveQueue<LoopbackRxQueueMeta<D>, Buf<Vec<u8>>>,
    /// Loopback device transmit queue.
    pub tx_queue: TransmitQueue<LoopbackTxQueueMeta<D>, Buf<Vec<u8>>, BufVecU8Allocator>,
}

#[derive(Derivative)]
#[derivative(Default(bound = ""))]
/// Metadata associated with a frame in the Loopback TX queue.
pub struct LoopbackTxQueueMeta<D: WeakDeviceIdentifier> {
    /// Device that should be used to deliver the packet. If not set then the
    /// packet delivered as if it came from the loopback device.
    target_device: Option<D>,
    /// Metadata that is produced and consumed by the IP layer but which traverses
    /// the device layer through the loopback device.
    ip_layer_metadata: DeviceIpLayerMetadata,
}

/// Metadata associated with a frame in the Loopback RX queue.
#[derive(Debug)]
pub struct LoopbackRxQueueMeta<D: WeakDeviceIdentifier> {
    /// Device that should be used to deliver the packet. If not set then the
    /// packet delivered as if it came from the loopback device.
    target_device: Option<D>,
    /// Metadata that is produced and consumed by the IP layer but which traverses
    /// the device layer through the loopback device.
    ip_layer_metadata: DeviceIpLayerMetadata,
}

impl<D: WeakDeviceIdentifier> From<LoopbackTxQueueMeta<D>> for LoopbackRxQueueMeta<D> {
    fn from(
        LoopbackTxQueueMeta { target_device, ip_layer_metadata }: LoopbackTxQueueMeta<D>,
    ) -> Self {
        Self { target_device, ip_layer_metadata }
    }
}

impl<BT: DeviceLayerTypes>
    OrderedLockAccess<ReceiveQueueState<LoopbackRxQueueMeta<WeakDeviceId<BT>>, Buf<Vec<u8>>>>
    for IpLinkDeviceState<LoopbackDevice, BT>
{
    type Lock = Mutex<ReceiveQueueState<LoopbackRxQueueMeta<WeakDeviceId<BT>>, Buf<Vec<u8>>>>;
    fn ordered_lock_access(&self) -> OrderedLockRef<'_, Self::Lock> {
        OrderedLockRef::new(&self.link.rx_queue.queue)
    }
}

impl<BT: DeviceLayerTypes>
    OrderedLockAccess<DequeueState<LoopbackRxQueueMeta<WeakDeviceId<BT>>, Buf<Vec<u8>>>>
    for IpLinkDeviceState<LoopbackDevice, BT>
{
    type Lock = Mutex<DequeueState<LoopbackRxQueueMeta<WeakDeviceId<BT>>, Buf<Vec<u8>>>>;
    fn ordered_lock_access(&self) -> OrderedLockRef<'_, Self::Lock> {
        OrderedLockRef::new(&self.link.rx_queue.deque)
    }
}

impl<BT: DeviceLayerTypes>
    OrderedLockAccess<
        TransmitQueueState<LoopbackTxQueueMeta<WeakDeviceId<BT>>, Buf<Vec<u8>>, BufVecU8Allocator>,
    > for IpLinkDeviceState<LoopbackDevice, BT>
{
    type Lock = Mutex<
        TransmitQueueState<LoopbackTxQueueMeta<WeakDeviceId<BT>>, Buf<Vec<u8>>, BufVecU8Allocator>,
    >;
    fn ordered_lock_access(&self) -> OrderedLockRef<'_, Self::Lock> {
        OrderedLockRef::new(&self.link.tx_queue.queue)
    }
}

impl<BT: DeviceLayerTypes>
    OrderedLockAccess<DequeueState<LoopbackTxQueueMeta<WeakDeviceId<BT>>, Buf<Vec<u8>>>>
    for IpLinkDeviceState<LoopbackDevice, BT>
{
    type Lock = Mutex<DequeueState<LoopbackTxQueueMeta<WeakDeviceId<BT>>, Buf<Vec<u8>>>>;
    fn ordered_lock_access(&self) -> OrderedLockRef<'_, Self::Lock> {
        OrderedLockRef::new(&self.link.tx_queue.deque)
    }
}

impl DeviceSocketSendTypes for LoopbackDevice {
    /// When `None`, data will be sent as a raw Ethernet frame without any
    /// system-applied headers.
    type Metadata = Option<EthernetHeaderParams>;
}

impl<CC, BC> ReceiveDequeFrameContext<LoopbackDevice, BC> for CC
where
    CC: DeviceIdContext<LoopbackDevice>
        + ResourceCounterContext<Self::DeviceId, EthernetDeviceCounters>
        + ReceiveQueueTypes<
            LoopbackDevice,
            BC,
            Meta = LoopbackRxQueueMeta<<CC as DeviceIdContext<AnyDevice>>::WeakDeviceId>,
        >,
    // Loopback needs to deliver messages to `AnyDevice`.
    CC: DeviceIdAnyCompatContext<LoopbackDevice>
        + RecvFrameContext<
            RecvIpFrameMeta<
                <CC as DeviceIdContext<AnyDevice>>::DeviceId,
                DeviceIpLayerMetadata,
                Ipv4,
            >,
            BC,
        > + RecvFrameContext<
            RecvIpFrameMeta<
                <CC as DeviceIdContext<AnyDevice>>::DeviceId,
                DeviceIpLayerMetadata,
                Ipv6,
            >,
            BC,
        > + ResourceCounterContext<<CC as DeviceIdContext<AnyDevice>>::DeviceId, DeviceCounters>
        + DeviceSocketHandler<AnyDevice, BC>,
    CC::Buffer: BufferMut + Debug,
    BC: DeviceLayerTypes,
{
    fn handle_frame(
        &mut self,
        bindings_ctx: &mut BC,
        device_id: &Self::DeviceId,
        rx_meta: Self::Meta,
        mut buf: Self::Buffer,
    ) {
        let (frame, whole_body) =
            match buf.parse_with_view::<_, EthernetFrame<_>>(EthernetFrameLengthCheck::NoCheck) {
                Err(e) => {
                    self.increment(&device_id.clone().into(), |counters: &DeviceCounters| {
                        &counters.recv_parse_error
                    });
                    trace!("dropping invalid ethernet frame over loopback: {:?}", e);
                    return;
                }
                Ok(e) => e,
            };

        let LoopbackRxQueueMeta { target_device, ip_layer_metadata } = rx_meta;
        let target_device: <CC as DeviceIdContext<AnyDevice>>::DeviceId =
            match target_device.map(|d| d.upgrade()) {
                // This is a packet that should be delivered on `target_device`.
                Some(Some(dev)) => dev,

                // `target_device` is gone. Drop the packet.
                Some(None) => return,

                // This is a packet sent to the loopback device.
                None => device_id.clone().into(),
            };

        self.increment(&target_device, |counters: &DeviceCounters| &counters.recv_frame);

        let frame_dest = FrameDestination::from_dest(frame.dst_mac(), Mac::UNSPECIFIED);
        let ethertype = frame.ethertype();

        DeviceSocketHandler::<AnyDevice, _>::handle_frame(
            self,
            bindings_ctx,
            &target_device,
            ReceivedFrame::from_ethernet(frame, frame_dest).into(),
            whole_body,
        );

        match ethertype {
            Some(EtherType::Ipv4) => {
                self.increment(&target_device, |counters: &DeviceCounters| {
                    &counters.recv_ipv4_delivered
                });
                self.receive_frame(
                    bindings_ctx,
                    RecvIpFrameMeta::<_, _, Ipv4>::new(
                        target_device,
                        Some(frame_dest),
                        ip_layer_metadata,
                    ),
                    buf,
                );
            }
            Some(EtherType::Ipv6) => {
                self.increment(&target_device, |counters: &DeviceCounters| {
                    &counters.recv_ipv6_delivered
                });
                self.receive_frame(
                    bindings_ctx,
                    RecvIpFrameMeta::<_, _, Ipv6>::new(
                        target_device,
                        Some(frame_dest),
                        ip_layer_metadata,
                    ),
                    buf,
                );
            }
            Some(ethertype @ (EtherType::Arp | EtherType::Other(_))) => {
                self.increment(device_id, |counters: &EthernetDeviceCounters| {
                    &counters.recv_unsupported_ethertype
                });
                trace!("not handling loopback frame of type {:?}", ethertype)
            }
            None => {
                self.increment(device_id, |counters: &EthernetDeviceCounters| {
                    &counters.recv_no_ethertype
                });
                trace!("dropping ethernet frame without ethertype");
            }
        }
    }
}

impl<CC, BC> SendableFrameMeta<CC, BC>
    for DeviceSocketMetadata<LoopbackDevice, <CC as DeviceIdContext<LoopbackDevice>>::DeviceId>
where
    CC: TransmitQueueHandler<
            LoopbackDevice,
            BC,
            Meta = LoopbackTxQueueMeta<<CC as DeviceIdContext<AnyDevice>>::WeakDeviceId>,
        > + ResourceCounterContext<<CC as DeviceIdContext<LoopbackDevice>>::DeviceId, DeviceCounters>
        + DeviceIdContext<AnyDevice>,
    BC: DeviceLayerTypes,
{
    fn send_meta<S>(
        self,
        core_ctx: &mut CC,
        bindings_ctx: &mut BC,
        body: S,
    ) -> Result<(), SendFrameError<S>>
    where
        S: Serializer,
        S::Buffer: BufferMut,
    {
        let Self { device_id, metadata } = self;
        let tx_meta = LoopbackTxQueueMeta::default();
        match metadata {
            Some(EthernetHeaderParams { dest_addr, protocol }) => send_as_ethernet_frame_to_dst(
                core_ctx,
                bindings_ctx,
                &device_id,
                body,
                protocol,
                dest_addr,
                LoopbackTxQueueMeta::default(),
            ),
            None => send_ethernet_frame(core_ctx, bindings_ctx, &device_id, body, tx_meta),
        }
    }
}

/// Sends an IP frame `packet` over `device_id`.
pub fn send_ip_frame<CC, BC, I, S>(
    core_ctx: &mut CC,
    bindings_ctx: &mut BC,
    device_id: &<CC as DeviceIdContext<LoopbackDevice>>::DeviceId,
    destination: IpPacketDestination<I, &<CC as DeviceIdContext<AnyDevice>>::DeviceId>,
    ip_layer_metadata: DeviceIpLayerMetadata,
    packet: S,
) -> Result<(), SendFrameError<S>>
where
    CC: TransmitQueueHandler<
            LoopbackDevice,
            BC,
            Meta = LoopbackTxQueueMeta<<CC as DeviceIdContext<AnyDevice>>::WeakDeviceId>,
        > + ResourceCounterContext<<CC as DeviceIdContext<LoopbackDevice>>::DeviceId, DeviceCounters>
        + DeviceIdContext<AnyDevice>,
    BC: DeviceLayerTypes,
    I: EthernetIpExt + BroadcastIpExt,
    S: Serializer,
    S::Buffer: BufferMut,
{
    core_ctx.increment(device_id, DeviceCounters::send_frame::<I>);

    let target_device = match destination {
        IpPacketDestination::Loopback(device) => Some(device.downgrade()),
        IpPacketDestination::Broadcast(_)
        | IpPacketDestination::Multicast(_)
        | IpPacketDestination::Neighbor(_) => None,
    };
    send_as_ethernet_frame_to_dst(
        core_ctx,
        bindings_ctx,
        device_id,
        packet,
        I::ETHER_TYPE,
        LOOPBACK_MAC,
        LoopbackTxQueueMeta { target_device, ip_layer_metadata },
    )
}

fn send_as_ethernet_frame_to_dst<CC, BC, S>(
    core_ctx: &mut CC,
    bindings_ctx: &mut BC,
    device_id: &<CC as DeviceIdContext<LoopbackDevice>>::DeviceId,
    packet: S,
    protocol: EtherType,
    dst_mac: Mac,
    meta: LoopbackTxQueueMeta<<CC as DeviceIdContext<AnyDevice>>::WeakDeviceId>,
) -> Result<(), SendFrameError<S>>
where
    CC: TransmitQueueHandler<
            LoopbackDevice,
            BC,
            Meta = LoopbackTxQueueMeta<<CC as DeviceIdContext<AnyDevice>>::WeakDeviceId>,
        > + ResourceCounterContext<<CC as DeviceIdContext<LoopbackDevice>>::DeviceId, DeviceCounters>
        + DeviceIdContext<AnyDevice>,
    BC: DeviceLayerTypes,
    S: Serializer,
    S::Buffer: BufferMut,
{
    /// The minimum length of bodies of Ethernet frames sent over the loopback
    /// device.
    ///
    /// Use zero since the frames are never sent out a physical device, so it
    /// doesn't matter if they are shorter than would be required.
    const MIN_BODY_LEN: usize = 0;

    let frame = packet.encapsulate(EthernetFrameBuilder::new(
        LOOPBACK_MAC,
        dst_mac,
        protocol,
        MIN_BODY_LEN,
    ));

    send_ethernet_frame(core_ctx, bindings_ctx, device_id, frame, meta)
        .map_err(|err| err.into_inner())
}

fn send_ethernet_frame<CC, BC, S>(
    core_ctx: &mut CC,
    bindings_ctx: &mut BC,
    device_id: &<CC as DeviceIdContext<LoopbackDevice>>::DeviceId,
    frame: S,
    meta: LoopbackTxQueueMeta<<CC as DeviceIdContext<AnyDevice>>::WeakDeviceId>,
) -> Result<(), SendFrameError<S>>
where
    CC: TransmitQueueHandler<
            LoopbackDevice,
            BC,
            Meta = LoopbackTxQueueMeta<<CC as DeviceIdContext<AnyDevice>>::WeakDeviceId>,
        > + ResourceCounterContext<<CC as DeviceIdContext<LoopbackDevice>>::DeviceId, DeviceCounters>
        + DeviceIdContext<AnyDevice>,
    S: Serializer,
    S::Buffer: BufferMut,
    BC: DeviceLayerTypes,
{
    core_ctx.increment(device_id, |counters: &DeviceCounters| &counters.send_total_frames);
    match TransmitQueueHandler::<LoopbackDevice, _>::queue_tx_frame(
        core_ctx,
        bindings_ctx,
        device_id,
        meta,
        frame,
    ) {
        Ok(()) => {
            core_ctx.increment(device_id, |counters: &DeviceCounters| &counters.send_frame);
            Ok(())
        }
        Err(TransmitQueueFrameError::NoQueue(err)) => {
            unreachable!("loopback never fails to send a frame: {err:?}")
        }
        Err(TransmitQueueFrameError::QueueFull(serializer)) => {
            core_ctx.increment(device_id, |counters: &DeviceCounters| &counters.send_queue_full);
            Err(SendFrameError { serializer, error: SendFrameErrorReason::QueueFull })
        }
        Err(TransmitQueueFrameError::SerializeError(err)) => {
            core_ctx
                .increment(device_id, |counters: &DeviceCounters| &counters.send_serialize_error);
            Err(err.err_into())
        }
    }
}

impl DeviceReceiveFrameSpec for LoopbackDevice {
    // Loopback never receives frames from bindings, so make it impossible to
    // instantiate it.
    type FrameMetadata<D> = Never;
}