routecore 0.7.1

A Library with Building Blocks for BGP Routing
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
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
//! BMP message parsing.
//!
//! This module contains functionality to parse BGP messages from raw bytes,
//! providing access to its contents based on the underlying `bytes` buffer
//! without allocating.

use inetnum::asn::Asn;
use crate::bgp::message::{Message as BgpMsg, OpenMessage as BgpOpen, UpdateMessage as BgpUpdate, NotificationMessage as BgpNotification};
use crate::bgp::types::{Afi, AfiSafiType};
use crate::bgp::message::update::{SessionConfig, FourOctetAsns};
use crate::bgp::message::open::CapabilityType;
use crate::util::parser::ParseError;
use crate::typeenum; // from util::macros

use bytes::Buf;
use chrono::{DateTime, LocalResult, TimeZone, Utc};
use log::warn;
use octseq::{Octets, Parser};


use std::error::Error;
use std::fmt::{Debug, Display, Formatter, Result as FmtResult};
use std::hash::Hash;
use std::io::Cursor;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};

#[cfg(feature = "serde")]
use serde::{Serialize, Deserialize};



// --- Error stuff, refactor this crate-wide after bgmp is merged ------------

/// Errors related to BMP messages.
#[derive(Debug)]
pub enum MessageError {
    Incomplete,
    IllegalSize,
    InvalidMsgType,
}

impl Display for MessageError {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        use MessageError::*;
        match self {
            Incomplete => write!(f, "incomplete message"),
            IllegalSize => write!(f, "illegaly sized message"),
            InvalidMsgType => write!(f, "invalid message type"),
        }
    }
}

impl Error for MessageError { }


/// Full BMP message.
/// 
/// The [`Message`] enum carries variants representing the full BMP Messages,
/// including the [`CommonHeader`], possibly a [`PerPeerHeader`] and the
/// additional payload. The payload often comprises one or multiple
/// [`bgp::Message`](crate::bgp::Message)s.
#[derive(Clone, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub enum Message<Octets: AsRef<[u8]>> {
    RouteMonitoring(RouteMonitoring<Octets>),
    StatisticsReport(StatisticsReport<Octets>),
    PeerDownNotification(PeerDownNotification<Octets>),
    PeerUpNotification(PeerUpNotification<Octets>),
    InitiationMessage(InitiationMessage<Octets>),
    TerminationMessage(TerminationMessage<Octets>),
    RouteMirroring(RouteMirroring<Octets>),
}

impl<Octs: AsRef<[u8]>, OtherOcts: AsRef<[u8]>> PartialEq<Message<OtherOcts>> for Message<Octs> {
    fn eq(&self, other: &Message<OtherOcts>) -> bool {
        self.as_ref().eq(other.as_ref())
    }
}

typeenum!(
    /// Types of BMP messages as defined in
    /// [RFC7854](https://datatracker.ietf.org/doc/html/rfc7854).
    MessageType, u8,
    {
        0 => RouteMonitoring,
        1 => StatisticsReport,
        2 => PeerDownNotification,
        3 => PeerUpNotification,
        4 => InitiationMessage,
        5 => TerminationMessage,
        6 => RouteMirroring,
    }
);


impl<Octets: AsRef<[u8]>> AsRef<[u8]> for InitiationMessage<Octets> {
    fn as_ref(&self) -> &[u8] {
        self.octets.as_ref()
    }
}

impl<Octets: AsRef<[u8]>> AsRef<[u8]> for TerminationMessage<Octets> {
    fn as_ref(&self) -> &[u8] {
        self.octets.as_ref()
    }
}


impl<Octets: AsRef<[u8]>> AsRef<[u8]> for StatisticsReport<Octets> {
    fn as_ref(&self) -> &[u8] {
        self.octets.as_ref()
    }
}

impl<Octets: AsRef<[u8]>> AsRef<[u8]> for PeerUpNotification<Octets> {
    fn as_ref(&self) -> &[u8] {
        self.octets.as_ref()
    }
}

impl<Octets: AsRef<[u8]>> AsRef<[u8]> for PeerDownNotification<Octets> {
    fn as_ref(&self) -> &[u8] {
        self.octets.as_ref()
    }
}

impl<Octets: AsRef<[u8]>> AsRef<[u8]> for RouteMonitoring<Octets> {
    fn as_ref(&self) -> &[u8] {
        self.octets.as_ref()
    }
}
impl<Octets: AsRef<[u8]>> AsRef<[u8]> for RouteMirroring<Octets> {
    fn as_ref(&self) -> &[u8] {
        self.octets.as_ref()
    }
}

//--- Parsing and impl of the Message enum wrapper ---------------------------

impl<Octs: Octets> Message<Octs> {
    pub fn from_octets(octets: Octs) -> Result<Self, ParseError> {
        let msg_type = {
            let mut parser = Parser::from_ref(&octets);
            let ch = CommonHeader::parse(&mut parser)?;
            ch.msg_type()
        };

        match msg_type {
            MessageType::RouteMonitoring =>
                Ok(Message::RouteMonitoring(RouteMonitoring::from_octets(octets)?)),
            MessageType::StatisticsReport =>
                Ok(Message::StatisticsReport(StatisticsReport::from_octets(octets)?)),
            MessageType::PeerDownNotification =>
                Ok(Message::PeerDownNotification(PeerDownNotification::from_octets(octets)?)),
            MessageType::PeerUpNotification =>
                Ok(Message::PeerUpNotification(PeerUpNotification::from_octets(octets)?)),
            MessageType::InitiationMessage =>
                Ok(Message::InitiationMessage(InitiationMessage::from_octets(octets)?)),
            MessageType::TerminationMessage =>
                Ok(Message::TerminationMessage(TerminationMessage::from_octets(octets)?)),
            MessageType::RouteMirroring =>
                Ok(Message::RouteMirroring(RouteMirroring::from_octets(octets)?)),
            MessageType::Unimplemented(_) => {
                Err(ParseError::form_error("Unimplemented BMP message type"))
            }
        }
    }
}

impl<Octs: Octets> Message<Octs> {
    pub fn check(src: &mut Cursor<Octs>) -> Result<u32, MessageError> {
        if src.remaining() >= 5 {
            let _version = src.get_u8();
			let len = src.get_u32();
            if len <= 6 {
                return Err(MessageError::IllegalSize)
            }
            if src.remaining() >= ((len as usize) - 5) {
                return Ok(len);
            }
        }
        Err(MessageError::Incomplete)
    }
}

impl<Octs: Octets> Message<Octs>
{
    /// Return the [`CommonHeader`] for this message.
    pub fn common_header(&self) -> CommonHeader<Octs::Range<'_>> {
        match self {
            Message::RouteMonitoring(m) => m.common_header(),
            Message::StatisticsReport(m) => m.common_header(),
            Message::PeerDownNotification(m) => m.common_header(),
            Message::PeerUpNotification(m) => m.common_header(),
            Message::InitiationMessage(m) => m.common_header(),
            Message::TerminationMessage(m) => m.common_header(),
            Message::RouteMirroring(m) => m.common_header(),
        }
    }

    /// Return the length of the message, including headers.
    pub fn length(&self) -> u32 {
        self.common_header().length()
    }

    /// Return the BMP version of the message.
    pub fn version(&self) -> u8 {
        self.common_header().version()
    }

    /// Return the message type.
    pub fn msg_type(&self) -> MessageType {
        self.common_header().msg_type()
    }
}

impl<Octets: AsRef<[u8]>> Display for Message<Octets> {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        match self {
            Message::RouteMonitoring(_) => write!(f, "RouteMonitoring"),
            Message::StatisticsReport(_) => write!(f, "StatisticsReport"),
            Message::PeerDownNotification(_) => write!(f, "PeerDownNotification"),
            Message::PeerUpNotification(_) => write!(f, "PeerUpNotification"),
            Message::InitiationMessage(_) => write!(f, "InitiationMessage"),
            Message::TerminationMessage(_) => write!(f, "TerminationMessage"),
            Message::RouteMirroring(_) => write!(f, "RouteMirroring"),
        }
    }
}

impl<Octs: Octets> Debug for Message<Octs> {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        let _ = writeln!(f, "{:?} ({})",
            &self.common_header().msg_type(),
            &self.common_header().length()
        );
        write!(f, "{:02x?}", &self.as_ref()[0..self.length() as usize])
    }
}

impl<Octets: AsRef<[u8]>> AsRef<[u8]> for Message<Octets> {
    fn as_ref(&self) -> &[u8] {
        match self {
            Message::RouteMonitoring(m) => m.as_ref(),
            Message::StatisticsReport(m) => m.as_ref(),
            Message::PeerDownNotification(m) => m.as_ref(),
            Message::PeerUpNotification(m) => m.as_ref(),
            Message::InitiationMessage(m) => m.as_ref(),
            Message::TerminationMessage(m) => m.as_ref(),
            Message::RouteMirroring(m) => m.as_ref(),
        }
    }
}

//--- The Common and Per Peer header -----------------------------------------

/// The Common Header of a BMP message.
///
/// Every BMP message type starts with the so called Common Header, providing
/// the BMP version, length, and type of the BMP message.
///
/// For convenience, the fields in the Common Header are available via methods
/// on `Message` directly.
///
//--- BMP Common Header  -----------------------------------------------------
// As per RFC7854:
//
//   0                   1                   2                   3
//   0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
//  +-+-+-+-+-+-+-+-+
//  |    Version    |
//  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//  |                        Message Length                         |
//  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//  |   Msg. Type   |
//  +---------------+

#[derive(Clone, Copy, Debug, Eq, Default, PartialEq)]
pub struct CommonHeader<Octets> {
	octets: Octets
}

impl<Octs: Octets> CommonHeader<Octs> {
    fn for_slice(s: Octs) -> Self {
        CommonHeader { octets: s }
    }

    fn check<Ref: Octets>(parser: &mut Parser<Ref>)
        -> Result<(), ParseError>
    {
        let version = parser.parse_u8()?;
        if version != 3 {
            return Err(ParseError::form_error("BMP version != 3"));
        }
        parser.advance(4)?; // u32 message length
        let typ = parser.parse_u8()?;
        if typ > 6 {
            return Err(ParseError::form_error("BMP message type unknown"));
        }
        Ok(())
    }

    /// Returns the BMP version of the message.
    pub fn version(&self) -> u8 {
        self.octets.as_ref()[0]
    }

    /// Returns the length of the message, including headers.
    pub fn length(&self) -> u32 {
        u32::from_be_bytes(self.octets.as_ref()[1..5].try_into().unwrap())
    }

    /// Returns the message type.
    pub fn msg_type(&self) -> MessageType {
        self.octets.as_ref()[5].into()
    }

}

impl<Octs: Octets> CommonHeader<Octs> {
    fn parse<'a>(parser: &mut Parser<'a, Octs>)
        -> Result<CommonHeader<Octs::Range<'a>>, ParseError>
    {
        // TODO check validity of version, length and msg type
        Ok (
            CommonHeader {
                octets: parser.parse_octets(6)?
            }
        )
    }
}


/// The Per Peer Header, present in some BMP messages.
///
/// BMP messages often contain encapsulated BGP messages. The Per Peer Header
/// provides information on the peer that sent that encapsulated BGP message,
/// such as the remote address and ASN, the time of receiving, etc.
// As per RFC7854:
//
//   0                   1                   2                   3
//   0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
//  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//  |   Peer Type   |  Peer Flags   |
//  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//  |         Peer Distinguisher (present based on peer type)       |
//  |                                                               |
//  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//  |                 Peer Address (16 bytes)                       |
//  ~                                                               ~
//  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//  |                           Peer AS                             |
//  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//  |                         Peer BGP ID                           |
//  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//  |                    Timestamp (seconds)                        |
//  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
//  |                  Timestamp (microseconds)                     |
//  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

#[derive(Clone, Copy, Debug, Eq, Ord, PartialOrd)]
pub struct PerPeerHeader<Octets: AsRef<[u8]>> {
    octets: Octets
}

impl<Octs: Octets> PerPeerHeader<Octs> {

    pub fn for_slice(s: Octs) -> Self {
        PerPeerHeader { octets: s }
    }

    pub fn check<Ref: Octets>(parser: &mut Parser<Ref>)
        -> Result<(), ParseError>
    {
        let peer_type = parser.parse_u8()?;
        if peer_type > 3 {
            return Err(ParseError::form_error("Unknown peer type in PPH"));
        }
        parser.advance(41)?;
        Ok(())
    }
}

impl<Octs: Octets> AsRef<[u8]> for PerPeerHeader<Octs> {
    fn as_ref(&self) -> &[u8] {
        self.octets.as_ref()
    }
}

impl<Octets: AsRef<[u8]>> PerPeerHeader<Octets> {
    /// Returns the peer type as defined in
    /// [RFC7854](https://datatracker.ietf.org/doc/html/rfc7854#section-10.2).
    pub fn peer_type(&self) -> PeerType {
        self.octets.as_ref()[0].into()
    }

    //  0 1 2 3 4 5 6 7
    // +-+-+-+-+-+-+-+-+
    // |V|L|A|O| Rservd|
    // +-+-+-+-+-+-+-+-+
    //
    // V: IP Version,  0 = IPv4, 1 = IPv6
    // L: 0 = pre-policy Adj-RIB-In, 1 = post-policy
    // A: 0 = 4-byte AS_PATH format, 1 = 2-byte legacy format
    // O: 0 = Adj-RIB-In, 1 = Adj-RIB-Out (RFC 8671)

    /// Returns the flags as a byte.
    pub fn flags(&self) -> u8 {
        self.octets.as_ref()[1]
    }

    /// Returns true if the IP Version bit is 0.
    pub fn is_ipv4(&self) -> bool {
        self.flags() & 0x80 == 0
    }

    /// Returns true if the IP Version bit is 1.
    pub fn is_ipv6(&self) -> bool {
        self.flags() & 0x80 == 0x80
    }

    /// Returns true if the L bit is 0.
    pub fn is_pre_policy(&self) -> bool {
        self.flags() & 0x40 == 0
    }

    /// Returns true if the A flags is 1.
    pub fn is_legacy_format(&self) -> bool {
        self.flags() & 0x20 == 0x20
    }

    /// Returns true if the L bit is 1.
    pub fn is_post_policy(&self) -> bool {
        self.flags() & 0x40 == 0x40
    }

    /// Returns the RIB type (Adj-RIB-In / Out) for this message.
    pub fn adj_rib_type(&self) -> RibType {
        match self.flags() & 0x10 == 0x10 {
            false => RibType::AdjRibIn,
            true => RibType::AdjRibOut
        }
    }
    pub fn rib_type(&self) -> RibType {
        if self.peer_type() == PeerType::LocalRibInstance {
            RibType::LocRib
        } else {
            self.adj_rib_type()
        }
    }

    /// Returns the peer distinguisher value in raw form.
    pub fn distinguisher(&'_ self) -> &'_ [u8] {
        &self.octets.as_ref()[2..=9]
    }

    // XXX not happy with this one.. TryInto [u8; n] ?
    /// Returns the remote address of the peer.
    pub fn address(&self) -> IpAddr {
        if self.is_ipv4() {
            IpAddr::V4(Ipv4Addr::from(
                u32::from_be_bytes(self.octets.as_ref()[10+12..=25].try_into().unwrap())
            ))
        } else {
            IpAddr::V6(Ipv6Addr::from(
                u128::from_be_bytes(self.octets.as_ref()[10..=25].try_into().unwrap())
            ))
        }
    }

    /// Returns the ASN of the peer.
    pub fn asn(&self) -> Asn {
        u32::from_be_bytes(self.octets.as_ref()[26..=29].try_into().unwrap()).into()
    }

    /// Returns the BGP Identifier of the peer.
    pub fn bgp_id(&self) -> [u8; 4] {
        self.octets.as_ref()[30..=33].try_into().unwrap()
    }

    fn ts_seconds(&self) -> u32 {
        u32::from_be_bytes(self.octets.as_ref()[34..=37].try_into().unwrap())
    }

    fn ts_micros(&self) -> u32 {
        u32::from_be_bytes(self.octets.as_ref()[38..=41].try_into().unwrap())
    }

    /// Returns the time when the encapsulated message was received.
    pub fn timestamp(&self) -> DateTime<Utc> {
        let s = self.ts_seconds() as i64;
        let us = self.ts_micros();
        if let LocalResult::Single(ts)= Utc.timestamp_opt(s, us*1000) {
            ts 
        } else {
            warn!(
                "invalid timestamp in Per-peer header: {}.{},\
                 returning epoch",
                 s, us
            );
            DateTime::<Utc>::MIN_UTC
        }
    } 
}

impl<Octets: AsRef<[u8]>> Display for PerPeerHeader<Octets> {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        write!(f, "{}/{}/{:02X?}", self.address(), self.asn(), self.bgp_id())
    }
}

impl<Octets: AsRef<[u8]>> Hash for PerPeerHeader<Octets> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.peer_type().hash(state);
        self.flags().hash(state);
        self.distinguisher().hash(state);
        self.address().hash(state);
        self.asn().hash(state);
        self.bgp_id().hash(state);
    }
}

impl<Octets: AsRef<[u8]>> PartialEq for PerPeerHeader<Octets> {
    fn eq(&self, other: &Self) -> bool {
        self.peer_type() == other.peer_type()
            && self.flags() == other.flags()
            && self.distinguisher() == other.distinguisher()
            && self.address() == other.address()
            && self.asn() == other.asn()
            && self.bgp_id() == other.bgp_id()
    }
}

typeenum!(
    /// The peer types as defined in
    /// https://www.iana.org/assignments/bmp-parameters/bmp-parameters.xhtml#peer-types
    PeerType, u8,
    {
        0 => GlobalInstance,
        1 => RdInstance,
        2 => LocalInstance,
        3 => LocalRibInstance,
        255 => Reserved
    },
    {
        4..=250 => Unassigned,
        251..=254 => Experimental,
    }
);


/// Specify which RIB the contents of a message originated from.
#[derive(Clone, Copy, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub enum RibType {
    AdjRibIn,
    AdjRibOut,
    LocRib,
}


//--- Specific Message types -------------------------------------------------


/// Route Monitoring message.
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RouteMonitoring<Octets: AsRef<[u8]>>
{
    octets: Octets
}

impl<Octs: Octets> RouteMonitoring<Octs> {
    pub fn from_octets(octets: Octs) -> Result<Self, ParseError> {
        Self::check(&octets)?;
        Ok(RouteMonitoring { octets })
    }

    pub fn check(octets: &Octs) -> Result<(), ParseError> {
        let mut parser = Parser::from_ref(octets);
        CommonHeader::<Octs>::check(&mut parser)?;
        PerPeerHeader::<Octs>::check(&mut parser)?;
        //  If we check/parse the encapsulated BGP UPDATE here, and it fails,
        //  this entire BMP RouteMonitoring message is lost.
        //  Instead, if we skip the parsing here, and do the parsing in
        //  RouteMonitoring::bgp_update(), we can retry parsing
        //  if we want to.
        Ok(())
    }
}

impl<Octs: Octets> RouteMonitoring<Octs> {
    /// Return the [`CommonHeader`] for this message.
    pub fn common_header(&self) -> CommonHeader<Octs::Range<'_>> {
        CommonHeader::for_slice(self.octets.range(..6))
    }

    /// Return the [`PerPeerHeader`] for this message.
    pub fn per_peer_header(&self) -> PerPeerHeader<Octs::Range<'_>> {
        PerPeerHeader::for_slice(self.octets.range(6..6+42))
    }

    /// Return the encapsulated
    /// [BGP UPDATE message](`crate::bgp::MessageUpdate`).
    pub fn bgp_update(&self, config: &SessionConfig)
        -> Result<BgpUpdate<Octs::Range<'_>>, ParseError>
    {
        let mut parser = Parser::from_ref(
            &self.octets,//.range_from(6+42),
        );
        // XXX note that the BGP PDU will move into a TLV in BMPv4
        parser.advance(6+42).expect("parsed before");
        BgpUpdate::parse(&mut parser, config)
    }
}

/// Statistics Report message.
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[derive(Clone, Eq, PartialEq)]
pub struct StatisticsReport<Octs> {
    octets: Octs,
}

impl<Octs: Octets> StatisticsReport<Octs> {
    /// Return the [`CommonHeader`] for this message.
    pub fn common_header(&self) -> CommonHeader<Octs::Range<'_>> {
        CommonHeader::for_slice(self.octets.range(..6))
    }

    /// Return the [`PerPeerHeader`] for this message.
    pub fn per_peer_header(&self) -> PerPeerHeader<Octs::Range<'_>> {
        PerPeerHeader::for_slice(self.octets.range(6..6+42))
    }

    /// Return the number of statistics listed in this report.
    pub fn stats_count(&self) -> u32 {
        u32::from_be_bytes(
            self.octets.as_ref()[COFF..=COFF+3].try_into().expect("parsed before")
        )
    }

    /// Return an iterator over the statistics.
    pub fn stats(&self) -> StatIter<'_> {
        StatIter::new(&self.octets.as_ref()[COFF+4..], self.stats_count())
    }

}

impl<Octs: Octets> StatisticsReport<Octs> {
    pub fn from_octets(octets: Octs) -> Result<Self, ParseError> {
        Self::check(&octets)?;
        Ok(Self { octets })
    }

    pub fn check(octets: &Octs) -> Result<(), ParseError> {
        let mut parser = Parser::from_ref(octets);
        CommonHeader::<Octs>::check(&mut parser)?;
        PerPeerHeader::<Octs>::check(&mut parser)?;

        let count = parser.parse_u32_be()?;
        for _ in 0..count {
            parser.advance(2)?; // u16
            let len = parser.parse_u16_be()?;
            parser.advance(len.into())?;
        }
        Ok(())
    }
}

impl<Octs: Octets> Debug for StatisticsReport<Octs> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for s in self.stats() {
            let _ = writeln!(f, "{}", s);
        }
        writeln!(f)
    }
}


/// Peer Down Notification. 
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PeerDownNotification<Octets: AsRef<[u8]>> {
    octets: Octets,
}

impl<Octs: Octets> PeerDownNotification<Octs> {
    /// Return the [`CommonHeader`] for this message.
    pub fn common_header(&self) -> CommonHeader<Octs::Range<'_>> {
        CommonHeader::for_slice(self.octets.range(..6))
    }

    /// Return the [`PerPeerHeader`] for this message.
    pub fn per_peer_header(&self) -> PerPeerHeader<Octs::Range<'_>> {
        PerPeerHeader::for_slice(self.octets.range(6..6+42))
    }

    /// Return the [`PeerDownReason`] for this message.
    pub fn reason(&self) -> PeerDownReason {
        match self.as_ref()[COFF] {
            0 => PeerDownReason::Reserved,
            1 => PeerDownReason::LocalNotification,
            2 => PeerDownReason::LocalFsm,
            3 => PeerDownReason::RemoteNotification,
            4 => PeerDownReason::RemoteNodata,
            5 => PeerDownReason::PeerDeconfigured,
            _ => PeerDownReason::Unknown,
        }
    }

    /// Return the optional encapsulated [BGP NOTIFICATION
    /// message](`crate::bgp::MessageNotification`), that should be present
    /// for the Local and Remote Notification PeerDownReasons.
    pub fn notification(&self) -> Option<BgpNotification<Octs::Range<'_>>> {
        if self.reason() == PeerDownReason::LocalNotification ||
           self.reason() == PeerDownReason::RemoteNotification
        {
            // If we are at the end of the message, there is no data and thus
            // no BGP NOTIFICATION.
            if COFF+1 == self.common_header().length() as usize {
                return None
            }
            Some({
                BgpNotification::from_octets(self.octets.range(COFF+1..))
                    .expect("parsed before")
            })
        } else {
            None
        }
    }

    // TODO convert this to a proper enum in bgp.rs
    //pub fn fsm(&self) -> Option(Bgp::FsmEvent) {
    pub fn fsm(&self) -> Option<u16> {
        if self.reason() == PeerDownReason::LocalFsm {
            if self.as_ref().len() < COFF + 3 {
                // Expected 2 bytes for FSM Event, but they are not in the PDU 
                None
            } else {
                Some(u16::from_be_bytes(self.as_ref()[COFF+1..COFF+3].try_into().unwrap()))
            }
        } else {
            None
        }
    }
}

/// Peer Down notification message reason codes.
#[derive(Debug, Eq, PartialEq)]
pub enum PeerDownReason {
    Reserved,
    LocalNotification,  // reason 1
    LocalFsm,           // reason 2
    RemoteNotification, // reason 3
    RemoteNodata,       // reason 4
    PeerDeconfigured,   // reason 5
    Unknown,
}


impl<Octs: Octets> PeerDownNotification<Octs> {
    pub fn from_octets(octets: Octs) -> Result<Self, ParseError> {
        Self::check(&octets)?;
        Ok(Self { octets })
    }

    pub fn check(octets: &Octs) -> Result<(), ParseError> {
        let mut parser = Parser::from_ref(octets);
        CommonHeader::<Octs>::check(&mut parser)?;
        PerPeerHeader::<Octs>::check(&mut parser)?;

        let reason = parser.parse_u8()?;
        match reason {
            1 | 3 => {
                if parser.remaining() == 0 {
                    warn!(
                    "Missing BGP NOTIFICATION in PeerDownNotification"
                    );
                } else {
                    BgpNotification::parse(&mut parser)?;
                }
            }
            2 => { parser.advance(2)?; } // TODO check BGP FSM state code
            4 => { /* remote system closed without NOTIFICATION */ },
            5 => { /* Information stop for this peer */ },
            _ => { warn!("Unknown PeerDownNotification reason"); }
        }

        Ok(())
    }
}


/// Peer Up Notification.
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PeerUpNotification<Octets: AsRef<[u8]>> {
    octets: Octets,
}

impl<Octs: Octets> PeerUpNotification<Octs> {
    /// Return the [`CommonHeader`] for this message.
    pub fn common_header(&self) -> CommonHeader<Octs::Range<'_>> {
        CommonHeader::for_slice(self.octets.range(..6))
    }

    /// Return the [`PerPeerHeader`] for this message.
    pub fn per_peer_header(&self) -> PerPeerHeader<Octs::Range<'_>> {
        PerPeerHeader::for_slice(self.octets.range(6..6+42))
    }

    /// Return the local address used for the BGP session.
    pub fn local_address(&self) -> IpAddr {
        if self.as_ref()[COFF..=COFF+11] == [0; 12] {
            // IPv4
            IpAddr::V4(Ipv4Addr::from(
                u32::from_be_bytes(self.as_ref()[COFF+12..=COFF+15].try_into().unwrap())
            ))
        } else {
            // XXX not tested, need v6 pcap
            IpAddr::V6(Ipv6Addr::from(
                u128::from_be_bytes(self.as_ref()[COFF..=COFF+15].try_into().unwrap())
            ))
        }
    }
    
    /// Return the local port used for the BGP session.
    pub fn local_port(&self) -> u16 {
        u16::from_be_bytes(
            self.as_ref()[COFF+16..=COFF+17].try_into().unwrap()
        )
    }

    /// Return the remote port used for the BGP session.
    pub fn remote_port(&self) -> u16 {
        u16::from_be_bytes(
            self.as_ref()[COFF+18..=COFF+19].try_into().unwrap()
        )
    }

    /// Return the [BGP OPEN message](BgpOpen) sent to the peer.
    pub fn bgp_open_sent(&self) -> BgpOpen<Octs::Range<'_>> {
        let mut parser = Parser::from_ref(
            &self.octets
        );
        parser.advance(COFF+20).expect("parsed before");
        BgpOpen::parse(&mut parser).unwrap()
        
        //TODO should we wrap all these BGP OPENs in Results?
        //BgpOpen::from_octets(self.octets.range_from(COFF+20)).expect("parsed before")
    }

    /// Return the [BGP OPEN message](BgpOpen) received from the peer.
    pub fn bgp_open_rcvd(&self) -> BgpOpen<Octs::Range<'_>> {
        let mut pos: usize = 20;
        pos += self.bgp_open_sent().as_ref().len();
        let mut parser = Parser::from_ref(
            &self.octets //.range_from(COFF+pos)
        );
        parser.advance(COFF + pos).unwrap();
        BgpOpen::parse(&mut parser).unwrap()
    }

    /// Return a tuple of the sent and received BGP OPEN messages.
    ///
    /// This method is more efficient than calling both `bgp_open_sent` and
    /// `bgp_open_rcvd` individually.
    #[allow(clippy::type_complexity)]
    pub fn bgp_open_sent_rcvd(&self)
        -> ( BgpOpen<Octs::Range<'_>>, BgpOpen<Octs::Range<'_>>,)
    {
        let mut parser = Parser::from_ref(
            &self.octets, //.range_from(COFF+20)
        );
        parser.advance(COFF+20).unwrap();
        let sent = BgpOpen::parse(&mut parser).unwrap();
        let rcvd = BgpOpen::parse(&mut parser).unwrap();

        (sent, rcvd) 
    }

    /// Create a [`SessionConfig`] to parse encapsulated BGP data based on the
    /// PerPeerHeader.
    ///
    /// The information in this `SessionConfig` is necessary for correctly
    /// parsing future messages, specifically BGP UPDATEs carried in
    /// RouteMonitoring BMP messages. See [`SessionConfig`] for an example
    /// using it in that way.
    /// 
    /// Note that this function returns the four octet capability set in the
    /// per peer header, *not* the same capability in the encapsulated BGP
    /// OPEN message. This method should normally be used by a BMP monitoring
    /// station, when receiving a PeerUpNotification.
    /// 
    /// Returns the SessionConfig and an optional tuple if the BGP OPEN four
    /// octet ASN capability and the one in the Per Peer Header are not the
    /// same.
    pub fn pph_session_config(&self) -> (SessionConfig, Option<(FourOctetAsns, FourOctetAsns)>)  {
        let (sent, rcvd) = self.bgp_open_sent_rcvd();
        let mut conf = SessionConfig::modern();

        // The 'modern' SessionConfig has four octet capability set to
        // enabled, so we need to disable it if any of both of the peers do
        // not support it.
        let bgp_four_octet =
            match sent.four_octet_capable() && rcvd.four_octet_capable() {
                true => FourOctetAsns(true),
                false => FourOctetAsns(false),
            }
        ;

        let four_octet_asn = match self.per_peer_header().is_legacy_format() {
            false => FourOctetAsns(true),
            true => FourOctetAsns(false),
        };

        conf.set_four_octet_asns(four_octet_asn);

        for famdir in sent.addpath_intersection(&rcvd) {
            conf.add_famdir(famdir);
        }

        let inconsistent = 
            if four_octet_asn == bgp_four_octet { 
                None 
            } else { 
                Some((four_octet_asn, bgp_four_octet)) 
            };

        (conf, inconsistent)
    }

    /// Create a [`SessionConfig`] to parse encapsulated BGP data based on the
    /// exchanged BGP OPENs. session between the monitored router and the
    /// remote peer.
    ///
    /// The information in this `SessionConfig` is necessary for correctly
    /// parsing future messages, specifically BGP UPDATEs carried in
    /// RouteMonitoring BMP messages. See [`SessionConfig`] for an example
    /// using it in that way.
    /// 
    /// Note that this function does not consider the Per Peer Header four
    /// octet ASN capability. Use `pph_session_config()` for that. This method
    /// should probably not be used by a BMP monitoring station by default.
    pub fn session_config(&self) -> SessionConfig  {
        let (sent, rcvd) = self.bgp_open_sent_rcvd();
        let mut conf = SessionConfig::modern();

        // The 'modern' SessionConfig has four octet capability set to
        // enabled, so we need to disable it if any of both of the peers do
        // not support it.
        let bgp_four_octet = match sent.four_octet_capable() && rcvd.four_octet_capable() {
            true => FourOctetAsns(true),
            false => FourOctetAsns(false),
        };

        conf.set_four_octet_asns(bgp_four_octet);

        for famdir in sent.addpath_intersection(&rcvd) {
            conf.add_famdir(famdir);
        }

        conf
    }

    pub fn supported_protocols(&self) -> Vec<AfiSafiType> {
        let mut v = Vec::new();
        let mut res = Vec::new();
        let (sent, rcvd) = self.bgp_open_sent_rcvd();
        sent.capabilities()
            .filter(|c| c.typ() == CapabilityType::MultiProtocol)
            .for_each(|c| {
                let afi = u16::from_be_bytes([c.value()[0], c.value()[1]]);
                let safi = c.value()[3];
                let afisafi = (afi, safi).into();
                v.push(afisafi);
            });
        rcvd.capabilities()
            .filter(|c| c.typ() == CapabilityType::MultiProtocol)
            .for_each(|c| {
                let afi = u16::from_be_bytes([c.value()[0], c.value()[1]]);
                let safi = c.value()[3];
                let afisafi = (afi, safi).into();
                if v.contains(&afisafi) {
                    res.push(afisafi);
                }
            });
        res
    }


    // XXX: 
    pub fn information_tlvs(&self) -> InformationTlvIter<'_> {
        let mut parser = Parser::from_ref(&self.octets);
        //Jump over the common header (6), the per peer header (42) and the
        //local address and local+remote ports (20)
        parser.advance(6+42+20).expect("parsed before");
        BgpOpen::parse(&mut parser).expect("parsed before");
        BgpOpen::parse(&mut parser).expect("parsed before");

        InformationTlvIter::new(&self.as_ref()[parser.pos()..])
    }

}

impl<Octs: Octets> PeerUpNotification<Octs> {
    pub fn from_octets(octets: Octs) -> Result<Self, ParseError> {
        Self::check(&octets)?;
        Ok(PeerUpNotification { octets })
    }

    pub fn check(octets: &Octs) -> Result<(), ParseError> {
        let mut parser = Parser::from_ref(octets);
        CommonHeader::<Octs>::check(&mut parser)?;
        PerPeerHeader::<Octs>::check(&mut parser)?;

        // local address, local port, remote port
        parser.advance(16 + 2 + 2)?;
        BgpOpen::parse(&mut parser)?; //TODO turn into check
        BgpOpen::parse(&mut parser)?; //TODO turn into check

        // optional Information
        if parser.remaining() > 0 { 
            // Information TLVs of type 0 (String)
            let info_type = parser.parse_u16_be()?;
            match info_type {
                0|3|4 => { },
                u => {
                    warn!("Unknown TLV type {u} in PeerUpNotification");
                }
            }
            let info_len = parser.parse_u16_be()?;
            parser.advance(info_len.into())?;
        }

        Ok(())
    }
}


/// Initiation Message.
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct InitiationMessage<Octets: AsRef<[u8]>> {
    octets: Octets,
}

impl<Octs: Octets> InitiationMessage<Octs> {
    /// Return the [`CommonHeader`] for this message.
    pub fn common_header(&self) -> CommonHeader<Octs::Range<'_>> {
        CommonHeader::for_slice(self.octets.range(..6))
    }

    /// Return an iterator over the Information TLVs.
    pub fn information_tlvs(&self) -> InformationTlvIter<'_> {
        InformationTlvIter::new(&self.as_ref()[
            6
            ..
        ])
    }
}

impl<Octs: Octets> InitiationMessage<Octs> {
    pub fn from_octets(octets: Octs) -> Result<Self, ParseError> {
        Self::check(&octets)?;
        Ok(Self { octets })
    }
    
    pub fn check(octets: &Octs) -> Result<(), ParseError> {
        let mut parser = Parser::from_ref(octets);
        CommonHeader::<Octs>::check(&mut parser)?;
        while parser.remaining() > 0 {
            parser.advance(2)?; // type u16
            let info_len = parser.parse_u16_be()?;
            parser.advance(info_len.into())?;
        }
        Ok(())
    }
}


/// Termination message.
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct TerminationMessage<Octets: AsRef<[u8]>> {
    octets: Octets,
}

impl<Octs: Octets> TerminationMessage<Octs> {
    /// Return the [`CommonHeader`] for this message.
    pub fn common_header(&self) -> CommonHeader<Octs::Range<'_>> {
        CommonHeader::for_slice(self.octets.range(..6))
    }

    /// Return an iterator over the Information TLVs.
    // XXX D-R-Y with TLVs from InitiationMessage
    pub fn information(&self) -> InformationIter<'_> {
        InformationIter::new(
            &self.octets.as_ref()[6..],
            self.common_header().length() as usize - 6
        )
    }
}

impl<Octs: Octets> TerminationMessage<Octs> {
    pub fn from_octets(octets: Octs) -> Result<Self, ParseError> {
        Self::check(&octets)?;
        Ok(Self { octets })
    }

    pub fn check(octets: &Octs) -> Result<(), ParseError> {
        let mut parser = Parser::from_ref(octets);
        CommonHeader::<Octs>::check(&mut parser)?;

        while parser.remaining() > 0 {
            parser.advance(2)?; // type u16
            let info_len = parser.parse_u16_be()?;
            parser.advance(info_len.into())?;
        }

        Ok(())
    }
}


/// RouteMirroring.
///
/// NB: Not well tested/supported at this moment!  
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RouteMirroring<Octs> {
    octets: Octs,
}

impl<Octs: Octets> RouteMirroring<Octs> {
    /// Return the [`CommonHeader`] for this message.
    pub fn common_header(&self) -> CommonHeader<Octs::Range<'_>> {
        CommonHeader::for_slice(self.octets.range(..6))
    }

    /// Return the [`PerPeerHeader`] for this message.
    pub fn per_peer_header(&self) -> PerPeerHeader<Octs::Range<'_>> {
        PerPeerHeader::for_slice(self.octets.range(6..6+42))
    }
}

impl<Octs: Octets> RouteMirroring<Octs> {
    pub fn from_octets(octets: Octs) -> Result<Self, ParseError> {
        Self::check(&octets)?;
        Ok(Self { octets })
    }

    pub fn check(octets: &Octs) -> Result<(), ParseError> {
        let mut parser = Parser::from_ref(octets);
        CommonHeader::<Octs>::check(&mut parser)?;
        PerPeerHeader::<Octs>::check(&mut parser)?;
        // TODO try to check the encapsulated BGP message, the TLVs..
        warn!("Route Mirroring message check not properly implemenented yet");
        Ok(())
    }
}


//--- Information TLVs -------------------------------------------------------
//
// Information TLVs are present in the BMP InitiationMessage, and optionally
// in the PeerUpNotification.

/// TLV used in Initiation Message and Peer Up Notification.
#[derive(Debug)]
pub struct InformationTlv<'a> {
    octets: &'a[u8]
}

impl<'a> InformationTlv<'a> {
    fn for_slice(slice: &'a[u8]) -> Self {
        InformationTlv {
            octets: slice,
        }
    }

    /// Returns the `InformationTlvType` for this TLV.
    pub fn typ(&self) -> InformationTlvType {
        InformationTlvType::from(u16::from_be_bytes(self.octets[0..=1].try_into().unwrap()))
    }

    /// Returns the length of the value.
    pub fn length(&self) -> u16 {
        u16::from_be_bytes(self.octets[2..=3].try_into().unwrap())
    }

    /// Returns the value as a slice.
    pub fn value(&self) -> &[u8] {
        &self.octets[4..]
    }
}

impl Display for InformationTlv<'_> {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        match self.typ() {
            InformationTlvType::String
                | InformationTlvType::SysDesc
                | InformationTlvType::SysName
                => write!(f, "{:?}: {}",
                    self.typ(),
                    String::from_utf8_lossy(self.value())
                    ),
            _ => write!(f, "{:?}", self.typ()), 
        }
    }

}

typeenum!(
    /// Types of Information TLVs.
    ///
    /// See also
    /// <https://www.iana.org/assignments/bmp-parameters/bmp-parameters.xhtml#initiation-peer-up-tlvs>
    InformationTlvType, u16,
    { 
        0 => String,
        1 => SysDesc,
        2 => SysName,
        3 => VrfTableName,
        4 => AdminLabel,
    },
    {
        5.. => Undefined,
    }
);

/// Iterator over `InformationTlv`'s.
pub struct InformationTlvIter<'a> {
    slice: &'a [u8],
    pos: usize,
}
impl<'a> InformationTlvIter<'a> {
    fn new(slice: &'a [u8]) -> Self {
        InformationTlvIter {
            slice,
            pos: 0,
        }
    }

    fn get_tlv(&mut self) -> InformationTlv<'a> {
        let s = u16::from_be_bytes(self.slice[(self.pos + 2)..=(self.pos + 3)].try_into().unwrap());
        let res = InformationTlv::for_slice(&self.slice[self.pos..self.pos+4+(s as usize)]);
        self.pos += (res.length() + 4) as usize;
        res
    }
}

impl<'a> Iterator for InformationTlvIter<'a> {
    type Item = InformationTlv<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.pos == self.slice.len() {
            return None;
        }
        Some(self.get_tlv())
    }
}


//--- StatisticsReport -------------------------------------------------------

/// Represents the type and value of statistics in a BMP StatisticsReport.
/// 
/// <https://datatracker.ietf.org/doc/html/rfc7854#section-4.8>
#[derive(Debug, Eq, PartialEq)]
pub enum Stat {
    Type0(u32),
    Type1(u32),
    Type2(u32),
    Type3(u32),
    Type4(u32),
    Type5(u32),
    Type6(u32),
    Type7(u64),
    Type8(u64),
    Type9(Afi,u8,u64),
    Type10(Afi,u8,u64),
    Type11(u32),
    Type12(u32),
    Type13(u32),
    // RFC 8671, Adj-RIB-Out
    Type14(u64),
    Type15(u64),
    Type16(Afi,u8,u64),
    Type17(Afi,u8,u64),

    Unimplemented(u16,u16) // type,len
}

impl std::fmt::Display for Stat {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error>{
        use Stat::*;
        match self {
            Type0(v) => write!(f, "rejected-inbound-policy: {}", v),
            Type1(v) => write!(f, "duplicate-prefix-adv: {}", v),
            Type2(v) => write!(f, "duplicate-prefix-wdraw: {}", v),
            Type3(v) => write!(f, "upd-invalid-clusterlist: {}", v),
            Type4(v) => write!(f, "upd-invalid-aspath: {}", v),
            Type5(v) => write!(f, "upd-invalid-originator: {}", v),
            Type6(v) => write!(f, "upd-invalid-asconfed: {}", v),
            Type7(v) => write!(f, "routes-adj-rib-in: {}", v),
            Type8(v) => write!(f, "routes-loc-rib: {}", v),
            Type9(a, s, v) => 
                write!(f, "routes-{}-{}-adj-rib-in: {}", a, s, v),
            Type10(a, s, v) => 
                write!(f, "routes-{}-{}-loc-rib: {}", a, s, v),
            Type11(v) => write!(f, "updates-treat-withdraw: {}", v),
            Type12(v) => write!(f, "prefixes-treat-withdraw: {}", v),
            Type13(v) => write!(f, "duplicate-updates: {}", v),

            Type14(v) => write!(f, "routes-pre-adj-rib-out: {}", v),
            Type15(v) => write!(f, "routes-post-adj-rib-out: {}", v),
            Type16(a, s, v) => 
                write!(f, "routes-{}-{}-pre-adj-rib-out: {}", a, s, v),
            Type17(a, s, v) => 
                write!(f, "routes-{}-{}-post-adj-rib-out: {}", a, s, v),
            Unimplemented(t,_) => write!(f, "unimplemented-stat-type-{}", t),
        }
        
    }
}

/// Iterator over statistics in a Statistics Report message.
pub struct StatIter<'a> {
    octets: &'a [u8],
    pos: usize,
    left: u32,
}

// XXX this can be improved
impl <'a>StatIter<'a> {
    fn new(octets: &'a [u8], left: u32) -> Self {
        StatIter{octets, pos: 0, left}
    }

    fn _take_u32(&mut self) -> u32 {
        let res = u32::from_be_bytes(
            self.octets[self.pos + 4 .. self.pos + 4 + 4]
            .try_into().unwrap()
        );
        self.pos += 4 + 4;
        res
    }

    fn _take_u64(&mut self) -> u64 {
        let res = u64::from_be_bytes(
            self.octets[self.pos + 4 .. self.pos + 4 + 8]
            .try_into().unwrap()
        );
        self.pos += 4 + 8;
        res
    }

    fn _take_afi_safi_u64(&mut self) -> (Afi, u8, u64) {

        let afi: Afi = u16::from_be_bytes(
            self.octets[self.pos + 4 .. self.pos + 4 + 2].try_into().unwrap()
        ).into();
        let safi = self.octets[self.pos + 4 + 2];

        let v = u64::from_be_bytes(
            self.octets[self.pos + 4 + 3 .. self.pos + 4 + 3 + 8]
            .try_into().unwrap()
        );
        self.pos += 4 + 2 + 1 + 8;
        (afi, safi, v)
    }

    fn get_stat(&mut self) -> Stat {
        let typ = u16::from_be_bytes(
            self.octets[(self.pos)..=(self.pos + 1)]
            .try_into().unwrap()
        );
        let len = u16::from_be_bytes(
            self.octets[(self.pos + 2)..=(self.pos + 3)]
            .try_into().unwrap()
        );

        self.left -= 1;
        match (typ, len) {
            (0, 4) => Stat::Type0(self._take_u32()),
            (1, 4) => Stat::Type1(self._take_u32()),
            (2, 4) => Stat::Type2(self._take_u32()),
            (3, 4) => Stat::Type3(self._take_u32()),
            (4, 4) => Stat::Type4(self._take_u32()),
            (5, 4) => Stat::Type5(self._take_u32()),
            (6, 4) => Stat::Type6(self._take_u32()),
            (7, 8) => Stat::Type7(self._take_u64()),
            (8, 8) => Stat::Type8(self._take_u64()),
            (9, 11) =>  {
                let (a, s, v) = self._take_afi_safi_u64();
                Stat::Type9(a, s, v)
            }
            (10, 11) =>  {
                let (a, s, v) = self._take_afi_safi_u64();
                Stat::Type10(a, s, v)
            }
            (11, 4) => Stat::Type11(self._take_u32()),
            (12, 4) => Stat::Type12(self._take_u32()),
            (13, 4) => Stat::Type13(self._take_u32()),
            (14, 8) => Stat::Type14(self._take_u64()),
            (15, 8) => Stat::Type15(self._take_u64()),
            (16, 11) =>  {
                let (a, s, v) = self._take_afi_safi_u64();
                Stat::Type16(a, s, v)
            }
            (17, 11) =>  {
                let (a, s, v) = self._take_afi_safi_u64();
                Stat::Type17(a, s, v)
            }

            (_,_) => { 
                self.pos += 4 + len as usize;
                Stat::Unimplemented(typ, len)
            }
        }
    }
}
impl Iterator for StatIter<'_> {
    type Item = Stat;
    fn next(&mut self) -> Option<Self::Item> {
        if self.left > 0 {
            Some(self.get_stat())
        } else {
            None
        }
    }
}


// Offset of actual payload within message
const COFF: usize = 
        6 + //std::mem::size_of::<CommonHeader>() +
        42 //std::mem::size_of::<PerPeerHeader>()
;



//--- Termination Message ----------------------------------------------------

/// Iterator over TLVs in a Termination message.
pub struct InformationIter<'a> {
    octets: &'a [u8],
    pos: usize,
    end: usize,
}

/// Termination message reason codes.
// XXX convert this to a typeenum! ?
#[derive(Debug, Eq, PartialEq)]
pub enum TerminationInformation {
    CustomString(String),
    AdminClose,             // reason 0
    Unspecified,            // reason 1
    OutOfResources,         // reason 2
    RedundantConnection,    // reason 3
    PermAdminClose,         // reason 4
    Undefined(u16),
}

impl<'a> InformationIter<'a> {
    fn new(octets: &'a [u8], end: usize) -> Self {
       InformationIter {
           octets,
           pos: 0,
           end
       }
    }

    fn get_info(&mut self) -> TerminationInformation {
        let typ = u16::from_be_bytes(self.octets[self.pos..self.pos+2].try_into().unwrap());
        let len = u16::from_be_bytes(self.octets[self.pos+2..self.pos+4].try_into().unwrap());
        if typ == 0 {
            let s = String::from_utf8_lossy(
                &self.octets[self.pos+4..self.pos+4+len as usize]
                )
                .into_owned();
            self.pos += 4 + len as usize;
            return TerminationInformation::CustomString(s)
        }
        let val = u16::from_be_bytes(self.octets[self.pos+4..self.pos+4+len as usize].try_into().unwrap());
        self.pos += 4 + len as usize;
        match val {
            0 => TerminationInformation::AdminClose,
            1 => TerminationInformation::Unspecified,
            2 => TerminationInformation::OutOfResources,
            3 => TerminationInformation::RedundantConnection,
            4 => TerminationInformation::PermAdminClose,
            u => TerminationInformation::Undefined(u)
        }

    }
}

impl Iterator for InformationIter<'_> {
    type Item = TerminationInformation;
    fn next(&mut self) -> Option<TerminationInformation> {
        if self.pos == self.end {
            return None
        }
        Some(self.get_info())
    }
}


impl Display for TerminationInformation {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
    match self {
            TerminationInformation::CustomString(s) => write!(f, "{}", s),
            TerminationInformation::AdminClose => write!(f, "Session administratively closed"),
            TerminationInformation::Unspecified => write!(f, "Unspecified reason"),
            TerminationInformation::OutOfResources => write!(f, "Out of resources"),
            TerminationInformation::RedundantConnection => write!(f, "Redundant connection"),
            TerminationInformation::PermAdminClose => {
                write!(f, "Session permanently administratively closed")
            }
            TerminationInformation::Undefined(v) => write!(f, "Undefined: {}", v),
        }
    }
}

//--- Route Mirroring --------------------------------------------------------

/// Types of Route Mirroring TLVs.
pub enum RouteMirroringType<Octs: Octets> {
    BgpMessage(Result<BgpMsg<Octs>, ParseError>),         // type 0
    InfoErrorPdu,       // type 1 code 0
    InfoMessagesLost,   // type 1 code 1
    Undefined(u16, Octs),     // carries the type
}

/*
/// Iterator over Route Mirroring TLVs.
pub struct RouteMirroringTlvIter<Octets> {
    octets: Octets,
    pos: usize,
}
impl<Octets: AsRef<[u8]>> RouteMirroringTlvIter<Octets>
where
    //Octets: AsRef<[u8]> + OctetsRef//<Range = Octets>
{
    fn get_item(&mut self) -> RouteMirroringType<Octets> {
        let typ = u16::from_be_bytes(
            self.octets.as_ref()[self.pos..self.pos+2].try_into().unwrap()
        );
        let len = u16::from_be_bytes(
            self.octets.as_ref()[self.pos+2..self.pos+4].try_into().unwrap()
        );
        if typ == 0 {
            let res = RouteMirroringType::BgpMessage(
                BgpMsg::from_octets(
                    self.octets.range(self.pos+5,self.pos+5+len as usize)
                )
            );
            self.pos += 4 + len as usize;
            return res;
        }

        // XXX expecting the TLV to be a type 1, revise when we have test data
        // with these asserts, the possible Undefined cases are limited
        assert!(typ == 1);
        assert!(len == 2);
        let val = u16::from_be_bytes(
            self.octets.as_ref()[self.pos+4..self.pos+4+len as usize]
            .try_into().unwrap()
        );
        self.pos += len as usize;

        match val {
            0 => RouteMirroringType::InfoErrorPdu,
            1 => RouteMirroringType::InfoMessagesLost,
            u => RouteMirroringType::Undefined(
                u, self.octets.range(self.pos+4,self.pos+4+len as usize)
            )
        }

    }
}
impl<Octets> Iterator for RouteMirroringTlvIter<Octets>
where
    Octets: AsRef<[u8]> + OctetsRef//<Range = Octets>
{
    type Item = RouteMirroringType<Octets>;
    fn next(&mut self) -> Option<RouteMirroringType<Octets>> {
        if self.pos == self.octets.as_ref().len() {
            return None
        }
        Some(self.get_item())
    }
}
*/


//--- From / Into ------------------------------------------------------------


impl<Octets: AsRef<[u8]>> TryFrom<Message<Octets>> for RouteMonitoring<Octets>
{
    type Error = MessageError;
    fn try_from(msg: Message<Octets>)
        -> Result<RouteMonitoring<Octets>, Self::Error>
    {
        match msg {
            Message::RouteMonitoring(m) => Ok(m),
            _ => Err(MessageError::InvalidMsgType),
        }
    }
}

impl<Octets: AsRef<[u8]>> TryFrom<Message<Octets>> for StatisticsReport<Octets>
{
    type Error = MessageError;
    fn try_from(msg: Message<Octets>)
        -> Result<StatisticsReport<Octets>, Self::Error>
    {
        match msg {
            Message::StatisticsReport(m) => Ok(m),
            _ => Err(MessageError::InvalidMsgType),
        }
    }
}

impl<Octets: AsRef<[u8]>> TryFrom<Message<Octets>> for PeerDownNotification<Octets>
{
    type Error = MessageError;
    fn try_from(msg: Message<Octets>)
        -> Result<PeerDownNotification<Octets>, Self::Error>
    {
        match msg {
            Message::PeerDownNotification(m) => Ok(m),
            _ => Err(MessageError::InvalidMsgType),
        }
    }
}

impl<Octets: AsRef<[u8]>> TryFrom<Message<Octets>> for PeerUpNotification<Octets>
{
    type Error = MessageError;
    fn try_from(msg: Message<Octets>)
        -> Result<PeerUpNotification<Octets>, Self::Error>
    {
        match msg {
            Message::PeerUpNotification(m) => Ok(m),
            _ => Err(MessageError::InvalidMsgType),
        }
    }
}

impl<Octets: AsRef<[u8]>> TryFrom<Message<Octets>> for InitiationMessage<Octets>
{
    type Error = MessageError;
    fn try_from(msg: Message<Octets>)
        -> Result<InitiationMessage<Octets>, Self::Error>
    {
        match msg {
            Message::InitiationMessage(m) => Ok(m),
            _ => Err(MessageError::InvalidMsgType),
        }
    }
}

impl<Octets: AsRef<[u8]>> TryFrom<Message<Octets>> for TerminationMessage<Octets>
{
    type Error = MessageError;
    fn try_from(msg: Message<Octets>)
        -> Result<TerminationMessage<Octets>, Self::Error>
    {
        match msg {
            Message::TerminationMessage(m) => Ok(m),
            _ => Err(MessageError::InvalidMsgType),
        }
    }
}

impl<Octets: AsRef<[u8]>> TryFrom<Message<Octets>> for RouteMirroring<Octets>
{
    type Error = MessageError;
    fn try_from(msg: Message<Octets>)
        -> Result<RouteMirroring<Octets>, Self::Error>
    {
        match msg {
            Message::RouteMirroring(m) => Ok(m),
            _ => Err(MessageError::InvalidMsgType),
        }
    }
}


//--- Tests ------------------------------------------------------------------

#[cfg(test)]
mod tests {

    use super::*;
    use bytes::Bytes;
    use std::str::FromStr;
    use inetnum::addr::Prefix;
    use crate::bgp::types::Afi;
    use crate::bgp::path_attributes::AttributeHeader;
    use crate::bgp::types::{ConventionalNextHop, MultiExitDisc};
    use crate::bgp::nlri::afisafi::{AfiSafiNlri, Nlri};

    // Helper for generating a .pcap, pass output to `text2pcap`.
    #[allow(dead_code)]
    fn print_pcap<T: AsRef<[u8]>>(msg: T) {
        println!();
        print!("000000 ");
        for b in msg.as_ref() {
            print!("{:02x} ", b);
        }
        println!();
    }

    //--- Headers ------------------------------------------------------------
    
    #[test]
    fn common_header_for_slice() {
        let buf = [0x03, 0x0, 0x0, 0x0, 0x6c, 0x04];
		let ch = CommonHeader::<&[u8]>::for_slice(&buf);
        assert_eq!(ch.version(), 3);
        assert_eq!(ch.length(), 108);
        assert_eq!(ch.msg_type(), MessageType::InitiationMessage);
    }

    #[test]
    fn common_header_parse() {
        let buf = vec![0x03, 0x0, 0x0, 0x0, 0x6c, 0x04];
        let mut parser = Parser::from_ref(&buf);
		let ch = CommonHeader::parse(&mut parser).unwrap();
        assert_eq!(ch.version(), 3);
        assert_eq!(ch.length(), 108);
        assert_eq!(ch.msg_type(), MessageType::InitiationMessage);
    }

    #[test]
    fn per_peer_header() {
        let buf = vec![
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x0a, 0xff, 0x00, 0x65, 0x00, 0x01, 0x00, 0x00, 0x0a, 0x0a, 0x0a,
            0x01, 0x54, 0xa2, 0x0e, 0x0b, 0x00, 0x0e, 0x0c, 0x20,
        ];

        let pph = PerPeerHeader::for_slice(&buf);
        assert_eq!(pph.peer_type(), PeerType::GlobalInstance);
        assert!(pph.is_ipv4());
        assert_eq!(pph.distinguisher(), [0; 8]);
        assert_eq!(
            pph.address(),
            Ipv4Addr::from_str("10.255.0.101").unwrap()
        );

        assert_eq!(pph.asn(), Asn::from_u32(65536));
        assert_eq!(pph.bgp_id(), [10, 10, 10, 1]);
        assert_eq!(pph.ts_seconds(), 1419906571);
        assert_eq!(pph.ts_micros(), 920608);

        assert_eq!(
            pph.timestamp().to_string(),
            "2014-12-30 02:29:31.920608 UTC"
        );
    }


    //--- Messages -----------------------------------------------------------
    
    // Helper to quickly parse bufs into specific BMP messages.
    //fn parse_msg<T, R>(buf: R) -> T
    //where
    //    T: TryFrom<Message<R>>,
    //    R: AsRef<[u8]> + OctetsRef,
    //    <T as TryFrom<Message<R>>>::Error: Debug
    //{
    //    Message::from_octets(buf).unwrap().try_into().unwrap()
    //}

    #[test]
    fn route_monitoring() {
        // a single BMP Route Monitoring message, containing one BGP UPDATE
        // message with 4 path attributes and 1 IPv4 NLRI
        let buf = vec![
            0x03, 0x00, 0x00, 0x00, 0x67, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x0a, 0xff, 0x00, 0x65,
            0x00, 0x01, 0x00, 0x00, 0x0a, 0x0a, 0x0a, 0x01,
            0x54, 0xa2, 0x0e, 0x0c, 0x00, 0x0e, 0x81, 0x09,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0x00, 0x37, 0x02, 0x00, 0x00, 0x00, 0x1b, 0x40,
            0x01, 0x01, 0x00, 0x40, 0x02, 0x06, 0x02, 0x01,
            0x00, 0x01, 0x00, 0x00, 0x40, 0x03, 0x04, 0x0a,
            0xff, 0x00, 0x65, 0x80, 0x04, 0x04, 0x00, 0x00,
            0x00, 0x01, 0x20, 0x0a, 0x0a, 0x0a, 0x02
        ]; 

        let bb = Bytes::from(buf);
        let bmp: RouteMonitoring<_> = Message::from_octets(&bb).unwrap().try_into().unwrap();
        assert_eq!(
            bmp.common_header().msg_type(),
            MessageType::RouteMonitoring
        );
        assert_eq!(bmp.common_header().length(), 103);

        let config = SessionConfig::modern();
        let bgp_update = bmp.bgp_update(&config).unwrap();

        //-- from here on, this actually tests the bgp parsing functionality
        // rather than the bmp one, but let's leave it for now ---------------
        
        assert_eq!(bgp_update.as_ref().len(), 55 - 19);
        assert_eq!(bgp_update.withdrawn_routes_len(), 0);
        
        let mut pas = bgp_update.path_attributes().unwrap().into_iter();
        let pa1 = pas.next().unwrap().unwrap();
        assert_eq!(pa1.type_code(), crate::bgp::types::Origin::TYPE_CODE);
        assert_eq!(pa1.flags(), 0x40.into());
        assert!( pa1.flags().is_transitive());
        assert!(!pa1.flags().is_optional());
        
        let pa2 = pas.next().unwrap().unwrap();
        assert_eq!(pa2.type_code(), crate::bgp::aspath::HopPath::TYPE_CODE);
        assert_eq!(pa2.flags(), 0x40.into());
        // TODO check actual AS_PATH contents

        let pa3 = pas.next().unwrap().unwrap();
        assert_eq!(pa3.type_code(), ConventionalNextHop::TYPE_CODE);
        assert_eq!(pa3.flags(), 0x40.into());
        //assert_eq!(pa3.as_ref(), [10, 255, 0, 101]); 

        let pa4 = pas.next().unwrap().unwrap();
        assert_eq!(pa4.type_code(), MultiExitDisc::TYPE_CODE);
        assert_eq!(pa4.flags(), 0x80.into());
        assert!(pa4.flags().is_optional());
        //assert_eq!(pa4.as_ref(), [0, 0, 0, 1]); 

        assert!(pas.next().is_none());


        // NLRI
        let mut nlris = bgp_update.announcements().unwrap();
        if let Some(Ok(Nlri::Ipv4Unicast(n1))) = nlris.next() {
            assert_eq!(
                *n1.nlri(),
                Prefix::from_str("10.10.10.2/32").unwrap()
            );
        } else {
            panic!()
        }
        assert!(nlris.next().is_none());
    }

    #[test]
    fn statistics_report() {
        // BMP statistics report with 13 stats.
        let buf = vec![
            0x03, 0x00, 0x00, 0x00, 0xba, 0x01, 0x00, 0x80,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x20, 0x01, 0x0d, 0xb8, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
            0x00, 0x01, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x05,
            0x62, 0x50, 0x11, 0x57, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00, 0x04,
            0x00, 0x00, 0x00, 0xb0, 0x00, 0x01, 0x00, 0x04,
            0x00, 0x00, 0x04, 0xde, 0x00, 0x02, 0x00, 0x04,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x04,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x04,
            0x00, 0x00, 0x00, 0x0a, 0x00, 0x05, 0x00, 0x04,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x04,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x00, 0x08,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x25,
            0x00, 0x08, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x1c, 0x00, 0x0e, 0x00, 0x08,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x21, 0x14,
            0x00, 0x0f, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x02, 0x21, 0x14, 0x00, 0x10, 0x00, 0x0b,
            0x00, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x02, 0x21, 0x14, 0x00, 0x11, 0x00, 0x0b, 0x00,
            0x02, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
            0x21, 0x14
        ];
        let bmp: StatisticsReport<_> = Message::from_octets(&buf).unwrap().try_into().unwrap();
        assert_eq!(bmp.stats_count(), 13);
        assert_eq!(bmp.stats().count(), 13);
        use Stat::*;
        let stats = [
            Type0(176),
            Type1(1246),
            Type2(0),
            Type3(0),
            Type4(10),
            Type5(0),
            Type6(0),
            Type7(37),
            Type8(28),
            Type14(139540),
            Type15(139540),
            Type16(Afi::Ipv6, 1, 139540),
            Type17(Afi::Ipv6, 1, 139540),
        ];

        for (s1, s2) in bmp.stats().zip(stats.iter()) {
            assert_eq!(s1, *s2);
        }
    }

    #[test]
    fn peer_down_notification() {
        use crate::bgp::message::notification::CeaseSubcode;

        // BMP PeerDownNotification type 3, containing a BGP NOTIFICATION.
        let buf = vec![
            0x03, 0x00, 0x00, 0x00, 0x46, 0x02, 0x00, 0x80,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x20, 0x01, 0x0d, 0xb8, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
            0x00, 0x01, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x0a,
            0x62, 0x2d, 0xea, 0x80, 0x00, 0x05, 0x58, 0x22,
            0x03, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
            0xff, 0x00, 0x15, 0x03, 0x06, 0x02
        ];
        let bmp: PeerDownNotification<_> = Message::from_octets(&buf).unwrap().try_into().unwrap();
        assert_eq!(bmp.reason(), PeerDownReason::RemoteNotification);
        assert!(bmp.notification().is_some());
        assert_eq!(bmp.fsm(), None);

        let bgp_notification = bmp.notification().unwrap();
        assert_eq!(
            bgp_notification.details(),
            CeaseSubcode::AdministrativeShutdown.into()
        );
    }

    #[test]
    fn peer_down_local_fsm() {
        let buf = vec![
            0x03, 0x00, 0x00, 0x00, 0x33, 0x02, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 127, 0, 0, 1,
            0x00, 0x01, 0x0, 0x0, 127, 0, 0, 1,
            0x69, 0xb9, 0x45, 0x2f, 0x00, 0x0d, 0x1c, 0x73,
            0x02, 0x01, 0x02
        ];
        let bmp: PeerDownNotification<_> = Message::from_octets(&buf).unwrap().try_into().unwrap();
        assert_eq!(bmp.reason(), PeerDownReason::LocalFsm);
        assert!(bmp.notification().is_none());
        assert_eq!(bmp.fsm(), Some(0x0102));
    }


    #[test]
    fn peer_down_lacking_notification() {
        // BMP PeerDownNotification with reason LocalNotification, but lacking
        // the BGP NOTIFICATION.
        let buf = vec![
            0x03, 0x00, 0x00, 0x00, 0x31, 0x02, 0x00, 0x80,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x20, 0x01, 0x0d, 0xb8, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,
            0x00, 0x01, 0x00, 0x00, 0xac, 0x11, 0x11, 0x0a,
            0x62, 0x2f, 0x06, 0x40, 0x00, 0x08, 0x6c, 0xb2,
            0x01
        ];
        let bmp: PeerDownNotification<_> = Message::from_octets(&buf).unwrap().try_into().unwrap();
        assert_eq!(bmp.reason(), PeerDownReason::LocalNotification);
        assert!(bmp.notification().is_none());
    }


    #[test]
    fn peer_up_notification() {
        // BMP PeerUpNotification, containing two BGP OPEN messages (the Sent
        // OPEN and the Received OPEN), both containing 5 Capabilities in the
        // Optional Parameters.
        // No optional Information field.
        // quoting RFC7854:
        // Inclusion of the Information field is OPTIONAL.  Its presence or
        // absence can be inferred by inspection of the Message Length in the
        // common header. TODO implement this presence check.
        //
		let buf = vec![
			0x03, 0x00, 0x00, 0x00, 0xba, 0x03, 0x00, 0x00,
			0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
			0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
			0x00, 0x00, 0x00, 0x00, 0x0a, 0xff, 0x00, 0x65,
			0x00, 0x00, 0xfb, 0xf0, 0x0a, 0x0a, 0x0a, 0x01,
			0x54, 0xa2, 0x0e, 0x0b, 0x00, 0x0e, 0x0c, 0x20,
			0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
			0x00, 0x00, 0x00, 0x00, 0x0a, 0xff, 0x00, 0x53,
			0x90, 0x6e, 0x00, 0xb3, 0xff, 0xff, 0xff, 0xff,
			0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
			0xff, 0xff, 0xff, 0xff, 0x00, 0x3b, 0x01, 0x04,
			0xfb, 0xff, 0x00, 0xb4, 0x0a, 0x0a, 0x0a, 0x67,
			0x1e, 0x02, 0x06, 0x01, 0x04, 0x00, 0x01, 0x00,
			0x01, 0x02, 0x02, 0x80, 0x00, 0x02, 0x02, 0x02,
			0x00, 0x02, 0x06, 0x41, 0x04, 0x00, 0x00, 0xfb,
			0xff, 0x02, 0x04, 0x40, 0x02, 0x00, 0x78, 0xff,
			0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
			0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00,
			0x3b, 0x01, 0x04, 0xfb, 0xf0, 0x00, 0x5a, 0x0a,
			0x0a, 0x0a, 0x01, 0x1e, 0x02, 0x06, 0x01, 0x04,
			0x00, 0x01, 0x00, 0x01, 0x02, 0x02, 0x80, 0x00,
			0x02, 0x02, 0x02, 0x00, 0x02, 0x04, 0x40, 0x02,
			0x00, 0x78, 0x02, 0x06, 0x41, 0x04, 0x00, 0x00,
			0xfb, 0xf0];

        let bb = Bytes::from(buf);
        //let bmp: PeerUpNotification<_> = Message::from_octets(&buf).unwrap().try_into().unwrap();
        let bmp: PeerUpNotification<_> = Message::from_octets(bb).unwrap().try_into().unwrap();

        assert_eq!(bmp.common_header().version(), 3);
        assert_eq!(bmp.common_header().length(), 186);
        assert_eq!(
            bmp.common_header().msg_type(),
            MessageType::PeerUpNotification
        );
        assert_eq!(
            bmp.per_peer_header().peer_type(),
            PeerType::GlobalInstance
        );
        assert!(bmp.per_peer_header().is_ipv4());
        assert_eq!(bmp.per_peer_header().distinguisher(), [0; 8]);
        assert_eq!(
            bmp.per_peer_header().address(),
            Ipv4Addr::from_str("10.255.0.101").unwrap()
        );

        assert_eq!(bmp.per_peer_header().asn(), Asn::from_u32(64496));
        assert_eq!(bmp.per_peer_header().bgp_id(), [0x0a, 0x0a, 0x0a, 0x1]);
        assert_eq!(bmp.per_peer_header().ts_seconds(), 1419906571);
        assert_eq!(bmp.per_peer_header().ts_micros(), 920608);

        assert_eq!(
            bmp.per_peer_header().timestamp().to_string(),
            "2014-12-30 02:29:31.920608 UTC"
        );

        // Now the actual PeerUpNotification
        assert_eq!(bmp.local_address(), Ipv4Addr::new(10, 255, 0, 83));
        assert_eq!(bmp.local_port(), 36974);
        assert_eq!(bmp.remote_port(), 179);
        
        // Now, the two variable length BGP OPEN messages
        // first, the sent one
        let bgp_open_sent = bmp.bgp_open_sent();
        assert_eq!(bgp_open_sent.version(), 4);
        assert_eq!(bgp_open_sent.my_asn(), Asn::from_u32(64511));
        assert_eq!(bgp_open_sent.identifier(), [10, 10, 10, 103]);
        assert_eq!(bgp_open_sent.opt_parm_len(), 30);
        assert_eq!(bgp_open_sent.parameters().count(), 5);
        
        // second, the received one
        let bgp_open_rcvd = bmp.bgp_open_rcvd();
        assert_eq!(bgp_open_rcvd.version(), 4);
        assert_eq!(bgp_open_rcvd.my_asn(), Asn::from_u32(64496));
        assert_eq!(bgp_open_rcvd.identifier(), [10, 10, 10, 1]);
        assert_eq!(bgp_open_rcvd.opt_parm_len(), 30);
        assert_eq!(bgp_open_rcvd.parameters().count(), 5);

        let (sent, rcvd) = bmp.bgp_open_sent_rcvd();
        assert_eq!(sent.as_ref(), bgp_open_sent.as_ref());
        assert_eq!(rcvd.as_ref(), bgp_open_rcvd.as_ref());

        let sc = bmp.pph_session_config();
        assert_eq!(sc.1, None);
        assert!(sc.0.four_octet_enabled());
        assert_eq!(sc.0.enabled_addpaths().count(), 0);

        assert_eq!(
            bmp.supported_protocols(),
            vec![(AfiSafiType::Ipv4Unicast)]
        );
    }

    #[test]
    fn initiation_message() {
		// BMP Initiation Messsage with two Information TLVs:
        // sysDesc and sysName
		let buf = vec![
			0x03, 0x00, 0x00, 0x00, 0x6c, 0x04, 0x00, 0x01,
			0x00, 0x5b, 0x43, 0x69, 0x73, 0x63, 0x6f, 0x20,
			0x49, 0x4f, 0x53, 0x20, 0x58, 0x52, 0x20, 0x53,
			0x6f, 0x66, 0x74, 0x77, 0x61, 0x72, 0x65, 0x2c,
			0x20, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e,
			0x20, 0x35, 0x2e, 0x32, 0x2e, 0x32, 0x2e, 0x32,
			0x31, 0x49, 0x5b, 0x44, 0x65, 0x66, 0x61, 0x75,
			0x6c, 0x74, 0x5d, 0x0a, 0x43, 0x6f, 0x70, 0x79,
			0x72, 0x69, 0x67, 0x68, 0x74, 0x20, 0x28, 0x63,
			0x29, 0x20, 0x32, 0x30, 0x31, 0x34, 0x20, 0x62,
			0x79, 0x20, 0x43, 0x69, 0x73, 0x63, 0x6f, 0x20,
			0x53, 0x79, 0x73, 0x74, 0x65, 0x6d, 0x73, 0x2c,
			0x20, 0x49, 0x6e, 0x63, 0x2e, 0x00, 0x02, 0x00,
			0x03, 0x78, 0x72, 0x33
		];
        let init: InitiationMessage<_> = Message::from_octets(&buf).unwrap().try_into().unwrap();
        assert_eq!(init.information_tlvs().count(), 2);
        let mut tlvs = init.information_tlvs();
        let tlv1 = tlvs.next().unwrap();
        assert_eq!(tlv1.typ(), InformationTlvType::SysDesc);
        assert_eq!(
            String::from_utf8_lossy(tlv1.value()),
            "Cisco IOS XR Software, Version 5.2.2.21I[Default]\
            \nCopyright (c) 2014 by Cisco Systems, Inc."
        );

        let tlv2 = tlvs.next().unwrap();
        assert_eq!(tlv2.typ(), InformationTlvType::SysName);
        assert_eq!(
            String::from_utf8_lossy(tlv2.value()),
            "xr3"
        );

    }

    #[test]
    fn termination_message() {
          // BMP Termination message
        let buf = vec![
            0x03, 0x00, 0x00, 0x00, 0x0C, 0x05, 0x00, 0x01, 0x00,
            0x02, 0x00, 0x03,
        ];
        let bmp: TerminationMessage<_> = Message::from_octets(&buf).unwrap().try_into().unwrap();
        assert_eq!(bmp.information().count(), 1);
        assert_eq!(
            bmp.information().next().unwrap(), 
            TerminationInformation::RedundantConnection,
        );

    }

    // XXX get proper RouteMirroring test data
    #[ignore]
    #[test]
    fn route_mirroring() {
        unimplemented!()
    }

    //--- Misc ---------------------------------------------------------------

    // As we rely on the `size_of` of some header types, make sure their size
    // is indeed what we expect it to be.
    //#[test]
    //fn header_sizes() {
    //    assert_eq!(std::mem::size_of::<CommonHeader>(), 6);
    //    assert_eq!(std::mem::size_of::<PerPeerHeader>(), 42);
    //}
    
}