Source

bgpdump / bgpdump_lib.c

   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
/*
 Copyright (c) 2007 - 2010 RIPE NCC - All Rights Reserved
 
 Permission to use, copy, modify, and distribute this software and its
 documentation for any purpose and without fee is hereby granted, provided
 that the above copyright notice appear in all copies and that both that
 copyright notice and this permission notice appear in supporting
 documentation, and that the name of the author not be used in advertising or
 publicity pertaining to distribution of the software without specific,
 written prior permission.
 
 THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
 ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS; IN NO EVENT SHALL
 AUTHOR BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
 DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
 AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 
Parts of this code have been engineered after analiyzing GNU Zebra's
source code and therefore might contain declarations/code from GNU
Zebra, Copyright (C) 1999 Kunihiro Ishiguro. Zebra is a free routing
software, distributed under the GNU General Public License. A copy of
this license is included with libbgpdump.
*/

#include "bgpdump-config.h"
#include "cfile_tools.h"
#include "bgpdump_lib.h"
#include "bgpdump_mstream.h"
#include "util.h"

#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdbool.h>

#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>

#include <zlib.h>
#include <assert.h>

void	  bgpdump_free_attr(attributes_t *attr);
static    int process_mrtd_table_dump(struct mstream *s,BGPDUMP_ENTRY *entry);
static    int process_mrtd_table_dump_v2(struct mstream *s,BGPDUMP_ENTRY *entry);
static    int process_mrtd_table_dump_v2_peer_index_table(struct mstream *s,BGPDUMP_ENTRY *entry);
static    int process_mrtd_table_dump_v2_ipv4_unicast(struct mstream *s,BGPDUMP_ENTRY *entry);
static    int process_mrtd_table_dump_v2_ipv6_unicast(struct mstream *s,BGPDUMP_ENTRY *entry);
static    int process_zebra_bgp(struct mstream *s,BGPDUMP_ENTRY *entry);
static    int process_zebra_bgp_state_change(struct mstream *s,BGPDUMP_ENTRY *entry, u_int8_t asn_len);

static    int process_zebra_bgp_message(struct mstream *s,BGPDUMP_ENTRY *entry, u_int8_t asn_len);
static    int process_zebra_bgp_message_update(struct mstream *s,BGPDUMP_ENTRY *entry, u_int8_t asn_len);
static    int process_zebra_bgp_message_open(struct mstream *s,BGPDUMP_ENTRY *entry, u_int8_t asn_len);
static    int process_zebra_bgp_message_notify(struct mstream *s,BGPDUMP_ENTRY *entry);

static    int process_zebra_bgp_entry(struct mstream *s,BGPDUMP_ENTRY *entry);
static    int process_zebra_bgp_snapshot(struct mstream *s,BGPDUMP_ENTRY *entry);

static    attributes_t *process_attributes(struct mstream *s, u_int8_t asn_len, struct zebra_incomplete *incomplete);
static    void process_attr_aspath_string(struct aspath *as);
static    char aspath_delimiter_char (u_char type, u_char which);
static    void process_attr_community_string(struct community *com);

static    void process_mp_announce(struct mstream *s, struct mp_info *info, struct zebra_incomplete *incomplete);
static    void process_mp_withdraw(struct mstream *s, struct mp_info *info, struct zebra_incomplete *incomplete);
static    int read_prefix_list(struct mstream *s, u_int16_t af, struct prefix *prefixes, struct zebra_incomplete *incomplete);

static    as_t read_asn(struct mstream *s, as_t *asn, u_int8_t len);
static    struct aspath *create_aspath(u_int16_t len, u_int8_t asn_len);
static    void aspath_error(struct aspath *as);
static    int check_new_aspath(struct aspath *aspath);
static    void process_asn32_trans(attributes_t *attr, u_int8_t asn_len);
static    struct aspath *asn32_merge_paths(struct aspath *path, struct aspath *newpath);
static    void asn32_expand_16_to_32(char *dst, char *src, int len);

BGPDUMP_TABLE_DUMP_V2_PEER_INDEX_TABLE *table_dump_v2_peer_index_table = NULL;

#if defined(linux)
static    size_t strlcat(char *dst, const char *src, size_t size);
#endif

char *bgpdump_version(void) {
    return PACKAGE_VERSION;
}


BGPDUMP *bgpdump_open_dump(const char *filename) {

    CFRFILE *f = cfr_open(filename);
    if(! f) {
        perror("can't open dumpfile");
        return NULL;
    }
    
    BGPDUMP *this_dump = malloc(sizeof(BGPDUMP));
    strcpy(this_dump->filename, "[STDIN]");
    if(filename && strcmp(filename, "-")) {
	strcpy(this_dump->filename, filename);
    }

    this_dump->f = f;
    this_dump->eof=0;
    this_dump->parsed = 0;
    this_dump->parsed_ok = 0;

    return this_dump;
}

void bgpdump_close_dump(BGPDUMP *dump) {
    if(dump!=NULL) {

    	if(table_dump_v2_peer_index_table){
		if(table_dump_v2_peer_index_table->entries) {
			free(table_dump_v2_peer_index_table->entries);
			table_dump_v2_peer_index_table->entries = NULL;
		}
		free(table_dump_v2_peer_index_table);
		table_dump_v2_peer_index_table = NULL;
	}
	cfr_close(dump->f);
        free(dump);
    }
}

BGPDUMP_ENTRY*	bgpdump_read_next(BGPDUMP *dump) {
    assert(dump);

    BGPDUMP_ENTRY *this_entry=NULL;
    struct mstream s;
    u_char *buffer;
    int ok=0;
    u_int32_t bytes_read;

    this_entry = malloc(sizeof(BGPDUMP_ENTRY));

    bytes_read = cfr_read_n(dump->f, &(this_entry->time), 4);
    bytes_read += cfr_read_n(dump->f, &(this_entry->type), 2);
    bytes_read += cfr_read_n(dump->f, &(this_entry->subtype), 2);
    bytes_read += cfr_read_n(dump->f, &(this_entry->length), 4);
    if(bytes_read != 12) {
	if(bytes_read > 0) {
	    /* Malformed record */
	    dump->parsed++;
	    err("bgpdump_read_next: incomplete MRT header (%d bytes read, expecting 12)",
		   bytes_read);
	}
	/* Nothing more to read, quit */
	free(this_entry);
	dump->eof=1;
	return(NULL);
    }

    dump->parsed++;

    /* Intel byte ordering stuff ... */
    this_entry->type=ntohs(this_entry->type);
    this_entry->subtype=ntohs(this_entry->subtype);
    this_entry->time=ntohl(this_entry->time);
    this_entry->length=ntohl(this_entry->length);

    this_entry->attr=NULL;

    buffer = malloc(this_entry->length);
    bytes_read = cfr_read_n(dump->f, buffer, this_entry->length);
    if(bytes_read != this_entry->length) {
	err("bgpdump_read_next: incomplete dump record (%d bytes read, expecting %d)",
	       bytes_read, this_entry->length);
	free(this_entry);
	free(buffer);
	dump->eof=1;
	return(NULL);
    }


    ok=0;
    mstream_init(&s,buffer,this_entry->length);

    switch(this_entry->type) {
	case BGPDUMP_TYPE_MRTD_BGP:
		break;
	case BGPDUMP_TYPE_MRTD_TABLE_DUMP:
		ok = process_mrtd_table_dump(&s,this_entry);
		break;
	case BGPDUMP_TYPE_ZEBRA_BGP:
		ok = process_zebra_bgp(&s,this_entry);
		break;
	case BGPDUMP_TYPE_TABLE_DUMP_V2:
		ok = process_mrtd_table_dump_v2(&s,this_entry);
		break;
    }

    free(buffer);
    if(ok) {
	dump->parsed_ok++;
    } else {
	bgpdump_free_mem(this_entry);
	return NULL;
    }
    return this_entry;
}

static void bgpdump_free_mp_info(struct mp_info *info) {
    u_int16_t afi;
    u_int8_t safi;

    for(afi = 1; afi <= BGPDUMP_MAX_AFI; afi++) {
	for(safi = 1; safi < BGPDUMP_MAX_SAFI; safi++) {
	    if(info->announce[afi][safi])
		free(info->announce[afi][safi]);
		info->announce[afi][safi] = NULL;
	    if(info->withdraw[afi][safi]) {
		free(info->withdraw[afi][safi]);
		info->withdraw[afi][safi] = NULL;
	    }
	}
    }

	free(info);
}

void bgpdump_free_mem(BGPDUMP_ENTRY *entry) {

    if(entry!=NULL) {

	bgpdump_free_attr(entry->attr);

	switch(entry->type) {
	    case BGPDUMP_TYPE_ZEBRA_BGP:
		switch(entry->subtype) {
		    case BGPDUMP_SUBTYPE_ZEBRA_BGP_MESSAGE:
			switch(entry->body.zebra_message.type) {
			    case BGP_MSG_NOTIFY:
				if(entry->body.zebra_message.notify_data)
				    free(entry->body.zebra_message.notify_data);
				break;
			    case BGP_MSG_OPEN:
				if(entry->body.zebra_message.opt_data)
				    free(entry->body.zebra_message.opt_data);
				break;
			}
			break;
		}
		break;
	    case BGPDUMP_TYPE_TABLE_DUMP_V2:
		if(entry->subtype == BGPDUMP_SUBTYPE_TABLE_DUMP_V2_RIB_IPV4_UNICAST ||
		   entry->subtype == BGPDUMP_SUBTYPE_TABLE_DUMP_V2_RIB_IPV6_UNICAST ){

			BGPDUMP_TABLE_DUMP_V2_PREFIX *e;
			e = &entry->body.mrtd_table_dump_v2_prefix;
			int i;

			for(i = 0; i < e->entry_count; i++){
				bgpdump_free_attr(e->entries[i].attr);
			}
			free(e->entries);
		}
		break;
	}

	free(entry);
    }
}

void bgpdump_free_attr(attributes_t *attr){
	if(attr != NULL) {
    	u_int16_t i;
    	struct aspath *path, *pathstofree[3] = { attr->aspath, attr->old_aspath, attr->new_aspath };
	    for(i = 0; i < sizeof(pathstofree) / sizeof(pathstofree[0]); i++) {
	      path = pathstofree[i];
	      if(path) {
		if(path->data)
		  free(path->data);
		if(path->str)
		  free(path->str);
		free(path);
	      }
	    }

	    if(attr->community != NULL) {
		if(attr->community->val != NULL)
		    free(attr->community->val);

		if(attr->community->str != NULL)
		    free(attr->community->str);

		free(attr->community);
	    }

	    if(attr->data != NULL)
		free(attr->data);

	    if(attr->mp_info != NULL)
		bgpdump_free_mp_info(attr->mp_info);

	    if(attr->cluster != NULL) {
			free(attr->cluster->list);
			free(attr->cluster);
		}

	    if (attr->unknown_num) {
		for (i = 0; i < attr->unknown_num; i++)
		    free(attr->unknown[i].raw);
		free(attr->unknown);
	    }

	    free(attr);
	}
}

int process_mrtd_table_dump(struct mstream *s,BGPDUMP_ENTRY *entry) {
    int afi = entry->subtype;
    u_int8_t asn_len;
    u_int32_t temp_time = 0;
    mstream_getw(s,&entry->body.mrtd_table_dump.view);
    mstream_getw(s,&entry->body.mrtd_table_dump.sequence);
    switch(afi) {
	case BGPDUMP_SUBTYPE_MRTD_TABLE_DUMP_AFI_IP:
	case BGPDUMP_SUBTYPE_MRTD_TABLE_DUMP_AFI_IP_32BIT_AS:
	    entry->body.mrtd_table_dump.prefix.v4_addr = mstream_get_ipv4(s);
	    break;
#ifdef BGPDUMP_HAVE_IPV6
	case BGPDUMP_SUBTYPE_MRTD_TABLE_DUMP_AFI_IP6:
	case BGPDUMP_SUBTYPE_MRTD_TABLE_DUMP_AFI_IP6_32BIT_AS:
	    mstream_get(s, &entry->body.mrtd_table_dump.prefix.v6_addr.s6_addr, 16);
	    break;
#endif
	default:
	    warn("process_mrtd_table_dump: unknown AFI %d",  afi);
	    mstream_get(s, NULL, mstream_can_read(s));
	    return 0;
    }
    mstream_getc(s,&entry->body.mrtd_table_dump.mask);
    mstream_getc(s,&entry->body.mrtd_table_dump.status);
    mstream_getl(s,&temp_time);
    (entry->body).mrtd_table_dump.uptime = temp_time;

    switch(afi) {
      case BGPDUMP_SUBTYPE_MRTD_TABLE_DUMP_AFI_IP:
      case BGPDUMP_SUBTYPE_MRTD_TABLE_DUMP_AFI_IP_32BIT_AS:
	entry->body.mrtd_table_dump.peer_ip.v4_addr = mstream_get_ipv4(s);
	break;
#ifdef BGPDUMP_HAVE_IPV6
      case BGPDUMP_SUBTYPE_MRTD_TABLE_DUMP_AFI_IP6:
      case BGPDUMP_SUBTYPE_MRTD_TABLE_DUMP_AFI_IP6_32BIT_AS:
	mstream_get(s, &entry->body.mrtd_table_dump.peer_ip.v6_addr.s6_addr, 16);
	break;
#endif
    }

    switch(afi) {
      case BGPDUMP_SUBTYPE_MRTD_TABLE_DUMP_AFI_IP:
      case BGPDUMP_SUBTYPE_MRTD_TABLE_DUMP_AFI_IP6:
	asn_len = ASN16_LEN;
	break;
      case BGPDUMP_SUBTYPE_MRTD_TABLE_DUMP_AFI_IP_32BIT_AS:
      case BGPDUMP_SUBTYPE_MRTD_TABLE_DUMP_AFI_IP6_32BIT_AS:
	asn_len = ASN32_LEN;
	break;
      default:
            assert(0); // unreachable
    }

    read_asn(s,&entry->body.mrtd_table_dump.peer_as, asn_len);

    entry->attr = process_attributes(s, asn_len, NULL);

    return 1;
}


int process_mrtd_table_dump_v2(struct mstream *s,BGPDUMP_ENTRY *entry) {

	switch(entry->subtype){
	case BGPDUMP_SUBTYPE_TABLE_DUMP_V2_PEER_INDEX_TABLE:
		return process_mrtd_table_dump_v2_peer_index_table(s, entry);
	break;
	case BGPDUMP_SUBTYPE_TABLE_DUMP_V2_RIB_IPV4_UNICAST:
		return process_mrtd_table_dump_v2_ipv4_unicast(s, entry);
	break;
	case BGPDUMP_SUBTYPE_TABLE_DUMP_V2_RIB_IPV6_UNICAST:
		return process_mrtd_table_dump_v2_ipv6_unicast(s, entry);
	break;
	case BGPDUMP_SUBTYPE_TABLE_DUMP_V2_RIB_GENERIC:
		//return process_mrtd_table_dump_v2_generic(s, entry);
	break;
	}

	return 0;
}

int process_mrtd_table_dump_v2_peer_index_table(struct mstream *s,BGPDUMP_ENTRY *entry) {
	BGPDUMP_TABLE_DUMP_V2_PEER_INDEX_TABLE *t;
	uint16_t i;
	uint8_t peertype;
	uint16_t view_name_len;

	if(table_dump_v2_peer_index_table){
		if(table_dump_v2_peer_index_table->entries)
			free(table_dump_v2_peer_index_table->entries);
		free(table_dump_v2_peer_index_table);
	}

	table_dump_v2_peer_index_table = malloc(sizeof(BGPDUMP_TABLE_DUMP_V2_PEER_INDEX_TABLE));
	t = table_dump_v2_peer_index_table;
	t->entries = NULL;

    t->local_bgp_id = mstream_get_ipv4(s);

    mstream_getw(s,&view_name_len);
	strcpy(t->view_name, "");

	// view_name_len is without trailing \0
	if(view_name_len+1 > BGPDUMP_TYPE_TABLE_DUMP_V2_MAX_VIEWNAME_LEN) {
	    warn("process_mrtd_table_dump_v2_peer_index_table: view name length more than maximum length (%d), ignoring view name", BGPDUMP_TYPE_TABLE_DUMP_V2_MAX_VIEWNAME_LEN);
	} else {
		mstream_get(s, t->view_name, view_name_len);
		t->view_name[view_name_len] = 0;
	}

    mstream_getw(s,&t->peer_count);

	t->entries = malloc(sizeof(BGPDUMP_TABLE_DUMP_V2_PEER_INDEX_TABLE_ENTRY) * t->peer_count);
	if(t->entries == NULL){
	    err("process_mrtd_table_dump_v2_peer_index_table: failed to allocate memory for index table");
		return 0;
	}

	for(i=0; i < t->peer_count; i++) {
    	mstream_getc(s,&peertype);
                t->entries[i].afi = AFI_IP;
#ifdef BGPDUMP_HAVE_IPV6
		if(peertype & BGPDUMP_PEERTYPE_TABLE_DUMP_V2_AFI_IP6)
			t->entries[i].afi = AFI_IP6;
#endif

                t->entries[i].peer_bgp_id = mstream_get_ipv4(s);

		if(t->entries[i].afi == AFI_IP)
			t->entries[i].peer_ip.v4_addr = mstream_get_ipv4(s);
#ifdef BGPDUMP_HAVE_IPV6
		else
			mstream_get(s, &t->entries[i].peer_ip.v6_addr.s6_addr, 16);
#endif


		if(peertype & BGPDUMP_PEERTYPE_TABLE_DUMP_V2_AS4)
			read_asn(s, &t->entries[i].peer_as, 4);
		else
			read_asn(s, &t->entries[i].peer_as, 2);

	}
	return 0;
}


int process_mrtd_table_dump_v2_ipv4_unicast(struct mstream *s, BGPDUMP_ENTRY *entry){
	BGPDUMP_TABLE_DUMP_V2_PREFIX *prefixdata;
	prefixdata = &entry->body.mrtd_table_dump_v2_prefix;
	uint16_t i;

	prefixdata->afi = AFI_IP;
	prefixdata->safi = SAFI_UNICAST;

	mstream_getl(s, &prefixdata->seq);
	mstream_getc(s, &prefixdata->prefix_length);
	bzero(&prefixdata->prefix.v4_addr.s_addr, 4);
	mstream_get(s, &prefixdata->prefix.v4_addr.s_addr, (prefixdata->prefix_length+7)/8);
	mstream_getw(s, &prefixdata->entry_count);

	prefixdata->entries = malloc(sizeof(BGPDUMP_TABLE_DUMP_V2_ROUTE_ENTRY) * prefixdata->entry_count);
	if(prefixdata->entries == NULL){
	    err("process_mrtd_table_dump_v2_ipv4_unicast: failed to allocate memory for entry table");
		return 0;
	}

	for(i=0; i < prefixdata->entry_count; i++){
		BGPDUMP_TABLE_DUMP_V2_ROUTE_ENTRY *e;
		e = &prefixdata->entries[i];

		mstream_getw(s, &e->peer_index);
		e->peer = &table_dump_v2_peer_index_table->entries[e->peer_index];
		mstream_getl(s, &e->originated_time);
            
		e->attr = process_attributes(s, 4, NULL);
	}

	return 1;
}


int process_mrtd_table_dump_v2_ipv6_unicast(struct mstream *s, BGPDUMP_ENTRY *entry){
#ifdef BGPDUMP_HAVE_IPV6
	BGPDUMP_TABLE_DUMP_V2_PREFIX *prefixdata;
	prefixdata = &entry->body.mrtd_table_dump_v2_prefix;
	uint16_t i;

	prefixdata->afi = AFI_IP6;
	prefixdata->safi = SAFI_UNICAST;

	mstream_getl(s, &prefixdata->seq);

	mstream_getc(s, &prefixdata->prefix_length);
	bzero(&prefixdata->prefix.v6_addr.s6_addr, 16);
	mstream_get(s, &prefixdata->prefix.v6_addr.s6_addr, (prefixdata->prefix_length+7)/8);

	mstream_getw(s, &prefixdata->entry_count);

	prefixdata->entries = malloc(sizeof(BGPDUMP_TABLE_DUMP_V2_ROUTE_ENTRY) * prefixdata->entry_count);
	if(prefixdata->entries == NULL){
	    err("process_mrtd_table_dump_v2_ipv6_unicast: failed to allocate memory for entry table");
		return 0;
	}

	for(i=0; i < prefixdata->entry_count; i++){
		BGPDUMP_TABLE_DUMP_V2_ROUTE_ENTRY *e;
		e = &prefixdata->entries[i];

		mstream_getw(s, &e->peer_index);
		e->peer = &table_dump_v2_peer_index_table->entries[e->peer_index];
		mstream_getl(s, &e->originated_time);

		e->attr = process_attributes(s, 4, NULL);
	}

#endif
	return 1;
}

int process_zebra_bgp(struct mstream *s,BGPDUMP_ENTRY *entry) {
    switch(entry->subtype) {
	case BGPDUMP_SUBTYPE_ZEBRA_BGP_STATE_CHANGE:
	    return process_zebra_bgp_state_change(s, entry, ASN16_LEN);
	case BGPDUMP_SUBTYPE_ZEBRA_BGP_STATE_CHANGE_AS4:
	    return process_zebra_bgp_state_change(s, entry, ASN32_LEN);
	case BGPDUMP_SUBTYPE_ZEBRA_BGP_MESSAGE:
	    return process_zebra_bgp_message(s, entry, ASN16_LEN);
	case BGPDUMP_SUBTYPE_ZEBRA_BGP_MESSAGE_AS4:
	    return process_zebra_bgp_message(s, entry, ASN32_LEN);
	case BGPDUMP_SUBTYPE_ZEBRA_BGP_ENTRY:
	    return process_zebra_bgp_entry(s,entry);
	case BGPDUMP_SUBTYPE_ZEBRA_BGP_SNAPSHOT:
	    return process_zebra_bgp_snapshot(s, entry);
	default:
	    warn("process_zebra_bgp: unknown subtype %d", entry->subtype);
	    return 0;
    }
}

int process_zebra_bgp_state_change(struct mstream *s,BGPDUMP_ENTRY *entry, u_int8_t asn_len) {
    read_asn(s, &entry->body.zebra_state_change.source_as, asn_len);
    read_asn(s, &entry->body.zebra_state_change.destination_as, asn_len);

    /* Work around Zebra dump corruption.
     * N.B. I don't see this in quagga 0.96.4 any more. Is it fixed? */
    if (entry->length == 8) {
	warn("process_zebra_bgp_state_change: 8-byte state change (zebra bug?)");

	mstream_getw(s,&entry->body.zebra_state_change.old_state);
	mstream_getw(s,&entry->body.zebra_state_change.new_state);

	/* Fill in with dummy values */
	entry->body.zebra_state_change.interface_index = 0;
	entry->body.zebra_state_change.address_family = AFI_IP;
	entry->body.zebra_state_change.source_ip.v4_addr.s_addr = 0;
	entry->body.zebra_state_change.destination_ip.v4_addr.s_addr = 0;

   	return 1;
    }

    mstream_getw(s,&entry->body.zebra_state_change.interface_index);
    mstream_getw(s,&entry->body.zebra_state_change.address_family);

    switch(entry->body.zebra_state_change.address_family) {
	case AFI_IP:
	    // length could be 20 or 24 (asn16 vs asn32)
	    if(entry->length != 20 && entry->length != 24) {
		warn("process_zebra_bgp_state_change: bad length %d",
		       entry->length);
		return 0;
	    }

	    entry->body.zebra_state_change.source_ip.v4_addr = mstream_get_ipv4(s);
	    entry->body.zebra_state_change.destination_ip.v4_addr = mstream_get_ipv4(s);
	    break;
#ifdef BGPDUMP_HAVE_IPV6
	case AFI_IP6:
	    // length could be 44 or 48 (asn16 vs asn32)
	    if(entry->length != 44 && entry->length != 48) {
		warn("process_zebra_bgp_state_change: bad length %d",
		       entry->length);
		return 0;
	    }

	    mstream_get(s, &entry->body.zebra_state_change.source_ip.v6_addr.s6_addr, 16);
	    mstream_get(s, &entry->body.zebra_state_change.destination_ip.v6_addr.s6_addr, 16);
	    break;
#endif
	default:
	    warn("process_zebra_bgp_state_change: unknown AFI %d",
		   entry->body.zebra_state_change.address_family);
	    return 0;
    }
    mstream_getw(s,&entry->body.zebra_state_change.old_state);
    mstream_getw(s,&entry->body.zebra_state_change.new_state);

    return 1;
}

int process_zebra_bgp_message(struct mstream *s,BGPDUMP_ENTRY *entry, u_int8_t asn_len) {
    u_char marker[16]; /* BGP marker */

    read_asn(s, &entry->body.zebra_message.source_as, asn_len);
    read_asn(s, &entry->body.zebra_message.destination_as, asn_len);
    mstream_getw(s,&entry->body.zebra_message.interface_index);
    mstream_getw(s,&entry->body.zebra_message.address_family);

    entry->body.zebra_message.opt_len = 0;
    entry->body.zebra_message.opt_data = NULL;
    entry->body.zebra_message.notify_len = 0;
    entry->body.zebra_message.notify_data = NULL;

    switch(entry->body.zebra_message.address_family) {
	case AFI_IP:
	    entry->body.zebra_message.source_ip.v4_addr = mstream_get_ipv4(s);
	    entry->body.zebra_message.destination_ip.v4_addr = mstream_get_ipv4(s);
	    mstream_get (s, marker, 16);
	    break;
#ifdef BGPDUMP_HAVE_IPV6
	case AFI_IP6:
	    mstream_get(s,&entry->body.zebra_message.source_ip.v6_addr.s6_addr, 16);
	    mstream_get(s,&entry->body.zebra_message.destination_ip.v6_addr.s6_addr, 16);
	    mstream_get (s, marker, 16);
	    break;
#endif
	case 0xFFFF:
	    /* Zebra doesn't dump ifindex or src/dest IPs in OPEN
	     * messages. Work around it. */
	    if (entry->body.zebra_message.interface_index == 0xFFFF) {
		memset(marker, 0xFF, 4);
		mstream_get (s, marker + 4, 12);
		entry->body.zebra_message.interface_index = 0;
		entry->body.zebra_message.address_family = AFI_IP;
		entry->body.zebra_message.source_ip.v4_addr.s_addr = 0;
		entry->body.zebra_message.destination_ip.v4_addr.s_addr = 0;
		break;
	    }
	    /* Note fall through! If we don't recognize this type of data corruption, we say
	     * the address family is unsupported (since FFFF is not a valid address family) */
	default:
	    /* unsupported address family */
	    warn("process_zebra_bgp_message: unsupported AFI %d",
		   entry->body.zebra_message.address_family);
	    return 0;
    }

    if(memcmp(marker, "\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377\377", 16) != 0) {
	/* bad marker... ignore packet */
	warn(
	       "bgp_message: bad marker: %02x.%02x.%02x.%02x.%02x.%02x.%02x.%02x.%02x.%02x.%02x.%02x.%02x.%02x.%02x.%02x",
	       marker[0],marker[1],marker[2],marker[3],marker[4],marker[5],marker[6],marker[7],
	       marker[8],marker[9],marker[10],marker[11],marker[12],marker[13],marker[14],marker[15]);
	return 0;
    }

    mstream_getw(s,&entry->body.zebra_message.size);
    
    int expected = entry->body.zebra_message.size - sizeof(marker) - sizeof(u_int16_t);
    
    mstream_t copy = mstream_copy(s, expected);
    
    entry->body.zebra_message.cut_bytes = expected - mstream_can_read(&copy);

    switch(mstream_getc (&copy, &entry->body.zebra_message.type)) {
	case BGP_MSG_OPEN:
	    return process_zebra_bgp_message_open(&copy, entry, asn_len);
	case BGP_MSG_UPDATE:
	    return process_zebra_bgp_message_update(&copy, entry, asn_len);
	case BGP_MSG_NOTIFY:
	    return process_zebra_bgp_message_notify(&copy, entry);
	case BGP_MSG_KEEPALIVE:
	    /* Nothing to do */
	    return 1;
	case BGP_MSG_ROUTE_REFRESH_01:
	    /* Not implemented yet */
	    warn("bgp_message: MSG_ROUTE_REFRESH_01 not implemented yet");
	    return 0;
	case BGP_MSG_ROUTE_REFRESH:
	    /* Not implemented yet */
	    warn("bgp_message: MSG_ROUTE_REFRESH not implemented yet");
	    return 0;
	default:
	    warn("bgp_message: unknown BGP message type %d",
		   entry->body.zebra_message.type);
	    return 0;
    }
}

int process_zebra_bgp_message_notify(struct mstream *s, BGPDUMP_ENTRY *entry) {
    mstream_getc(s, &entry->body.zebra_message.error_code);
    mstream_getc(s, &entry->body.zebra_message.sub_error_code);
    entry->body.zebra_message.notify_len = entry->body.zebra_message.size - 21;

    if(entry->body.zebra_message.notify_len > 0) {
	entry->body.zebra_message.notify_data = malloc(entry->body.zebra_message.notify_len);
	mstream_get(s, entry->body.zebra_message.notify_data, entry->body.zebra_message.notify_len);
    }

    return 1;
}

int process_zebra_bgp_message_open(struct mstream *s, BGPDUMP_ENTRY *entry, u_int8_t asn_len) {
    mstream_getc(s, &entry->body.zebra_message.version);
    read_asn(s, &entry->body.zebra_message.my_as, asn_len);
    mstream_getw(s, &entry->body.zebra_message.hold_time);
    entry->body.zebra_message.bgp_id = mstream_get_ipv4(s);
    mstream_getc(s, &entry->body.zebra_message.opt_len);

    if(entry->body.zebra_message.opt_len) {
	entry->body.zebra_message.opt_data = malloc(entry->body.zebra_message.opt_len);
	mstream_get(s, entry->body.zebra_message.opt_data, entry->body.zebra_message.opt_len);
    }

    return 1;
}

int process_zebra_bgp_message_update(struct mstream *s, BGPDUMP_ENTRY *entry, u_int8_t asn_len) {
    entry->body.zebra_message.incomplete.orig_len = 0;

    mstream_t withdraw_stream = mstream_copy(s, mstream_getw(s, NULL));
    entry->body.zebra_message.withdraw_count = read_prefix_list(&withdraw_stream, AFI_IP,
                         entry->body.zebra_message.withdraw,
			 &entry->body.zebra_message.incomplete);

    entry->attr = process_attributes(s, asn_len, &entry->body.zebra_message.incomplete);

    entry->body.zebra_message.announce_count = read_prefix_list(s, AFI_IP, 
                         entry->body.zebra_message.announce,
			 &entry->body.zebra_message.incomplete);

    return 1;
}

int process_zebra_bgp_entry(struct mstream *s, BGPDUMP_ENTRY *entry) {
    warn("process_zebra_bgp_entry: record type not implemented yet");
    return 0;
}

int process_zebra_bgp_snapshot(struct mstream *s, BGPDUMP_ENTRY *entry) {
    warn("process_zebra_bgp_snapshot: record type not implemented yet");
    return 0;
}

static attributes_t *attr_init(struct mstream *s, int len) {

    attributes_t *attr = malloc(sizeof(struct attr));
    
    attr->data=malloc(len);
    memcpy(attr->data, &s->start[s->position], len);
    
    attr->len = len;
    attr->flag			= 0;
    attr->origin		= -1;
    attr->nexthop.s_addr	= INADDR_NONE;
    attr->med			= -1;
    attr->local_pref		= -1;
    attr->aggregator_as		= -1;
    attr->aggregator_addr.s_addr = INADDR_NONE;
    attr->weight		= -1;

    attr->originator_id.s_addr	= -1;
    attr->cluster		= NULL;

    attr->aspath			= NULL;
    attr->community		= NULL;
    attr->transit		= NULL;
    attr->mp_info		= calloc(1, sizeof(struct mp_info));;

    attr->unknown_num = 0;
    attr->unknown = NULL;

    attr->new_aspath		= NULL;
    attr->old_aspath		= NULL;
    attr->new_aggregator_as	= -1;
    attr->new_aggregator_addr.s_addr = INADDR_NONE;
    
    return attr;
}

static void process_unknown_attr(struct mstream *s, attributes_t *attr, int flag, int type, int len) {
    /* Unknown attribute. Save as is */
    attr->unknown_num++;
    attr->unknown = realloc(attr->unknown, attr->unknown_num * sizeof(struct unknown_attr));
    
    /* Pointer to the unknown attribute we want to fill in */
    struct unknown_attr unknown = {
        .flag = flag,
        .type = type,
        .len = len,
        .raw = malloc(len)
    };
    
    attr->unknown[attr->unknown_num - 1] = unknown;
    
    mstream_get(s, unknown.raw, len);
}

static void process_one_attr(struct mstream *outer_stream, attributes_t *attr, u_int8_t asn_len, struct zebra_incomplete *incomplete) {
    int flag = mstream_getc(outer_stream, NULL);
    int type = mstream_getc(outer_stream, NULL);
    int len;
    
    if(flag & BGP_ATTR_FLAG_EXTLEN)
        len = mstream_getw(outer_stream,NULL);
    else
        len = mstream_getc(outer_stream,NULL);    

    //info("flag:%-2i type:%-2i length:%i", flag, type, len);

    mstream_t ms = mstream_copy(outer_stream, len), *s = &ms;
    if(mstream_can_read(s) != len) {
        warn("ERROR attribute is truncated: expected=%u remaining=%u\n", len, mstream_can_read(s));
        return;
    }
    
    /* Take note of all attributes, including unknown ones */
    if(type <= sizeof(attr->flag) * 8)
        attr->flag |= ATTR_FLAG_BIT(type);
        
    switch(type) {
        case BGP_ATTR_MP_REACH_NLRI:
            process_mp_announce(s, attr->mp_info, incomplete);
            break;
        case BGP_ATTR_MP_UNREACH_NLRI:
            process_mp_withdraw(s, attr->mp_info, incomplete);
            break;
        case BGP_ATTR_ORIGIN:
            assert(attr->origin == -1);
            attr->origin = mstream_getc(s, NULL);
            break;
        case BGP_ATTR_AS_PATH:
            assert(! attr->aspath);
            attr->aspath = create_aspath(len, asn_len);
            mstream_get(s, attr->aspath->data, len);
            process_attr_aspath_string(attr->aspath);
            break;
        case BGP_ATTR_NEXT_HOP:
            assert(INADDR_NONE == attr->nexthop.s_addr);
            attr->nexthop = mstream_get_ipv4(s);
            break;
        case BGP_ATTR_MULTI_EXIT_DISC:
            assert(-1 == attr->med);
            mstream_getl(s,&attr->med);
            break;
        case BGP_ATTR_LOCAL_PREF:
            assert(-1 == attr->local_pref);
            mstream_getl(s,&attr->local_pref);
            break;
        case BGP_ATTR_ATOMIC_AGGREGATE:
            break;
        case BGP_ATTR_AGGREGATOR:
            assert(-1 == attr->new_aggregator_as);
            read_asn(s, &attr->aggregator_as, asn_len);
            attr->aggregator_addr = mstream_get_ipv4(s);
            break;
        case BGP_ATTR_COMMUNITIES:
            assert(! attr->community);
            attr->community		= malloc(sizeof(struct community));
            attr->community->size	= len / 4;
            attr->community->val	= malloc(len);
            mstream_get(s,attr->community->val,len);
            attr->community->str	= NULL;
            process_attr_community_string(attr->community);
            break;
        case BGP_ATTR_NEW_AS_PATH:
            assert(! attr->new_aspath);
            attr->new_aspath = create_aspath(len, ASN32_LEN);
            mstream_get(s,attr->new_aspath->data, len);
            process_attr_aspath_string(attr->new_aspath);
            /* AS_CONFED_SEQUENCE and AS_CONFED_SET segments invalid in NEW_AS_PATH */
            check_new_aspath(attr->new_aspath);
            break;
        case BGP_ATTR_NEW_AGGREGATOR:
            assert(-1 == attr->new_aggregator_as);
            read_asn(s, &attr->new_aggregator_as, ASN32_LEN);
            attr->new_aggregator_addr = mstream_get_ipv4(s);
            break;
        case BGP_ATTR_ORIGINATOR_ID:
            assert(INADDR_NONE == attr->originator_id.s_addr);
            attr->originator_id = mstream_get_ipv4(s);
            break;
        case BGP_ATTR_CLUSTER_LIST:
            assert(! attr->cluster);
            attr->cluster		= malloc(sizeof(struct cluster_list));
            attr->cluster->length	= len/4;
            attr->cluster->list = malloc((attr->cluster->length) * sizeof(struct in_addr));
            
            int i; // cluster index
            for (i = 0; i < attr->cluster->length; i++)
                attr->cluster->list[i] = mstream_get_ipv4(s);
            break;
        default:
            process_unknown_attr(s, attr, flag, type, len);
    }    
}

attributes_t *process_attributes(struct mstream *s, u_int8_t asn_len, struct zebra_incomplete *incomplete) {
    int	total = mstream_getw(s, NULL);
    
    attributes_t *attr = attr_init(s, total);
    mstream_t copy = mstream_copy(s, total);

    if(mstream_can_read(&copy) != total)
        warn("entry is truncated: expected=%u remaining=%u", total, mstream_can_read(&copy));
    
    while(mstream_can_read(&copy))
        process_one_attr(&copy, attr, asn_len, incomplete);
    
    // Once all attributes have been read, take care of ASN32 transition
    process_asn32_trans(attr, asn_len);
    
    return attr;
}

struct aspath *create_aspath(u_int16_t len, u_int8_t asn_len) {
  struct aspath *aspath = malloc(sizeof(struct aspath));
  if(aspath) {
    aspath->asn_len	= asn_len;
    aspath->length	= len;
    aspath->count	= 0;
    aspath->str		= NULL;
    if(len > 0)
       aspath->data	= malloc(len);
    else
       aspath->data	= NULL;
  }
  return aspath;
}

void aspath_error(struct aspath *as) {
  as->count = 0;

  if(as->str) {
    free(as->str);
    as->str = NULL;
  }

  as->str = malloc(strlen(ASPATH_STR_ERROR) + 1);
  strcpy(as->str, ASPATH_STR_ERROR);
}

void process_attr_aspath_string(struct aspath *as) {
    const int MAX_ASPATH_LEN = 8000;  
    as->str = malloc(MAX_ASPATH_LEN);
    
    /* Set default values */
    int space = 0;
    u_char type = AS_SEQUENCE;
    int pos = 0;
    
    /* Set initial pointer. */
    caddr_t pnt = as->data;
    caddr_t end = pnt + as->length;
    struct assegment *segment = NULL;
    
    while (pnt < end) {
      int i;

      /* For fetch value. */
      segment = (struct assegment *) pnt;

      /* Check AS type validity. */
      if ((segment->type != AS_SET) &&
	  (segment->type != AS_SEQUENCE) &&
	  (segment->type != AS_CONFED_SET) &&
	  (segment->type != AS_CONFED_SEQUENCE))
	{
	  aspath_error(as);
	  return;
	}

      /* Check AS length. */
      if ((pnt + (segment->length * as->asn_len) + AS_HEADER_SIZE) > end)
	{
	  aspath_error(as);
	  return;
	}

      /* If segment type is changed, print previous type's end
         character. */
      if (type != AS_SEQUENCE)
	as->str[pos++] = aspath_delimiter_char (type, AS_SEG_END);
      if (space)
	as->str[pos++] = ' ';

      if (segment->type != AS_SEQUENCE)
	as->str[pos++] = aspath_delimiter_char (segment->type, AS_SEG_START);

      space = 0;

      /* Increment as->count - NOT ignoring CONFED_SETS/SEQUENCES any more.
         I doubt anybody was relying on this behaviour anyway. */
      switch(segment->type) {
	case AS_SEQUENCE:
	case AS_CONFED_SEQUENCE:
	  as->count += segment->length;
	break;
	case AS_SET:
	case AS_CONFED_SET:
	  as->count += 1;
	break;
      }

      for (i = 0; i < segment->length; i++)
	{
	  as_t asn;

	  if (space)
	    {
	      if (segment->type == AS_SET
		  || segment->type == AS_CONFED_SET)
		as->str[pos++] = ',';
	      else
		as->str[pos++] = ' ';
	    }
	  else
	    space = 1;

	  int asn_pos = i * as->asn_len;
          switch(as->asn_len) {
                case ASN16_LEN:
                    asn = ntohs (*(u_int16_t *) (segment->data + asn_pos));
                    break;
                case ASN32_LEN:
                    asn = ntohl (*(u_int32_t *) (segment->data + asn_pos));
                    break;
                default:
                    assert("invalid asn_len" && false);
          }

          pos += int2str(asn, as->str + pos);
          if(pos > MAX_ASPATH_LEN - 100) {
              strcpy(as->str + pos, "...");
              return;
          };
	}

      type = segment->type;
      pnt += (segment->length * as->asn_len) + AS_HEADER_SIZE;
    }

  if (segment && segment->type != AS_SEQUENCE)
    as->str[pos++] = aspath_delimiter_char (segment->type, AS_SEG_END);

  as->str[pos] = '\0';
}

char aspath_delimiter_char (u_char type, u_char which) {
  int i;
  struct
  {
    int type;
    char start;
    char end;
  } aspath_delim_char [] =
    {
      { AS_SET,             '{', '}' },
      { AS_SEQUENCE,        ' ', ' ' },
      { AS_CONFED_SET,      '[', ']' },
      { AS_CONFED_SEQUENCE, '(', ')' },
      { 0, '\0', '\0' }
    };

  for (i = 0; aspath_delim_char[i].type != 0; i++)
    {
      if (aspath_delim_char[i].type == type)
	{
	  if (which == AS_SEG_START)
	    return aspath_delim_char[i].start;
	  else if (which == AS_SEG_END)
	    return aspath_delim_char[i].end;
	}
    }
  return ' ';
}


void process_attr_community_string(struct community *com) {

  char buf[BUFSIZ];
  int i;
  u_int32_t comval;
  u_int16_t as;
  u_int16_t val;

  memset (buf, 0, BUFSIZ);

  for (i = 0; i < com->size; i++)
    {
      memcpy (&comval, com_nthval (com, i), sizeof (u_int32_t));
      comval = ntohl (comval);
      switch (comval)
	{
	case COMMUNITY_NO_EXPORT:
	  strlcat (buf, " no-export", BUFSIZ);
	  break;
	case COMMUNITY_NO_ADVERTISE:
	  strlcat (buf, " no-advertise", BUFSIZ);
	  break;
	case COMMUNITY_LOCAL_AS:
	  strlcat (buf, " local-AS", BUFSIZ);
	  break;
	default:
	  as = (comval >> 16) & 0xFFFF;
	  val = comval & 0xFFFF;
	  snprintf (buf + strlen (buf), BUFSIZ - strlen (buf),
		    " %d:%d", as, val);
	  break;
	}
    }

    com->str = malloc(strlen(buf)+1);
    strcpy(com->str, buf);
}

static struct mp_nlri *get_nexthop(struct mstream *s, u_int16_t afi) {
    struct mp_nlri *nlri = calloc(1, sizeof(struct mp_nlri));
    
    nlri->nexthop_len = mstream_getc(s, NULL);
    
    // sometimes nexthop_len is 0 - not sure what this means (see IS-626)
    // if(mp_nlri->nexthop_len == 0)
    //    return len;

    if(afi == AFI_IP) {
        assert(nlri->nexthop_len == 4);
        nlri->nexthop.v4_addr = mstream_get_ipv4(s);
        return nlri;
    }

#ifdef BGPDUMP_HAVE_IPV6
    assert(afi == AFI_IP6);
    mstream_get(s, &nlri->nexthop.v6_addr, 16);
    if(nlri->nexthop_len == 32) {
        /* Is there also a link-local address? */
        mstream_get(s, &nlri->nexthop_local.v6_addr.s6_addr, 16);
    } else if(nlri->nexthop_len != 16) {
        warn("process_mp_announce: unknown MP nexthop length %d", nlri->nexthop_len);
    }
#endif
    return nlri;
}

void process_mp_announce(struct mstream *s, struct mp_info *info, struct zebra_incomplete *incomplete) {
    u_int16_t afi;
    u_int8_t safi;

    // look for MRT abbreviated MP_NLRI packets
    if(s->start[s->position] != 0) {
        assert(info->announce[AFI_IP6][SAFI_UNICAST] == NULL);
        info->announce[AFI_IP6][SAFI_UNICAST] = get_nexthop(s, AFI_IP6);
        return;
    }
    
    mstream_getw(s, &afi);
    mstream_getc(s, &safi);
        
    if(afi > BGPDUMP_MAX_AFI || safi > BGPDUMP_MAX_SAFI) {
            warn("process_mp_announce: unknown protocol(AFI=%d, SAFI=%d)!", afi, safi);
            return;
    }

    if(info->announce[afi][safi] != NULL) {
            warn("process_mp_announce: two MP_NLRI for the same protocol(%d, %d)!", afi, safi);
            return;
    }

    info->announce[afi][safi] = get_nexthop(s, afi);

    // SNPA is defunct and num_snpa should always be 0
    u_int8_t num_snpa;
    if(mstream_getc(s, &num_snpa))
        warn("process_mp_announce: MP_NLRI contains SNPAs, skipping");
    for(; num_snpa > 0; --num_snpa) {
        mstream_get(s, NULL, mstream_getc(s, NULL));
    }

    info->announce[afi][safi]->prefix_count = read_prefix_list(s, afi, info->announce[afi][safi]->nlri, incomplete);
}

void process_mp_withdraw(struct mstream *s, struct mp_info *info, struct zebra_incomplete *incomplete) {
	u_int16_t afi;
	u_int8_t safi;
	struct mp_nlri *mp_nlri;

	mstream_getw(s, &afi);
	mstream_getc(s, &safi);

	/* Do we know about this address family? */
	if(afi > BGPDUMP_MAX_AFI || safi > BGPDUMP_MAX_SAFI) {
		warn("process_mp_withdraw: unknown AFI,SAFI %d,%d!", afi, safi);
		return;
	}

	/* If there are 2 NLRI's for the same protocol, fail but don't burn and die */
	if(info->withdraw[afi][safi] != NULL) {
		warn("process_mp_withdraw: update contains more than one MP_NLRI with AFI,SAFI %d,%d!", afi, safi);
		return;
	}

	/* Allocate structure */
	mp_nlri = malloc(sizeof(struct mp_nlri));
	memset(mp_nlri, 0, sizeof(struct mp_nlri));
	info->withdraw[afi][safi] = mp_nlri;

	mp_nlri->prefix_count = read_prefix_list(s, afi, mp_nlri->nlri, incomplete);
}

static int read_prefix_list(struct mstream *s, u_int16_t afi, struct prefix *prefixes, struct zebra_incomplete *incomplete) {
    int count = 0;
    
    while(mstream_can_read(s)) {
        u_int8_t p_len = mstream_getc(s,NULL); // length in bits
        u_int8_t p_bytes = (p_len + 7) / 8;
        
        /* Truncated prefix list? */
        if(mstream_can_read(s) < p_bytes) {
            if(! incomplete)
                break;
            
            /* Put prefix in incomplete structure */
            incomplete->afi = afi;
            incomplete->orig_len = p_len;
            incomplete->prefix = (struct prefix) {
                .len = mstream_can_read(s) * 8
            };
            mstream_get(s, &incomplete->prefix.address, p_bytes);
            break;
        }
        
        struct prefix *prefix = prefixes + count;
        
        if(count++ > MAX_PREFIXES)
            continue;

        *prefix = (struct prefix) { .len = p_len };
        mstream_get(s, &prefix->address, p_bytes);
    }
    
    if(count > MAX_PREFIXES) {
        err("too many prefixes (%i > %i)", count, MAX_PREFIXES);
        return MAX_PREFIXES;
    }
    
    return count;
}

static as_t read_asn(struct mstream *s, as_t *asn, u_int8_t len) {
  u_int16_t asn16;

  assert(len == sizeof(u_int32_t) || len == sizeof(u_int16_t));
  switch(len) {
    case sizeof(u_int32_t):
      return mstream_getl(s, asn);
    case sizeof(u_int16_t):
      mstream_getw(s, &asn16);
      if(asn)
	*asn = asn16;
	return asn16;
    default:
      /* Not reached. Avoid compiler warning */
      return 0;
  }
}

int check_new_aspath(struct aspath *aspath) {
  struct assegment *segment;
  for(segment = (struct assegment *) aspath->data;
      segment < (struct assegment *) (aspath->data + aspath->length);
      segment = (struct assegment *) ((char *) segment + sizeof(*segment) + segment->length * ASN32_LEN)) {
    if(segment->type == AS_CONFED_SEQUENCE || segment->type == AS_CONFED_SET) {
      warn("check_new_aspath: invalid segment of type AS_CONFED_%s in NEW_AS_PATH",
	     segment->type == AS_CONFED_SET ? "SET" : "SEQUENCE");
      return 0;
    }
  }
  return 1;
}

void process_asn32_trans(attributes_t *attr, u_int8_t asn_len) {
  if(asn_len == ASN32_LEN) {
    /* These attributes "SHOULD NOT" be used with ASN32. */
    if(attr->flag & ATTR_FLAG_BIT(BGP_ATTR_NEW_AS_PATH))
      warn("process_asn32_trans: ASN32 message contains NEW_AS_PATH attribute");

    if(attr->flag & ATTR_FLAG_BIT(BGP_ATTR_NEW_AGGREGATOR))
      warn("process_asn32_trans: ASN32 message contains NEW_AGGREGATOR attribute");

    /* Don't compute anything, just leave AS_PATH and AGGREGATOR as they are */
    return;
  }

  /* Process NEW_AGGREGATOR */
  if(attr->flag & ATTR_FLAG_BIT(BGP_ATTR_AGGREGATOR) &&
     attr->flag & ATTR_FLAG_BIT(BGP_ATTR_NEW_AGGREGATOR)) {
      /* Both AGGREGATOR and NEW_AGGREGATOR present, merge */
      if(attr->aggregator_as != AS_TRAN) {
	/* Don't do anything */
	return;
      } else {
	attr->old_aggregator_as = attr->aggregator_as;
	attr->old_aggregator_addr = attr->aggregator_addr;
	attr->aggregator_as = attr->new_aggregator_as;
	attr->aggregator_addr = attr->new_aggregator_addr;
      }
  }

  /* Process NEW_AS_PATH */
  if(! (attr->flag & ATTR_FLAG_BIT(BGP_ATTR_NEW_AS_PATH)))
    return;

  // attr->aspath may be NULL, at least in case of MP_UNREACH_NLRI
  if(attr->aspath == NULL) return;
  if(attr->aspath->count < attr->new_aspath->count) {
    return;
  }

  /* Merge paths */
  attr->old_aspath = attr->aspath;
  attr->aspath = asn32_merge_paths(attr->old_aspath, attr->new_aspath);
  if(attr->aspath) {
    process_attr_aspath_string(attr->aspath);
  }
}

struct aspath *asn32_merge_paths(struct aspath *path, struct aspath *newpath) {
  struct aspath *mergedpath = create_aspath(0, ASN32_LEN);
  struct assegment *segment, *mergedsegment;
  int newlen;

  /* Keep copying segments from AS_PATH until our path is as long as AS_PATH - NEW_AS_PATH. */
  segment = (struct assegment *) (path->data);
  while(mergedpath->count < path->count - newpath->count) {
    /* Make room */
    newlen = mergedpath->length + sizeof(struct assegment) + segment->length * ASN32_LEN;
    mergedpath->data = realloc(mergedpath->data, newlen);

    /* Create a new AS-path segment */
    mergedsegment = (struct assegment *) (mergedpath->data + mergedpath->length);

    /* Copy segment over. AS_PATH contains 16-bit ASes, so expand */
    mergedsegment->type = segment->type;
    mergedsegment->length = segment->length;
    asn32_expand_16_to_32(mergedsegment->data, segment->data, segment->length);

    /* Update length */
    mergedpath->length = newlen;
    if(segment->type == AS_SET || segment->type == AS_CONFED_SET) {
      mergedpath->count += 1;
    } else {
      mergedpath->count += segment->length;
      /* Did we copy too many ASes over? */
      if(mergedpath->count > path->count - newpath->count) {
	mergedsegment->length -= mergedpath->count - (path->count - newpath->count);
	mergedpath->length -= (mergedpath->count - (path->count - newpath->count)) * ASN32_LEN;
      }
    }
  }

  /* Append NEW_AS_PATH to merged path */
  mergedpath->data = realloc(mergedpath->data, mergedpath->length + newpath->length);
  memcpy(mergedpath->data + mergedpath->length, newpath->data, newpath->length);
  mergedpath->length += newpath->length;

  return mergedpath;
}

void asn32_expand_16_to_32(char *dst, char *src, int len) {
  u_int32_t *dstarray = (u_int32_t *) dst;
  u_int16_t *srcarray = (u_int16_t *) src;
  int i;

  for(i = 0; i < len; i++) {
    dstarray[i] = htonl(ntohs(srcarray[i]));
  }
}

#if defined(linux)
size_t strlcat(char *dst, const char *src, size_t size) {
  if (strlen (dst) + strlen (src) >= size)
    return -1;

  strcat (dst, src);

  return (strlen(dst));
}
#endif