1use core::convert::Infallible as Never;
9use core::fmt::Debug;
10use core::hash::Hash;
11use core::marker::PhantomData;
12use core::num::NonZeroU16;
13
14use derivative::Derivative;
15use net_types::ip::{GenericOverIp, Ip, IpAddress, IpVersionMarker, Ipv4, Ipv6};
16use net_types::{
17 AddrAndZone, MulticastAddress, ScopeableAddress, SpecifiedAddr, Witness, ZonedAddr,
18};
19use thiserror::Error;
20
21use crate::data_structures::socketmap::{
22 Entry, IterShadows, OccupiedEntry as SocketMapOccupiedEntry, SocketMap, Tagged,
23};
24use crate::device::{
25 DeviceIdentifier, EitherDeviceId, StrongDeviceIdentifier, WeakDeviceIdentifier,
26};
27use crate::error::{ExistsError, NotFoundError, ZonedAddressError};
28use crate::ip::BroadcastIpExt;
29use crate::socket::address::{
30 AddrVecIter, ConnAddr, ConnIpAddr, ListenerAddr, ListenerIpAddr, SocketIpAddr,
31};
32
33pub trait DualStackIpExt: Ip {
36 type OtherVersion: DualStackIpExt<OtherVersion = Self>;
38}
39
40impl DualStackIpExt for Ipv4 {
41 type OtherVersion = Ipv6;
42}
43
44impl DualStackIpExt for Ipv6 {
45 type OtherVersion = Ipv4;
46}
47
48pub struct DualStackTuple<I: DualStackIpExt, T: GenericOverIp<I> + GenericOverIp<I::OtherVersion>> {
50 this_stack: <T as GenericOverIp<I>>::Type,
51 other_stack: <T as GenericOverIp<I::OtherVersion>>::Type,
52 _marker: IpVersionMarker<I>,
53}
54
55impl<I: DualStackIpExt, T: GenericOverIp<I> + GenericOverIp<I::OtherVersion>> DualStackTuple<I, T> {
56 pub fn new(this_stack: T, other_stack: <T as GenericOverIp<I::OtherVersion>>::Type) -> Self
58 where
59 T: GenericOverIp<I, Type = T>,
60 {
61 Self { this_stack, other_stack, _marker: IpVersionMarker::new() }
62 }
63
64 pub fn into_inner(
66 self,
67 ) -> (<T as GenericOverIp<I>>::Type, <T as GenericOverIp<I::OtherVersion>>::Type) {
68 let Self { this_stack, other_stack, _marker } = self;
69 (this_stack, other_stack)
70 }
71
72 pub fn into_this_stack(self) -> <T as GenericOverIp<I>>::Type {
74 self.this_stack
75 }
76
77 pub fn this_stack(&self) -> &<T as GenericOverIp<I>>::Type {
79 &self.this_stack
80 }
81
82 pub fn into_other_stack(self) -> <T as GenericOverIp<I::OtherVersion>>::Type {
84 self.other_stack
85 }
86
87 pub fn other_stack(&self) -> &<T as GenericOverIp<I::OtherVersion>>::Type {
89 &self.other_stack
90 }
91
92 pub fn flip(self) -> DualStackTuple<I::OtherVersion, T> {
94 let Self { this_stack, other_stack, _marker } = self;
95 DualStackTuple {
96 this_stack: other_stack,
97 other_stack: this_stack,
98 _marker: IpVersionMarker::new(),
99 }
100 }
101
102 pub fn cast<X>(self) -> DualStackTuple<X, T>
111 where
112 X: DualStackIpExt,
113 T: GenericOverIp<X>
114 + GenericOverIp<X::OtherVersion>
115 + GenericOverIp<Ipv4>
116 + GenericOverIp<Ipv6>,
117 {
118 I::map_ip_in(
119 self,
120 |v4| X::map_ip_out(v4, |t| t, |t| t.flip()),
121 |v6| X::map_ip_out(v6, |t| t.flip(), |t| t),
122 )
123 }
124}
125
126impl<
127 I: DualStackIpExt,
128 NewIp: DualStackIpExt,
129 T: GenericOverIp<NewIp>
130 + GenericOverIp<NewIp::OtherVersion>
131 + GenericOverIp<I>
132 + GenericOverIp<I::OtherVersion>,
133> GenericOverIp<NewIp> for DualStackTuple<I, T>
134{
135 type Type = DualStackTuple<NewIp, T>;
136}
137
138pub trait SocketIpExt: Ip {
140 const LOOPBACK_ADDRESS_AS_SOCKET_IP_ADDR: SocketIpAddr<Self::Addr> = unsafe {
142 SocketIpAddr::new_from_specified_unchecked(Self::LOOPBACK_ADDRESS)
145 };
146}
147
148impl<I: Ip> SocketIpExt for I {}
149
150#[cfg(test)]
151mod socket_ip_ext_test {
152 use super::*;
153 use ip_test_macro::ip_test;
154
155 #[ip_test(I)]
156 fn loopback_addr_is_valid_socket_addr<I: SocketIpExt>() {
157 let _addr = SocketIpAddr::new(I::LOOPBACK_ADDRESS_AS_SOCKET_IP_ADDR.addr())
162 .expect("loopback address should be a valid SocketIpAddr");
163 }
164}
165
166#[derive(Debug, PartialEq, Eq)]
174pub enum EitherStack<T, O> {
175 ThisStack(T),
177 OtherStack(O),
179}
180
181impl<T, O> Clone for EitherStack<T, O>
182where
183 T: Clone,
184 O: Clone,
185{
186 #[cfg_attr(feature = "instrumented", track_caller)]
187 fn clone(&self) -> Self {
188 match self {
189 Self::ThisStack(t) => Self::ThisStack(t.clone()),
190 Self::OtherStack(t) => Self::OtherStack(t.clone()),
191 }
192 }
193}
194
195#[derive(Debug)]
213#[allow(missing_docs)]
214pub enum MaybeDualStack<DS, NDS> {
215 DualStack(DS),
216 NotDualStack(NDS),
217}
218
219impl<I: DualStackIpExt, DS: GenericOverIp<I>, NDS: GenericOverIp<I>> GenericOverIp<I>
222 for MaybeDualStack<DS, NDS>
223{
224 type Type = MaybeDualStack<<DS as GenericOverIp<I>>::Type, <NDS as GenericOverIp<I>>::Type>;
225}
226
227#[derive(Copy, Clone, Debug, Eq, GenericOverIp, PartialEq, Error)]
229#[generic_over_ip()]
230pub enum SetDualStackEnabledError {
231 #[error("a socket can only have dual stack enabled or disabled while unbound")]
233 SocketIsBound,
234 #[error(transparent)]
236 NotCapable(#[from] NotDualStackCapableError),
237}
238
239#[derive(Copy, Clone, Debug, Eq, GenericOverIp, PartialEq, Error)]
242#[generic_over_ip()]
243#[error("socket's protocol is not dual-stack capable")]
244pub struct NotDualStackCapableError;
245
246#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
248pub struct Shutdown {
249 pub send: bool,
253 pub receive: bool,
257}
258
259#[derive(Copy, Clone, Debug, Eq, GenericOverIp, PartialEq)]
261#[generic_over_ip()]
262pub enum ShutdownType {
263 Send,
265 Receive,
267 SendAndReceive,
269}
270
271impl ShutdownType {
272 pub fn to_send_receive(&self) -> (bool, bool) {
274 match self {
275 Self::Send => (true, false),
276 Self::Receive => (false, true),
277 Self::SendAndReceive => (true, true),
278 }
279 }
280
281 pub fn from_send_receive(send: bool, receive: bool) -> Option<Self> {
283 match (send, receive) {
284 (true, false) => Some(Self::Send),
285 (false, true) => Some(Self::Receive),
286 (true, true) => Some(Self::SendAndReceive),
287 (false, false) => None,
288 }
289 }
290}
291
292pub trait SocketIpAddrExt<A: IpAddress>: Witness<A> + ScopeableAddress {
294 fn must_have_zone(&self) -> bool
300 where
301 Self: Copy,
302 {
303 self.try_into_null_zoned().is_some()
304 }
305
306 fn try_into_null_zoned(self) -> Option<AddrAndZone<Self, ()>> {
310 if self.get().is_loopback() {
311 return None;
312 }
313 AddrAndZone::new(self, ())
314 }
315}
316
317impl<A: IpAddress, W: Witness<A> + ScopeableAddress> SocketIpAddrExt<A> for W {}
318
319pub trait SocketZonedAddrExt<W, A, D> {
321 fn resolve_addr_with_device(
329 self,
330 device: Option<D::Weak>,
331 ) -> Result<(W, Option<EitherDeviceId<D, D::Weak>>), ZonedAddressError>
332 where
333 D: StrongDeviceIdentifier;
334}
335
336impl<W, A, D> SocketZonedAddrExt<W, A, D> for ZonedAddr<W, D>
337where
338 W: ScopeableAddress + AsRef<SpecifiedAddr<A>>,
339 A: IpAddress,
340{
341 fn resolve_addr_with_device(
342 self,
343 device: Option<D::Weak>,
344 ) -> Result<(W, Option<EitherDeviceId<D, D::Weak>>), ZonedAddressError>
345 where
346 D: StrongDeviceIdentifier,
347 {
348 let (addr, zone) = self.into_addr_zone();
349 let device = match (zone, device) {
350 (Some(zone), Some(device)) => {
351 if device != zone {
352 return Err(ZonedAddressError::DeviceZoneMismatch);
353 }
354 Some(EitherDeviceId::Strong(zone))
355 }
356 (Some(zone), None) => Some(EitherDeviceId::Strong(zone)),
357 (None, Some(device)) => Some(EitherDeviceId::Weak(device)),
358 (None, None) => {
359 if addr.as_ref().must_have_zone() {
360 return Err(ZonedAddressError::RequiredZoneNotProvided);
361 } else {
362 None
363 }
364 }
365 };
366 Ok((addr, device))
367 }
368}
369
370pub struct SocketDeviceUpdate<'a, A: IpAddress, D: WeakDeviceIdentifier> {
376 pub local_ip: Option<&'a SpecifiedAddr<A>>,
378 pub remote_ip: Option<&'a SpecifiedAddr<A>>,
380 pub old_device: Option<&'a D>,
382}
383
384impl<'a, A: IpAddress, D: WeakDeviceIdentifier> SocketDeviceUpdate<'a, A, D> {
385 pub fn check_update<N>(
388 self,
389 new_device: Option<&N>,
390 ) -> Result<(), SocketDeviceUpdateNotAllowedError>
391 where
392 D: PartialEq<N>,
393 {
394 let Self { local_ip, remote_ip, old_device } = self;
395 let must_have_zone = local_ip.is_some_and(|a| a.must_have_zone())
396 || remote_ip.is_some_and(|a| a.must_have_zone());
397
398 if !must_have_zone {
399 return Ok(());
400 }
401
402 let old_device = old_device.unwrap_or_else(|| {
403 panic!("local_ip={:?} or remote_ip={:?} must have zone", local_ip, remote_ip)
404 });
405
406 if new_device.is_some_and(|new_device| old_device == new_device) {
407 Ok(())
408 } else {
409 Err(SocketDeviceUpdateNotAllowedError)
410 }
411 }
412}
413
414pub struct SocketDeviceUpdateNotAllowedError;
416
417pub trait SocketMapAddrSpec {
422 type LocalIdentifier: Copy + Clone + Debug + Send + Sync + Hash + Eq + Into<NonZeroU16>;
424 type RemoteIdentifier: Copy + Clone + Debug + Send + Sync + Hash + Eq;
426}
427
428pub struct ListenerAddrInfo {
430 pub has_device: bool,
432 pub specified_addr: bool,
435}
436
437impl<A: IpAddress, D: DeviceIdentifier, LI> ListenerAddr<ListenerIpAddr<A, LI>, D> {
438 pub(crate) fn info(&self) -> ListenerAddrInfo {
439 let Self { device, ip: ListenerIpAddr { addr, identifier: _ } } = self;
440 ListenerAddrInfo { has_device: device.is_some(), specified_addr: addr.is_some() }
441 }
442}
443
444pub trait SocketMapStateSpec {
446 type AddrVecTag: Eq + Copy + Debug + 'static;
451
452 fn listener_tag(info: ListenerAddrInfo, state: &Self::ListenerAddrState) -> Self::AddrVecTag;
454
455 fn connected_tag(has_device: bool, state: &Self::ConnAddrState) -> Self::AddrVecTag;
457
458 type ListenerId: Clone + Debug;
460 type ConnId: Clone + Debug;
462
463 type ListenerSharingState: Clone + Debug;
466
467 type ConnSharingState: Clone + Debug;
470
471 type ListenerAddrState: SocketMapAddrStateSpec<Id = Self::ListenerId, SharingState = Self::ListenerSharingState>
473 + Debug;
474
475 type ConnAddrState: SocketMapAddrStateSpec<Id = Self::ConnId, SharingState = Self::ConnSharingState>
477 + Debug;
478}
479
480#[derive(Copy, Clone, Debug, Eq, PartialEq)]
483pub struct IncompatibleError;
484
485pub trait Inserter<T> {
487 fn insert(self, item: T);
492}
493
494impl<'a, T, E: Extend<T>> Inserter<T> for &'a mut E {
495 fn insert(self, item: T) {
496 self.extend([item])
497 }
498}
499
500impl<T> Inserter<T> for Never {
501 fn insert(self, _: T) {
502 match self {}
503 }
504}
505
506pub trait SocketMapAddrStateSpec {
508 type Id;
510
511 type SharingState;
518
519 type Inserter<'a>: Inserter<Self::Id> + 'a
521 where
522 Self: 'a,
523 Self::Id: 'a;
524
525 fn new(new_sharing_state: &Self::SharingState, id: Self::Id) -> Self;
528
529 fn contains_id(&self, id: &Self::Id) -> bool;
531
532 fn try_get_inserter<'a, 'b>(
540 &'b mut self,
541 new_sharing_state: &'a Self::SharingState,
542 ) -> Result<Self::Inserter<'b>, IncompatibleError>;
543
544 fn could_insert(&self, new_sharing_state: &Self::SharingState)
549 -> Result<(), IncompatibleError>;
550
551 fn remove_by_id(&mut self, id: Self::Id) -> RemoveResult;
555}
556
557pub trait SocketMapAddrStateUpdateSharingSpec: SocketMapAddrStateSpec {
559 fn try_update_sharing(
562 &mut self,
563 id: Self::Id,
564 new_sharing_state: &Self::SharingState,
565 ) -> Result<(), IncompatibleError>;
566}
567
568pub trait SocketMapConflictPolicy<
570 Addr,
571 SharingState,
572 I: Ip,
573 D: DeviceIdentifier,
574 A: SocketMapAddrSpec,
575>: SocketMapStateSpec
576{
577 fn check_insert_conflicts(
586 new_sharing_state: &SharingState,
587 addr: &Addr,
588 socketmap: &SocketMap<AddrVec<I, D, A>, Bound<Self>>,
589 ) -> Result<(), InsertError>;
590}
591
592pub trait SocketMapUpdateSharingPolicy<Addr, SharingState, I: Ip, D: DeviceIdentifier, A>:
595 SocketMapConflictPolicy<Addr, SharingState, I, D, A>
596where
597 A: SocketMapAddrSpec,
598{
599 fn allows_sharing_update(
602 socketmap: &SocketMap<AddrVec<I, D, A>, Bound<Self>>,
603 addr: &Addr,
604 old_sharing: &SharingState,
605 new_sharing: &SharingState,
606 ) -> Result<(), UpdateSharingError>;
607}
608
609#[derive(Derivative)]
611#[derivative(Debug(bound = "S::ListenerAddrState: Debug, S::ConnAddrState: Debug"))]
612#[allow(missing_docs)]
613pub enum Bound<S: SocketMapStateSpec + ?Sized> {
614 Listen(S::ListenerAddrState),
615 Conn(S::ConnAddrState),
616}
617
618#[derive(Derivative)]
633#[derivative(
634 Debug(bound = "D: Debug"),
635 Clone(bound = "D: Clone"),
636 Eq(bound = "D: Eq"),
637 PartialEq(bound = "D: PartialEq"),
638 Hash(bound = "D: Hash")
639)]
640#[allow(missing_docs)]
641pub enum AddrVec<I: Ip, D, A: SocketMapAddrSpec + ?Sized> {
642 Listen(ListenerAddr<ListenerIpAddr<I::Addr, A::LocalIdentifier>, D>),
643 Conn(ConnAddr<ConnIpAddr<I::Addr, A::LocalIdentifier, A::RemoteIdentifier>, D>),
644}
645
646impl<I: Ip, D: DeviceIdentifier, A: SocketMapAddrSpec, S: SocketMapStateSpec + ?Sized>
647 Tagged<AddrVec<I, D, A>> for Bound<S>
648{
649 type Tag = S::AddrVecTag;
650 fn tag(&self, address: &AddrVec<I, D, A>) -> Self::Tag {
651 match (self, address) {
652 (Bound::Listen(l), AddrVec::Listen(addr)) => S::listener_tag(addr.info(), l),
653 (Bound::Conn(c), AddrVec::Conn(ConnAddr { device, ip: _ })) => {
654 S::connected_tag(device.is_some(), c)
655 }
656 (Bound::Listen(_), AddrVec::Conn(_)) => {
657 unreachable!("found listen state for conn addr")
658 }
659 (Bound::Conn(_), AddrVec::Listen(_)) => {
660 unreachable!("found conn state for listen addr")
661 }
662 }
663 }
664}
665
666impl<I: Ip, D: DeviceIdentifier, A: SocketMapAddrSpec> IterShadows for AddrVec<I, D, A> {
667 type IterShadows = AddrVecIter<I, D, A>;
668
669 fn iter_shadows(&self) -> Self::IterShadows {
670 let (socket_ip_addr, device) = match self.clone() {
671 AddrVec::Conn(ConnAddr { ip, device }) => (ip.into(), device),
672 AddrVec::Listen(ListenerAddr { ip, device }) => (ip.into(), device),
673 };
674 let mut iter = match device {
675 Some(device) => AddrVecIter::with_device(socket_ip_addr, device),
676 None => AddrVecIter::without_device(socket_ip_addr),
677 };
678 assert_eq!(iter.next().as_ref(), Some(self));
680 iter
681 }
682}
683
684#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
686#[allow(missing_docs)]
687pub enum SocketAddrType {
688 AnyListener,
689 SpecificListener,
690 Connected,
691}
692
693impl<'a, A: IpAddress, LI> From<&'a ListenerIpAddr<A, LI>> for SocketAddrType {
694 fn from(ListenerIpAddr { addr, identifier: _ }: &'a ListenerIpAddr<A, LI>) -> Self {
695 match addr {
696 Some(_) => SocketAddrType::SpecificListener,
697 None => SocketAddrType::AnyListener,
698 }
699 }
700}
701
702impl<'a, A: IpAddress, LI, RI> From<&'a ConnIpAddr<A, LI, RI>> for SocketAddrType {
703 fn from(_: &'a ConnIpAddr<A, LI, RI>) -> Self {
704 SocketAddrType::Connected
705 }
706}
707
708pub enum RemoveResult {
710 Success,
712 IsLast,
715}
716
717#[derive(Derivative)]
718#[derivative(Clone(bound = "S::ListenerId: Clone, S::ConnId: Clone"), Debug(bound = ""))]
719pub enum SocketId<S: SocketMapStateSpec> {
720 Listener(S::ListenerId),
721 Connection(S::ConnId),
722}
723
724#[derive(Derivative)]
738#[derivative(Default(bound = ""))]
739pub struct BoundSocketMap<I: Ip, D: DeviceIdentifier, A: SocketMapAddrSpec, S: SocketMapStateSpec> {
740 addr_to_state: SocketMap<AddrVec<I, D, A>, Bound<S>>,
741}
742
743impl<I: Ip, D: DeviceIdentifier, A: SocketMapAddrSpec, S: SocketMapStateSpec>
744 BoundSocketMap<I, D, A, S>
745{
746 pub fn len(&self) -> usize {
748 self.addr_to_state.len()
749 }
750}
751
752pub enum Listener {}
754pub enum Connection {}
756
757pub struct Sockets<AddrToStateMap, SocketType>(AddrToStateMap, PhantomData<SocketType>);
759
760impl<
761 'a,
762 I: Ip,
763 D: DeviceIdentifier,
764 SocketType: ConvertSocketMapState<I, D, A, S>,
765 A: SocketMapAddrSpec,
766 S: SocketMapStateSpec,
767> Sockets<&'a SocketMap<AddrVec<I, D, A>, Bound<S>>, SocketType>
768where
769 S: SocketMapConflictPolicy<SocketType::Addr, SocketType::SharingState, I, D, A>,
770{
771 pub fn get_by_addr(self, addr: &SocketType::Addr) -> Option<&'a SocketType::AddrState> {
773 let Self(addr_to_state, _marker) = self;
774 addr_to_state.get(&SocketType::to_addr_vec(addr)).map(|state| {
775 SocketType::from_bound_ref(state)
776 .unwrap_or_else(|| unreachable!("found {:?} for address {:?}", state, addr))
777 })
778 }
779
780 pub fn could_insert(
786 self,
787 addr: &SocketType::Addr,
788 sharing: &SocketType::SharingState,
789 ) -> Result<(), InsertError> {
790 let Self(addr_to_state, _) = self;
791 match self.get_by_addr(addr) {
792 Some(state) => {
793 state.could_insert(sharing).map_err(|IncompatibleError| InsertError::Exists)
794 }
795 None => S::check_insert_conflicts(&sharing, &addr, &addr_to_state),
796 }
797 }
798}
799
800#[derive(Derivative)]
802#[derivative(Debug(bound = ""))]
803pub struct SocketStateEntry<
804 'a,
805 I: Ip,
806 D: DeviceIdentifier,
807 A: SocketMapAddrSpec,
808 S: SocketMapStateSpec,
809 SocketType,
810> {
811 id: SocketId<S>,
812 addr_entry: SocketMapOccupiedEntry<'a, AddrVec<I, D, A>, Bound<S>>,
813 _marker: PhantomData<SocketType>,
814}
815
816impl<
817 'a,
818 I: Ip,
819 D: DeviceIdentifier,
820 SocketType: ConvertSocketMapState<I, D, A, S>,
821 A: SocketMapAddrSpec,
822 S: SocketMapStateSpec
823 + SocketMapConflictPolicy<SocketType::Addr, SocketType::SharingState, I, D, A>,
824> Sockets<&'a mut SocketMap<AddrVec<I, D, A>, Bound<S>>, SocketType>
825where
826 SocketType::SharingState: Clone,
827 SocketType::Id: Clone,
828{
829 pub fn try_insert(
832 self,
833 socket_addr: SocketType::Addr,
834 tag_state: SocketType::SharingState,
835 id: SocketType::Id,
836 ) -> Result<SocketStateEntry<'a, I, D, A, S, SocketType>, (InsertError, SocketType::SharingState)>
837 {
838 self.try_insert_with(socket_addr, tag_state, |_addr, _sharing| (id, ()))
839 .map(|(entry, ())| entry)
840 }
841
842 pub fn try_insert_with<R>(
847 self,
848 socket_addr: SocketType::Addr,
849 tag_state: SocketType::SharingState,
850 make_id: impl FnOnce(SocketType::Addr, SocketType::SharingState) -> (SocketType::Id, R),
851 ) -> Result<
852 (SocketStateEntry<'a, I, D, A, S, SocketType>, R),
853 (InsertError, SocketType::SharingState),
854 > {
855 let Self(addr_to_state, _) = self;
856 match S::check_insert_conflicts(&tag_state, &socket_addr, &addr_to_state) {
857 Err(e) => return Err((e, tag_state)),
858 Ok(()) => (),
859 };
860
861 let addr = SocketType::to_addr_vec(&socket_addr);
862
863 match addr_to_state.entry(addr) {
864 Entry::Occupied(mut o) => {
865 let (id, ret) = o.map_mut(|bound| {
866 let bound = match SocketType::from_bound_mut(bound) {
867 Some(bound) => bound,
868 None => unreachable!("found {:?} for address {:?}", bound, socket_addr),
869 };
870 match <SocketType::AddrState as SocketMapAddrStateSpec>::try_get_inserter(
871 bound, &tag_state,
872 ) {
873 Ok(v) => {
874 let (id, ret) = make_id(socket_addr, tag_state);
875 v.insert(id.clone());
876 Ok((SocketType::to_socket_id(id), ret))
877 }
878 Err(IncompatibleError) => Err((InsertError::Exists, tag_state)),
879 }
880 })?;
881 Ok((SocketStateEntry { id, addr_entry: o, _marker: Default::default() }, ret))
882 }
883 Entry::Vacant(v) => {
884 let (id, ret) = make_id(socket_addr, tag_state.clone());
885 let addr_entry = v.insert(SocketType::to_bound(SocketType::AddrState::new(
886 &tag_state,
887 id.clone(),
888 )));
889 let id = SocketType::to_socket_id(id);
890 Ok((SocketStateEntry { id, addr_entry, _marker: Default::default() }, ret))
891 }
892 }
893 }
894
895 pub fn entry(
897 self,
898 id: &SocketType::Id,
899 addr: &SocketType::Addr,
900 ) -> Option<SocketStateEntry<'a, I, D, A, S, SocketType>> {
901 let Self(addr_to_state, _) = self;
902 let addr_entry = match addr_to_state.entry(SocketType::to_addr_vec(addr)) {
903 Entry::Vacant(_) => return None,
904 Entry::Occupied(o) => o,
905 };
906 let state = SocketType::from_bound_ref(addr_entry.get())?;
907
908 state.contains_id(id).then_some(SocketStateEntry {
909 id: SocketType::to_socket_id(id.clone()),
910 addr_entry,
911 _marker: PhantomData::default(),
912 })
913 }
914
915 pub fn remove(self, id: &SocketType::Id, addr: &SocketType::Addr) -> Result<(), NotFoundError> {
917 self.entry(id, addr)
918 .map(|entry| {
919 entry.remove();
920 })
921 .ok_or(NotFoundError)
922 }
923}
924
925#[derive(Debug)]
928pub struct UpdateSharingError;
929
930impl<
931 'a,
932 I: Ip,
933 D: DeviceIdentifier,
934 SocketType: ConvertSocketMapState<I, D, A, S>,
935 A: SocketMapAddrSpec,
936 S: SocketMapStateSpec,
937> SocketStateEntry<'a, I, D, A, S, SocketType>
938where
939 SocketType::Id: Clone,
940{
941 pub fn get_addr(&self) -> &SocketType::Addr {
943 let Self { id: _, addr_entry, _marker } = self;
944 SocketType::from_addr_vec_ref(addr_entry.key())
945 }
946
947 pub fn id(&self) -> &SocketType::Id {
949 let Self { id, addr_entry: _, _marker } = self;
950 SocketType::from_socket_id_ref(id)
951 }
952
953 pub fn try_update_addr(self, new_addr: SocketType::Addr) -> Result<Self, (ExistsError, Self)> {
955 let Self { id, addr_entry, _marker } = self;
956
957 let new_addrvec = SocketType::to_addr_vec(&new_addr);
958 let old_addr = addr_entry.key().clone();
959 let (addr_state, addr_to_state) = addr_entry.remove_from_map();
960 let addr_to_state = match addr_to_state.entry(new_addrvec) {
961 Entry::Occupied(o) => o.into_map(),
962 Entry::Vacant(v) => {
963 if v.descendant_counts().len() != 0 {
964 v.into_map()
965 } else {
966 let new_addr_entry = v.insert(addr_state);
967 return Ok(SocketStateEntry { id, addr_entry: new_addr_entry, _marker });
968 }
969 }
970 };
971 let to_restore = addr_state;
972 let addr_entry = match addr_to_state.entry(old_addr) {
974 Entry::Occupied(_) => unreachable!("just-removed-from entry is occupied"),
975 Entry::Vacant(v) => v.insert(to_restore),
976 };
977 return Err((ExistsError, SocketStateEntry { id, addr_entry, _marker }));
978 }
979
980 pub fn remove(self) {
982 let Self { id, mut addr_entry, _marker } = self;
983 let addr = addr_entry.key().clone();
984 match addr_entry.map_mut(|value| {
985 let value = match SocketType::from_bound_mut(value) {
986 Some(value) => value,
987 None => unreachable!("found {:?} for address {:?}", value, addr),
988 };
989 value.remove_by_id(SocketType::from_socket_id_ref(&id).clone())
990 }) {
991 RemoveResult::Success => (),
992 RemoveResult::IsLast => {
993 let _: Bound<S> = addr_entry.remove();
994 }
995 }
996 }
997
998 pub fn try_update_sharing(
1000 &mut self,
1001 old_sharing_state: &SocketType::SharingState,
1002 new_sharing_state: SocketType::SharingState,
1003 ) -> Result<(), UpdateSharingError>
1004 where
1005 SocketType::AddrState: SocketMapAddrStateUpdateSharingSpec,
1006 S: SocketMapUpdateSharingPolicy<SocketType::Addr, SocketType::SharingState, I, D, A>,
1007 {
1008 let Self { id, addr_entry, _marker } = self;
1009 let addr = SocketType::from_addr_vec_ref(addr_entry.key());
1010
1011 S::allows_sharing_update(
1012 addr_entry.get_map(),
1013 addr,
1014 old_sharing_state,
1015 &new_sharing_state,
1016 )?;
1017
1018 addr_entry
1019 .map_mut(|value| {
1020 let value = match SocketType::from_bound_mut(value) {
1021 Some(value) => value,
1022 None => unreachable!("found invalid state {:?}", value),
1026 };
1027
1028 value.try_update_sharing(
1029 SocketType::from_socket_id_ref(id).clone(),
1030 &new_sharing_state,
1031 )
1032 })
1033 .map_err(|IncompatibleError| UpdateSharingError)
1034 }
1035}
1036
1037impl<I: Ip, D: DeviceIdentifier, A: SocketMapAddrSpec, S> BoundSocketMap<I, D, A, S>
1038where
1039 AddrVec<I, D, A>: IterShadows,
1040 S: SocketMapStateSpec,
1041{
1042 pub fn listeners(&self) -> Sockets<&SocketMap<AddrVec<I, D, A>, Bound<S>>, Listener>
1044 where
1045 S: SocketMapConflictPolicy<
1046 ListenerAddr<ListenerIpAddr<I::Addr, A::LocalIdentifier>, D>,
1047 <S as SocketMapStateSpec>::ListenerSharingState,
1048 I,
1049 D,
1050 A,
1051 >,
1052 S::ListenerAddrState:
1053 SocketMapAddrStateSpec<Id = S::ListenerId, SharingState = S::ListenerSharingState>,
1054 {
1055 let Self { addr_to_state } = self;
1056 Sockets(addr_to_state, Default::default())
1057 }
1058
1059 pub fn listeners_mut(&mut self) -> Sockets<&mut SocketMap<AddrVec<I, D, A>, Bound<S>>, Listener>
1061 where
1062 S: SocketMapConflictPolicy<
1063 ListenerAddr<ListenerIpAddr<I::Addr, A::LocalIdentifier>, D>,
1064 <S as SocketMapStateSpec>::ListenerSharingState,
1065 I,
1066 D,
1067 A,
1068 >,
1069 S::ListenerAddrState:
1070 SocketMapAddrStateSpec<Id = S::ListenerId, SharingState = S::ListenerSharingState>,
1071 {
1072 let Self { addr_to_state } = self;
1073 Sockets(addr_to_state, Default::default())
1074 }
1075
1076 pub fn conns(&self) -> Sockets<&SocketMap<AddrVec<I, D, A>, Bound<S>>, Connection>
1078 where
1079 S: SocketMapConflictPolicy<
1080 ConnAddr<ConnIpAddr<I::Addr, A::LocalIdentifier, A::RemoteIdentifier>, D>,
1081 <S as SocketMapStateSpec>::ConnSharingState,
1082 I,
1083 D,
1084 A,
1085 >,
1086 S::ConnAddrState:
1087 SocketMapAddrStateSpec<Id = S::ConnId, SharingState = S::ConnSharingState>,
1088 {
1089 let Self { addr_to_state } = self;
1090 Sockets(addr_to_state, Default::default())
1091 }
1092
1093 pub fn conns_mut(&mut self) -> Sockets<&mut SocketMap<AddrVec<I, D, A>, Bound<S>>, Connection>
1095 where
1096 S: SocketMapConflictPolicy<
1097 ConnAddr<ConnIpAddr<I::Addr, A::LocalIdentifier, A::RemoteIdentifier>, D>,
1098 <S as SocketMapStateSpec>::ConnSharingState,
1099 I,
1100 D,
1101 A,
1102 >,
1103 S::ConnAddrState:
1104 SocketMapAddrStateSpec<Id = S::ConnId, SharingState = S::ConnSharingState>,
1105 {
1106 let Self { addr_to_state } = self;
1107 Sockets(addr_to_state, Default::default())
1108 }
1109
1110 #[cfg(test)]
1111 pub(crate) fn iter_addrs(&self) -> impl Iterator<Item = &AddrVec<I, D, A>> {
1112 let Self { addr_to_state } = self;
1113 addr_to_state.iter().map(|(a, _v): (_, &Bound<S>)| a)
1114 }
1115
1116 pub fn get_shadower_counts(&self, addr: &AddrVec<I, D, A>) -> usize {
1118 let Self { addr_to_state } = self;
1119 addr_to_state.descendant_counts(&addr).map(|(_sharing, size)| size.get()).sum()
1120 }
1121}
1122
1123pub enum FoundSockets<A, It> {
1125 Single(A),
1127 Multicast(It),
1130}
1131
1132#[allow(missing_docs)]
1134#[derive(Debug)]
1135pub enum AddrEntry<'a, I: Ip, D, A: SocketMapAddrSpec, S: SocketMapStateSpec> {
1136 Listen(&'a S::ListenerAddrState, ListenerAddr<ListenerIpAddr<I::Addr, A::LocalIdentifier>, D>),
1137 Conn(
1138 &'a S::ConnAddrState,
1139 ConnAddr<ConnIpAddr<I::Addr, A::LocalIdentifier, A::RemoteIdentifier>, D>,
1140 ),
1141}
1142
1143impl<I, D, A, S> BoundSocketMap<I, D, A, S>
1144where
1145 I: BroadcastIpExt<Addr: MulticastAddress>,
1146 D: DeviceIdentifier,
1147 A: SocketMapAddrSpec,
1148 S: SocketMapStateSpec
1149 + SocketMapConflictPolicy<
1150 ListenerAddr<ListenerIpAddr<I::Addr, A::LocalIdentifier>, D>,
1151 <S as SocketMapStateSpec>::ListenerSharingState,
1152 I,
1153 D,
1154 A,
1155 > + SocketMapConflictPolicy<
1156 ConnAddr<ConnIpAddr<I::Addr, A::LocalIdentifier, A::RemoteIdentifier>, D>,
1157 <S as SocketMapStateSpec>::ConnSharingState,
1158 I,
1159 D,
1160 A,
1161 >,
1162{
1163 pub fn iter_receivers(
1169 &self,
1170 (src_ip, src_port): (Option<SocketIpAddr<I::Addr>>, Option<A::RemoteIdentifier>),
1171 (dst_ip, dst_port): (SocketIpAddr<I::Addr>, A::LocalIdentifier),
1172 device: D,
1173 broadcast: Option<I::BroadcastMarker>,
1174 ) -> Option<
1175 FoundSockets<
1176 AddrEntry<'_, I, D, A, S>,
1177 impl Iterator<Item = AddrEntry<'_, I, D, A, S>> + '_,
1178 >,
1179 > {
1180 let mut matching_entries = AddrVecIter::with_device(
1181 match (src_ip, src_port) {
1182 (Some(specified_src_ip), Some(src_port)) => {
1183 ConnIpAddr { local: (dst_ip, dst_port), remote: (specified_src_ip, src_port) }
1184 .into()
1185 }
1186 _ => ListenerIpAddr { addr: Some(dst_ip), identifier: dst_port }.into(),
1187 },
1188 device,
1189 )
1190 .filter_map(move |addr: AddrVec<I, D, A>| match addr {
1191 AddrVec::Listen(l) => {
1192 self.listeners().get_by_addr(&l).map(|state| AddrEntry::Listen(state, l))
1193 }
1194 AddrVec::Conn(c) => self.conns().get_by_addr(&c).map(|state| AddrEntry::Conn(state, c)),
1195 });
1196
1197 if broadcast.is_some() || dst_ip.addr().is_multicast() {
1198 Some(FoundSockets::Multicast(matching_entries))
1199 } else {
1200 let single_entry: Option<_> = matching_entries.next();
1201 single_entry.map(FoundSockets::Single)
1202 }
1203 }
1204}
1205
1206#[derive(Debug, Eq, PartialEq)]
1208pub enum InsertError {
1209 ShadowAddrExists,
1211 Exists,
1213 ShadowerExists,
1215 IndirectConflict,
1217}
1218
1219pub trait ConvertSocketMapState<I: Ip, D, A: SocketMapAddrSpec, S: SocketMapStateSpec> {
1222 type Id;
1223 type SharingState;
1224 type Addr: Debug;
1225 type AddrState: SocketMapAddrStateSpec<Id = Self::Id, SharingState = Self::SharingState>;
1226
1227 fn to_addr_vec(addr: &Self::Addr) -> AddrVec<I, D, A>;
1228 fn from_addr_vec_ref(addr: &AddrVec<I, D, A>) -> &Self::Addr;
1229 fn from_bound_ref(bound: &Bound<S>) -> Option<&Self::AddrState>;
1230 fn from_bound_mut(bound: &mut Bound<S>) -> Option<&mut Self::AddrState>;
1231 fn to_bound(state: Self::AddrState) -> Bound<S>;
1232 fn to_socket_id(id: Self::Id) -> SocketId<S>;
1233 fn from_socket_id_ref(id: &SocketId<S>) -> &Self::Id;
1234}
1235
1236impl<I: Ip, D: DeviceIdentifier, A: SocketMapAddrSpec, S: SocketMapStateSpec>
1237 ConvertSocketMapState<I, D, A, S> for Listener
1238{
1239 type Id = S::ListenerId;
1240 type SharingState = S::ListenerSharingState;
1241 type Addr = ListenerAddr<ListenerIpAddr<I::Addr, A::LocalIdentifier>, D>;
1242 type AddrState = S::ListenerAddrState;
1243 fn to_addr_vec(addr: &Self::Addr) -> AddrVec<I, D, A> {
1244 AddrVec::Listen(addr.clone())
1245 }
1246
1247 fn from_addr_vec_ref(addr: &AddrVec<I, D, A>) -> &Self::Addr {
1248 match addr {
1249 AddrVec::Listen(l) => l,
1250 AddrVec::Conn(c) => unreachable!("conn addr for listener: {c:?}"),
1251 }
1252 }
1253
1254 fn from_bound_ref(bound: &Bound<S>) -> Option<&S::ListenerAddrState> {
1255 match bound {
1256 Bound::Listen(l) => Some(l),
1257 Bound::Conn(_c) => None,
1258 }
1259 }
1260
1261 fn from_bound_mut(bound: &mut Bound<S>) -> Option<&mut S::ListenerAddrState> {
1262 match bound {
1263 Bound::Listen(l) => Some(l),
1264 Bound::Conn(_c) => None,
1265 }
1266 }
1267
1268 fn to_bound(state: S::ListenerAddrState) -> Bound<S> {
1269 Bound::Listen(state)
1270 }
1271 fn from_socket_id_ref(id: &SocketId<S>) -> &Self::Id {
1272 match id {
1273 SocketId::Listener(id) => id,
1274 SocketId::Connection(_) => unreachable!("connection ID for listener"),
1275 }
1276 }
1277 fn to_socket_id(id: Self::Id) -> SocketId<S> {
1278 SocketId::Listener(id)
1279 }
1280}
1281
1282impl<I: Ip, D: DeviceIdentifier, A: SocketMapAddrSpec, S: SocketMapStateSpec>
1283 ConvertSocketMapState<I, D, A, S> for Connection
1284{
1285 type Id = S::ConnId;
1286 type SharingState = S::ConnSharingState;
1287 type Addr = ConnAddr<ConnIpAddr<I::Addr, A::LocalIdentifier, A::RemoteIdentifier>, D>;
1288 type AddrState = S::ConnAddrState;
1289 fn to_addr_vec(addr: &Self::Addr) -> AddrVec<I, D, A> {
1290 AddrVec::Conn(addr.clone())
1291 }
1292
1293 fn from_addr_vec_ref(addr: &AddrVec<I, D, A>) -> &Self::Addr {
1294 match addr {
1295 AddrVec::Conn(c) => c,
1296 AddrVec::Listen(l) => unreachable!("listener addr for conn: {l:?}"),
1297 }
1298 }
1299
1300 fn from_bound_ref(bound: &Bound<S>) -> Option<&S::ConnAddrState> {
1301 match bound {
1302 Bound::Listen(_l) => None,
1303 Bound::Conn(c) => Some(c),
1304 }
1305 }
1306
1307 fn from_bound_mut(bound: &mut Bound<S>) -> Option<&mut S::ConnAddrState> {
1308 match bound {
1309 Bound::Listen(_l) => None,
1310 Bound::Conn(c) => Some(c),
1311 }
1312 }
1313
1314 fn to_bound(state: S::ConnAddrState) -> Bound<S> {
1315 Bound::Conn(state)
1316 }
1317
1318 fn from_socket_id_ref(id: &SocketId<S>) -> &Self::Id {
1319 match id {
1320 SocketId::Connection(id) => id,
1321 SocketId::Listener(_) => unreachable!("listener ID for connection"),
1322 }
1323 }
1324 fn to_socket_id(id: Self::Id) -> SocketId<S> {
1325 SocketId::Connection(id)
1326 }
1327}
1328
1329#[derive(Debug, Eq, PartialEq, Clone, Copy, Hash)]
1331pub struct SharingDomain(u64);
1332
1333impl SharingDomain {
1334 pub const fn new(id: u64) -> Self {
1338 SharingDomain(id)
1339 }
1340}
1341
1342#[derive(Default, Debug, Eq, PartialEq, Clone, Copy, Hash)]
1345pub enum ReusePortOption {
1346 #[default]
1348 Disabled,
1349
1350 Enabled(SharingDomain),
1353}
1354
1355impl ReusePortOption {
1356 pub fn is_enabled(&self) -> bool {
1358 matches!(self, ReusePortOption::Enabled(_))
1359 }
1360
1361 pub fn is_shareable_with(&self, other: &Self) -> bool {
1364 match (self, other) {
1365 (ReusePortOption::Enabled(domain1), ReusePortOption::Enabled(domain2)) => {
1366 domain1 == domain2
1367 }
1368 _ => false,
1369 }
1370 }
1371}
1372
1373#[cfg(test)]
1374mod tests {
1375 use alloc::vec;
1376 use alloc::vec::Vec;
1377
1378 use assert_matches::assert_matches;
1379 use net_declare::{net_ip_v4, net_ip_v6};
1380 use net_types::ip::{Ipv4Addr, Ipv6, Ipv6Addr};
1381 use netstack3_hashmap::HashSet;
1382 use test_case::test_case;
1383
1384 use crate::device::testutil::{FakeDeviceId, FakeWeakDeviceId};
1385 use crate::testutil::set_logger_for_test;
1386
1387 use super::*;
1388
1389 #[test_case(net_ip_v4!("8.8.8.8"))]
1390 #[test_case(net_ip_v4!("127.0.0.1"))]
1391 #[test_case(net_ip_v4!("127.0.8.9"))]
1392 #[test_case(net_ip_v4!("224.1.2.3"))]
1393 fn must_never_have_zone_ipv4(addr: Ipv4Addr) {
1394 let addr = SpecifiedAddr::new(addr).unwrap();
1396 assert_eq!(addr.must_have_zone(), false);
1397 }
1398
1399 #[test_case(net_ip_v6!("1::2:3"), false)]
1400 #[test_case(net_ip_v6!("::1"), false; "localhost")]
1401 #[test_case(net_ip_v6!("1::"), false)]
1402 #[test_case(net_ip_v6!("ff03:1:2:3::1"), false)]
1403 #[test_case(net_ip_v6!("ff02:1:2:3::1"), true)]
1404 #[test_case(Ipv6::ALL_NODES_LINK_LOCAL_MULTICAST_ADDRESS.get(), true)]
1405 #[test_case(net_ip_v6!("fe80::1"), true)]
1406 fn must_have_zone_ipv6(addr: Ipv6Addr, must_have: bool) {
1407 let addr = SpecifiedAddr::new(addr).unwrap();
1410 assert_eq!(addr.must_have_zone(), must_have);
1411 }
1412
1413 #[test]
1414 fn try_into_null_zoned_ipv6() {
1415 assert_eq!(Ipv6::LOOPBACK_ADDRESS.try_into_null_zoned(), None);
1416 let zoned = Ipv6::ALL_NODES_LINK_LOCAL_MULTICAST_ADDRESS.into_specified();
1417 const ZONE: u32 = 5;
1418 assert_eq!(
1419 zoned.try_into_null_zoned().map(|a| a.map_zone(|()| ZONE)),
1420 Some(AddrAndZone::new(zoned, ZONE).unwrap())
1421 );
1422 }
1423
1424 enum FakeSpec {}
1425
1426 #[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)]
1427 struct Listener(usize);
1428
1429 #[derive(PartialEq, Eq, Debug)]
1430 struct Multiple<T>(char, Vec<T>);
1431
1432 impl<T> Multiple<T> {
1433 fn tag(&self) -> char {
1434 let Multiple(c, _) = self;
1435 *c
1436 }
1437 }
1438
1439 #[derive(Copy, Clone, Eq, PartialEq, Debug, Hash)]
1440 struct Conn(usize);
1441
1442 enum FakeAddrSpec {}
1443
1444 impl SocketMapAddrSpec for FakeAddrSpec {
1445 type LocalIdentifier = NonZeroU16;
1446 type RemoteIdentifier = ();
1447 }
1448
1449 impl SocketMapStateSpec for FakeSpec {
1450 type AddrVecTag = char;
1451
1452 type ListenerId = Listener;
1453 type ConnId = Conn;
1454
1455 type ListenerSharingState = char;
1456 type ConnSharingState = char;
1457
1458 type ListenerAddrState = Multiple<Listener>;
1459 type ConnAddrState = Multiple<Conn>;
1460
1461 fn listener_tag(_: ListenerAddrInfo, state: &Self::ListenerAddrState) -> Self::AddrVecTag {
1462 state.tag()
1463 }
1464
1465 fn connected_tag(_has_device: bool, state: &Self::ConnAddrState) -> Self::AddrVecTag {
1466 state.tag()
1467 }
1468 }
1469
1470 type FakeBoundSocketMap =
1471 BoundSocketMap<Ipv4, FakeWeakDeviceId<FakeDeviceId>, FakeAddrSpec, FakeSpec>;
1472
1473 #[derive(Default)]
1477 struct FakeSocketIdGen {
1478 next_id: usize,
1479 }
1480
1481 impl FakeSocketIdGen {
1482 fn next(&mut self) -> usize {
1483 let next_next_id = self.next_id + 1;
1484 core::mem::replace(&mut self.next_id, next_next_id)
1485 }
1486 }
1487
1488 impl<I: Eq> SocketMapAddrStateSpec for Multiple<I> {
1489 type Id = I;
1490 type SharingState = char;
1491 type Inserter<'a>
1492 = &'a mut Vec<I>
1493 where
1494 I: 'a;
1495
1496 fn new(new_sharing_state: &char, id: I) -> Self {
1497 Self(*new_sharing_state, vec![id])
1498 }
1499
1500 fn contains_id(&self, id: &Self::Id) -> bool {
1501 self.1.contains(id)
1502 }
1503
1504 fn try_get_inserter<'a, 'b>(
1505 &'b mut self,
1506 new_state: &'a char,
1507 ) -> Result<Self::Inserter<'b>, IncompatibleError> {
1508 let Self(c, v) = self;
1509 (new_state == c).then_some(v).ok_or(IncompatibleError)
1510 }
1511
1512 fn could_insert(
1513 &self,
1514 new_sharing_state: &Self::SharingState,
1515 ) -> Result<(), IncompatibleError> {
1516 let Self(c, _) = self;
1517 (new_sharing_state == c).then_some(()).ok_or(IncompatibleError)
1518 }
1519
1520 fn remove_by_id(&mut self, id: I) -> RemoveResult {
1521 let Self(_, v) = self;
1522 let index = v.iter().position(|i| i == &id).expect("did not find id");
1523 let _: I = v.swap_remove(index);
1524 if v.is_empty() { RemoveResult::IsLast } else { RemoveResult::Success }
1525 }
1526 }
1527
1528 impl<A: Into<AddrVec<Ipv4, FakeWeakDeviceId<FakeDeviceId>, FakeAddrSpec>> + Clone>
1529 SocketMapConflictPolicy<A, char, Ipv4, FakeWeakDeviceId<FakeDeviceId>, FakeAddrSpec>
1530 for FakeSpec
1531 {
1532 fn check_insert_conflicts(
1533 new_state: &char,
1534 addr: &A,
1535 socketmap: &SocketMap<
1536 AddrVec<Ipv4, FakeWeakDeviceId<FakeDeviceId>, FakeAddrSpec>,
1537 Bound<FakeSpec>,
1538 >,
1539 ) -> Result<(), InsertError> {
1540 let dest = addr.clone().into();
1541 if dest.iter_shadows().any(|a| socketmap.get(&a).is_some()) {
1542 return Err(InsertError::ShadowAddrExists);
1543 }
1544 match socketmap.get(&dest) {
1545 Some(Bound::Listen(Multiple(c, _))) | Some(Bound::Conn(Multiple(c, _))) => {
1546 if c != new_state {
1549 return Err(InsertError::Exists);
1550 }
1551 }
1552 None => (),
1553 }
1554 if socketmap.descendant_counts(&dest).len() != 0 {
1555 Err(InsertError::ShadowerExists)
1556 } else {
1557 Ok(())
1558 }
1559 }
1560 }
1561
1562 impl<I: Eq> SocketMapAddrStateUpdateSharingSpec for Multiple<I> {
1563 fn try_update_sharing(
1564 &mut self,
1565 id: Self::Id,
1566 new_sharing_state: &Self::SharingState,
1567 ) -> Result<(), IncompatibleError> {
1568 let Self(sharing, v) = self;
1569 if new_sharing_state == sharing {
1570 return Ok(());
1571 }
1572
1573 if v.len() != 1 {
1578 return Err(IncompatibleError);
1579 }
1580 assert!(v.contains(&id));
1581 *sharing = *new_sharing_state;
1582 Ok(())
1583 }
1584 }
1585
1586 impl<A: Into<AddrVec<Ipv4, FakeWeakDeviceId<FakeDeviceId>, FakeAddrSpec>> + Clone>
1587 SocketMapUpdateSharingPolicy<A, char, Ipv4, FakeWeakDeviceId<FakeDeviceId>, FakeAddrSpec>
1588 for FakeSpec
1589 {
1590 fn allows_sharing_update(
1591 _socketmap: &SocketMap<
1592 AddrVec<Ipv4, FakeWeakDeviceId<FakeDeviceId>, FakeAddrSpec>,
1593 Bound<Self>,
1594 >,
1595 _addr: &A,
1596 _old_sharing: &char,
1597 _new_sharing_state: &char,
1598 ) -> Result<(), UpdateSharingError> {
1599 Ok(())
1600 }
1601 }
1602
1603 const LISTENER_ADDR: ListenerAddr<
1604 ListenerIpAddr<Ipv4Addr, NonZeroU16>,
1605 FakeWeakDeviceId<FakeDeviceId>,
1606 > = ListenerAddr {
1607 ip: ListenerIpAddr {
1608 addr: Some(unsafe { SocketIpAddr::new_unchecked(net_ip_v4!("1.2.3.4")) }),
1609 identifier: NonZeroU16::new(1).unwrap(),
1610 },
1611 device: None,
1612 };
1613
1614 const CONN_ADDR: ConnAddr<
1615 ConnIpAddr<Ipv4Addr, NonZeroU16, ()>,
1616 FakeWeakDeviceId<FakeDeviceId>,
1617 > = ConnAddr {
1618 ip: ConnIpAddr {
1619 local: (
1620 unsafe { SocketIpAddr::new_unchecked(net_ip_v4!("5.6.7.8")) },
1621 NonZeroU16::new(1).unwrap(),
1622 ),
1623 remote: unsafe { (SocketIpAddr::new_unchecked(net_ip_v4!("8.7.6.5")), ()) },
1624 },
1625 device: None,
1626 };
1627
1628 #[test]
1629 fn bound_insert_get_remove_listener() {
1630 set_logger_for_test();
1631 let mut bound = FakeBoundSocketMap::default();
1632 let mut fake_id_gen = FakeSocketIdGen::default();
1633
1634 let addr = LISTENER_ADDR;
1635
1636 let id = {
1637 let entry =
1638 bound.listeners_mut().try_insert(addr, 'v', Listener(fake_id_gen.next())).unwrap();
1639 assert_eq!(entry.get_addr(), &addr);
1640 entry.id().clone()
1641 };
1642
1643 assert_eq!(bound.listeners().get_by_addr(&addr), Some(&Multiple('v', vec![id])));
1644
1645 assert_eq!(bound.listeners_mut().remove(&id, &addr), Ok(()));
1646 assert_eq!(bound.listeners().get_by_addr(&addr), None);
1647 }
1648
1649 #[test]
1650 fn bound_insert_get_remove_conn() {
1651 set_logger_for_test();
1652 let mut bound = FakeBoundSocketMap::default();
1653 let mut fake_id_gen = FakeSocketIdGen::default();
1654
1655 let addr = CONN_ADDR;
1656
1657 let id = {
1658 let entry = bound.conns_mut().try_insert(addr, 'v', Conn(fake_id_gen.next())).unwrap();
1659 assert_eq!(entry.get_addr(), &addr);
1660 entry.id().clone()
1661 };
1662
1663 assert_eq!(bound.conns().get_by_addr(&addr), Some(&Multiple('v', vec![id])));
1664
1665 assert_eq!(bound.conns_mut().remove(&id, &addr), Ok(()));
1666 assert_eq!(bound.conns().get_by_addr(&addr), None);
1667 }
1668
1669 #[test]
1670 fn bound_iter_addrs() {
1671 set_logger_for_test();
1672 let mut bound = FakeBoundSocketMap::default();
1673 let mut fake_id_gen = FakeSocketIdGen::default();
1674
1675 let listener_addrs = [
1676 (Some(net_ip_v4!("1.1.1.1")), 1),
1677 (Some(net_ip_v4!("2.2.2.2")), 2),
1678 (Some(net_ip_v4!("1.1.1.1")), 3),
1679 (None, 4),
1680 ]
1681 .map(|(ip, identifier)| ListenerAddr {
1682 device: None,
1683 ip: ListenerIpAddr {
1684 addr: ip.map(|x| SocketIpAddr::new(x).unwrap()),
1685 identifier: NonZeroU16::new(identifier).unwrap(),
1686 },
1687 });
1688 let conn_addrs = [
1689 (net_ip_v4!("3.3.3.3"), 3, net_ip_v4!("4.4.4.4")),
1690 (net_ip_v4!("4.4.4.4"), 3, net_ip_v4!("3.3.3.3")),
1691 ]
1692 .map(|(local_ip, local_identifier, remote_ip)| ConnAddr {
1693 ip: ConnIpAddr {
1694 local: (
1695 SocketIpAddr::new(local_ip).unwrap(),
1696 NonZeroU16::new(local_identifier).unwrap(),
1697 ),
1698 remote: (SocketIpAddr::new(remote_ip).unwrap(), ()),
1699 },
1700 device: None,
1701 });
1702
1703 for addr in listener_addrs.iter().cloned() {
1704 let _entry =
1705 bound.listeners_mut().try_insert(addr, 'a', Listener(fake_id_gen.next())).unwrap();
1706 }
1707 for addr in conn_addrs.iter().cloned() {
1708 let _entry = bound.conns_mut().try_insert(addr, 'a', Conn(fake_id_gen.next())).unwrap();
1709 }
1710 let expected_addrs = listener_addrs
1711 .into_iter()
1712 .map(Into::into)
1713 .chain(conn_addrs.into_iter().map(Into::into))
1714 .collect::<HashSet<_>>();
1715
1716 assert_eq!(expected_addrs, bound.iter_addrs().cloned().collect());
1717 }
1718
1719 #[test]
1720 fn try_insert_with_callback_not_called_on_error() {
1721 set_logger_for_test();
1724 let mut bound = FakeBoundSocketMap::default();
1725 let addr = LISTENER_ADDR;
1726
1727 let _: &Listener = bound.listeners_mut().try_insert(addr, 'a', Listener(0)).unwrap().id();
1729
1730 fn is_never_called<A, B, T>(_: A, _: B) -> (T, ()) {
1734 panic!("should never be called");
1735 }
1736
1737 assert_matches!(
1738 bound.listeners_mut().try_insert_with(addr, 'b', is_never_called),
1739 Err((InsertError::Exists, _))
1740 );
1741 assert_matches!(
1742 bound.listeners_mut().try_insert_with(
1743 ListenerAddr { device: Some(FakeWeakDeviceId(FakeDeviceId)), ..addr },
1744 'b',
1745 is_never_called
1746 ),
1747 Err((InsertError::ShadowAddrExists, _))
1748 );
1749 assert_matches!(
1750 bound.conns_mut().try_insert_with(
1751 ConnAddr {
1752 device: None,
1753 ip: ConnIpAddr {
1754 local: (addr.ip.addr.unwrap(), addr.ip.identifier),
1755 remote: (SocketIpAddr::new(net_ip_v4!("1.1.1.1")).unwrap(), ()),
1756 },
1757 },
1758 'b',
1759 is_never_called,
1760 ),
1761 Err((InsertError::ShadowAddrExists, _))
1762 );
1763 }
1764
1765 #[test]
1766 fn insert_listener_conflict_with_listener() {
1767 set_logger_for_test();
1768 let mut bound = FakeBoundSocketMap::default();
1769 let mut fake_id_gen = FakeSocketIdGen::default();
1770 let addr = LISTENER_ADDR;
1771
1772 let _: &Listener =
1773 bound.listeners_mut().try_insert(addr, 'a', Listener(fake_id_gen.next())).unwrap().id();
1774 assert_matches!(
1775 bound.listeners_mut().try_insert(addr, 'b', Listener(fake_id_gen.next())),
1776 Err((InsertError::Exists, 'b'))
1777 );
1778 }
1779
1780 #[test]
1781 fn insert_listener_conflict_with_shadower() {
1782 set_logger_for_test();
1783 let mut bound = FakeBoundSocketMap::default();
1784 let mut fake_id_gen = FakeSocketIdGen::default();
1785 let addr = LISTENER_ADDR;
1786 let shadows_addr = {
1787 assert_eq!(addr.device, None);
1788 ListenerAddr { device: Some(FakeWeakDeviceId(FakeDeviceId)), ..addr }
1789 };
1790
1791 let _: &Listener =
1792 bound.listeners_mut().try_insert(addr, 'a', Listener(fake_id_gen.next())).unwrap().id();
1793 assert_matches!(
1794 bound.listeners_mut().try_insert(shadows_addr, 'b', Listener(fake_id_gen.next())),
1795 Err((InsertError::ShadowAddrExists, 'b'))
1796 );
1797 }
1798
1799 #[test]
1800 fn insert_conn_conflict_with_listener() {
1801 set_logger_for_test();
1802 let mut bound = FakeBoundSocketMap::default();
1803 let mut fake_id_gen = FakeSocketIdGen::default();
1804 let addr = LISTENER_ADDR;
1805 let shadows_addr = ConnAddr {
1806 device: None,
1807 ip: ConnIpAddr {
1808 local: (addr.ip.addr.unwrap(), addr.ip.identifier),
1809 remote: (SocketIpAddr::new(net_ip_v4!("1.1.1.1")).unwrap(), ()),
1810 },
1811 };
1812
1813 let _: &Listener =
1814 bound.listeners_mut().try_insert(addr, 'a', Listener(fake_id_gen.next())).unwrap().id();
1815 assert_matches!(
1816 bound.conns_mut().try_insert(shadows_addr, 'b', Conn(fake_id_gen.next())),
1817 Err((InsertError::ShadowAddrExists, 'b'))
1818 );
1819 }
1820
1821 #[test]
1822 fn insert_and_remove_listener() {
1823 set_logger_for_test();
1824 let mut bound = FakeBoundSocketMap::default();
1825 let mut fake_id_gen = FakeSocketIdGen::default();
1826 let addr = LISTENER_ADDR;
1827
1828 let a = bound
1829 .listeners_mut()
1830 .try_insert(addr, 'x', Listener(fake_id_gen.next()))
1831 .unwrap()
1832 .id()
1833 .clone();
1834 let b = bound
1835 .listeners_mut()
1836 .try_insert(addr, 'x', Listener(fake_id_gen.next()))
1837 .unwrap()
1838 .id()
1839 .clone();
1840 assert_ne!(a, b);
1841
1842 assert_eq!(bound.listeners_mut().remove(&a, &addr), Ok(()));
1843 assert_eq!(bound.listeners().get_by_addr(&addr), Some(&Multiple('x', vec![b])));
1844 }
1845
1846 #[test]
1847 fn insert_and_remove_conn() {
1848 set_logger_for_test();
1849 let mut bound = FakeBoundSocketMap::default();
1850 let mut fake_id_gen = FakeSocketIdGen::default();
1851 let addr = CONN_ADDR;
1852
1853 let a =
1854 bound.conns_mut().try_insert(addr, 'x', Conn(fake_id_gen.next())).unwrap().id().clone();
1855 let b =
1856 bound.conns_mut().try_insert(addr, 'x', Conn(fake_id_gen.next())).unwrap().id().clone();
1857 assert_ne!(a, b);
1858
1859 assert_eq!(bound.conns_mut().remove(&a, &addr), Ok(()));
1860 assert_eq!(bound.conns().get_by_addr(&addr), Some(&Multiple('x', vec![b])));
1861 }
1862
1863 #[test]
1864 fn update_listener_to_shadowed_addr_fails() {
1865 let mut bound = FakeBoundSocketMap::default();
1866 let mut fake_id_gen = FakeSocketIdGen::default();
1867
1868 let first_addr = LISTENER_ADDR;
1869 let second_addr = ListenerAddr {
1870 ip: ListenerIpAddr {
1871 addr: Some(SocketIpAddr::new(net_ip_v4!("1.1.1.1")).unwrap()),
1872 ..LISTENER_ADDR.ip
1873 },
1874 ..LISTENER_ADDR
1875 };
1876 let both_shadow = ListenerAddr {
1877 ip: ListenerIpAddr { addr: None, identifier: first_addr.ip.identifier },
1878 device: None,
1879 };
1880
1881 let first = bound
1882 .listeners_mut()
1883 .try_insert(first_addr, 'a', Listener(fake_id_gen.next()))
1884 .unwrap()
1885 .id()
1886 .clone();
1887 let second = bound
1888 .listeners_mut()
1889 .try_insert(second_addr, 'b', Listener(fake_id_gen.next()))
1890 .unwrap()
1891 .id()
1892 .clone();
1893
1894 let (ExistsError, entry) = bound
1897 .listeners_mut()
1898 .entry(&second, &second_addr)
1899 .unwrap()
1900 .try_update_addr(both_shadow)
1901 .expect_err("update should fail");
1902
1903 assert_eq!(entry.id(), &second);
1905 drop(entry);
1906
1907 let (ExistsError, entry) = bound
1908 .listeners_mut()
1909 .entry(&first, &first_addr)
1910 .unwrap()
1911 .try_update_addr(both_shadow)
1912 .expect_err("update should fail");
1913 assert_eq!(entry.get_addr(), &first_addr);
1914 }
1915
1916 #[test]
1917 fn nonexistent_conn_entry() {
1918 let mut map = FakeBoundSocketMap::default();
1919 let mut fake_id_gen = FakeSocketIdGen::default();
1920 let addr = CONN_ADDR;
1921 let conn_id = map
1922 .conns_mut()
1923 .try_insert(addr.clone(), 'a', Conn(fake_id_gen.next()))
1924 .expect("failed to insert")
1925 .id()
1926 .clone();
1927 assert_matches!(map.conns_mut().remove(&conn_id, &addr), Ok(()));
1928
1929 assert!(map.conns_mut().entry(&conn_id, &addr).is_none());
1930 }
1931
1932 #[test]
1933 fn update_conn_sharing() {
1934 let mut map = FakeBoundSocketMap::default();
1935 let mut fake_id_gen = FakeSocketIdGen::default();
1936 let addr = CONN_ADDR;
1937 let mut entry = map
1938 .conns_mut()
1939 .try_insert(addr.clone(), 'a', Conn(fake_id_gen.next()))
1940 .expect("failed to insert");
1941
1942 entry.try_update_sharing(&'a', 'd').expect("worked");
1943 let mut second_conn = map
1946 .conns_mut()
1947 .try_insert(addr.clone(), 'd', Conn(fake_id_gen.next()))
1948 .expect("can insert");
1949 assert_matches!(second_conn.try_update_sharing(&'d', 'e'), Err(UpdateSharingError));
1950 }
1951}