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, GsoInfo, Ipv4IdMode, LocalFrameDestination,
68    MAX_GSO_PAYLOAD_LEN, NeverBuffer, PacketType, ReceivableFrameMeta, RecvFrameContext,
69    RecvIpFrameMeta, SendFrameContext, SendFrameError, SendFrameErrorReason, SendableFrameMeta,
70    TxMetadata, TxMetadataBindingsTypes,
71};
72pub use inspect::{Inspectable, InspectableValue, Inspector, InspectorDeviceExt, InspectorExt};
73pub use ip::{
74    BroadcastIpExt, IcmpErrorCode, IcmpIpExt, Icmpv4ErrorCode, Icmpv6ErrorCode, IpExt,
75    IpTypesIpExt, Mark, MarkDomain, MarkStorage, Marks, Mms, WrapBroadcastMarker,
76};
77pub use map_deref::{MapDeref, MapDerefExt};
78pub use matchers::{
79    AddressMatcher, AddressMatcherEither, AddressMatcherType, BoundAddressMatcherEither,
80    BoundInterfaceMatcher, BoundPortMatcher, InterfaceMatcher, InterfaceProperties,
81    IpSocketMatcher, IpSocketProperties, IpSocketPropertiesMatcher, MarkInDomainMatcher,
82    MarkMatcher, MarkMatchers, Matcher, MatcherBindingsTypes, MaybeSocketTransportProperties,
83    PortMatcher, SocketCookieMatcher, SocketTransportProtocolMatcher, SubnetMatcher,
84    TcpSocketMatcher, TcpSocketProperties, TcpSocketState, TcpStateMatcher, UdpSocketMatcher,
85    UdpSocketProperties, UdpSocketState, UdpStateMatcher,
86};
87pub use num::PositiveIsize;
88pub use packet::{
89    ChecksumOffloadResult, ChecksumOffloadSpec, ChecksumRxOffloading,
90    DynamicNetworkPartialSerializer, DynamicNetworkSerializer, NetworkParsingContext,
91    NetworkPartialSerializer, NetworkSerializationContext, NetworkSerializer,
92    ProtocolSpecificOffloadSpec,
93};
94pub use port_alloc::{EphemeralPort, PortAllocImpl, simple_randomized_port_alloc};
95pub use resource_references::{
96    DeferredResourceRemovalContext, ReferenceNotifiers, ReferenceNotifiersExt,
97    RemoveResourceResult, RemoveResourceResultWithContext,
98};
99
100pub use rng::RngContext;
101pub use settings::{BufferSizeSettings, SettingsContext};
102pub use socket::SocketDiagnosticsSeed;
103pub use tcp::base::{Control, EffectiveMss, FragmentedPayload, Mss, MssSizeLimiters};
104pub use tcp::segment::{
105    HandshakeOptions, MalformedFlags, Options, Payload, PayloadLen, ResetOptions, SackBlock,
106    SackBlocks, Segment, SegmentHeader, SegmentOptions, VerifiedTcpSegment,
107};
108pub use tcp::seqnum::{SeqNum, UnscaledWindowSize, WindowScale, WindowSize};
109pub use tcp::timestamp::{
110    Milliseconds, RxTimestampOption, Timestamp, TimestampOption, TxTimestampOption, Unitless,
111};
112pub use test_only::TestOnlyPartialEq;
113pub use time::local_timer_heap::LocalTimerHeap;
114pub use time::{
115    AtomicInstant, CoreTimerContext, HandleableTimer, Instant, InstantBindingsTypes,
116    InstantContext, IntoCoreTimerCtx, NestedIntoCoreTimerCtx, TimerBindingsTypes, TimerContext,
117    TimerHandler,
118};
119pub use uninstantiable::{Uninstantiable, UninstantiableWrapper};
120pub use work_queue::WorkQueueReport;
121
122/// Reference counted hash map data structure.
123pub mod ref_counted_hash_map {
124    pub use crate::data_structures::ref_counted_hash_map::{
125        InsertResult, RefCountedHashMap, RefCountedHashSet, RemoveResult,
126    };
127}
128
129/// Common types and utilities for sockets.
130pub mod socket {
131    mod address;
132    mod base;
133    mod cookie;
134    pub(crate) mod sndbuf;
135
136    pub use address::{
137        AddrIsMappedError, AddrVecIter, ConnAddr, ConnInfoAddr, ConnIpAddr, DualStackConnIpAddr,
138        DualStackListenerIpAddr, DualStackLocalIp, DualStackRemoteIp, IpAddrVec, ListenerAddr,
139        ListenerIpAddr, SocketIpAddr, StrictlyZonedAddr,
140    };
141    pub use base::{
142        AddrEntry, AddrVec, Bound, BoundSocketMap, DualStackIpExt, DualStackTuple, EitherIpProto,
143        EitherStack, FoundSockets, IncompatibleError, InsertError, Inserter, Listener,
144        ListenerAddrInfo, MaybeDualStack, NotDualStackCapableError, RemoveResult, ReusePortOption,
145        SetDualStackEnabledError, SharingDomain, Shutdown, ShutdownType, SocketAddrType,
146        SocketDeviceUpdate, SocketDeviceUpdateNotAllowedError, SocketDiagnosticsSeed, SocketInfo,
147        SocketIpAddrExt, SocketIpExt, SocketMapAddrSpec, SocketMapAddrStateSpec,
148        SocketMapAddrStateUpdateSharingSpec, SocketMapConflictPolicy, SocketMapStateSpec,
149        SocketMapUpdateSharingPolicy, SocketStateEntry, SocketZonedAddrExt, UpdateSharingError,
150    };
151    pub use cookie::SocketCookie;
152    pub use sndbuf::{
153        SendBufferFullError, SendBufferSpace, SendBufferTracking, SocketWritableListener,
154    };
155}
156
157/// Defines generic data structures used to implement common application socket
158/// functionality for multiple protocols.
159pub mod socketmap {
160    pub use crate::data_structures::socketmap::{
161        Entry, IterShadows, OccupiedEntry, SocketMap, Tagged, VacantEntry,
162    };
163}
164
165/// Sync utilities common to netstack3.
166#[path = "."]
167pub mod sync {
168    // TODO(https://fxbug.dev/42062225): Support single-threaded variants of
169    // types exported from this module.
170
171    mod sync;
172
173    pub use netstack3_sync::once::{Once, OnceLock};
174    pub use netstack3_sync::rc::{
175        DebugReferences, DynDebugReferences, MapNotifier as MapRcNotifier, Notifier as RcNotifier,
176        Primary as PrimaryRc, ResourceToken, ResourceTokenValue, Strong as StrongRc,
177        Weak as WeakRc,
178    };
179    pub use netstack3_sync::{LockGuard, Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard};
180    pub use sync::BindingsSyncTypes;
181
182    #[cfg(any(test, feature = "testutils"))]
183    pub use sync::lock_impl;
184}
185
186pub use sync::BindingsSyncTypes;
187
188/// Test utilities provided to all crates.
189#[cfg(any(test, feature = "testutils"))]
190pub mod testutil {
191    mod addr;
192    mod benchmarks;
193    mod fake_bindings;
194    mod fake_core;
195    mod fake_network;
196    mod misc;
197    mod monotonic_id;
198    mod send_token;
199
200    pub use crate::device::address::testutil::FakeWeakAddressId;
201    pub use crate::device::link::testutil::{FakeLinkAddress, FakeLinkDevice, FakeLinkDeviceId};
202    pub use crate::device::testutil::{
203        FakeDeviceClass, FakeDeviceId, FakeReferencyDeviceId, FakeStrongDeviceId, FakeWeakDeviceId,
204        MultipleDevicesId, MultipleDevicesIdState,
205    };
206    pub use crate::event::testutil::FakeEventCtx;
207    pub use crate::frame::testutil::{FakeFrameCtx, FakeTxMetadata, WithFakeFrameContext};
208    pub use crate::matchers::testutil::FakeMatcherDeviceId;
209    pub use crate::rng::testutil::{FakeCryptoRng, new_rng, run_with_many_seeds};
210    pub use crate::settings::testutil::AlwaysDefaultsSettingsContext;
211    pub use crate::socket::sndbuf::testutil::FakeSocketWritableListener;
212    pub use crate::sync::lock_impl;
213    pub use crate::time::testutil::{
214        FakeAtomicInstant, FakeInstant, FakeInstantCtx, FakeTimerCtx, FakeTimerCtxExt, FakeTimerId,
215        InstantAndData, WithFakeTimerContext,
216    };
217    pub use addr::{TEST_ADDRS_V4, TEST_ADDRS_V6, TestAddrs, TestDualStackIpExt, TestIpExt};
218    pub use benchmarks::{Bencher, RealBencher, TestBencher};
219    pub use fake_bindings::FakeBindingsCtx;
220    pub use fake_core::FakeCoreCtx;
221    pub use fake_network::{
222        FakeNetwork, FakeNetworkLinks, FakeNetworkSpec, PendingFrame, PendingFrameData, StepResult,
223    };
224    pub use misc::{assert_empty, set_logger_for_test};
225    pub use monotonic_id::MonotonicIdentifier;
226    pub use send_token::{FakeSendToken, FakeSendTokenTracker};
227}
228
229/// Benchmarks defined in the base crate.
230#[cfg(benchmark)]
231pub mod benchmarks {
232    /// Adds benchmarks defined in the base crate to the provided benchmarker.
233    pub fn add_benches(
234        group: &mut criterion::BenchmarkGroup<'_, criterion::measurement::WallTime>,
235    ) {
236        crate::data_structures::token_bucket::benchmarks::add_benches(group)
237    }
238}