summaryrefslogtreecommitdiffstats
path: root/bgpd/bgp_msg_read.c
blob: 5eef4d1fd6637dd6705238921f9f6912a83467a1 (plain)
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
/* BGP Message Read -- functions
 * Copyright (C) 2009 Chris Hall (GMCH), Highwayman
 *
 * This file is part of GNU Zebra.
 *
 * GNU Zebra is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2, or (at your option) any
 * later version.
 *
 * GNU Zebra is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with GNU Zebra; see the file COPYING.  If not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

#include <zebra.h>
#include <time.h>

#include "bgpd/bgp_common.h"
#include "bgpd/bgp_msg_read.h"
#include "bgpd/bgp_open.h"
#include "bgpd/bgpd.h"
#include "bgpd/bgp_debug.h"
#include "bgpd/bgp_aspath.h"
#include "bgpd/bgp_session.h"
#include "bgpd/bgp_open_state.h"
#include "bgpd/bgp_route_refresh.h"
#include "bgpd/bgp_fsm.h"
#include "bgpd/bgp_vty.h"

/*------------------------------------------------------------------------------
 * Message handler functions.
 */
static void bgp_msg_unknown_receive(bgp_connection connection,
                                                         bgp_size_t body_size) ;
static void bgp_msg_open_receive(bgp_connection connection,
                                                         bgp_size_t body_size) ;
static void bgp_msg_update_receive(bgp_connection connection,
                                                         bgp_size_t body_size) ;
static void bgp_msg_notify_receive(bgp_connection connection,
                                                         bgp_size_t body_size) ;
static void bgp_msg_keepalive_receive(bgp_connection connection,
                                                         bgp_size_t body_size) ;
static void bgp_msg_route_refresh_receive(bgp_connection connection,
                                                         bgp_size_t body_size) ;
static void bgp_msg_capability_receive(bgp_connection connection,
                                                         bgp_size_t body_size) ;

/*------------------------------------------------------------------------------
 * Get BGP message length, given a pointer to the start of a message.
 *
 * Make sure things are kosher.
 */
extern bgp_size_t
bgp_msg_get_mlen(uint8_t* p, uint8_t* limit)
{
  uint16_t mlen ;
  passert((p + BGP_MH_HEAD_L) <= limit) ;

  mlen = ((bgp_size_t)(*(p + BGP_MH_MARKER_L)) << 8)
                    + (*(p + BGP_MH_MARKER_L + 1)) ;

  passert((p + mlen) <= limit) ;

  return mlen ;
} ;

/*==============================================================================
 * Header validation and sexing of messages
 */
enum
{
  qBGP_MT_unknown      = 0,
  qBGP_MT_OPEN,
  qBGP_MT_UPDATE,
  qBGP_MT_NOTIFICATION,
  qBGP_MT_KEEPALIVE,
  qBGP_MT_ROUTE_REFRESH,
  qBGP_MT_CAPABILITY,
  qBGP_MT_ROUTE_REFRESH_pre,

  qBGP_MT_count,
} ;
                                    /*   0     1     2     3    */
static const uint8_t bgp_header[] = { 0xFF, 0xFF, 0xFF, 0xFF, /*  4 */
                                      0xFF, 0xFF, 0xFF, 0xFF, /*  8 */
                                      0xFF, 0xFF, 0xFF, 0xFF, /* 12 */
                                      0xFF, 0xFF, 0xFF, 0xFF  /* 16 */
                                 } ;
CONFIRM(sizeof(bgp_header) == BGP_MH_MARKER_L) ;

/* Array to map real BGP message type to qBGP message type      */
static const uint8_t bgp_type_map[256] =
{
  [BGP_MT_OPEN]              = qBGP_MT_OPEN,
  [BGP_MT_UPDATE]            = qBGP_MT_UPDATE,
  [BGP_MT_NOTIFICATION]      = qBGP_MT_NOTIFICATION,
  [BGP_MT_KEEPALIVE]         = qBGP_MT_KEEPALIVE,
  [BGP_MT_ROUTE_REFRESH]     = qBGP_MT_ROUTE_REFRESH,
  [BGP_MT_CAPABILITY]        = qBGP_MT_CAPABILITY,
  [BGP_MT_ROUTE_REFRESH_pre] = qBGP_MT_ROUTE_REFRESH_pre
} ;
CONFIRM(qBGP_MT_unknown == 0) ;

/* Array of minimum message length -- by qBGP_MT_xxx                    */
static const bgp_size_t bgp_type_min_size[] =
{
  [qBGP_MT_unknown]           = BGP_MSG_MAX_L + 1,      /* invalid !    */

  [qBGP_MT_OPEN]              = BGP_OPM_MIN_L,
  [qBGP_MT_OPEN]              = BGP_OPM_MIN_L,
  [qBGP_MT_UPDATE]            = BGP_UPM_MIN_L,
  [qBGP_MT_NOTIFICATION]      = BGP_NOM_MIN_L,
  [qBGP_MT_KEEPALIVE]         = BGP_KAM_L,
  [qBGP_MT_ROUTE_REFRESH]     = BGP_RRM_MIN_L,
  [qBGP_MT_CAPABILITY]        = BGP_MH_HEAD_L,          /* pro tem      */
  [qBGP_MT_ROUTE_REFRESH_pre] = BGP_RRM_MIN_L
} ;

/* Array of message handler functions -- by qBGP_MT_xxx                 */
static bgp_msg_handler* const bgp_type_handler[] =
{
  [qBGP_MT_unknown]           = bgp_msg_unknown_receive,

  [qBGP_MT_OPEN]              = bgp_msg_open_receive,
  [qBGP_MT_UPDATE]            = bgp_msg_update_receive,
  [qBGP_MT_NOTIFICATION]      = bgp_msg_notify_receive,
  [qBGP_MT_KEEPALIVE]         = bgp_msg_keepalive_receive,
  [qBGP_MT_ROUTE_REFRESH]     = bgp_msg_route_refresh_receive,
  [qBGP_MT_CAPABILITY]        = bgp_msg_capability_receive,
  [qBGP_MT_ROUTE_REFRESH_pre] = bgp_msg_route_refresh_receive
} ;

/* Array of message type names by qBGP_MT_xxxx                          */
static const char* bgp_type_name[] =
{
  [qBGP_MT_unknown]           = "*unknown*",

  [qBGP_MT_OPEN]              = "OPEN",
  [qBGP_MT_UPDATE]            = "UPDATE",
  [qBGP_MT_NOTIFICATION]      = "NOTIFICATION",
  [qBGP_MT_KEEPALIVE]         = "KEEPALIVE",
  [qBGP_MT_ROUTE_REFRESH]     = "ROUTE-REFRESH",
  [qBGP_MT_CAPABILITY]        = "CAPABILITY",
  [qBGP_MT_ROUTE_REFRESH_pre] = "ROUTE-REFRESH(pre)"
} ;

/*------------------------------------------------------------------------------
 * The message size field is invalid per RFC
 *
 * Issue notification and kick FSM.
 */
static void
bgp_msg_header_bad_len(bgp_connection connection, uint8_t type, bgp_size_t size)
{
  uint16_t notify_size = htons(size) ;

  if (BGP_DEBUG (normal, NORMAL))
    plog_debug (connection->log,
                "%s bad message length - %d for %s",
                connection->host, size,
                bgp_type_name[bgp_type_map[type]]) ;

  bgp_fsm_exception(connection, bgp_session_eInvalid_msg,
     bgp_notify_new_with_data(BGP_NOMC_HEADER, BGP_NOMS_H_BAD_LEN,
                                                      (void*)&notify_size, 2)) ;
} ;

/*------------------------------------------------------------------------------
 * The message type is either unknown, or not enabled by capability exchange.
 *
 * Issue notification and kick FSM.
 */
static void
bgp_msg_header_bad_type(bgp_connection connection, uint8_t type)
{
  if (BGP_DEBUG (normal, NORMAL))
    {
      if (bgp_type_map[type] == qBGP_MT_unknown)
        plog_debug (connection->log, "%s unknown message type 0x%02x",
                    connection->host, type) ;
      else
        plog_err (connection->log, "%s [Error] BGP %s is not enabled",
                          connection->host, bgp_type_name[bgp_type_map[type]]) ;
    } ;

  bgp_fsm_exception(connection, bgp_session_eInvalid_msg,
     bgp_notify_new_with_data(BGP_NOMC_HEADER, BGP_NOMS_H_BAD_TYPE,
                                                             (void*)&type, 1)) ;
} ;

/*------------------------------------------------------------------------------
 * Validate header part of BGP message.
 *
 * Have just read the header part (BGP_MH_HEAD_L) into connection->ibuf, need
 * to check it's valid, and find how much more to read to complete the
 * message.
 *
 * Advances the stream getp past the header.
 *
 * Plants:  msg_type      -- the message type
 *          msg_body_size -- the size of the message *body*
 *          msg_func      -- the function to process the message
 *
 * in the connection, ready for bgp_msg_dispatch().
 *
 * Returns: number of bytes still to read (ie msg_body_size) -- may be 0
 *
 * NB: deals with invalid header, unknown message type and less than minimum
 *     message length for the message type.
 *
 *     These all raise the required events, and return with minimum size
 *     message and the function set to bgp_msg_unknown_receive.
 *
 *     The effect is that the reader will not read any more, and will dispatch
 *     to bgp_msg_unknown_receive.
 */
int
bgp_msg_check_header(bgp_connection connection)
{
  uint8_t    type ;
  bgp_size_t size ;
  uint8_t    qt ;
  bgp_size_t min_size ;

  /* Get size and type.                                                 */
  stream_forward_getp (connection->ibuf, BGP_MH_MARKER_L);
  size = stream_getw (connection->ibuf);
  type = stream_getc (connection->ibuf);

  if (BGP_DEBUG (normal, NORMAL) && type != 2 && type != 0)
    zlog_debug ("%s rcv message type %d, length (excl. header) %d",
               connection->host, type, size - BGP_MH_HEAD_L);

  /* Marker check                                                       */
  /* TODO: why did old code only do this on OPEN and KEEPALIVE ?        */
  if (memcmp(connection->ibuf->data, bgp_header, BGP_MH_MARKER_L) == 0)
    {
      /* BGP type check and minimum/maximum message length checks.      */

      qt       = bgp_type_map[type] ;   /* qBGP_MT_unknown if not valid */
      min_size = bgp_type_min_size[qt] ;/* > BGP_MSG_MAX_L if not valid */

      if ((size < min_size) || (size > BGP_MSG_MAX_L))
        {
          if (qt == qBGP_MT_unknown)
            {
              if (BGP_DEBUG (normal, NORMAL))
                plog_debug (connection->log, "%s unknown message type 0x%02x",
                            connection->host, type);

              bgp_fsm_exception(connection, bgp_session_eInvalid_msg,
                 bgp_notify_new_with_data(BGP_NOMC_HEADER, BGP_NOMS_H_BAD_TYPE,
                                                             (void*)&type, 1)) ;
            }
          else
            bgp_msg_header_bad_len(connection, type, size) ;

          size = BGP_MH_HEAD_L ;            /* can stop reading, now        */
        }
    }
  else
    {
      bgp_fsm_exception(connection, bgp_session_eInvalid_msg,
                      bgp_notify_new(BGP_NOMC_HEADER, BGP_NOMS_H_NOT_SYNC)) ;
      qt   = qBGP_MT_unknown ;          /* force unknown message        */
      size = BGP_MH_HEAD_L ;            /* can stop reading, now        */
    } ;


  connection->msg_type      = type ;
  connection->msg_body_size = size - BGP_MH_HEAD_L ;
  connection->msg_func      = bgp_type_handler[qt] ;

  return connection->msg_body_size ;
} ;

/*==============================================================================
 * Invalid message handler.
 *
 * Does nothing at all -- the error has already been deal with, this just
 * allows unknown (and invalid) messages to be handled just like OK ones.
 */
static void bgp_msg_unknown_receive(bgp_connection connection, bgp_size_t body_size)
{
  return ;
} ;

/*==============================================================================
 * BGP OPEN message
 *
 *
 *
 */

static int
bgp_msg_open_option_parse (bgp_connection connection, bgp_notify notification,
                                                                    sucker sr) ;
static int
bgp_msg_capability_option_parse (bgp_connection connection,
                                           bgp_notify notification, sucker sr) ;
static int
bgp_msg_open_error(bgp_notify notification, bgp_nom_subcode_t subcode) ;

static int
bgp_msg_open_invalid(bgp_notify notification) ;

/*------------------------------------------------------------------------------
 * Receive BGP open packet and parse it into the connection's open_recv
 *
 * NB: requires the session to be locked (connection-wise) and not NULL.
 */
static void
bgp_msg_open_receive (bgp_connection connection, bgp_size_t body_size)
{
  int ret;
  u_char version;
  u_char optlen;
  struct in_addr remote_id;
  bgp_open_state open_recv;
  struct stream* s ;
  struct sucker ssr ;
  unsigned holdtime ;

  ++connection->session->stats.open_in ;

  /* Start with an unspecific OPEN notification                         */
  bgp_notify notification = bgp_notify_new(BGP_NOMC_OPEN,
                                                       BGP_NOMS_UNSPECIFIC) ;

  /* To receive the parsed open message                                 */
  open_recv = connection->open_recv
                              = bgp_open_state_init_new(connection->open_recv) ;

  /* Parse fixed part of the open packet                                */
  s = connection->ibuf ;

  version = stream_getc (s);
  open_recv->my_as2   = stream_getw (s);
  open_recv->holdtime = stream_getw (s);
  open_recv->bgp_id   = stream_get_ipv4 (s);

  open_recv->my_as    = open_recv->my_as2 ;

  remote_id.s_addr = open_recv->bgp_id ;

  /* Receive OPEN message log                                           */
  if (BGP_DEBUG (normal, NORMAL))
    zlog_debug ("%s rcv OPEN, version %d, remote-as (in open) %u,"
                " holdtime %d, id %s",
                connection->host, version,
                open_recv->my_as, open_recv->holdtime,
                safe_inet_ntoa (remote_id));

  /* Peer BGP version check.                                            */
  if (version != BGP_VERSION_4)
    {
      if (BGP_DEBUG (normal, NORMAL))
        zlog_debug("%s bad protocol version, remote requested %d, local max %d",
                   connection->host, version, BGP_VERSION_4);

      bgp_msg_open_error(notification, BGP_NOMS_O_VERSION) ;
      bgp_notify_append_w(notification, BGP_VERSION_4) ;

      goto reject ;
    }

  /* Remote bgp_id may not be multicast, or the same as here            */
  if (IN_MULTICAST(ntohl(open_recv->bgp_id)) ||
           (open_recv->bgp_id == connection->session->open_send->bgp_id))
    {
      zlog_debug ("%s rcv OPEN, multicast or our id %s",
                  connection->host, safe_inet_ntoa (remote_id)) ;
      bgp_msg_noms_o_bad_id(notification, open_recv->bgp_id) ;
      goto reject ;
    } ;

  /* From the rfc: Upon receipt of an OPEN message, a BGP speaker MUST
     calculate the value of the Hold Timer by using the smaller of its
     configured Hold Time and the Hold Time received in the OPEN message.
     The Hold Time MUST be either zero or at least three seconds.  An
     implementation may reject connections on the basis of the Hold Time.

     See below where sets keepalive to hold / 3 !!
  */
  if (open_recv->holdtime < 3 && open_recv->holdtime != 0)
    {
      bgp_msg_open_error(notification, BGP_NOMS_O_H_TIME) ;
      goto reject ;
    } ;

  /* Open option part parse                                             */

  optlen = stream_getc(s) ;

  if (BGP_DEBUG (normal, NORMAL))
    zlog_debug ("%s rcv OPEN w/ OPTION parameter len: %u",
                                                    connection->host, optlen) ;

  if (optlen != stream_get_left(s))
    {
      zlog_err ("%s bad OPEN, message length %u but option length %u",
                connection->host, (unsigned)stream_get_endp(s), optlen) ;
      bgp_msg_open_invalid(notification) ;
      goto reject ;
    } ;

  suck_init(&ssr, stream_pnt(s), optlen) ;

  ret = bgp_msg_open_option_parse (connection, notification, &ssr) ;
  if (ret < 0)
    goto reject ;

  /* Now worry about the AS number                                      */

  /* ASN == 0 is odd for AS2, error for AS4             */
  if (open_recv->my_as == 0)
    {
      if (open_recv->can_as4)
        {
          zlog_err ("%s [AS4] bad OPEN, got AS4 capability, but AS4 set to 0",
                    connection->host) ;
          bgp_msg_open_error(notification, BGP_NOMS_O_BAD_AS) ;
          goto reject ;
        }
      else
        {
          if (BGP_DEBUG (as4, AS4))
            zlog_debug ("%s [AS4] OPEN remote_as is 0 (not AS4 speaker)"
                                    " odd, but proceeding.", connection->host) ;
        } ;
    } ;

  /* ASN = BGP_AS_TRANS is odd for AS2, error for AS4   */
  if (open_recv->my_as == BGP_ASN_TRANS)
    {
      if (open_recv->can_as4)
        {
          zlog_err ("%s [AS4] NEW speaker using AS_TRANS for AS4, not allowed",
                    connection->host);
          bgp_msg_open_error(notification, BGP_NOMS_O_BAD_AS) ;
          goto reject ;
        }
      else
        {
          if (BGP_DEBUG (as4, AS4))
            zlog_debug ("%s [AS4] OPEN remote_as is AS_TRANS (not AS4 speaker)"
                                    " odd, but proceeding.", connection->host) ;
        } ;
    } ;

  /* Worry about my_as2 for AS4 speaker, if as2 != as4  */
  if ((open_recv->can_as4) && (open_recv->my_as != open_recv->my_as2))
    {
      if (open_recv->my_as2 == BGP_ASN_TRANS)
        {
          if ((open_recv->my_as <= BGP_AS2_MAX) && BGP_DEBUG(as4, AS4))
            zlog_debug ("%s [AS4] OPEN remote_as is AS_TRANS,"
                        " but AS4 (%u) fits in 2-bytes, very odd peer.",
                        connection->host, open_recv->my_as) ;
        }
      else
        {
          zlog_err ("%s bad OPEN, got AS4 capability, but remote_as %u"
                    " mismatch with 16bit 'myasn' %u in open",
                    connection->host, open_recv->my_as, open_recv->my_as2) ;

          bgp_msg_open_error(notification, BGP_NOMS_O_BAD_AS) ;
          goto reject ;
        } ;
    } ;

  /* Finally -- require the AS to be the configured AS  */
  if (open_recv->my_as != connection->session->as_peer)
    {
      if (BGP_DEBUG (normal, NORMAL))
        zlog_debug ("%s bad OPEN, remote AS is %u, expected %u",
                   connection->host, open_recv->my_as,
                                                 connection->session->as_peer) ;

      bgp_msg_open_error(notification, BGP_NOMS_O_BAD_AS) ;
      if (open_recv->can_as4)
        bgp_notify_append_l(notification, open_recv->my_as) ;
      else
        bgp_notify_append_w(notification, open_recv->my_as) ;

      goto reject ;
    }

  /*............................................................................
   * It's OK !  Update the connection and issue event.
   */
  bgp_notify_free(notification) ;       /* No further use for this      */

  holdtime = connection->session->open_send->holdtime ;

  if (holdtime > open_recv->holdtime)
    holdtime = open_recv->holdtime ;    /* use smaller of theirs & ours */
  if (holdtime < 3)
    holdtime = 0 ;                      /* no slip ups                  */

  connection->hold_timer_interval       = holdtime ;
  connection->keepalive_timer_interval  = holdtime / 3 ;

  connection->as4            = open_recv->can_as4 ;
  connection->route_refresh  = open_recv->can_r_refresh ;
  connection->orf_prefix     = open_recv->can_orf_prefix ;

  bgp_fsm_open_received(connection) ;

  return ;

  /*............................................................................
   * Failed.  Reject the OPEN with the required notification.
   */
reject:
  bgp_fsm_exception(connection, bgp_session_eOpen_reject, notification);
} ;

/*------------------------------------------------------------------------------
 * Set notification to BGP_NOMC_OPEN/BGP_NOMS_O_BAD_ID and set the data part
 * to be the given bad id.
 *
 * Create notification if required.
 */
extern bgp_notify
bgp_msg_noms_o_bad_id(bgp_notify notification, bgp_id_t id)
{
  notification = bgp_notify_reset(notification, BGP_NOMC_OPEN,
                                                            BGP_NOMS_O_BAD_ID) ;
  bgp_notify_append_data(notification, &id, 4) ;

  return notification ;
} ;

/*------------------------------------------------------------------------------
 * Reset notification to BGP_NOMC_OPEN with the given subcode, and return -1.
 */
static int
bgp_msg_open_error(bgp_notify notification, bgp_nom_subcode_t subcode)
{
  bgp_notify_reset(notification, BGP_NOMC_OPEN, subcode) ;
  return -1 ;
} ;

/*------------------------------------------------------------------------------
 * Reset notification to BGP_NOMC_OPEN/BGP_NOMS_UNSPECIFIC, and return -1.
 */
static int
bgp_msg_open_invalid(bgp_notify notification)
{
  return bgp_msg_open_error(notification, BGP_NOMS_UNSPECIFIC) ;
} ;

/*------------------------------------------------------------------------------
 * Add unsupported capability to notification.
 *
 * The sr points at the start of the capability value.
 */
static void
bgp_msg_capability_unsupported(bgp_notify notification, sucker sr)
{
  ptr_t  p_cap ;
  int    cap_len ;

  if (notification->subcode != BGP_NOMS_O_CAPABILITY)
    bgp_notify_reset(notification, BGP_NOMC_OPEN, BGP_NOMS_O_CAPABILITY) ;

  cap_len = suck_total(sr) ;
  p_cap   = suck_start(sr) - BGP_CAP_MIN_L ;

  assert(*(p_cap + 1) == cap_len) ;

  bgp_notify_append_data(notification, p_cap, BGP_CAP_MIN_L + cap_len) ;
} ;

/*------------------------------------------------------------------------------
 * Parse OPEN message options part.
 *
 * Expects the notification to be set up: BGP_NOMC_OPEN, BGP_NOMS_UNSPECIFIC
 *                                        with no data, yet.
 *
 * Returns: -1 => error -- see notification
 *           0 => OK, no capabilities
 *           1 => OK, at least one capability
 */
static int
bgp_msg_open_option_parse (bgp_connection connection, bgp_notify notification,
                                                                      sucker sr)
{
  int ret, capability ;
  int left ;
  bgp_session session = connection->session ;
  bgp_open_state open_send = session->open_send ;
  bgp_open_state open_recv = connection->open_recv ;

  /* Prepare to read BGP OPEN message options                           */

  ret        = 0 ;      /* OK so far                    */
  capability = 0 ;      /* No capability option, yet    */

  while ((left = suck_left(sr)) > 0)
    {
      struct sucker ssr ;
      u_char opt_type ;
      u_char opt_length ;

      /* Fetch option type and length, if possible      */
      if ((left -= 2) > 0)
        {
          opt_type   = suck_b(sr);
          opt_length = suck_b(sr);
          left -= opt_length ;
        }
      else
        {
          opt_type   = 0 ;      /* ensure initialised   */
          opt_length = 0 ;
        }

      /* Must not have exceeded available bytes         */
      if (left < 0)
        {
          zlog_info ("%s Option length error", connection->host);
          return bgp_msg_open_invalid(notification) ;
        }

      if (BGP_DEBUG (normal, NORMAL))
        zlog_debug ("%s rcvd OPEN w/ optional parameter type %u (%s) len %u",
                   connection->host, opt_type,
                   opt_type == BGP_OPEN_OPT_AUTH ? "Authentication" :
                   opt_type == BGP_OPEN_OPT_CAP ? "Capability" : "Unknown",
                   opt_length);

      suck_push(sr, opt_length, &ssr) ;

      switch (opt_type)
        {
        case BGP_OPT_AUTH:
          return bgp_msg_open_error(notification, BGP_NOMS_O_AUTH) ;

        case BGP_OPT_CAPS:
          capability = 1 ;      /* does => can  */

          ret = bgp_msg_capability_option_parse(connection, notification, sr) ;
          if (ret < 0)
            return bgp_msg_open_invalid(notification) ;

          break;

        default:
          return bgp_msg_open_error(notification, BGP_NOMS_O_OPTION) ;
        } ;

      suck_pop(sr, &ssr) ;
    } ;

  /* All OPEN option is parsed.
   *
   * Do "strict" capability checks:
   *
   *   1) if there were any unknown capabilities, or any AFI/SAFI which are
   *      unknown or are not configured, then that is now an error.
   *
   *   2) the local AFI/SAFI must be the same as the remote AFI/SAFI.
   *
   * NB: cap_override and cap_strict are mutually exclusive
   *
   * TODO: what about graceful restart and no CAP-MP ??
   */
  if (session->cap_strict)
    {
      /* Treat any unsupported capability as an error.          */
      if (bgp_notify_get_subcode(notification) == BGP_NOMS_O_CAPABILITY)
        return -1 ;

      /* Check local AFI/SAFI set is same as the remote one.    */
      if (open_recv->can_mp_ext != open_send->can_mp_ext)
        return bgp_msg_open_error(notification, BGP_NOMS_O_CAPABILITY) ;
    } ;

  /* If there were any capabilities, and not going to override AFI/SAFI,
   * then check that there is at least one AFI/SAFI in common.
   */
  if (capability && ! session->cap_override)
    {
      if ((open_recv->can_mp_ext & open_send->can_mp_ext) == 0)
        {
          plog_err (connection->log, "%s [Error] No common capability",
                                                             connection->host) ;
          if (bgp_notify_get_subcode(notification) != BGP_NOMS_O_CAPABILITY)
            bgp_msg_open_error(notification, BGP_NOMS_O_CAPABILITY) ;

          return -1 ;
        }
    } ;

  return connection->open_recv->can_capability = capability ;
} ;

/*------------------------------------------------------------------------------
 * From IANA "Capability Codes (last updated 2009-08-04) Reference: [RFC5492]"
 *
 *   Range      Registration Procedures
 *   ---------  --------------------------
 *     1- 63    IETF Review
 *    64-127    First Come First Served
 *   128-255    Reserved for Private Use    (IANA does not assign)
 *
 *    1  Multiprotocol Extensions for BGP-4                     [RFC2858]
 *    2  Route Refresh Capability for BGP-4                     [RFC2918]
 *    3  Outbound Route Filtering Capability                    [RFC5291]
 *    4  Multiple routes to a destination capability            [RFC3107]
 *    5  Extended Next Hop Encoding                             [RFC5549]
 *   64  Graceful Restart Capability                            [RFC4724]
 *   65  Support for 4-octet AS number capability               [RFC4893]
 *   66  Deprecated (2003-03-06)
 *   67  Support for Dynamic Capability (capability specific)      [Chen]
 *   68  Multisession BGP Capability                            [Appanna]
 *   69  ADD-PATH Capability                   [draft-ietf-idr-add-paths]
 *
 * 66 is, in fact, for draft-ietf-idr-dynamic-cap-02 of the Support for
 *                                      Dynamic Capability (capability specific)
 *
 * Supported:
 *
 *    1  BGP_CAN_MP_EXT           -- Multiprotocol Extensions
 *    2  BGP_CAN_R_REFRESH        -- Route Refresh
 *    3  BGP_CAN_ORF              -- Outbound Route Filtering
 *   64  BGP_CAN_G_RESTART        -- Graceful Restart
 *   65  BGP_CAN_AS4              -- AS4
 *   66  BGP_CAN_DYNAMIC_CAP_old  -- Dynamic Capability (old form)
 *  128  BGP_CAN_R_REFRESH_pre    -- pre-RFC Route Refresh
 *  130  BGP_CAN_ORF_pre          -- pre-RFC Outbound Route Filtering
 */

CONFIRM(BGP_CAP_MPE_L       == sizeof (struct capability_mp_data)) ;
CONFIRM(BGP_CAP_RRF_L       == CAPABILITY_CODE_REFRESH_LEN) ;
CONFIRM(BGP_CAP_ORFE_MIN_L  == sizeof (struct capability_orf_entry)) ;
CONFIRM(BGP_CAP_GR_MIN_L    == sizeof (struct capability_gr)) ;
CONFIRM(BGP_CAP_AS4_L       == CAPABILITY_CODE_AS4_LEN) ;
CONFIRM(BGP_CAP_DYN_L       == CAPABILITY_CODE_DYNAMIC_LEN) ;

CONFIRM(BGP_CAN_MP_EXT          == CAPABILITY_CODE_MP) ;
CONFIRM(BGP_CAN_R_REFRESH       == CAPABILITY_CODE_REFRESH) ;
CONFIRM(BGP_CAN_ORF             == CAPABILITY_CODE_ORF) ;
CONFIRM(BGP_CAN_G_RESTART       == CAPABILITY_CODE_RESTART) ;
CONFIRM(BGP_CAN_AS4             == CAPABILITY_CODE_AS4) ;
CONFIRM(BGP_CAN_DYNAMIC_CAP_old == CAPABILITY_CODE_DYNAMIC) ;
CONFIRM(BGP_CAN_R_REFRESH_pre   == CAPABILITY_CODE_REFRESH_OLD) ;
CONFIRM(BGP_CAN_ORF_pre         == CAPABILITY_CODE_ORF_OLD) ;

/* TODO: clarify value for BGP_CAN_DYNAMIC_CAP  !!      */

/* Minimum sizes for length field of each cap (so not inc. the header) */
static const unsigned cap_minsizes[] =
{
  [BGP_CAN_MP_EXT]          = BGP_CAP_MPE_L,
  [BGP_CAN_R_REFRESH]       = BGP_CAP_RRF_L,
  [BGP_CAN_ORF]             = BGP_CAP_ORFE_MIN_L,
  [BGP_CAN_G_RESTART]       = BGP_CAP_GR_MIN_L,
  [BGP_CAN_AS4]             = BGP_CAP_AS4_L,
  [BGP_CAN_DYNAMIC_CAP_old] = BGP_CAP_DYN_L,
  [BGP_CAN_DYNAMIC_CAP]     = BGP_CAP_DYN_L,
  [BGP_CAN_R_REFRESH_pre]   = BGP_CAP_RRF_L,
  [BGP_CAN_ORF_pre]         = BGP_CAP_ORFE_MIN_L,
} ;

static const unsigned cap_maxsizes[] =
{
  [BGP_CAN_MP_EXT]          = BGP_CAP_MPE_L,
  [BGP_CAN_R_REFRESH]       = BGP_CAP_RRF_L,
  [BGP_CAN_ORF]             = BGP_CAP_MAX_L,  /* variable      */
  [BGP_CAN_G_RESTART]       = BGP_CAP_MAX_L,  /* variable      */
  [BGP_CAN_AS4]             = BGP_CAP_AS4_L,
  [BGP_CAN_DYNAMIC_CAP_old] = BGP_CAP_DYN_L,
  [BGP_CAN_DYNAMIC_CAP]     = BGP_CAP_DYN_L,
  [BGP_CAN_R_REFRESH_pre]   = BGP_CAP_RRF_L,
  [BGP_CAN_ORF_pre]         = BGP_CAP_MAX_L,  /* variable      */
} ;

/* Forward references for parsing individual capabilities, return -1 if the
 * capability is malformed or contains invalid values.
 */
static int
bgp_msg_capability_mp(bgp_connection connection, sucker sr) ;

static int
bgp_msg_capability_orf (bgp_connection connection, uint8_t cap_code, sucker sr);

static int
bgp_msg_capability_restart (bgp_connection connection, sucker sr) ;

static int
bgp_msg_capability_as4 (bgp_connection connection, sucker sr) ;

/*------------------------------------------------------------------------------
 * Set notification to malformed/invalid.
 *
 * Returns -1 !
 */
static int
bgp_msg_capability_bad(bgp_notify notification)
{
  bgp_notify_reset(notification, BGP_NOMC_OPEN, BGP_NOMS_UNSPECIFIC) ;
  return -1 ;
} ;

/*------------------------------------------------------------------------------
 * Parse given capability option -- may contain multiple capabilities.
 *
 * Adjusts the open_recv open state according to the capabilities seen.
 *
 * Collects unsupported capabilities in the notification, where a
 * BGP_NOMS_O_CAPABILITY message will be created.  So, at the end of the
 * process, can tell if there are any unsupported capabilities.
 *
 * The unsupported capabilities will be:
 *
 *    * MP Extensions AFI/SAFI which are unknown or are not configured at
 *      this end.
 *
 *    * any unknown capabilities < 128
 *
 * If an invalid or malformed capability is found, the notification is set
 * BGP_NOMS_UNSPECIFIC -- see bgp_msg_capability_bad() above.
 *
 * Returns:  0 => OK (but may have collected some unsupported capabilities)
 *          -1 => invalid or malformed
 */
static int
bgp_msg_capability_option_parse (bgp_connection connection,
                                             bgp_notify notification, sucker sr)
{
  int ret, left ;
  bgp_open_state open_recv = connection->open_recv ;

  while ((left = suck_left(sr)) > 0)
    {
      struct sucker ssr ;
      int      cap_code ;
      unsigned cap_length ;

      /* We need at least capability code and capability length. */
      if ((left -= 2) >= 0)
        {
          cap_code   = suck_b(sr);
          cap_length = suck_b(sr);
          left -= cap_length ;
        }

      if (left < 0)
        {
          zlog_info ("%s Capability length error (< header)", connection->host);
          return bgp_msg_capability_bad(notification) ;
        } ;

      if (BGP_DEBUG (normal, NORMAL))
        zlog_debug ("%s OPEN has %s capability (%u), length %u",
                   connection->host,
                   LOOKUP (capcode_str, cap_code),
                   cap_code, cap_length) ;

      /* Length sanity check, type-specific, for known capabilities */
      switch (cap_code)
        {
          case BGP_CAN_MP_EXT:
          case BGP_CAN_R_REFRESH:
          case BGP_CAN_ORF:
          case BGP_CAN_G_RESTART:
          case BGP_CAN_AS4:
          case BGP_CAN_DYNAMIC_CAP:
          case BGP_CAN_R_REFRESH_pre:
          case BGP_CAN_ORF_pre:
              /* Check length. */
              if ( (cap_length < cap_minsizes[cap_code]) ||
                   (cap_length > cap_maxsizes[cap_code]) )
                {
                  const char* tag = "" ;
                  if (cap_minsizes[cap_code] != cap_maxsizes[cap_code])
                    tag = "at least " ;
                  zlog_info ("%s %s Capability length error: got %u,"
                             " expected %s%u",
                             connection->host,
                             LOOKUP (capcode_str, cap_code),
                             cap_length, tag,
                             (unsigned) cap_minsizes[cap_code]) ;
                  return bgp_msg_capability_bad(notification) ;
                                                        /* invalid: stop dead */
                } ;
              break ;
          /* we deliberately ignore unknown codes, see below */
          default:
            break ;
        } ;

      /* By this point the capability length is exactly right for the
       * fixed length capabilities, at least the minimum length for the rest.
       * Also, then capability fits within the capability option.
       */
      suck_push(sr, cap_length, &ssr) ;

      ret = 0 ;
      switch (cap_code)
        {
          case BGP_CAN_MP_EXT:
            /* Ignore capability when override-capability is set.
             *
             * NB: bgp_msg_capability_mp() returns > 0 if the AFI/SAFI is not
             *     recognised or is not one of the configured ones.
             */
            if (! connection->session->cap_override)
              ret = bgp_msg_capability_mp(connection, sr);
            break;

          case BGP_CAN_R_REFRESH:
            open_recv->can_r_refresh |= bgp_form_rfc ;
            break ;

          case BGP_CAN_R_REFRESH_pre:
            open_recv->can_r_refresh |= bgp_form_pre;
            break;

          case BGP_CAN_ORF:
          case BGP_CAN_ORF_pre:
            ret = bgp_msg_capability_orf(connection, cap_code, sr) ;
            break;

          case BGP_CAN_G_RESTART:
            ret = bgp_msg_capability_restart(connection, sr) ;
            break;

          case BGP_CAN_DYNAMIC_CAP_old:
            open_recv->can_dynamic = 1;
            break;

          case BGP_CAN_AS4:
            ret = bgp_msg_capability_as4(connection, sr) ;
            break;

          default:
            if (cap_code >= 128)
              {
                /* We don't send Notification for unknown vendor specific
                   capabilities.  It seems reasonable for now...  */
                zlog_warn ("%s Vendor specific capability %d",
                           connection->host, cap_code);
              }
            else
              {
                zlog_warn ("%s unrecognized capability code: %d - ignored",
                           connection->host, cap_code) ;
                ret = 1 ;       /* collect unsupported capability       */
              }

            /* Add given unknown capability and its value */
            bgp_open_state_unknown_add(open_recv, cap_code,
                                               suck_start(sr), suck_total(sr)) ;
          }

      if (ret < 0)
        return bgp_msg_capability_bad(notification) ;

      if (ret > 0)
        bgp_msg_capability_unsupported(notification, sr) ;

      suck_pop(sr, &ssr) ;
    }

  return 0 ;
} ;

static qafx_bit_t
bgp_msg_afi_safi(sucker sr, struct iAFI_SAFI* mp)
{
  mp->afi  = suck_w(sr) ;
             suck_x(sr) ;
  mp->safi = suck_b(sr) ;

  return qafx_bit_from_iAFI_iSAFI(mp->afi, mp->safi) ;
} ;

/*------------------------------------------------------------------------------
 * Process value of Multiprotocol Extensions -- BGP_CAN_MP_EXT -- RFC2858
 *
 * Capability is:  AFI       -- word
 *                 reserved  -- byte
 *                 SAFI      -- byte
 *
 * This is a fixed length capability, so that's been dealt with.
 *
 * Treats: invalid AFI/SAFI combinations )
 *         unknown AFI/SAFI combinations ) unsupported capability
 *     unsupported AFI/SAFI combinations )
 *
 * Sets any known AFI/SAFI combination in open_recv->can_mp_ext.
 *
 * Returns:  0 => OK -- AFI/SAFI is in the open_sent set
 *           1 =>    -- AFI/SAFI is known, but not in the open_sent set
 *           2 =>    -- AFI/SAFI is not known, may be invalid
 */
static int
bgp_msg_capability_mp(bgp_connection connection, sucker sr)
{
  struct iAFI_SAFI mp ;
  qafx_bit_t qb ;
  bgp_cap_afi_safi cap ;

  qb = bgp_msg_afi_safi(sr, &mp) ;

  if (BGP_DEBUG (normal, NORMAL))
    zlog_debug ("%s OPEN has MP_EXT CAP for afi/safi: %u/%u",
                                          connection->host, mp.afi, mp.safi) ;

  cap = bgp_open_state_afi_safi_add(connection->open_recv, mp.afi, mp.safi,
                                                    (qb != 0), BGP_CAN_MP_EXT) ;
  if (qb == 0)
    {
      zlog_warn ("Unknown afi/safi combination (%u/%u)", mp.afi, mp.safi) ;
      return 2 ;
    } ;

  /* Now can register the capability                    */
  connection->open_recv->can_mp_ext |= qb;

  /* Return: 0 => is in the open_send set
   *         1 => is not
   */
  return ((connection->session->open_send->can_mp_ext & qb) != 0) ? 0 : 1 ;
} ;

/*------------------------------------------------------------------------------
 * Process value of Outbound Route Filtering -- BGP_CAN_ORF -- RFC5291
 *
 * Must have at least one ORF Entry, but may have several and each is of
 * variable length.
 *
 * Requirement for at least one entry has already been checked.
 *
 * Returns:  0 => OK
 *          -1 => malformed !
 *
 * NB: treats multiple ORF capabilities and multiple entries as additive.
 *     Does not track what AFI/SAFI and ORF types have been declared.
 */

static int bgp_msg_capability_orf_entry(bgp_connection connection,
                                                  uint8_t cap_code, sucker sr) ;

static int
bgp_msg_capability_orf(bgp_connection connection, uint8_t cap_code, sucker sr)
{
  while (suck_left(sr) > 0)
    {
      if (suck_left(sr) < BGP_CAP_ORFE_MIN_L)
        {
          zlog_info ("%s ORF Capability length error,"
                     " Cap length left %u",
                     connection->host, suck_left(sr)) ;
          return -1;
        } ;

      if (bgp_msg_capability_orf_entry (connection, cap_code, sr) == -1)
        return -1;
    } ;

  return 0;
} ;

/* Process ORF Entry:
 *
 * Entry is:  AFI       -- word
 *            reserved  -- byte
 *            SAFI      -- byte
 *            number    -- byte
 *            type      -- byte ) repeated "number" times
 *            send/recv -- byte )
 *
 * Returns:  0 => OK
 *          -1 => malformed
 */
static int
bgp_msg_capability_orf_entry(bgp_connection connection, uint8_t cap_code,
                                                                      sucker sr)
{
  iAFI_SAFI_t  mp ;
  int          number ;
  int          length ;
  sucker_t     ssr ;
  bgp_cap_afi_safi cap ;

  bgp_open_state open_recv = connection->open_recv ;
  qafx_bit_t qb ;

  /* ORF Entry header                                                   */
  qb     = bgp_msg_afi_safi(sr, &mp) ;
  number = suck_b(sr) ;

  if (BGP_DEBUG (normal, NORMAL))
    zlog_debug ("%s ORF Cap entry for afi/safi: %u/%u %d types",
                connection->host, mp.afi, mp.safi, number) ;

  /* Check AFI and SAFI.                                                */
  if (qb == 0)
    zlog_info ("%s Addr-family %d/%d not known."
               " Ignoring the ORF capability",
               connection->host, mp.afi, mp.safi) ;

  /* Validate number field                                              */
  length = number * BGP_CAP_ORFT_L ;

  if (suck_left(sr) < length)
    {
      zlog_info ("%s ORF Capability entry length error,"
                 " Cap length left %u, num %u",
                 connection->host, suck_left(sr), number) ;
      return -1;
    } ;

  /* Process the supported ORF types                                    */

  suck_push(sr, length, &ssr) ;

  while (number--)
    {
      qafx_bit_t qbs ;

      uint8_t type = suck_b(sr) ;
      uint8_t mode = suck_b(sr) ;

      /* ORF Mode error check                                           */
      switch (mode)
        {
          case BGP_CAP_ORFT_M_RECV:
          case BGP_CAP_ORFT_M_SEND:
          case BGP_CAP_ORFT_M_BOTH:
            break;
          default:
            zlog_info ("%s Invalid send/receive 'mode' value %d"
                       " in ORF capability",
                       connection->host, mode) ;
            return -1 ;
        } ;

      /* ORF Type and afi/safi sexing                                   */
      qbs = 0 ;
      switch (cap_code)
        {
          case BGP_CAN_ORF:
            switch (type)
              {
                case BGP_CAP_ORFT_T_PFIX:
                  open_recv->can_orf_prefix |= bgp_form_rfc ;
                  qbs =   qafx_ipv4_unicast_bit
                        | qafx_ipv4_multicast_bit
                        | qafx_ipv6_unicast_bit ;
                  break ;
                default:
                  break ;
              }
            break;
          case BGP_CAN_ORF_pre:
            switch (type)
              {
                case BGP_CAP_ORFT_T_PFIX_pre:
                  open_recv->can_orf_prefix |= bgp_form_pre ;
                  qbs =   qafx_ipv4_unicast_bit
                        | qafx_ipv4_multicast_bit
                        | qafx_ipv6_unicast_bit ;
                  break ;
                default:
                  break ;
              }
            break ;
          default:
            break ;
        } ;

      cap = bgp_open_state_afi_safi_add(connection->open_recv, mp.afi, mp.safi,
                                                          (qb != 0), cap_code) ;
      cap->caps.orf.known_orf_type = (qbs != 0) ;
      cap->caps.orf.type           = type ;
      cap->caps.orf.send           = ((mode & BGP_CAP_ORFT_M_SEND) != 0) ;
      cap->caps.orf.recv           = ((mode & BGP_CAP_ORFT_M_RECV) != 0) ;

      if ((qbs & qb) == 0)
        {
          if (BGP_DEBUG (normal, NORMAL))
              zlog_debug ("%s Addr-family %d/%d has"
                          " ORF type/mode %d/%d not supported",
                         connection->host, mp.afi, mp.safi, type, mode) ;
          continue ;
        } ;

      if (BGP_DEBUG (normal, NORMAL))
        zlog_debug ("%s OPEN has %s ORF capability"
                    " as %s for afi/safi: %d/%d",
                    connection->host, LOOKUP (orf_type_str, type),
                    LOOKUP (orf_mode_str, mode),
                    mp.afi, mp.safi) ;

      if (mode & BGP_CAP_ORFT_M_SEND)
        open_recv->can_orf_prefix_send |= qb ;
      if (mode & BGP_CAP_ORFT_M_RECV)
        open_recv->can_orf_prefix_recv |= qb ;

      confirm((BGP_CAP_ORFT_M_RECV & BGP_CAP_ORFT_M_SEND) == 0) ;

      confirm((BGP_CAP_ORFT_M_SEND & BGP_CAP_ORFT_M_SEND) != 0) ;
      confirm((BGP_CAP_ORFT_M_BOTH & BGP_CAP_ORFT_M_SEND) != 0) ;

      confirm((BGP_CAP_ORFT_M_RECV & BGP_CAP_ORFT_M_RECV) != 0) ;
      confirm((BGP_CAP_ORFT_M_BOTH & BGP_CAP_ORFT_M_RECV) != 0) ;
    } ;

  /* Should now be exactly at the end.                                  */
  suck_pop_exact(sr, &ssr) ;

  return 0;
} ;

/*------------------------------------------------------------------------------
 * Process value of Graceful Restart capability -- BGP_CAN_G_RESTART -- RFC2918
 *
 * Capability is:  time      -- word
 *                 AFI       -- word )
 *                 SAFI      -- byte ) repeated 0 or more times
 *                 flag      -- byte )
 *
 * This is a variable length capability, minimum size already checked.
 *
 * The sr covers from the start to the end of the capability value.
 *
 * Returns:  0 => OK
 *          -1 => malformed !
 *
 * TODO: RFC 4724 suggests "implicit" IPv4/Unicast if no CAP-MP
 * TODO: RFC 4760 says MUST CAP-MP if propose to use CAP-MP !
 *
 */
static int
bgp_msg_capability_restart (bgp_connection connection, sucker sr)
{
  bgp_open_state open_recv = connection->open_recv;
  u_int16_t restart_flag_time ;
  int length ;
  bgp_cap_afi_safi cap ;

  length = suck_left(sr) ;      /* total length of value, for reporting */

  /* RFC4724: "If more than one instance of the Graceful Restart Capability
   *           is carried in the capability advertisement, the receiver of
   *           the advertisement MUST ignore all but the last instance..."
   */

  open_recv->can_g_restart = 1;

  /* Deal with the restart time and restarted flag                      */
  restart_flag_time = suck_w(sr) ;

  open_recv->has_restarted = (restart_flag_time & BGP_CAP_GR_T_R_FLAG) != 0 ;
  open_recv->restart_time  =  restart_flag_time & BGP_CAP_GR_T_MASK ;

  open_recv->can_preserve  = 0 ;
  open_recv->has_preserved = 0 ;

  if (BGP_DEBUG (normal, NORMAL))
    {
      zlog_debug ("%s OPEN has Graceful Restart capability", connection->host);
      zlog_debug ("%s Peer has%srestarted. Restart Time : %d",
                  connection->host, open_recv->has_restarted ? " " : " not ",
                  open_recv->restart_time);
    } ;

  if ((suck_left(sr) % BGP_CAP_GRE_L) != 0)
    {
      zlog_info ("%s Graceful Restart Capability length error,"
                 " Cap length %u",
                 connection->host, length);
      return -1;
    } ;

  while (suck_left(sr) > 0)
    {
      iAFI_SAFI_t  mp ;
      uint8_t      flags ;
      qafx_bit_t   qb ;
      int          has_preserved ;

      mp.afi   = suck_w(sr) ;
      mp.safi  = suck_b(sr) ;
      flags    = suck_b(sr) ;

      qb = qafx_bit_from_iAFI_iSAFI(mp.afi, mp.safi) ;
      has_preserved = ((flags & BGP_CAP_GRE_F_FORW) != 0) ;

      cap = bgp_open_state_afi_safi_add(connection->open_recv, mp.afi, mp.safi,
                                                 (qb != 0), BGP_CAN_G_RESTART) ;
      cap->caps.gr.has_preserved = has_preserved ;

      if (qb == 0)
        {
          if (BGP_DEBUG (normal, NORMAL))
            zlog_debug ("%s Addr-family %d/%d(afi/safi) not supported."
                        " Ignore the Graceful Restart capability",
                        connection->host, mp.afi, mp.safi);
        }
      else
        {
          /* Now can register the capability                    */

          if (connection->session->open_send->can_mp_ext & qb)
            {
              open_recv->can_preserve  |= qb ;
              open_recv->has_preserved |= (has_preserved ? qb : 0) ;

              if (BGP_DEBUG (normal, NORMAL))
                zlog_debug ("%s Address family %s is%spreserved",
                            connection->host,
                            afi_safi_print (mp.afi, mp.safi),
                            (has_preserved ? " " : " not ")) ;
            }
          else
            {
              if (BGP_DEBUG (normal, NORMAL))
                zlog_debug ("%s Addr-family %d/%d(afi/safi) not enabled."
                            " Ignore the Graceful Restart capability",
                            connection->host, mp.afi, mp.safi);
            } ;
        } ;
    } ;

  return 0 ;
} ;

/*------------------------------------------------------------------------------
 * Process value of AS4 capability -- BGP_CAN_AS4 -- RFC4893
 *
 * Capability is:  ASN       -- long word (4 bytes)
 *
 * This is a fixed length capability, so that's been dealt with.
 *
 * Validation of ASN and cross-check against my_as2, done elsewhere.
 *
 * Returns:  0 => OK
 */
static int
bgp_msg_capability_as4 (bgp_connection connection, sucker sr)
{
  bgp_open_state open_recv = connection->open_recv ;

  open_recv->can_as4 = 1 ;
  open_recv->my_as   = suck_l(sr) ;

  if (BGP_DEBUG (as4, AS4))
    zlog_debug ("%s [AS4] about to set cap PEER_CAP_AS4_RCV, got as4 %u",
                connection->host, open_recv->my_as) ;

  return 0 ;
} ;

/*==============================================================================
 * BGP UPDATE message
 *
 * NB: requires the session to be locked (connection-wise) and not NULL.
 */
static void
bgp_msg_update_receive (bgp_connection connection, bgp_size_t body_size)
{
  /* Must be prepared to receive "update" like messages                 */
  if (bgp_fsm_pre_update(connection) != 0)
    {
      plog_err(connection->log,
                "%s [Error] Update message received while in %s State",
                  connection->host, LOOKUP(bgp_status_msg, connection->state)) ;
      return ;
    } ;

  ++connection->session->stats.update_in ;
  connection->session->stats.update_time = bgp_clock() ;

  /* PRO TEM: pass raw update message across to Routing Engine          */
  /* TODO: decode update messages in the BGP Engine.                    */
  bgp_session_update_recv(connection->session, connection->ibuf, body_size);
}

/*==============================================================================
 * BGP KEEPALIVE message
 *
 * NB: requires the session to be locked (connection-wise) and not NULL.
 */
static void
bgp_msg_keepalive_receive (bgp_connection connection, bgp_size_t body_size)
{
  ++connection->session->stats.keepalive_in ;

  if (BGP_DEBUG (keepalive, KEEPALIVE))
    zlog_debug ("%s KEEPALIVE rcvd", connection->host);

  if (body_size == 0)
    bgp_fsm_keepalive_received(connection) ;
  else
    bgp_msg_header_bad_len(connection, BGP_MT_KEEPALIVE, body_size) ;
} ;

/*==============================================================================
 * BGP NOTIFICATION message
 *
 * NB: requires the session to be locked (connection-wise) and not NULL.
 */
static void
bgp_msg_notify_receive (bgp_connection connection, bgp_size_t body_size)
{
  bgp_notify        notification ;

  bgp_nom_code_t    code    = stream_getc (connection->ibuf);
  bgp_nom_subcode_t subcode = stream_getc (connection->ibuf);

  ++connection->session->stats.notify_in ;

  notification = bgp_notify_new_with_data(code, subcode,
                                  stream_pnt(connection->ibuf), body_size - 2) ;
  bgp_notify_set_received(notification) ;

  bgp_notify_print(connection->session->peer, notification) ;   /* Logging */

  bgp_fsm_notification_exception(connection, notification) ;
} ;

/*==============================================================================
 * BGP ROUTE-REFRESH message
 *
 * NB: requires the session to be locked (connection-wise) and not NULL.
 */
static int
bgp_msg_orf_recv(bgp_connection connection, bgp_route_refresh rr,
                                                     qafx_bit_t qb, sucker sr) ;
static int
bgp_msg_orf_prefix_recv(orf_prefix orfpe, qafx_bit_t qb, sucker sr) ;

/*------------------------------------------------------------------------------
 * Process BGP ROUTE-REFRESH message
 *
 * This may contain ORF stuff !
 */
static void
bgp_msg_route_refresh_receive(bgp_connection connection, bgp_size_t body_size)
{
  struct iAFI_SAFI mp ;
  sucker_t   ssr ;
  qafx_bit_t qb ;
  bgp_route_refresh rr ;
  unsigned   form ;
  int        ret ;

  ++connection->session->stats.refresh_in ;

  /* If peer does not have the capability, treat as bad message type    */

  switch (connection->msg_type)
  {
    case BGP_MT_ROUTE_REFRESH:
      form = bgp_form_rfc ;
      break ;
    case BGP_MT_ROUTE_REFRESH_pre:
      form = bgp_form_pre ;
      break ;
    default:                            /* should not happen, really    */
      form = 0 ;
      break ;
  } ;

  if ((connection->route_refresh & form) == 0)
    {
      bgp_msg_header_bad_type(connection, connection->msg_type) ;
      return ;
    } ;

  /* Must be prepared to receive "update" like messages                 */
  if (connection->state != bgp_fsm_sEstablished)
    {
      plog_err(connection->log,
                "%s [Error] Route-Refresh message received while in %s State",
                  connection->host, LOOKUP(bgp_status_msg, connection->state)) ;
      return ;
    } ;

  /* Set about parsing the message                                      */

  dassert(stream_get_left(connection->ibuf) == body_size) ;
  suck_init(&ssr, stream_pnt(connection->ibuf), body_size) ;

  /* Start with AFI, reserved, SAFI                                     */
  qb = bgp_msg_afi_safi(&ssr, &mp) ;

  qb &= qafx_ipv4_unicast_bit | qafx_ipv4_multicast_bit |
        qafx_ipv6_unicast_bit | qafx_ipv6_multicast_bit |
        qafx_ipv4_mpls_vpn_bit ;

  if (BGP_DEBUG (normal, NORMAL))
    zlog_debug ("%s rcvd REFRESH_REQ for afi/safi: %d/%d%s",
                                           connection->host, mp.afi, mp.safi,
                                   (qb == 0) ? " -- unknown combination" : "") ;

  rr = bgp_route_refresh_new(mp.afi, mp.safi, 0) ;

  /* If there are any ORF entries, time to suck them up now.            */
  ret = 0 ;

  if (suck_left(&ssr) != 0)
    {
      uint8_t when_to_refresh ;
      bool    defer = 0 ;

      when_to_refresh = suck_b(&ssr) ;

      switch (when_to_refresh)
      {
        case BGP_ORF_WTR_IMMEDIATE:
          defer = 0 ;
          break ;
        case BGP_ORF_WTR_DEFER:
          defer = 1 ;
          break ;
        default:
          zlog_info ("%s ORF route refresh invalid 'when' value %d"
                     " (AFI/SAFI %d/%d)",
                     connection->host, when_to_refresh, rr->afi, rr->safi) ;
          ret = -1 ;
          break ;
      } ;

      if (ret >= 0)
        {
          bgp_route_refresh_set_orf_defer(rr, defer) ;

          /* After the when to refresh, expect 1 or more ORFs           */
          do
            {
              ret = bgp_msg_orf_recv(connection, rr, qb, &ssr) ;
            } while ((ret == 0) && (suck_left(&ssr) != 0)) ;
        } ;
    } ;

  if (ret < 0)
    {
      bgp_fsm_exception(connection, bgp_session_eInvalid_msg,
                       bgp_notify_new(BGP_NOMC_CEASE, BGP_NOMS_UNSPECIFIC)) ;
      return ;
    }

  bgp_session_route_refresh_recv(connection->session, rr) ;
  return ;
} ;

/*------------------------------------------------------------------------------
 * Process ORF Type and following ORF Entries.
 *
 * Expects there to be at least one ORF entry -- that is, the length of the
 * ORF Entries may not be 0.
 *
 * Returns:  0 => OK
 *          -1 => invalid or malformed
 */
static int
bgp_msg_orf_recv(bgp_connection connection, bgp_route_refresh rr,
                                                       qafx_bit_t qb, sucker sr)
{
  sucker_t   ssr ;
  int        left ;
  uint8_t    orf_type ;
  bgp_size_t orf_len ;
  int        unknown ;
  int        form ;
  int        ret ;

  /* Suck up the ORF type and the length of the entries that follow     */
  left = suck_left(sr) - BGP_ORF_MIN_L ;
  if (left >= 0)
    {
      orf_type  = suck_b(sr) ;
      orf_len   = suck_w(sr) ;
    }
  else
    {
      orf_type  = 0 ;   /* ensure initialised   */
      orf_len   = 0 ;
    } ;

  /* The length may not be zero and may not exceed what there is left   */
  if ((orf_len == 0) || (left < orf_len))
    {
      zlog_info ("%s ORF route refresh length error: %d when %d left"
                 " (AFI/SAFI %d/%d, type %d length %d)",
                 connection->host, orf_len, left,
                                         rr->afi, rr->safi, orf_type, orf_len) ;
      return -1 ;
    } ;

  if (BGP_DEBUG (normal, NORMAL))
    zlog_debug ("%s rcvd ORF type %d length %d",
                 connection->host, orf_type, orf_len);

  /* Sex the ORF type                                                   */
  form    = bgp_form_none ;
  unknown = 1 ;
  switch (orf_type)
    {
      case BGP_ORF_T_PREFIX:
        if ((connection->orf_prefix & bgp_form_rfc) != 0)
          {
            form     = bgp_form_rfc ;
            unknown  = (qb != 0) ;
          } ;
        break ;

      case BGP_ORF_T_PREFIX_pre:
        if ((connection->orf_prefix & bgp_form_pre) != 0)
        {
          orf_type = BGP_ORF_T_PREFIX ;
          form     = bgp_form_pre ;
          unknown  = (qb != 0) ;
        } ;
        break ;

      default:
        break ;
    } ;

  /* Suck up the ORF entries.  NB: orf_len != 0                         */
  suck_push(sr, orf_len, &ssr) ;

  if (unknown)
    bgp_orf_add_unknown(rr, orf_type, orf_len, suck_step(sr, orf_len)) ;
  else
    {
      do
        {
          bool    remove_all   = 0 ;
          bool    remove       = 0 ;
          bool    deny         = 0 ;
          uint8_t common ;

          common = suck_b(sr) ;
          switch (common & BGP_ORF_EA_MASK)
          {
            case BGP_ORF_EA_ADD:
              break ;
            case BGP_ORF_EA_REMOVE:
              remove = 1 ;
              break ;
            case BGP_ORF_EA_RM_ALL:
              remove_all = 1 ;
              break ;
            default:
              zlog_info ("%s ORF route refresh invalid common byte: %u"
                         " (AFI/SAFI %d/%d, type %d length %d)",
                         connection->host, common,
                                         rr->afi, rr->safi, orf_type, orf_len) ;
              return -1 ;
          } ;

          deny = ((common & BGP_ORF_EA_DENY) != 0) ;

          ret = 0 ;
          if (remove_all)
            bgp_orf_add_remove_all(rr, orf_type, form) ;
          else
            {
              bgp_orf_entry orfe ;
              orfe = bgp_orf_add(rr, orf_type, form, remove, deny) ;

              switch (orf_type)
                {
                  case BGP_ORF_T_PREFIX:
                    ret = bgp_msg_orf_prefix_recv(&orfe->body.orf_prefix, qb,
                                                                           sr) ;
                    break ;

                  default:
                    zabort("Lost track of ORF type") ;
                    break ;
                } ;

              if (ret < 0)
                {
                  zlog_info ("%s ORF route refresh invalid Prefix ORF entry"
                             " (AFI/SAFI %d/%d, type %d length %d)",
                             connection->host,
                                         rr->afi, rr->safi, orf_type, orf_len) ;
                  return -1 ;
                } ;
            } ;

        } while (suck_left(sr) > 0) ;
    } ;

  suck_pop_exact(sr, &ssr) ;
  return 0 ;
} ;

/*------------------------------------------------------------------------------
 * Process ORF Prefix entry, from after the common byte.
 *
 * This is for entries which are *not* remove-all
 *
 * Returns:  0 => OK
 *          -1 => invalid or malformed
 */
static int
bgp_msg_orf_prefix_recv(orf_prefix orfpe, qafx_bit_t qb, sucker sr)
{
  pAF_t paf ;
  int left ;

  assert(qb != 0) ;
  paf = get_pAF(qafx_num(qb)) ;

  /* Must have the minimum Prefix ORF entry, less the common byte, left */
  left = suck_left(sr) - (BGP_ORF_E_P_MIN_L - BGP_ORF_E_COM_L) ;
  if (left >= 0)
    {
      uint8_t plen ;
      uint8_t blen ;

      orfpe->seq   = suck_l(sr) ;
      orfpe->ge    = suck_b(sr) ;       /* aka min      */
      orfpe->le    = suck_b(sr) ;       /* aka max      */
      plen         = suck_b(sr) ;

      memset(&orfpe->p, 0, sizeof(struct prefix)) ;

      blen = (plen + 7) / 8 ;
      if ((left -= blen) >= 0)
        {
          orfpe->p.family    = paf ;
          orfpe->p.prefixlen = plen ;
          if (blen != 0)
            {
              if (blen <= prefix_blen(&orfpe->p))
                memcpy(&orfpe->p.u.prefix, suck_step(sr, blen), blen) ;
              else
                left = -1 ;
            } ;
        } ;
    } ;

  return left ;
} ;

/*==============================================================================
 * BGP CAPABILITY message -- Dynamic Capabilities
 *
 * NB: requires the session to be locked (connection-wise) and not NULL.
 */
static void bgp_msg_capability_receive(bgp_connection connection,
                                                           bgp_size_t body_size)
{
  ++connection->session->stats.dynamic_cap_in ;

  return ;
} ;