rustbgpd_wire/lib.rs
1//! rustbgpd-wire — BGP message codec
2//!
3//! Pure codec library for BGP message encoding and decoding.
4//! Zero internal dependencies. This crate is independently publishable.
5//!
6//! # Message Types
7//!
8//! - [`OpenMessage`] — BGP OPEN with capability negotiation
9//! - [`NotificationMessage`] — BGP NOTIFICATION with error codes
10//! - [`UpdateMessage`] — BGP UPDATE (wire-level framing, raw bytes in M0)
11//! - `Keepalive` — represented as [`Message::Keepalive`] unit variant
12//!
13//! # Entry Points
14//!
15//! - [`decode_message`] — decode a complete BGP message from bytes
16//! - [`encode_message`] — encode a BGP message to bytes
17//! - [`peek_message_length`] — check if a
18//! complete message is available (for transport framing)
19//!
20//! # Invariants
21//!
22//! - Maximum message size: 4096 bytes (RFC 4271 §4.1)
23//! - No panics on malformed input — all paths return `Result`
24//! - No `unsafe` code
25
26#![deny(unsafe_code)]
27#![deny(clippy::all)]
28#![warn(clippy::pedantic)]
29
30/// Path attribute types and codec (`ORIGIN`, `AS_PATH`, `NEXT_HOP`, etc.).
31pub mod attribute;
32/// BGP capability negotiation types and codec (RFC 5492).
33pub mod capability;
34/// Wire-format constants: markers, lengths, type codes.
35pub mod constants;
36/// Decode and encode error types.
37pub mod error;
38/// EVPN NLRI types and codec (RFC 7432 + RFC 9136).
39pub mod evpn;
40/// FlowSpec NLRI types and codec (RFC 8955 / RFC 8956).
41pub mod flowspec;
42/// BGP message header codec (RFC 4271 §4.1).
43pub mod header;
44/// KEEPALIVE message encoding and validation.
45pub mod keepalive;
46/// Top-level BGP message enum and codec dispatch.
47pub mod message;
48/// NLRI prefix types and codec (IPv4, IPv6, Add-Path).
49pub mod nlri;
50/// NOTIFICATION error codes, subcodes, and shutdown communication.
51pub mod notification;
52/// NOTIFICATION message struct and codec.
53pub mod notification_msg;
54/// OPEN message struct and codec.
55pub mod open;
56/// PMSI Tunnel path attribute (RFC 6514 §5) — used by EVPN Type 3 IMET
57/// for ingress-replication BUM.
58pub mod pmsi;
59/// ROUTE-REFRESH message struct and codec (RFC 2918 / RFC 7313).
60pub mod route_refresh;
61/// UPDATE message struct, codec, and builder.
62pub mod update;
63/// UPDATE attribute semantic validation (RFC 4271 §6.3).
64pub mod validate;
65
66// Re-export primary public API
67pub use capability::{
68 AddPathFamily, AddPathMode, Afi, Capability, ExtendedNextHopFamily, GracefulRestartFamily,
69 LlgrFamily, Safi,
70};
71pub use constants::{EXTENDED_MAX_MESSAGE_LEN, MAX_MESSAGE_LEN};
72pub use error::{DecodeError, EncodeError};
73pub use header::{BgpHeader, MessageType, peek_message_length};
74pub use message::{Message, decode_message, encode_message, encode_message_with_limit};
75pub use notification::NotificationCode;
76pub use notification_msg::NotificationMessage;
77pub use open::OpenMessage;
78pub use route_refresh::{RouteRefreshMessage, RouteRefreshSubtype};
79pub use update::{Ipv4UnicastMode, UpdateMessage};
80
81// ── Routing-domain result enums ──────────────────────────────────────
82//
83// `RpkiValidation` and `AspaValidation` are routing-domain concepts, not
84// wire-format types. They live here because the wire crate is the current
85// lowest common dependency shared by rib, policy, and transport — avoiding
86// a rib → rpki dependency edge. If more shared non-wire types accumulate,
87// extract them into a dedicated domain-types crate.
88
89/// RPKI origin validation state per RFC 6811.
90#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
91pub enum RpkiValidation {
92 /// A VRP covers the prefix and the origin AS matches.
93 Valid,
94 /// A VRP covers the prefix but the origin AS does not match.
95 Invalid,
96 /// No VRP covers the prefix.
97 #[default]
98 NotFound,
99}
100
101impl std::fmt::Display for RpkiValidation {
102 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103 match self {
104 Self::Valid => write!(f, "valid"),
105 Self::Invalid => write!(f, "invalid"),
106 Self::NotFound => write!(f, "not_found"),
107 }
108 }
109}
110
111impl std::str::FromStr for RpkiValidation {
112 type Err = String;
113
114 fn from_str(s: &str) -> Result<Self, Self::Err> {
115 match s {
116 "valid" => Ok(Self::Valid),
117 "invalid" => Ok(Self::Invalid),
118 "not_found" => Ok(Self::NotFound),
119 other => Err(format!(
120 "unknown RPKI validation state {other:?}, expected \"valid\", \"invalid\", or \"not_found\""
121 )),
122 }
123 }
124}
125
126/// ASPA path verification state per draft-ietf-sidrops-aspa-verification.
127#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
128pub enum AspaValidation {
129 /// All hops in the `AS_PATH` have authorized provider relationships.
130 Valid,
131 /// At least one hop has a proven unauthorized provider relationship.
132 Invalid,
133 /// Verification could not complete due to missing ASPA records.
134 #[default]
135 Unknown,
136}
137
138impl std::fmt::Display for AspaValidation {
139 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140 match self {
141 Self::Valid => write!(f, "valid"),
142 Self::Invalid => write!(f, "invalid"),
143 Self::Unknown => write!(f, "unknown"),
144 }
145 }
146}
147
148impl std::str::FromStr for AspaValidation {
149 type Err = String;
150
151 fn from_str(s: &str) -> Result<Self, Self::Err> {
152 match s {
153 "valid" => Ok(Self::Valid),
154 "invalid" => Ok(Self::Invalid),
155 "unknown" => Ok(Self::Unknown),
156 other => Err(format!(
157 "unknown ASPA validation state {other:?}, expected \"valid\", \"invalid\", or \"unknown\""
158 )),
159 }
160 }
161}
162
163// Re-export attribute types
164pub use attribute::{
165 AsPath, AsPathSegment, ExtendedCommunity, LargeCommunity, MpReachNlri, MpUnreachNlri, Origin,
166 PathAttribute, RawAttribute, is_private_asn,
167};
168pub use nlri::{Ipv4NlriEntry, Ipv4Prefix, Ipv6Prefix, NlriEntry, Prefix};
169pub use pmsi::{PmsiTunnel, PmsiTunnelIdentifier, PmsiTunnelType};
170pub use update::ParsedUpdate;
171pub use validate::{UpdateError, is_valid_ipv6_nexthop};
172
173// Re-export FlowSpec types
174pub use flowspec::{
175 BitmaskMatch, FlowSpecAction, FlowSpecComponent, FlowSpecPrefix, FlowSpecRule,
176 Ipv6PrefixOffset, NumericMatch,
177};
178
179// Re-export EVPN types
180pub use evpn::{
181 EthernetSegmentIdentifier, EthernetTagId, EvpnEadPerEs, EvpnEadPerEvi, EvpnEs, EvpnImet,
182 EvpnIpPrefixRoute, EvpnIpPrefixValue, EvpnMacIp, EvpnRoute, EvpnRouteKey, MacAddress,
183 MplsLabel, RouteDistinguisher, RouteDistinguisherParseError, decode_evpn_nlri,
184 encode_evpn_nlri,
185};
186
187// Well-known communities (RFC 1997 + RFC 7999 + RFC 8326 + RFC 9494)
188/// `NO_EXPORT` community (RFC 1997): routes carrying this community must not
189/// be advertised outside a BGP confederation boundary.
190pub const COMMUNITY_NO_EXPORT: u32 = 0xFFFF_FF01;
191/// `NO_ADVERTISE` community (RFC 1997): routes carrying this community must
192/// not be advertised to any other BGP peer.
193pub const COMMUNITY_NO_ADVERTISE: u32 = 0xFFFF_FF02;
194/// `NO_EXPORT_SUBCONFED` community (RFC 1997): routes carrying this community
195/// must not be advertised to external BGP peers, including confederation
196/// external peers.
197pub const COMMUNITY_NO_EXPORT_SUBCONFED: u32 = 0xFFFF_FF03;
198/// `BLACKHOLE` community (RFC 7999 §5): advisory signal that traffic destined
199/// toward the tagged prefix should be discarded by receivers that explicitly
200/// opted in to honoring the request.
201pub const COMMUNITY_BLACKHOLE: u32 = 0xFFFF_029A;
202/// `GRACEFUL_SHUTDOWN` community (RFC 8326 §3): tags routes on a session
203/// being brought down for maintenance so receivers de-prefer them by
204/// setting `LOCAL_PREF` to a low value (canonical: 0).
205pub const COMMUNITY_GRACEFUL_SHUTDOWN: u32 = 0xFFFF_0000;
206/// `LLGR_STALE` community (RFC 9494 §4.6): marks a route as long-lived stale.
207pub const COMMUNITY_LLGR_STALE: u32 = 0xFFFF_0006;
208/// `NO_LLGR` community (RFC 9494 §4.7): this route must not enter LLGR stale phase.
209pub const COMMUNITY_NO_LLGR: u32 = 0xFFFF_0007;
210
211// Re-export RPKI types
212// (RpkiValidation is defined above in this file)
213
214#[cfg(test)]
215mod well_known_community_tests {
216 use super::*;
217
218 /// Pins the spec-mandated well-known community values. A refactor that
219 /// accidentally renames or repurposes these constants is silently
220 /// behavior-preserving at the type level — this test makes the value
221 /// drift loud.
222 #[test]
223 fn well_known_community_values_match_specs() {
224 assert_eq!(COMMUNITY_NO_EXPORT, 0xFFFF_FF01, "RFC 1997");
225 assert_eq!(COMMUNITY_NO_ADVERTISE, 0xFFFF_FF02, "RFC 1997");
226 assert_eq!(COMMUNITY_NO_EXPORT_SUBCONFED, 0xFFFF_FF03, "RFC 1997");
227 assert_eq!(COMMUNITY_BLACKHOLE, 0xFFFF_029A, "RFC 7999 §5");
228 assert_eq!(COMMUNITY_GRACEFUL_SHUTDOWN, 0xFFFF_0000, "RFC 8326 §3");
229 assert_eq!(COMMUNITY_LLGR_STALE, 0xFFFF_0006, "RFC 9494 §4.6");
230 assert_eq!(COMMUNITY_NO_LLGR, 0xFFFF_0007, "RFC 9494 §4.7");
231 }
232}