Skip to main content

netstack3_base/
lib.rs

1// Copyright 2024 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! Base type definitions for netstack3 core.
6//!
7//! This crate contains definitions common to the other netstack3 core crates
8//! and is the base dependency for most of them.
9
10#![no_std]
11#![warn(
12    missing_docs,
13    unreachable_patterns,
14    clippy::useless_conversion,
15    clippy::redundant_clone,
16    clippy::precedence
17)]
18
19extern crate alloc;
20
21mod context;
22mod convert;
23mod counters;
24mod data_structures;
25mod device;
26mod error;
27mod event;
28mod frame;
29mod inspect;
30mod ip;
31mod map_deref;
32mod matchers;
33mod num;
34mod packet;
35mod port_alloc;
36mod resource_references;
37mod rng;
38mod settings;
39mod tcp;
40mod test_only;
41mod time;
42mod uninstantiable;
43mod work_queue;
44
45pub use context::{BuildableCoreContext, ContextPair, ContextProvider, CtxPair};
46pub use convert::{BidirectionalConverter, OwnedOrRefsBidirectionalConverter};
47pub use counters::{
48    Counter, CounterCollection, CounterCollectionSpec, CounterContext, CounterRepr,
49    ResourceCounterContext,
50};
51pub use data_structures::token_bucket::TokenBucket;
52pub use device::address::{
53    AssignedAddrIpExt, IpAddressId, IpDeviceAddr, IpDeviceAddressIdContext, Ipv4DeviceAddr,
54    Ipv6DeviceAddr, WeakIpAddressId,
55};
56pub use device::link::{LinkAddress, LinkDevice, LinkDeviceAddress};
57pub use device::{
58    AnyDevice, Device, DeviceIdAnyCompatContext, DeviceIdContext, DeviceIdentifier, EitherDeviceId,
59    StrongDeviceIdentifier, WeakDeviceIdentifier,
60};
61pub use error::{
62    AddressResolutionFailed, ErrorAndSerializer, ExistsError, LocalAddressError, NotFoundError,
63    NotSupportedError, RemoteAddressError, SocketError, ZonedAddressError,
64};
65pub use event::EventContext;
66pub use frame::{
67    CoreTxMetadataContext, FrameDestination, LocalFrameDestination, NeverBuffer,
68    ReceivableFrameMeta, RecvFrameContext, RecvIpFrameMeta, SendFrameContext, SendFrameError,
69    SendFrameErrorReason, SendableFrameMeta, TxMetadata, TxMetadataBindingsTypes,
70};
71pub use inspect::{Inspectable, InspectableValue, Inspector, InspectorDeviceExt, InspectorExt};
72pub use ip::{
73    BroadcastIpExt, IcmpErrorCode, IcmpIpExt, Icmpv4ErrorCode, Icmpv6ErrorCode, IpExt,
74    IpTypesIpExt, Mark, MarkDomain, MarkStorage, Marks, Mms, WrapBroadcastMarker,
75};
76pub use map_deref::{MapDeref, MapDerefExt};
77pub use matchers::{
78    AddressMatcher, AddressMatcherEither, AddressMatcherType, BoundAddressMatcherEither,
79    BoundInterfaceMatcher, BoundPortMatcher, InterfaceMatcher, InterfaceProperties,
80    IpSocketMatcher, IpSocketProperties, IpSocketPropertiesMatcher, MarkInDomainMatcher,
81    MarkMatcher, MarkMatchers, Matcher, MatcherBindingsTypes, MaybeSocketTransportProperties,
82    PortMatcher, SocketCookieMatcher, SocketTransportProtocolMatcher, SubnetMatcher,
83    TcpSocketMatcher, TcpSocketProperties, TcpSocketState, TcpStateMatcher, UdpSocketMatcher,
84    UdpSocketProperties, UdpSocketState, UdpStateMatcher,
85};
86pub use num::PositiveIsize;
87pub use packet::{
88    ChecksumOffloadResult, ChecksumOffloadSpec, ChecksumRxOffloading,
89    DynamicNetworkPartialSerializer, DynamicNetworkSerializer, NetworkParsingContext,
90    NetworkPartialSerializer, NetworkSerializationContext, NetworkSerializer,
91    ProtocolSpecificOffloadSpec,
92};
93pub use port_alloc::{EphemeralPort, PortAllocImpl, simple_randomized_port_alloc};
94pub use resource_references::{
95    DeferredResourceRemovalContext, ReferenceNotifiers, ReferenceNotifiersExt,
96    RemoveResourceResult, RemoveResourceResultWithContext,
97};
98
99pub use rng::RngContext;
100pub use settings::{BufferSizeSettings, SettingsContext};
101pub use socket::SocketDiagnosticsSeed;
102pub use tcp::base::{Control, EffectiveMss, FragmentedPayload, Mss, MssSizeLimiters};
103pub use tcp::segment::{
104    HandshakeOptions, MalformedFlags, Options, Payload, PayloadLen, ResetOptions, SackBlock,
105    SackBlocks, Segment, SegmentHeader, SegmentOptions, VerifiedTcpSegment,
106};
107pub use tcp::seqnum::{SeqNum, UnscaledWindowSize, WindowScale, WindowSize};
108pub use tcp::timestamp::{
109    Milliseconds, RxTimestampOption, Timestamp, TimestampOption, TxTimestampOption, Unitless,
110};
111pub use test_only::TestOnlyPartialEq;
112pub use time::local_timer_heap::LocalTimerHeap;
113pub use time::{
114    AtomicInstant, CoreTimerContext, HandleableTimer, Instant, InstantBindingsTypes,
115    InstantContext, IntoCoreTimerCtx, NestedIntoCoreTimerCtx, TimerBindingsTypes, TimerContext,
116    TimerHandler,
117};
118pub use uninstantiable::{Uninstantiable, UninstantiableWrapper};
119pub use work_queue::WorkQueueReport;
120
121/// Reference counted hash map data structure.
122pub mod ref_counted_hash_map {
123    pub use crate::data_structures::ref_counted_hash_map::{
124        InsertResult, RefCountedHashMap, RefCountedHashSet, RemoveResult,
125    };
126}
127
128/// Read-copy-update data structure.
129pub mod rcu {
130    pub use crate::data_structures::rcu::{ReadGuard, SynchronizedWriterRcu, WriteGuard};
131}
132
133/// Common types and utilities for sockets.
134pub mod socket {
135    mod address;
136    mod base;
137    mod cookie;
138    pub(crate) mod sndbuf;
139
140    pub use address::{
141        AddrIsMappedError, AddrVecIter, ConnAddr, ConnInfoAddr, ConnIpAddr, DualStackConnIpAddr,
142        DualStackListenerIpAddr, DualStackLocalIp, DualStackRemoteIp, IpAddrVec, ListenerAddr,
143        ListenerIpAddr, SocketIpAddr, StrictlyZonedAddr,
144    };
145    pub use base::{
146        AddrEntry, AddrVec, Bound, BoundSocketMap, DualStackIpExt, DualStackTuple, EitherIpProto,
147        EitherStack, FoundSockets, IncompatibleError, InsertError, Inserter, Listener,
148        ListenerAddrInfo, MaybeDualStack, NotDualStackCapableError, RemoveResult, ReusePortOption,
149        SetDualStackEnabledError, SharingDomain, Shutdown, ShutdownType, SocketAddrType,
150        SocketDeviceUpdate, SocketDeviceUpdateNotAllowedError, SocketDiagnosticsSeed, SocketInfo,
151        SocketIpAddrExt, SocketIpExt, SocketMapAddrSpec, SocketMapAddrStateSpec,
152        SocketMapAddrStateUpdateSharingSpec, SocketMapConflictPolicy, SocketMapStateSpec,
153        SocketMapUpdateSharingPolicy, SocketStateEntry, SocketZonedAddrExt, UpdateSharingError,
154    };
155    pub use cookie::SocketCookie;
156    pub use sndbuf::{
157        SendBufferFullError, SendBufferSpace, SendBufferTracking, SocketWritableListener,
158    };
159}
160
161/// Defines generic data structures used to implement common application socket
162/// functionality for multiple protocols.
163pub mod socketmap {
164    pub use crate::data_structures::socketmap::{
165        Entry, IterShadows, OccupiedEntry, SocketMap, Tagged, VacantEntry,
166    };
167}
168
169/// Sync utilities common to netstack3.
170pub mod sync {
171    // TODO(https://fxbug.dev/42062225): Support single-threaded variants of
172    // types exported from this module.
173
174    // Exclusively re-exports from the sync crate.
175    pub use netstack3_sync::rc::{
176        DebugReferences, DynDebugReferences, MapNotifier as MapRcNotifier, Notifier as RcNotifier,
177        Primary as PrimaryRc, ResourceToken, ResourceTokenValue, Strong as StrongRc,
178        Weak as WeakRc,
179    };
180    pub use netstack3_sync::{LockGuard, Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard};
181}
182
183/// Test utilities provided to all crates.
184#[cfg(any(test, feature = "testutils"))]
185pub mod testutil {
186    mod addr;
187    mod benchmarks;
188    mod fake_bindings;
189    mod fake_core;
190    mod fake_network;
191    mod misc;
192    mod monotonic_id;
193
194    pub use crate::device::address::testutil::FakeWeakAddressId;
195    pub use crate::device::link::testutil::{FakeLinkAddress, FakeLinkDevice, FakeLinkDeviceId};
196    pub use crate::device::testutil::{
197        FakeDeviceClass, FakeDeviceId, FakeReferencyDeviceId, FakeStrongDeviceId, FakeWeakDeviceId,
198        MultipleDevicesId, MultipleDevicesIdState,
199    };
200    pub use crate::event::testutil::FakeEventCtx;
201    pub use crate::frame::testutil::{FakeFrameCtx, FakeTxMetadata, WithFakeFrameContext};
202    pub use crate::matchers::testutil::FakeMatcherDeviceId;
203    pub use crate::rng::testutil::{FakeCryptoRng, new_rng, run_with_many_seeds};
204    pub use crate::settings::testutil::AlwaysDefaultsSettingsContext;
205    pub use crate::socket::sndbuf::testutil::FakeSocketWritableListener;
206    pub use crate::time::testutil::{
207        FakeAtomicInstant, FakeInstant, FakeInstantCtx, FakeTimerCtx, FakeTimerCtxExt, FakeTimerId,
208        InstantAndData, WithFakeTimerContext,
209    };
210    pub use addr::{TEST_ADDRS_V4, TEST_ADDRS_V6, TestAddrs, TestDualStackIpExt, TestIpExt};
211    pub use benchmarks::{Bencher, RealBencher, TestBencher};
212    pub use fake_bindings::FakeBindingsCtx;
213    pub use fake_core::FakeCoreCtx;
214    pub use fake_network::{
215        FakeNetwork, FakeNetworkLinks, FakeNetworkSpec, PendingFrame, PendingFrameData, StepResult,
216    };
217    pub use misc::{assert_empty, set_logger_for_test};
218    pub use monotonic_id::MonotonicIdentifier;
219}
220
221/// Benchmarks defined in the base crate.
222#[cfg(benchmark)]
223pub mod benchmarks {
224    /// Adds benchmarks defined in the base crate to the provided benchmarker.
225    pub fn add_benches(b: criterion::Benchmark) -> criterion::Benchmark {
226        crate::data_structures::token_bucket::benchmarks::add_benches(b)
227    }
228}