crafter 0.3.1

Packet-level network interaction for Rust tools and agents.
Documentation
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
//! Border Gateway Protocol version 4 (BGP-4, RFC 4271) support.
//!
//! This module provides packet-layer construction and decoding for BGP-4
//! messages. Types and constants are added incrementally; the [`Bgp`] layer
//! implements the [`Layer`] trait for the currently modeled BGP message bodies.

mod constants;

pub mod attribute;
pub mod capability;
pub mod decode;
pub mod message;

// Re-export the populated BGP codepoint constants at the module root.
pub use capability::{BgpCapability, BgpOptParam, BGP_OPT_PARAM_CAPABILITIES};
pub use constants::*;
pub use message::{BgpNotification, BgpOpen, BgpRouteRefresh, BgpUpdate};

use crate::packet::{Layer, LayerContext};
use crate::protocols::transport::common::{impl_layer_div, impl_layer_object};
use crate::Result;

use self::attribute::{BgpAttrValue, BgpPathAttribute, BgpPrefix};
use self::message::{notification_name, BgpHeader};

/// Human-readable name for a BGP message Type code (IANA `bgp-parameters-1`).
///
/// Maps the `BGP_TYPE_*` constants to their canonical names for `summary()` and
/// inspection output. An unmodelled or reserved code resolves to `"UNKNOWN"` so
/// decoded messages stay inspectable rather than surfacing a bare number.
fn message_type_name(message_type: u8) -> &'static str {
    match message_type {
        BGP_TYPE_OPEN => "OPEN",
        BGP_TYPE_UPDATE => "UPDATE",
        BGP_TYPE_NOTIFICATION => "NOTIFICATION",
        BGP_TYPE_KEEPALIVE => "KEEPALIVE",
        BGP_TYPE_ROUTE_REFRESH => "ROUTE-REFRESH",
        _ => "UNKNOWN",
    }
}

fn afi_name(afi: u16) -> String {
    match afi {
        AFI_IPV4 => "ipv4".to_string(),
        AFI_IPV6 => "ipv6".to_string(),
        _ => format!("afi-{afi}"),
    }
}

fn safi_name(safi: u8) -> String {
    match safi {
        SAFI_UNICAST => "unicast".to_string(),
        SAFI_MULTICAST => "multicast".to_string(),
        _ => format!("safi-{safi}"),
    }
}

fn capability_name(capability: &BgpCapability) -> String {
    match capability.code {
        CAP_MULTIPROTOCOL => match capability.multiprotocol_afi_safi() {
            Ok((afi, safi)) => format!("mp-{}-{}", afi_name(afi), safi_name(safi)),
            Err(_) => "multiprotocol".to_string(),
        },
        CAP_ROUTE_REFRESH => "route-refresh".to_string(),
        CAP_GRACEFUL_RESTART => "graceful-restart".to_string(),
        CAP_FOUR_OCTET_AS => "4-octet-as".to_string(),
        CAP_ADD_PATH => "add-path".to_string(),
        CAP_ENHANCED_ROUTE_REFRESH => "enhanced-route-refresh".to_string(),
        CAP_ROUTE_REFRESH_OLD => "route-refresh-old".to_string(),
        code => format!("cap-{code}"),
    }
}

fn capability_list_summary(capabilities: &[BgpCapability]) -> String {
    let names = capabilities
        .iter()
        .map(capability_name)
        .collect::<Vec<_>>()
        .join(", ");
    format!("[{names}]")
}

fn prefix_summary(prefix: &BgpPrefix) -> String {
    if prefix.length <= 32 && prefix.prefix.len() <= 4 {
        let mut octets = [0; 4];
        octets[..prefix.prefix.len()].copy_from_slice(&prefix.prefix);
        return format!("{}/{}", std::net::Ipv4Addr::from(octets), prefix.length);
    }

    format!("prefix-{}({}b)", prefix.length, prefix.prefix.len())
}

fn prefix_list_summary(prefixes: &[BgpPrefix]) -> String {
    let values = prefixes
        .iter()
        .map(prefix_summary)
        .collect::<Vec<_>>()
        .join(", ");
    format!("[{values}]")
}

fn attribute_summary(attribute: &BgpPathAttribute) -> String {
    match &attribute.value {
        BgpAttrValue::Origin(_)
        | BgpAttrValue::AsPath { .. }
        | BgpAttrValue::As4Path(_)
        | BgpAttrValue::NextHop(_)
        | BgpAttrValue::MultiExitDisc(_)
        | BgpAttrValue::LocalPref(_)
        | BgpAttrValue::AtomicAggregate
        | BgpAttrValue::Aggregator { .. }
        | BgpAttrValue::As4Aggregator { .. }
        | BgpAttrValue::Communities(_)
        | BgpAttrValue::ExtendedCommunities(_)
        | BgpAttrValue::LargeCommunities(_)
        | BgpAttrValue::MpReachNlri { .. }
        | BgpAttrValue::MpUnreachNlri { .. } => attribute.summary(),
        BgpAttrValue::Unknown(value) => format!("attr-{}({}b)", attribute.type_code, value.len()),
    }
}

fn attribute_list_summary(attributes: &[BgpPathAttribute]) -> String {
    let values = attributes
        .iter()
        .map(attribute_summary)
        .collect::<Vec<_>>()
        .join(", ");
    format!("[{values}]")
}

/// The body of a BGP-4 message (RFC 4271 §4), following the shared 19-octet
/// header.
///
/// KEEPALIVE (RFC 4271 §4.4) is header-only, so its variant carries no fields.
/// OPEN carries its fixed RFC 4271 §4.2 fields and raw optional parameters for
/// capabilities. UPDATE is added in later steps. The [`BgpBody::Unknown`]
/// variant preserves the raw body of a message type the builder/decoder does
/// not model, keeping the bytes verbatim rather than discarding them.
#[derive(Debug, Clone)]
pub(crate) enum BgpBody {
    /// OPEN message (RFC 4271 §4.2).
    Open(BgpOpen),
    /// NOTIFICATION message (RFC 4271 §4.5).
    Notification(BgpNotification),
    /// UPDATE message (RFC 4271 §4.3).
    Update(BgpUpdate),
    /// ROUTE-REFRESH message (RFC 2918).
    RouteRefresh(BgpRouteRefresh),
    /// KEEPALIVE message (RFC 4271 §4.4): the header alone, no body.
    Keepalive,
    /// A message body the layer does not (yet) model, preserved verbatim.
    #[allow(dead_code)]
    Unknown {
        /// The BGP message Type code this body belongs to.
        type_code: u8,
        /// The raw body bytes following the 19-octet header.
        body: Vec<u8>,
    },
}

impl BgpBody {
    /// The on-wire length of this body, in octets (the bytes after the header).
    fn encoded_len(&self) -> usize {
        match self {
            BgpBody::Open(open) => open.body_len(),
            BgpBody::Notification(notification) => notification.body_len(),
            BgpBody::Update(update) => update.encoded_len(),
            BgpBody::RouteRefresh(route_refresh) => route_refresh.body_len(),
            BgpBody::Keepalive => 0,
            BgpBody::Unknown { body, .. } => body.len(),
        }
    }

    /// Append this body's bytes to `out` (none for KEEPALIVE).
    fn write_body(&self, out: &mut Vec<u8>) {
        match self {
            BgpBody::Open(open) => open.write_body(out),
            BgpBody::Notification(notification) => notification.write_body(out),
            BgpBody::Update(update) => update.write_body(out),
            BgpBody::RouteRefresh(route_refresh) => route_refresh.write_body(out),
            BgpBody::Keepalive => {}
            BgpBody::Unknown { body, .. } => out.extend_from_slice(body),
        }
    }
}

/// BGP-4 message layer (RFC 4271).
///
/// A `Bgp` layer is the shared 19-octet message header followed by a typed
/// body. `compile()` writes the header - auto-filling the
/// Length field from the body size unless the caller pinned it — then the body
/// bytes. KEEPALIVE (RFC 4271 §4.4) is header-only, so `Bgp::keepalive()`
/// compiles to exactly the 19-octet header.
#[derive(Debug, Clone)]
pub struct Bgp {
    /// The shared 19-octet BGP message header (Marker, Length, Type).
    header: BgpHeader,
    /// The typed message body following the header.
    body: BgpBody,
}

impl Bgp {
    /// Build an OPEN message (RFC 4271 §4.2).
    ///
    /// The header Type defaults to [`BGP_TYPE_OPEN`]. The body defaults to
    /// BGP-4 and empty optional parameters; other OPEN fields are filled through
    /// the chainable setters.
    pub fn open() -> Self {
        Self {
            header: BgpHeader::new(BGP_TYPE_OPEN),
            body: BgpBody::Open(BgpOpen::new()),
        }
    }

    /// Build a KEEPALIVE message (RFC 4271 §4.4).
    ///
    /// The header Type defaults to [`BGP_TYPE_KEEPALIVE`] and the Length is left
    /// unset so `compile()` fills it with the 19-octet header length (KEEPALIVE
    /// has no body). Composing `Packet::from_layer(Bgp::keepalive())` therefore
    /// compiles to exactly 19 octets.
    pub fn keepalive() -> Self {
        Self {
            header: BgpHeader::new(BGP_TYPE_KEEPALIVE),
            body: BgpBody::Keepalive,
        }
    }

    /// Build a NOTIFICATION message (RFC 4271 §4.5).
    ///
    /// The header Type defaults to [`BGP_TYPE_NOTIFICATION`]. The body carries
    /// the caller-supplied error code and subcode, followed by optional data
    /// set through [`Bgp::data`].
    pub fn notification(error_code: u8, error_subcode: u8) -> Self {
        Self {
            header: BgpHeader::new(BGP_TYPE_NOTIFICATION),
            body: BgpBody::Notification(BgpNotification::new(error_code, error_subcode)),
        }
    }

    /// Build an UPDATE message (RFC 4271 §4.3).
    ///
    /// The header Type defaults to [`BGP_TYPE_UPDATE`]. The body starts empty:
    /// zero withdrawn routes, zero path attributes, and zero NLRI prefixes.
    pub fn update() -> Self {
        Self {
            header: BgpHeader::new(BGP_TYPE_UPDATE),
            body: BgpBody::Update(BgpUpdate::new()),
        }
    }

    /// Build a Cease NOTIFICATION with no subcode-specific detail.
    pub fn cease() -> Self {
        Self::notification(NOTIFY_CEASE, 0)
    }

    /// Build a ROUTE-REFRESH message (RFC 2918) for the given AFI/SAFI pair.
    pub fn route_refresh(afi: u16, safi: u8) -> Self {
        Self {
            header: BgpHeader::new(BGP_TYPE_ROUTE_REFRESH),
            body: BgpBody::RouteRefresh(BgpRouteRefresh::new(afi, safi)),
        }
    }

    /// Force the shared BGP Marker field.
    ///
    /// This preserves malformed-on-purpose messages whose Marker is not the
    /// default all-ones value.
    pub fn marker(mut self, marker: [u8; BGP_MARKER_LEN]) -> Self {
        self.header.set_marker(marker);
        self
    }

    /// Force the shared BGP message Length field.
    ///
    /// This preserves malformed-on-purpose messages whose declared length
    /// disagrees with the emitted body bytes.
    pub fn length(mut self, length: u16) -> Self {
        self.header.set_length(length);
        self
    }

    /// Set the OPEN version field.
    pub fn version(mut self, version: u8) -> Self {
        if let BgpBody::Open(open) = &mut self.body {
            open.version.set_user(version);
        }
        self
    }

    /// Set the OPEN My Autonomous System field.
    pub fn my_as(mut self, my_as: u16) -> Self {
        if let BgpBody::Open(open) = &mut self.body {
            open.my_as.set_user(my_as);
        }
        self
    }

    /// Set the OPEN Hold Time field, in seconds.
    pub fn hold_time(mut self, hold_time: u16) -> Self {
        if let BgpBody::Open(open) = &mut self.body {
            open.hold_time.set_user(hold_time);
        }
        self
    }

    /// Set the OPEN BGP Identifier field.
    pub fn bgp_id(mut self, bgp_id: impl Into<std::net::Ipv4Addr>) -> Self {
        if let BgpBody::Open(open) = &mut self.body {
            open.bgp_id.set_user(bgp_id.into());
        }
        self
    }

    /// Force the OPEN optional-parameters length field.
    ///
    /// This preserves malformed-on-purpose OPEN messages whose declared
    /// optional-parameters length differs from the emitted parameter bytes.
    pub fn opt_params_len(mut self, opt_params_len: u8) -> Self {
        if let BgpBody::Open(open) = &mut self.body {
            open.opt_params_len.set_user(opt_params_len);
        }
        self
    }

    /// Append an OPEN optional parameter.
    pub fn push_param(mut self, param: BgpOptParam) -> Self {
        if let BgpBody::Open(open) = &mut self.body {
            open.push_param(param);
        }
        self
    }

    /// Append an OPEN optional parameter with a raw type code and value.
    pub fn raw_param(mut self, param_type: u8, value: Vec<u8>) -> Self {
        if let BgpBody::Open(open) = &mut self.body {
            open.raw_param(param_type, value);
        }
        self
    }

    /// Append one OPEN capabilities optional parameter.
    pub fn capabilities(mut self, capabilities: impl IntoIterator<Item = BgpCapability>) -> Self {
        if let BgpBody::Open(open) = &mut self.body {
            open.capabilities(capabilities);
        }
        self
    }

    /// Set the NOTIFICATION data field.
    pub fn data(mut self, data: Vec<u8>) -> Self {
        if let BgpBody::Notification(notification) = &mut self.body {
            notification.data = data;
        }
        self
    }

    /// Append a withdrawn-route prefix to an UPDATE.
    pub fn withdraw(mut self, prefix: BgpPrefix) -> Self {
        if let BgpBody::Update(update) = &mut self.body {
            update.withdrawn.push(prefix);
        }
        self
    }

    /// Force the UPDATE Withdrawn Routes Length field.
    ///
    /// This preserves malformed-on-purpose UPDATEs whose declared withdrawn
    /// routes length differs from the emitted withdrawn route bytes.
    pub fn withdrawn_len(mut self, withdrawn_len: u16) -> Self {
        if let BgpBody::Update(update) = &mut self.body {
            update.withdrawn_len.set_user(withdrawn_len);
        }
        self
    }

    /// Append a path attribute to an UPDATE.
    pub fn attribute(mut self, attribute: BgpPathAttribute) -> Self {
        if let BgpBody::Update(update) = &mut self.body {
            update.attributes.push(attribute);
        }
        self
    }

    /// Force the UPDATE Total Path Attribute Length field.
    ///
    /// This preserves malformed-on-purpose UPDATEs whose declared attribute
    /// length differs from the emitted path attribute bytes.
    pub fn attr_len(mut self, attr_len: u16) -> Self {
        if let BgpBody::Update(update) = &mut self.body {
            update.attr_len.set_user(attr_len);
        }
        self
    }

    /// Append an NLRI prefix to an UPDATE.
    pub fn nlri(mut self, prefix: BgpPrefix) -> Self {
        if let BgpBody::Update(update) = &mut self.body {
            update.nlri.push(prefix);
        }
        self
    }

    /// Set the ROUTE-REFRESH reserved byte / RFC 7313 subtype.
    pub fn subtype(mut self, subtype: u8) -> Self {
        if let BgpBody::RouteRefresh(route_refresh) = &mut self.body {
            route_refresh.subtype.set_user(subtype);
        }
        self
    }

    /// Build a `Bgp` layer from decoded wire fields.
    ///
    /// The header is reconstructed from the observed marker, length, and type
    /// (every field marked caller-supplied so re-compiling preserves the bytes
    /// exactly), and the typed `body` is the decoded message body. Used by the
    /// decode path so a round-trip through `decode_bgp_message` reproduces the
    /// original bytes.
    pub(crate) fn from_decoded_parts(
        marker: [u8; BGP_MARKER_LEN],
        length: u16,
        message_type: u8,
        body: BgpBody,
    ) -> Self {
        Self {
            header: BgpHeader::from_decoded_parts(marker, length, message_type),
            body,
        }
    }
}

impl Layer for Bgp {
    fn name(&self) -> &'static str {
        "BGP"
    }

    fn summary(&self) -> String {
        // The effective length over the current body — auto-filled from the body
        // size unless the caller pinned it. Dispatch on the body variant so later
        // message types extend this with their own fields.
        let len = self.header.effective_length(self.body.encoded_len());
        match &self.body {
            BgpBody::Open(open) => format!(
                "BGP {} version={} as={} hold={} id={} caps={}",
                message_type_name(BGP_TYPE_OPEN),
                open.version.value().copied().unwrap_or(BGP_VERSION),
                open.my_as.value().copied().unwrap_or(0),
                open.hold_time.value().copied().unwrap_or(0),
                open.bgp_id
                    .value()
                    .copied()
                    .unwrap_or(std::net::Ipv4Addr::UNSPECIFIED),
                capability_list_summary(&open.capabilities)
            ),
            BgpBody::Keepalive => {
                format!("BGP {} len={len}", message_type_name(BGP_TYPE_KEEPALIVE))
            }
            BgpBody::Notification(notification) => {
                let code = notification.error_code.value().copied().unwrap_or(0);
                let subcode = notification.error_subcode.value().copied().unwrap_or(0);
                format!(
                    "BGP {} {} data={} bytes",
                    message_type_name(BGP_TYPE_NOTIFICATION),
                    notification_name(code, subcode),
                    notification.data.len()
                )
            }
            BgpBody::Update(update) => format!(
                "BGP {} nlri={} withdrawn={} attrs={}",
                message_type_name(BGP_TYPE_UPDATE),
                prefix_list_summary(&update.nlri),
                prefix_list_summary(&update.withdrawn),
                attribute_list_summary(&update.attributes)
            ),
            BgpBody::RouteRefresh(route_refresh) => format!(
                "BGP {} afi={} safi={}",
                message_type_name(BGP_TYPE_ROUTE_REFRESH),
                route_refresh.afi.value().copied().unwrap_or(0),
                route_refresh.safi.value().copied().unwrap_or(0)
            ),
            BgpBody::Unknown { type_code, .. } => {
                format!("BGP {} len={len}", message_type_name(*type_code))
            }
        }
    }

    fn inspection_fields(&self) -> Vec<(&'static str, String)> {
        // Report the marker presence (all-ones per RFC 4271 §4.1, or modified for
        // a deliberately malformed message), the effective on-wire length, and the
        // message type name so decoded messages are readable without log-fishing.
        let marker = if self.header.effective_marker() == [0xFF; BGP_MARKER_LEN] {
            "all-ones".to_string()
        } else {
            "modified".to_string()
        };
        let len = self.header.effective_length(self.body.encoded_len());
        let mut fields = vec![
            ("marker", marker),
            ("length", len.to_string()),
            (
                "type",
                message_type_name(self.header.effective_type()).to_string(),
            ),
        ];

        if let BgpBody::Open(open) = &self.body {
            fields.push((
                "version",
                open.version
                    .value()
                    .copied()
                    .unwrap_or(BGP_VERSION)
                    .to_string(),
            ));
            fields.push((
                "my_as",
                open.my_as.value().copied().unwrap_or(0).to_string(),
            ));
            fields.push((
                "hold_time",
                open.hold_time.value().copied().unwrap_or(0).to_string(),
            ));
            fields.push((
                "bgp_id",
                open.bgp_id
                    .value()
                    .copied()
                    .unwrap_or(std::net::Ipv4Addr::UNSPECIFIED)
                    .to_string(),
            ));
            for capability in &open.capabilities {
                fields.push(("capability", capability_name(capability)));
            }
        }

        if let BgpBody::Notification(notification) = &self.body {
            let code = notification.error_code.value().copied().unwrap_or(0);
            let subcode = notification.error_subcode.value().copied().unwrap_or(0);
            fields.push(("error_code", code.to_string()));
            fields.push(("error_subcode", subcode.to_string()));
            fields.push(("data_length", notification.data.len().to_string()));
            fields.push(("error", notification_name(code, subcode)));
        }

        if let BgpBody::Update(update) = &self.body {
            fields.push(("withdrawn_routes", update.withdrawn.len().to_string()));
            fields.push(("withdrawn_length", update.withdrawn_len().to_string()));
            for prefix in &update.withdrawn {
                fields.push(("withdrawn_prefix", prefix_summary(prefix)));
            }
            fields.push(("path_attributes", update.attributes.len().to_string()));
            fields.push(("path_attribute_length", update.attributes_len().to_string()));
            for attribute in &update.attributes {
                fields.push(("path_attribute", attribute_summary(attribute)));
            }
            fields.push(("nlri", update.nlri.len().to_string()));
            for prefix in &update.nlri {
                fields.push(("nlri_prefix", prefix_summary(prefix)));
            }
        }

        if let BgpBody::RouteRefresh(route_refresh) = &self.body {
            fields.push((
                "afi",
                route_refresh.afi.value().copied().unwrap_or(0).to_string(),
            ));
            fields.push((
                "subtype",
                route_refresh
                    .subtype
                    .value()
                    .copied()
                    .unwrap_or(0)
                    .to_string(),
            ));
            fields.push((
                "safi",
                route_refresh.safi.value().copied().unwrap_or(0).to_string(),
            ));
        }

        fields
    }

    fn encoded_len(&self) -> usize {
        BGP_HEADER_LEN + self.body.encoded_len()
    }

    fn compile(&self, _ctx: &LayerContext<'_>, out: &mut Vec<u8>) -> Result<()> {
        // The header Length auto-fills from the body size unless the caller
        // pinned it; the body bytes (none for KEEPALIVE) follow the 19-octet
        // header.
        let body_len = self.body.encoded_len();
        self.header.write_header(body_len, out);
        self.body.write_body(out);
        Ok(())
    }

    impl_layer_object!(Bgp);
}

impl_layer_div!(Bgp);

/// BGP KEEPALIVE message (RFC 4271 §4.4). Placeholder stub; filled in a later step.
#[allow(dead_code)]
pub struct BgpKeepalive;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::packet::Packet;

    /// Confirms the BGP type names resolve through the public prelude path so
    /// generated tools can reach them via `use crafter::prelude::*;`.
    #[test]
    fn bgp_prelude_resolves() {
        let _ = core::mem::size_of::<crate::prelude::Bgp>();
    }

    #[test]
    fn keepalive_defaults_to_type_four() {
        let bgp = Bgp::keepalive();
        assert_eq!(bgp.name(), "BGP");
        assert!(matches!(bgp.body, BgpBody::Keepalive));
        assert_eq!(bgp.encoded_len(), BGP_HEADER_LEN);
    }

    #[test]
    fn open_builder_stores_values() {
        let bgp = Bgp::open()
            .version(4)
            .my_as(65000)
            .hold_time(90)
            .bgp_id([192, 0, 2, 1]);

        assert_eq!(bgp.header.effective_type(), BGP_TYPE_OPEN);
        match bgp.body {
            BgpBody::Open(open) => {
                assert_eq!(open.version.value(), Some(&BGP_VERSION));
                assert!(open.version.is_user_set());
                assert_eq!(open.my_as.value(), Some(&65000));
                assert!(open.my_as.is_user_set());
                assert_eq!(open.hold_time.value(), Some(&90));
                assert!(open.hold_time.is_user_set());
                assert_eq!(
                    open.bgp_id.value(),
                    Some(&std::net::Ipv4Addr::new(192, 0, 2, 1))
                );
                assert!(open.bgp_id.is_user_set());
                assert_eq!(open.opt_params_len.value(), None);
                assert!(open.params.is_empty());
                assert_eq!(open.body_len(), 10);
            }
            other => panic!("expected OPEN body, got {other:?}"),
        }
    }

    #[test]
    fn message_type_name_maps_known_and_unknown_codes() {
        assert_eq!(message_type_name(BGP_TYPE_OPEN), "OPEN");
        assert_eq!(message_type_name(BGP_TYPE_UPDATE), "UPDATE");
        assert_eq!(message_type_name(BGP_TYPE_NOTIFICATION), "NOTIFICATION");
        assert_eq!(message_type_name(BGP_TYPE_KEEPALIVE), "KEEPALIVE");
        assert_eq!(message_type_name(BGP_TYPE_ROUTE_REFRESH), "ROUTE-REFRESH");
        assert_eq!(message_type_name(0), "UNKNOWN");
        assert_eq!(message_type_name(99), "UNKNOWN");
    }

    #[test]
    fn keepalive_summary_reports_type_and_length() {
        let summary = Bgp::keepalive().summary();
        assert_eq!(summary, "BGP KEEPALIVE len=19");
    }

    #[test]
    fn open_summary_reports_as_and_capability_names() {
        let summary = Bgp::open()
            .my_as(65000)
            .hold_time(180)
            .bgp_id([192, 0, 2, 1])
            .capabilities([
                BgpCapability::ipv4_unicast(),
                BgpCapability::four_octet_as(65000),
                BgpCapability::route_refresh(),
            ])
            .summary();

        assert!(summary.contains("BGP OPEN"), "summary was: {summary}");
        assert!(summary.contains("as=65000"), "summary was: {summary}");
        assert!(
            summary.contains("mp-ipv4-unicast"),
            "summary was: {summary}"
        );
        assert!(summary.contains("4-octet-as"), "summary was: {summary}");
        assert!(summary.contains("route-refresh"), "summary was: {summary}");
    }

    #[test]
    fn open_inspection_fields_report_body_and_capabilities() {
        let fields = Bgp::open()
            .my_as(65000)
            .hold_time(180)
            .bgp_id([192, 0, 2, 1])
            .capabilities([
                BgpCapability::route_refresh(),
                BgpCapability::raw(200, Vec::new()),
            ])
            .inspection_fields();

        assert!(fields.contains(&("type", "OPEN".to_string())));
        assert!(fields.contains(&("version", "4".to_string())));
        assert!(fields.contains(&("my_as", "65000".to_string())));
        assert!(fields.contains(&("hold_time", "180".to_string())));
        assert!(fields.contains(&("bgp_id", "192.0.2.1".to_string())));
        assert!(fields.contains(&("capability", "route-refresh".to_string())));
        assert!(fields.contains(&("capability", "cap-200".to_string())));
    }

    #[test]
    fn keepalive_show_contains_keepalive() {
        let shown = Packet::from_layer(Bgp::keepalive()).show();

        // The inspection fields surface the marker presence, length, and the
        // message type name, so the rendered tree names the KEEPALIVE message.
        assert!(
            shown.contains("KEEPALIVE"),
            "show() should name the KEEPALIVE message, got:\n{shown}"
        );
        assert!(shown.contains("marker: all-ones"));
        assert!(shown.contains("length: 19"));
    }

    #[test]
    fn keepalive_compiles_to_nineteen_bytes() {
        let packet = Packet::from_layer(Bgp::keepalive());
        let bytes = packet.compile().unwrap();

        // KEEPALIVE is header-only: 16-octet marker (all ones), 2-octet length
        // (19, big-endian), 1-octet type (4). RFC 4271 §4.4.
        assert_eq!(bytes.len(), 19);
        assert_eq!(&bytes[..BGP_MARKER_LEN], &[0xFF; BGP_MARKER_LEN]);
        assert_eq!(
            &bytes[BGP_MARKER_LEN..BGP_MARKER_LEN + 2],
            &(BGP_HEADER_LEN as u16).to_be_bytes()
        );
        assert_eq!(bytes[BGP_MARKER_LEN + 2], BGP_TYPE_KEEPALIVE);
    }

    #[test]
    fn cease_notification_compiles_to_twenty_one_bytes() {
        let packet = Packet::from_layer(Bgp::cease());
        let bytes = packet.compile().unwrap();

        assert_eq!(bytes.len(), 21);
        assert_eq!(&bytes[..BGP_MARKER_LEN], &[0xFF; BGP_MARKER_LEN]);
        assert_eq!(
            &bytes[BGP_MARKER_LEN..BGP_MARKER_LEN + 2],
            &(21u16).to_be_bytes()
        );
        assert_eq!(bytes[BGP_MARKER_LEN + 2], BGP_TYPE_NOTIFICATION);
        assert_eq!(&bytes[BGP_HEADER_LEN..], &[NOTIFY_CEASE, 0]);
    }

    #[test]
    fn empty_update_compiles_to_twenty_three_bytes() {
        let packet = Packet::from_layer(Bgp::update());
        let bytes = packet.compile().unwrap();

        assert_eq!(bytes.len(), 23);
        assert_eq!(&bytes[..BGP_MARKER_LEN], &[0xFF; BGP_MARKER_LEN]);
        assert_eq!(
            &bytes[BGP_MARKER_LEN..BGP_MARKER_LEN + 2],
            &(23u16).to_be_bytes()
        );
        assert_eq!(bytes[BGP_MARKER_LEN + 2], BGP_TYPE_UPDATE);
        assert_eq!(&bytes[BGP_HEADER_LEN..], &[0, 0, 0, 0]);
    }

    #[test]
    fn update_announcement_compiles_with_attribute_lengths_and_order() {
        let origin = super::attribute::BgpPathAttribute::origin(super::attribute::BGP_ORIGIN_IGP);
        let as_path = super::attribute::BgpPathAttribute::as_sequence(&[65000]);
        let next_hop =
            super::attribute::BgpPathAttribute::next_hop(std::net::Ipv4Addr::new(192, 0, 2, 1));
        let nlri =
            super::attribute::BgpPrefix::from_ipv4(std::net::Ipv4Addr::new(203, 0, 113, 0), 24)
                .expect("valid documentation prefix");

        let mut attr_bytes = Vec::new();
        origin.encode(&mut attr_bytes);
        as_path.encode(&mut attr_bytes);
        next_hop.encode(&mut attr_bytes);
        assert_eq!(
            attr_bytes,
            [
                0x40, 0x01, 0x01, 0x00, 0x40, 0x02, 0x04, 0x02, 0x01, 0xfd, 0xe8, 0x40, 0x03, 0x04,
                0xc0, 0x00, 0x02, 0x01,
            ]
        );

        let mut nlri_bytes = Vec::new();
        nlri.encode_prefix(&mut nlri_bytes);
        assert_eq!(nlri_bytes, [0x18, 0xcb, 0x00, 0x71]);

        let bgp = Bgp::update()
            .attribute(origin)
            .attribute(as_path)
            .attribute(next_hop)
            .nlri(nlri);
        let expected_body_len = 2 + 2 + attr_bytes.len() + nlri_bytes.len();
        let expected_total_len = BGP_HEADER_LEN + expected_body_len;

        match &bgp.body {
            BgpBody::Update(update) => {
                assert_eq!(update.withdrawn_len(), 0);
                assert_eq!(update.attributes_len(), attr_bytes.len());
                assert_eq!(update.nlri_len(), nlri_bytes.len());
                assert_eq!(update.encoded_len(), expected_body_len);
            }
            other => panic!("expected UPDATE body, got {other:?}"),
        }
        assert_eq!(bgp.encoded_len(), expected_total_len);

        let bytes = Packet::from_layer(bgp).compile().unwrap();
        assert_eq!(bytes.len(), expected_total_len);
        assert_eq!(
            &bytes[BGP_MARKER_LEN..BGP_MARKER_LEN + 2],
            &(expected_total_len as u16).to_be_bytes()
        );
        assert_eq!(bytes[BGP_MARKER_LEN + 2], BGP_TYPE_UPDATE);

        let body = &bytes[BGP_HEADER_LEN..];
        assert_eq!(&body[..2], &0u16.to_be_bytes());
        assert_eq!(&body[2..4], &(attr_bytes.len() as u16).to_be_bytes());
        assert_eq!(&body[4..4 + attr_bytes.len()], attr_bytes.as_slice());
        assert_eq!(&body[4 + attr_bytes.len()..], nlri_bytes.as_slice());
    }

    #[test]
    fn update_summary_reports_prefixes_and_attributes() {
        let bgp = Bgp::update()
            .attribute(super::attribute::BgpPathAttribute::origin(
                super::attribute::BGP_ORIGIN_IGP,
            ))
            .attribute(super::attribute::BgpPathAttribute::as_sequence(&[65000]))
            .attribute(super::attribute::BgpPathAttribute::next_hop(
                std::net::Ipv4Addr::new(192, 0, 2, 1),
            ))
            .nlri(
                super::attribute::BgpPrefix::from_ipv4(std::net::Ipv4Addr::new(203, 0, 113, 0), 24)
                    .expect("valid documentation prefix"),
            );

        let summary = bgp.summary();
        assert!(summary.contains("203.0.113.0/24"), "summary was: {summary}");
        assert!(summary.contains("AS_PATH"), "summary was: {summary}");
        assert!(
            summary.contains("NEXT_HOP=192.0.2.1"),
            "summary was: {summary}"
        );

        let fields = bgp.inspection_fields();
        assert!(fields.contains(&("nlri", "1".to_string())));
        assert!(fields.contains(&("path_attributes", "3".to_string())));
        assert!(fields.contains(&("nlri_prefix", "203.0.113.0/24".to_string())));
        assert!(fields.contains(&("path_attribute", "AS_PATH=65000".to_string())));
    }

    #[test]
    fn update_internal_length_overrides_are_preserved() {
        let packet = Packet::from_layer(Bgp::update().withdrawn_len(7).attr_len(9));
        let bytes = packet.compile().unwrap();

        assert_eq!(bytes.len(), 23);
        assert_eq!(&bytes[BGP_HEADER_LEN..], &[0, 7, 0, 9]);
    }

    #[test]
    fn minimal_open_compiles_with_auto_lengths() {
        let packet = Packet::from_layer(
            Bgp::open()
                .version(4)
                .my_as(65000)
                .hold_time(180)
                .bgp_id([192, 0, 2, 1]),
        );
        let bytes = packet.compile().unwrap();

        assert_eq!(bytes.len(), 29);
        assert_eq!(&bytes[..BGP_MARKER_LEN], &[0xFF; BGP_MARKER_LEN]);
        assert_eq!(&bytes[BGP_MARKER_LEN..BGP_MARKER_LEN + 2], &[0x00, 0x1d]);
        assert_eq!(bytes[BGP_MARKER_LEN + 2], BGP_TYPE_OPEN);
        assert_eq!(
            &bytes[BGP_HEADER_LEN..],
            &[4, 0xfd, 0xe8, 0x00, 0xb4, 192, 0, 2, 1, 0]
        );
        assert_eq!(bytes[BGP_HEADER_LEN + 9], 0);
    }

    #[test]
    fn open_optional_parameters_length_override_is_preserved() {
        let packet = Packet::from_layer(
            Bgp::open()
                .my_as(65000)
                .hold_time(180)
                .bgp_id([192, 0, 2, 1])
                .opt_params_len(7),
        );
        let bytes = packet.compile().unwrap();

        assert_eq!(bytes[BGP_HEADER_LEN + 9], 7);
    }

    #[test]
    fn open_raw_optional_parameter_compiles_with_framing() {
        let packet = Packet::from_layer(
            Bgp::open()
                .my_as(65000)
                .hold_time(180)
                .bgp_id([192, 0, 2, 1])
                .raw_param(99, vec![0xaa, 0xbb, 0xcc]),
        );
        let bytes = packet.compile().unwrap();

        assert_eq!(bytes[BGP_HEADER_LEN + 9], 5);
        assert_eq!(&bytes[BGP_HEADER_LEN + 10..], &[99, 3, 0xaa, 0xbb, 0xcc]);
    }
}