-
Notifications
You must be signed in to change notification settings - Fork 427
/
interface.rs
3411 lines (3083 loc) · 125 KB
/
interface.rs
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Heads up! Before working on this file you should read the parts
// of RFC 1122 that discuss Ethernet, ARP and IP for any IPv4 work
// and RFCs 8200 and 4861 for any IPv6 and NDISC work.
use core::cmp;
use managed::{ManagedMap, ManagedSlice};
use crate::iface::Routes;
#[cfg(feature = "medium-ethernet")]
use crate::iface::{NeighborAnswer, NeighborCache};
use crate::phy::{Device, DeviceCapabilities, Medium, RxToken, TxToken};
use crate::socket::*;
use crate::time::{Duration, Instant};
use crate::wire::*;
use crate::{Error, Result};
/// A network interface.
///
/// The network interface logically owns a number of other data structures; to avoid
/// a dependency on heap allocation, it instead owns a `BorrowMut<[T]>`, which can be
/// a `&mut [T]`, or `Vec<T>` if a heap is available.
pub struct Interface<'a, DeviceT: for<'d> Device<'d>> {
device: DeviceT,
inner: InterfaceInner<'a>,
}
/// The device independent part of an Ethernet network interface.
///
/// Separating the device from the data required for prorcessing and dispatching makes
/// it possible to borrow them independently. For example, the tx and rx tokens borrow
/// the `device` mutably until they're used, which makes it impossible to call other
/// methods on the `Interface` in this time (since its `device` field is borrowed
/// exclusively). However, it is still possible to call methods on its `inner` field.
struct InterfaceInner<'a> {
#[cfg(feature = "medium-ethernet")]
neighbor_cache: Option<NeighborCache<'a>>,
#[cfg(feature = "medium-ethernet")]
ethernet_addr: Option<EthernetAddress>,
ip_addrs: ManagedSlice<'a, IpCidr>,
#[cfg(feature = "proto-ipv4")]
any_ip: bool,
routes: Routes<'a>,
#[cfg(feature = "proto-igmp")]
ipv4_multicast_groups: ManagedMap<'a, Ipv4Address, ()>,
/// When to report for (all or) the next multicast group membership via IGMP
#[cfg(feature = "proto-igmp")]
igmp_report_state: IgmpReportState,
}
/// A builder structure used for creating a network interface.
pub struct InterfaceBuilder<'a, DeviceT: for<'d> Device<'d>> {
device: DeviceT,
#[cfg(feature = "medium-ethernet")]
ethernet_addr: Option<EthernetAddress>,
#[cfg(feature = "medium-ethernet")]
neighbor_cache: Option<NeighborCache<'a>>,
ip_addrs: ManagedSlice<'a, IpCidr>,
#[cfg(feature = "proto-ipv4")]
any_ip: bool,
routes: Routes<'a>,
/// Does not share storage with `ipv6_multicast_groups` to avoid IPv6 size overhead.
#[cfg(feature = "proto-igmp")]
ipv4_multicast_groups: ManagedMap<'a, Ipv4Address, ()>,
}
impl<'a, DeviceT> InterfaceBuilder<'a, DeviceT>
where
DeviceT: for<'d> Device<'d>,
{
/// Create a builder used for creating a network interface using the
/// given device and address.
#[cfg_attr(
feature = "medium-ethernet",
doc = r##"
# Examples
```
# use std::collections::BTreeMap;
use smoltcp::iface::{InterfaceBuilder, NeighborCache};
# use smoltcp::phy::{Loopback, Medium};
use smoltcp::wire::{EthernetAddress, IpCidr, IpAddress};
let device = // ...
# Loopback::new(Medium::Ethernet);
let hw_addr = // ...
# EthernetAddress::default();
let neighbor_cache = // ...
# NeighborCache::new(BTreeMap::new());
let ip_addrs = // ...
# [];
let iface = InterfaceBuilder::new(device)
.ethernet_addr(hw_addr)
.neighbor_cache(neighbor_cache)
.ip_addrs(ip_addrs)
.finalize();
```
"##
)]
pub fn new(device: DeviceT) -> Self {
InterfaceBuilder {
device: device,
#[cfg(feature = "medium-ethernet")]
ethernet_addr: None,
#[cfg(feature = "medium-ethernet")]
neighbor_cache: None,
ip_addrs: ManagedSlice::Borrowed(&mut []),
#[cfg(feature = "proto-ipv4")]
any_ip: false,
routes: Routes::new(ManagedMap::Borrowed(&mut [])),
#[cfg(feature = "proto-igmp")]
ipv4_multicast_groups: ManagedMap::Borrowed(&mut []),
}
}
/// Set the Ethernet address the interface will use. See also
/// [ethernet_addr].
///
/// # Panics
/// This function panics if the address is not unicast.
///
/// [ethernet_addr]: struct.Interface.html#method.ethernet_addr
#[cfg(feature = "medium-ethernet")]
pub fn ethernet_addr(mut self, addr: EthernetAddress) -> Self {
InterfaceInner::check_ethernet_addr(&addr);
self.ethernet_addr = Some(addr);
self
}
/// Set the IP addresses the interface will use. See also
/// [ip_addrs].
///
/// # Panics
/// This function panics if any of the addresses are not unicast.
///
/// [ip_addrs]: struct.Interface.html#method.ip_addrs
pub fn ip_addrs<T>(mut self, ip_addrs: T) -> Self
where
T: Into<ManagedSlice<'a, IpCidr>>,
{
let ip_addrs = ip_addrs.into();
InterfaceInner::check_ip_addrs(&ip_addrs);
self.ip_addrs = ip_addrs;
self
}
/// Enable or disable the AnyIP capability, allowing packets to be received
/// locally on IPv4 addresses other than the interface's configured [ip_addrs].
/// When AnyIP is enabled and a route prefix in [routes] specifies one of
/// the interface's [ip_addrs] as its gateway, the interface will accept
/// packets addressed to that prefix.
///
/// # IPv6
///
/// This option is not available or required for IPv6 as packets sent to
/// the interface are not filtered by IPv6 address.
///
/// [routes]: struct.Interface.html#method.routes
/// [ip_addrs]: struct.Interface.html#method.ip_addrs
#[cfg(feature = "proto-ipv4")]
pub fn any_ip(mut self, enabled: bool) -> Self {
self.any_ip = enabled;
self
}
/// Set the IP routes the interface will use. See also
/// [routes].
///
/// [routes]: struct.Interface.html#method.routes
pub fn routes<T>(mut self, routes: T) -> InterfaceBuilder<'a, DeviceT>
where
T: Into<Routes<'a>>,
{
self.routes = routes.into();
self
}
/// Provide storage for multicast groups.
///
/// Join multicast groups by calling [`join_multicast_group()`] on an `Interface`.
/// Using [`join_multicast_group()`] will send initial membership reports.
///
/// A previously destroyed interface can be recreated by reusing the multicast group
/// storage, i.e. providing a non-empty storage to `ipv4_multicast_groups()`.
/// Note that this way initial membership reports are **not** sent.
///
/// [`join_multicast_group()`]: struct.Interface.html#method.join_multicast_group
#[cfg(feature = "proto-igmp")]
pub fn ipv4_multicast_groups<T>(mut self, ipv4_multicast_groups: T) -> Self
where
T: Into<ManagedMap<'a, Ipv4Address, ()>>,
{
self.ipv4_multicast_groups = ipv4_multicast_groups.into();
self
}
/// Set the Neighbor Cache the interface will use.
#[cfg(feature = "medium-ethernet")]
pub fn neighbor_cache(mut self, neighbor_cache: NeighborCache<'a>) -> Self {
self.neighbor_cache = Some(neighbor_cache);
self
}
/// Create a network interface using the previously provided configuration.
///
/// # Panics
/// If a required option is not provided, this function will panic. Required
/// options are:
///
/// - [ethernet_addr]
/// - [neighbor_cache]
///
/// [ethernet_addr]: #method.ethernet_addr
/// [neighbor_cache]: #method.neighbor_cache
pub fn finalize(self) -> Interface<'a, DeviceT> {
let device_capabilities = self.device.capabilities();
#[cfg(feature = "medium-ethernet")]
let (ethernet_addr, neighbor_cache) = match device_capabilities.medium {
Medium::Ethernet => (
Some(
self.ethernet_addr
.expect("ethernet_addr required option was not set"),
),
Some(
self.neighbor_cache
.expect("neighbor_cache required option was not set"),
),
),
#[cfg(feature = "medium-ip")]
Medium::Ip => {
assert!(
self.ethernet_addr.is_none(),
"ethernet_addr is set, but device medium is IP"
);
assert!(
self.neighbor_cache.is_none(),
"neighbor_cache is set, but device medium is IP"
);
(None, None)
}
};
Interface {
device: self.device,
inner: InterfaceInner {
#[cfg(feature = "medium-ethernet")]
ethernet_addr,
ip_addrs: self.ip_addrs,
#[cfg(feature = "proto-ipv4")]
any_ip: self.any_ip,
routes: self.routes,
#[cfg(feature = "medium-ethernet")]
neighbor_cache,
#[cfg(feature = "proto-igmp")]
ipv4_multicast_groups: self.ipv4_multicast_groups,
#[cfg(feature = "proto-igmp")]
igmp_report_state: IgmpReportState::Inactive,
},
}
}
}
#[derive(Debug, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[cfg(feature = "medium-ethernet")]
enum EthernetPacket<'a> {
#[cfg(feature = "proto-ipv4")]
Arp(ArpRepr),
Ip(IpPacket<'a>),
}
#[derive(Debug, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub(crate) enum IpPacket<'a> {
#[cfg(feature = "proto-ipv4")]
Icmpv4((Ipv4Repr, Icmpv4Repr<'a>)),
#[cfg(feature = "proto-igmp")]
Igmp((Ipv4Repr, IgmpRepr)),
#[cfg(feature = "proto-ipv6")]
Icmpv6((Ipv6Repr, Icmpv6Repr<'a>)),
#[cfg(feature = "socket-raw")]
Raw((IpRepr, &'a [u8])),
#[cfg(feature = "socket-udp")]
Udp((IpRepr, UdpRepr, &'a [u8])),
#[cfg(feature = "socket-tcp")]
Tcp((IpRepr, TcpRepr<'a>)),
#[cfg(feature = "socket-dhcpv4")]
Dhcpv4((Ipv4Repr, UdpRepr, DhcpRepr<'a>)),
}
impl<'a> IpPacket<'a> {
pub(crate) fn ip_repr(&self) -> IpRepr {
match self {
#[cfg(feature = "proto-ipv4")]
IpPacket::Icmpv4((ipv4_repr, _)) => IpRepr::Ipv4(*ipv4_repr),
#[cfg(feature = "proto-igmp")]
IpPacket::Igmp((ipv4_repr, _)) => IpRepr::Ipv4(*ipv4_repr),
#[cfg(feature = "proto-ipv6")]
IpPacket::Icmpv6((ipv6_repr, _)) => IpRepr::Ipv6(*ipv6_repr),
#[cfg(feature = "socket-raw")]
IpPacket::Raw((ip_repr, _)) => ip_repr.clone(),
#[cfg(feature = "socket-udp")]
IpPacket::Udp((ip_repr, _, _)) => ip_repr.clone(),
#[cfg(feature = "socket-tcp")]
IpPacket::Tcp((ip_repr, _)) => ip_repr.clone(),
#[cfg(feature = "socket-dhcpv4")]
IpPacket::Dhcpv4((ipv4_repr, _, _)) => IpRepr::Ipv4(*ipv4_repr),
}
}
pub(crate) fn emit_payload(
&self,
_ip_repr: IpRepr,
payload: &mut [u8],
caps: &DeviceCapabilities,
) {
match self {
#[cfg(feature = "proto-ipv4")]
IpPacket::Icmpv4((_, icmpv4_repr)) => {
icmpv4_repr.emit(&mut Icmpv4Packet::new_unchecked(payload), &caps.checksum)
}
#[cfg(feature = "proto-igmp")]
IpPacket::Igmp((_, igmp_repr)) => {
igmp_repr.emit(&mut IgmpPacket::new_unchecked(payload))
}
#[cfg(feature = "proto-ipv6")]
IpPacket::Icmpv6((_, icmpv6_repr)) => icmpv6_repr.emit(
&_ip_repr.src_addr(),
&_ip_repr.dst_addr(),
&mut Icmpv6Packet::new_unchecked(payload),
&caps.checksum,
),
#[cfg(feature = "socket-raw")]
IpPacket::Raw((_, raw_packet)) => payload.copy_from_slice(raw_packet),
#[cfg(feature = "socket-udp")]
IpPacket::Udp((_, udp_repr, inner_payload)) => udp_repr.emit(
&mut UdpPacket::new_unchecked(payload),
&_ip_repr.src_addr(),
&_ip_repr.dst_addr(),
inner_payload.len(),
|buf| buf.copy_from_slice(inner_payload),
&caps.checksum,
),
#[cfg(feature = "socket-tcp")]
IpPacket::Tcp((_, mut tcp_repr)) => {
// This is a terrible hack to make TCP performance more acceptable on systems
// where the TCP buffers are significantly larger than network buffers,
// e.g. a 64 kB TCP receive buffer (and so, when empty, a 64k window)
// together with four 1500 B Ethernet receive buffers. If left untreated,
// this would result in our peer pushing our window and sever packet loss.
//
// I'm really not happy about this "solution" but I don't know what else to do.
if let Some(max_burst_size) = caps.max_burst_size {
let mut max_segment_size = caps.max_transmission_unit;
max_segment_size -= _ip_repr.buffer_len();
max_segment_size -= tcp_repr.header_len();
let max_window_size = max_burst_size * max_segment_size;
if tcp_repr.window_len as usize > max_window_size {
tcp_repr.window_len = max_window_size as u16;
}
}
tcp_repr.emit(
&mut TcpPacket::new_unchecked(payload),
&_ip_repr.src_addr(),
&_ip_repr.dst_addr(),
&caps.checksum,
);
}
#[cfg(feature = "socket-dhcpv4")]
IpPacket::Dhcpv4((_, udp_repr, dhcp_repr)) => udp_repr.emit(
&mut UdpPacket::new_unchecked(payload),
&_ip_repr.src_addr(),
&_ip_repr.dst_addr(),
dhcp_repr.buffer_len(),
|buf| dhcp_repr.emit(&mut DhcpPacket::new_unchecked(buf)).unwrap(),
&caps.checksum,
),
}
}
}
#[cfg(any(feature = "proto-ipv4", feature = "proto-ipv6"))]
fn icmp_reply_payload_len(len: usize, mtu: usize, header_len: usize) -> usize {
// Send back as much of the original payload as will fit within
// the minimum MTU required by IPv4. See RFC 1812 § 4.3.2.3 for
// more details.
//
// Since the entire network layer packet must fit within the minumum
// MTU supported, the payload must not exceed the following:
//
// <min mtu> - IP Header Size * 2 - ICMPv4 DstUnreachable hdr size
cmp::min(len, mtu - header_len * 2 - 8)
}
#[cfg(feature = "proto-igmp")]
enum IgmpReportState {
Inactive,
ToGeneralQuery {
version: IgmpVersion,
timeout: Instant,
interval: Duration,
next_index: usize,
},
ToSpecificQuery {
version: IgmpVersion,
timeout: Instant,
group: Ipv4Address,
},
}
impl<'a, DeviceT> Interface<'a, DeviceT>
where
DeviceT: for<'d> Device<'d>,
{
/// Get the Ethernet address of the interface.
///
/// # Panics
/// This function panics if if the interface's medium is not Ethernet.
#[cfg(feature = "medium-ethernet")]
pub fn ethernet_addr(&self) -> EthernetAddress {
self.inner.ethernet_addr.unwrap()
}
/// Set the Ethernet address of the interface.
///
/// # Panics
/// This function panics if the address is not unicast, or if the
/// interface's medium is not Ethernet.
#[cfg(feature = "medium-ethernet")]
pub fn set_ethernet_addr(&mut self, addr: EthernetAddress) {
assert!(self.device.capabilities().medium == Medium::Ethernet);
InterfaceInner::check_ethernet_addr(&addr);
self.inner.ethernet_addr = Some(addr);
}
/// Get a reference to the inner device.
pub fn device(&self) -> &DeviceT {
&self.device
}
/// Get a mutable reference to the inner device.
///
/// There are no invariants imposed on the device by the interface itself. Furthermore the
/// trait implementations, required for references of all lifetimes, guarantees that the
/// mutable reference can not invalidate the device as such. For some devices, such access may
/// still allow modifications with adverse effects on the usability as a `phy` device. You
/// should not use them this way.
pub fn device_mut(&mut self) -> &mut DeviceT {
&mut self.device
}
/// Add an address to a list of subscribed multicast IP addresses.
///
/// Returns `Ok(announce_sent)` if the address was added successfully, where `annouce_sent`
/// indicates whether an initial immediate announcement has been sent.
pub fn join_multicast_group<T: Into<IpAddress>>(
&mut self,
addr: T,
_timestamp: Instant,
) -> Result<bool> {
match addr.into() {
#[cfg(feature = "proto-igmp")]
IpAddress::Ipv4(addr) => {
let is_not_new = self
.inner
.ipv4_multicast_groups
.insert(addr, ())
.map_err(|_| Error::Exhausted)?
.is_some();
if is_not_new {
Ok(false)
} else if let Some(pkt) = self.inner.igmp_report_packet(IgmpVersion::Version2, addr)
{
let cx = self.context(_timestamp);
// Send initial membership report
let tx_token = self.device.transmit().ok_or(Error::Exhausted)?;
self.inner.dispatch_ip(&cx, tx_token, pkt)?;
Ok(true)
} else {
Ok(false)
}
}
// Multicast is not yet implemented for other address families
_ => Err(Error::Unaddressable),
}
}
/// Remove an address from the subscribed multicast IP addresses.
///
/// Returns `Ok(leave_sent)` if the address was removed successfully, where `leave_sent`
/// indicates whether an immediate leave packet has been sent.
pub fn leave_multicast_group<T: Into<IpAddress>>(
&mut self,
addr: T,
_timestamp: Instant,
) -> Result<bool> {
match addr.into() {
#[cfg(feature = "proto-igmp")]
IpAddress::Ipv4(addr) => {
let was_not_present = self.inner.ipv4_multicast_groups.remove(&addr).is_none();
if was_not_present {
Ok(false)
} else if let Some(pkt) = self.inner.igmp_leave_packet(addr) {
let cx = self.context(_timestamp);
// Send group leave packet
let tx_token = self.device.transmit().ok_or(Error::Exhausted)?;
self.inner.dispatch_ip(&cx, tx_token, pkt)?;
Ok(true)
} else {
Ok(false)
}
}
// Multicast is not yet implemented for other address families
_ => Err(Error::Unaddressable),
}
}
/// Check whether the interface listens to given destination multicast IP address.
pub fn has_multicast_group<T: Into<IpAddress>>(&self, addr: T) -> bool {
self.inner.has_multicast_group(addr)
}
/// Get the IP addresses of the interface.
pub fn ip_addrs(&self) -> &[IpCidr] {
self.inner.ip_addrs.as_ref()
}
/// Get the first IPv4 address if present.
#[cfg(feature = "proto-ipv4")]
pub fn ipv4_addr(&self) -> Option<Ipv4Address> {
self.ip_addrs()
.iter()
.filter_map(|cidr| match cidr.address() {
IpAddress::Ipv4(addr) => Some(addr),
_ => None,
})
.next()
}
/// Update the IP addresses of the interface.
///
/// # Panics
/// This function panics if any of the addresses are not unicast.
pub fn update_ip_addrs<F: FnOnce(&mut ManagedSlice<'a, IpCidr>)>(&mut self, f: F) {
f(&mut self.inner.ip_addrs);
InterfaceInner::check_ip_addrs(&self.inner.ip_addrs)
}
/// Check whether the interface has the given IP address assigned.
pub fn has_ip_addr<T: Into<IpAddress>>(&self, addr: T) -> bool {
self.inner.has_ip_addr(addr)
}
/// Get the first IPv4 address of the interface.
#[cfg(feature = "proto-ipv4")]
pub fn ipv4_address(&self) -> Option<Ipv4Address> {
self.inner.ipv4_address()
}
pub fn routes(&self) -> &Routes<'a> {
&self.inner.routes
}
pub fn routes_mut(&mut self) -> &mut Routes<'a> {
&mut self.inner.routes
}
/// Transmit packets queued in the given sockets, and receive packets queued
/// in the device.
///
/// This function returns a boolean value indicating whether any packets were
/// processed or emitted, and thus, whether the readiness of any socket might
/// have changed.
///
/// # Errors
/// This method will routinely return errors in response to normal network
/// activity as well as certain boundary conditions such as buffer exhaustion.
/// These errors are provided as an aid for troubleshooting, and are meant
/// to be logged and ignored.
///
/// As a special case, `Err(Error::Unrecognized)` is returned in response to
/// packets containing any unsupported protocol, option, or form, which is
/// a very common occurrence and on a production system it should not even
/// be logged.
pub fn poll(&mut self, sockets: &mut SocketSet, timestamp: Instant) -> Result<bool> {
let cx = self.context(timestamp);
let mut readiness_may_have_changed = false;
loop {
let processed_any = self.socket_ingress(&cx, sockets);
let emitted_any = self.socket_egress(&cx, sockets)?;
#[cfg(feature = "proto-igmp")]
self.igmp_egress(&cx, timestamp)?;
if processed_any || emitted_any {
readiness_may_have_changed = true;
} else {
break;
}
}
Ok(readiness_may_have_changed)
}
/// Return a _soft deadline_ for calling [poll] the next time.
/// The [Instant] returned is the time at which you should call [poll] next.
/// It is harmless (but wastes energy) to call it before the [Instant], and
/// potentially harmful (impacting quality of service) to call it after the
/// [Instant]
///
/// [poll]: #method.poll
/// [Instant]: struct.Instant.html
pub fn poll_at(&self, sockets: &SocketSet, timestamp: Instant) -> Option<Instant> {
let cx = self.context(timestamp);
sockets
.iter()
.filter_map(|socket| {
let socket_poll_at = socket.poll_at(&cx);
match socket.meta().poll_at(socket_poll_at, |ip_addr| {
self.inner.has_neighbor(&cx, &ip_addr)
}) {
PollAt::Ingress => None,
PollAt::Time(instant) => Some(instant),
PollAt::Now => Some(Instant::from_millis(0)),
}
})
.min()
}
/// Return an _advisory wait time_ for calling [poll] the next time.
/// The [Duration] returned is the time left to wait before calling [poll] next.
/// It is harmless (but wastes energy) to call it before the [Duration] has passed,
/// and potentially harmful (impacting quality of service) to call it after the
/// [Duration] has passed.
///
/// [poll]: #method.poll
/// [Duration]: struct.Duration.html
pub fn poll_delay(&self, sockets: &SocketSet, timestamp: Instant) -> Option<Duration> {
match self.poll_at(sockets, timestamp) {
Some(poll_at) if timestamp < poll_at => Some(poll_at - timestamp),
Some(_) => Some(Duration::from_millis(0)),
_ => None,
}
}
fn socket_ingress(&mut self, cx: &Context, sockets: &mut SocketSet) -> bool {
let mut processed_any = false;
let &mut Self {
ref mut device,
ref mut inner,
} = self;
while let Some((rx_token, tx_token)) = device.receive() {
if let Err(err) = rx_token.consume(cx.now, |frame| {
match cx.caps.medium {
#[cfg(feature = "medium-ethernet")]
Medium::Ethernet => match inner.process_ethernet(cx, sockets, &frame) {
Ok(response) => {
processed_any = true;
if let Some(packet) = response {
if let Err(err) = inner.dispatch(cx, tx_token, packet) {
net_debug!("Failed to send response: {}", err);
}
}
}
Err(err) => {
net_debug!("cannot process ingress packet: {}", err);
#[cfg(not(feature = "defmt"))]
net_debug!(
"packet dump follows:\n{}",
PrettyPrinter::<EthernetFrame<&[u8]>>::new("", &frame)
);
}
},
#[cfg(feature = "medium-ip")]
Medium::Ip => match inner.process_ip(cx, sockets, &frame) {
Ok(response) => {
processed_any = true;
if let Some(packet) = response {
if let Err(err) = inner.dispatch_ip(cx, tx_token, packet) {
net_debug!("Failed to send response: {}", err);
}
}
}
Err(err) => net_debug!("cannot process ingress packet: {}", err),
},
}
Ok(())
}) {
net_debug!("Failed to consume RX token: {}", err);
}
}
processed_any
}
fn socket_egress(&mut self, cx: &Context, sockets: &mut SocketSet) -> Result<bool> {
let _caps = self.device.capabilities();
let mut emitted_any = false;
for mut socket in sockets.iter_mut() {
if !socket
.meta_mut()
.egress_permitted(cx.now, |ip_addr| self.inner.has_neighbor(cx, &ip_addr))
{
continue;
}
let mut neighbor_addr = None;
let mut device_result = Ok(());
let &mut Self {
ref mut device,
ref mut inner,
} = self;
macro_rules! respond {
($response:expr) => {{
let response = $response;
neighbor_addr = Some(response.ip_repr().dst_addr());
let tx_token = device.transmit().ok_or(Error::Exhausted)?;
device_result = inner.dispatch_ip(cx, tx_token, response);
device_result
}};
}
let socket_result = match *socket {
#[cfg(feature = "socket-raw")]
Socket::Raw(ref mut socket) => {
socket.dispatch(cx, |response| respond!(IpPacket::Raw(response)))
}
#[cfg(all(
feature = "socket-icmp",
any(feature = "proto-ipv4", feature = "proto-ipv6")
))]
Socket::Icmp(ref mut socket) => socket.dispatch(cx, |response| match response {
#[cfg(feature = "proto-ipv4")]
(IpRepr::Ipv4(ipv4_repr), IcmpRepr::Ipv4(icmpv4_repr)) => {
respond!(IpPacket::Icmpv4((ipv4_repr, icmpv4_repr)))
}
#[cfg(feature = "proto-ipv6")]
(IpRepr::Ipv6(ipv6_repr), IcmpRepr::Ipv6(icmpv6_repr)) => {
respond!(IpPacket::Icmpv6((ipv6_repr, icmpv6_repr)))
}
_ => Err(Error::Unaddressable),
}),
#[cfg(feature = "socket-udp")]
Socket::Udp(ref mut socket) => {
socket.dispatch(cx, |response| respond!(IpPacket::Udp(response)))
}
#[cfg(feature = "socket-tcp")]
Socket::Tcp(ref mut socket) => {
socket.dispatch(cx, |response| respond!(IpPacket::Tcp(response)))
}
#[cfg(feature = "socket-dhcpv4")]
Socket::Dhcpv4(ref mut socket) =>
// todo don't unwrap
{
socket.dispatch(cx, |response| respond!(IpPacket::Dhcpv4(response)))
}
};
match (device_result, socket_result) {
(Err(Error::Exhausted), _) => break, // nowhere to transmit
(Ok(()), Err(Error::Exhausted)) => (), // nothing to transmit
(Err(Error::Unaddressable), _) => {
// `NeighborCache` already takes care of rate limiting the neighbor discovery
// requests from the socket. However, without an additional rate limiting
// mechanism, we would spin on every socket that has yet to discover its
// neighboor.
socket
.meta_mut()
.neighbor_missing(cx.now, neighbor_addr.expect("non-IP response packet"));
break;
}
(Err(err), _) | (_, Err(err)) => {
net_debug!(
"{}: cannot dispatch egress packet: {}",
socket.meta().handle,
err
);
return Err(err);
}
(Ok(()), Ok(())) => emitted_any = true,
}
}
Ok(emitted_any)
}
/// Depending on `igmp_report_state` and the therein contained
/// timeouts, send IGMP membership reports.
#[cfg(feature = "proto-igmp")]
fn igmp_egress(&mut self, cx: &Context, timestamp: Instant) -> Result<bool> {
match self.inner.igmp_report_state {
IgmpReportState::ToSpecificQuery {
version,
timeout,
group,
} if timestamp >= timeout => {
if let Some(pkt) = self.inner.igmp_report_packet(version, group) {
// Send initial membership report
let tx_token = self.device.transmit().ok_or(Error::Exhausted)?;
self.inner.dispatch_ip(cx, tx_token, pkt)?;
}
self.inner.igmp_report_state = IgmpReportState::Inactive;
Ok(true)
}
IgmpReportState::ToGeneralQuery {
version,
timeout,
interval,
next_index,
} if timestamp >= timeout => {
let addr = self
.inner
.ipv4_multicast_groups
.iter()
.nth(next_index)
.map(|(addr, ())| *addr);
match addr {
Some(addr) => {
if let Some(pkt) = self.inner.igmp_report_packet(version, addr) {
// Send initial membership report
let tx_token = self.device.transmit().ok_or(Error::Exhausted)?;
self.inner.dispatch_ip(cx, tx_token, pkt)?;
}
let next_timeout = (timeout + interval).max(timestamp);
self.inner.igmp_report_state = IgmpReportState::ToGeneralQuery {
version,
timeout: next_timeout,
interval,
next_index: next_index + 1,
};
Ok(true)
}
None => {
self.inner.igmp_report_state = IgmpReportState::Inactive;
Ok(false)
}
}
}
_ => Ok(false),
}
}
fn context(&self, now: Instant) -> Context {
Context {
now,
caps: self.device.capabilities(),
#[cfg(all(feature = "medium-ethernet", feature = "socket-dhcpv4"))]
ethernet_address: self.inner.ethernet_addr,
}
}
}
impl<'a> InterfaceInner<'a> {
#[cfg(feature = "medium-ethernet")]
fn check_ethernet_addr(addr: &EthernetAddress) {
if addr.is_multicast() {
panic!("Ethernet address {} is not unicast", addr)
}
}
fn check_ip_addrs(addrs: &[IpCidr]) {
for cidr in addrs {
if !cidr.address().is_unicast() && !cidr.address().is_unspecified() {
panic!("IP address {} is not unicast", cidr.address())
}
}
}
/// Determine if the given `Ipv6Address` is the solicited node
/// multicast address for a IPv6 addresses assigned to the interface.
/// See [RFC 4291 § 2.7.1] for more details.
///
/// [RFC 4291 § 2.7.1]: https://tools.ietf.org/html/rfc4291#section-2.7.1
#[cfg(feature = "proto-ipv6")]
pub fn has_solicited_node(&self, addr: Ipv6Address) -> bool {
self.ip_addrs.iter().any(|cidr| {
match *cidr {
IpCidr::Ipv6(cidr) if cidr.address() != Ipv6Address::LOOPBACK => {
// Take the lower order 24 bits of the IPv6 address and
// append those bits to FF02:0:0:0:0:1:FF00::/104.
addr.as_bytes()[14..] == cidr.address().as_bytes()[14..]
}
_ => false,
}
})
}
/// Check whether the interface has the given IP address assigned.
fn has_ip_addr<T: Into<IpAddress>>(&self, addr: T) -> bool {
let addr = addr.into();
self.ip_addrs.iter().any(|probe| probe.address() == addr)
}
/// Get the first IPv4 address of the interface.
#[cfg(feature = "proto-ipv4")]
pub fn ipv4_address(&self) -> Option<Ipv4Address> {
self.ip_addrs
.iter()
.filter_map(|addr| match *addr {
IpCidr::Ipv4(cidr) => Some(cidr.address()),
#[cfg(feature = "proto-ipv6")]
IpCidr::Ipv6(_) => None,
})
.next()
}
/// Check whether the interface listens to given destination multicast IP address.
///
/// If built without feature `proto-igmp` this function will
/// always return `false`.
pub fn has_multicast_group<T: Into<IpAddress>>(&self, addr: T) -> bool {
match addr.into() {
#[cfg(feature = "proto-igmp")]
IpAddress::Ipv4(key) => {
key == Ipv4Address::MULTICAST_ALL_SYSTEMS
|| self.ipv4_multicast_groups.get(&key).is_some()
}
_ => false,
}
}
#[cfg(feature = "medium-ethernet")]
fn process_ethernet<'frame, T: AsRef<[u8]>>(
&mut self,
cx: &Context,
sockets: &mut SocketSet,
frame: &'frame T,
) -> Result<Option<EthernetPacket<'frame>>> {
let eth_frame = EthernetFrame::new_checked(frame)?;
// Ignore any packets not directed to our hardware address or any of the multicast groups.
if !eth_frame.dst_addr().is_broadcast()
&& !eth_frame.dst_addr().is_multicast()
&& eth_frame.dst_addr() != self.ethernet_addr.unwrap()
{
return Ok(None);
}
match eth_frame.ethertype() {
#[cfg(feature = "proto-ipv4")]
EthernetProtocol::Arp => self.process_arp(cx.now, ð_frame),
#[cfg(feature = "proto-ipv4")]
EthernetProtocol::Ipv4 => {
let ipv4_packet = Ipv4Packet::new_checked(eth_frame.payload())?;
if eth_frame.src_addr().is_unicast() && ipv4_packet.src_addr().is_unicast() {
// Fill the neighbor cache from IP header of unicast frames.
let ip_addr = IpAddress::Ipv4(ipv4_packet.src_addr());
if self.in_same_network(&ip_addr) {
self.neighbor_cache.as_mut().unwrap().fill(
ip_addr,
eth_frame.src_addr(),
cx.now,
);
}
}
self.process_ipv4(cx, sockets, &ipv4_packet)
.map(|o| o.map(EthernetPacket::Ip))
}
#[cfg(feature = "proto-ipv6")]
EthernetProtocol::Ipv6 => {
let ipv6_packet = Ipv6Packet::new_checked(eth_frame.payload())?;
if eth_frame.src_addr().is_unicast() && ipv6_packet.src_addr().is_unicast() {
// Fill the neighbor cache from IP header of unicast frames.
let ip_addr = IpAddress::Ipv6(ipv6_packet.src_addr());
if self.in_same_network(&ip_addr)
&& self
.neighbor_cache
.as_mut()
.unwrap()
.lookup(&ip_addr, cx.now)
.found()
{
self.neighbor_cache.as_mut().unwrap().fill(
ip_addr,
eth_frame.src_addr(),
cx.now,
);
}
}
self.process_ipv6(cx, sockets, &ipv6_packet)
.map(|o| o.map(EthernetPacket::Ip))
}
// Drop all other traffic.
_ => Err(Error::Unrecognized),
}
}
#[cfg(feature = "medium-ip")]