summaryrefslogtreecommitdiffhomepage
path: root/pkg/packet/mrt/mrt.go
blob: dc07ba9be2966202933583d5d86d438cd5ec8733 (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
// Copyright (C) 2015 Nippon Telegraph and Telephone Corporation.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package mrt

import (
	"bytes"
	"encoding/binary"
	"fmt"
	"math"
	"net"
	"time"

	"github.com/osrg/gobgp/pkg/packet/bgp"
)

const (
	MRT_COMMON_HEADER_LEN = 12
)

type MRTType uint16

const (
	NULL         MRTType = 0  // deprecated
	START        MRTType = 1  // deprecated
	DIE          MRTType = 2  // deprecated
	I_AM_DEAD    MRTType = 3  // deprecated
	PEER_DOWN    MRTType = 4  // deprecated
	BGP          MRTType = 5  // deprecated
	RIP          MRTType = 6  // deprecated
	IDRP         MRTType = 7  // deprecated
	RIPNG        MRTType = 8  // deprecated
	BGP4PLUS     MRTType = 9  // deprecated
	BGP4PLUS01   MRTType = 10 // deprecated
	OSPFv2       MRTType = 11
	TABLE_DUMP   MRTType = 12
	TABLE_DUMPv2 MRTType = 13
	BGP4MP       MRTType = 16
	BGP4MP_ET    MRTType = 17
	ISIS         MRTType = 32
	ISIS_ET      MRTType = 33
	OSPFv3       MRTType = 48
	OSPFv3_ET    MRTType = 49
)

type MRTSubTyper interface {
	ToUint16() uint16
}

type MRTSubTypeTableDumpv2 uint16

const (
	PEER_INDEX_TABLE           MRTSubTypeTableDumpv2 = 1
	RIB_IPV4_UNICAST           MRTSubTypeTableDumpv2 = 2
	RIB_IPV4_MULTICAST         MRTSubTypeTableDumpv2 = 3
	RIB_IPV6_UNICAST           MRTSubTypeTableDumpv2 = 4
	RIB_IPV6_MULTICAST         MRTSubTypeTableDumpv2 = 5
	RIB_GENERIC                MRTSubTypeTableDumpv2 = 6
	GEO_PEER_TABLE             MRTSubTypeTableDumpv2 = 7  // RFC6397
	RIB_IPV4_UNICAST_ADDPATH   MRTSubTypeTableDumpv2 = 8  // RFC8050
	RIB_IPV4_MULTICAST_ADDPATH MRTSubTypeTableDumpv2 = 9  // RFC8050
	RIB_IPV6_UNICAST_ADDPATH   MRTSubTypeTableDumpv2 = 10 // RFC8050
	RIB_IPV6_MULTICAST_ADDPATH MRTSubTypeTableDumpv2 = 11 // RFC8050
	RIB_GENERIC_ADDPATH        MRTSubTypeTableDumpv2 = 12 // RFC8050
)

func (t MRTSubTypeTableDumpv2) ToUint16() uint16 {
	return uint16(t)
}

type MRTSubTypeBGP4MP uint16

const (
	STATE_CHANGE              MRTSubTypeBGP4MP = 0
	MESSAGE                   MRTSubTypeBGP4MP = 1
	MESSAGE_AS4               MRTSubTypeBGP4MP = 4
	STATE_CHANGE_AS4          MRTSubTypeBGP4MP = 5
	MESSAGE_LOCAL             MRTSubTypeBGP4MP = 6
	MESSAGE_AS4_LOCAL         MRTSubTypeBGP4MP = 7
	MESSAGE_ADDPATH           MRTSubTypeBGP4MP = 8  // RFC8050
	MESSAGE_AS4_ADDPATH       MRTSubTypeBGP4MP = 9  // RFC8050
	MESSAGE_LOCAL_ADDPATH     MRTSubTypeBGP4MP = 10 // RFC8050
	MESSAGE_AS4_LOCAL_ADDPATH MRTSubTypeBGP4MP = 11 // RFC8050
)

func (t MRTSubTypeBGP4MP) ToUint16() uint16 {
	return uint16(t)
}

type BGPState uint16

const (
	IDLE        BGPState = 1
	CONNECT     BGPState = 2
	ACTIVE      BGPState = 3
	OPENSENT    BGPState = 4
	OPENCONFIRM BGPState = 5
	ESTABLISHED BGPState = 6
)

func packValues(values []interface{}) ([]byte, error) {
	b := new(bytes.Buffer)
	for _, v := range values {
		err := binary.Write(b, binary.BigEndian, v)
		if err != nil {
			return nil, err
		}
	}
	return b.Bytes(), nil
}

type MRTHeader struct {
	Timestamp uint32
	Type      MRTType
	SubType   uint16
	Len       uint32
}

func (h *MRTHeader) DecodeFromBytes(data []byte) error {
	if len(data) < MRT_COMMON_HEADER_LEN {
		return fmt.Errorf("not all MRTHeader bytes are available. expected: %d, actual: %d", MRT_COMMON_HEADER_LEN, len(data))
	}
	h.Timestamp = binary.BigEndian.Uint32(data[:4])
	h.Type = MRTType(binary.BigEndian.Uint16(data[4:6]))
	h.SubType = binary.BigEndian.Uint16(data[6:8])
	h.Len = binary.BigEndian.Uint32(data[8:12])
	return nil
}

func (h *MRTHeader) Serialize() ([]byte, error) {
	return packValues([]interface{}{h.Timestamp, h.Type, h.SubType, h.Len})
}

func NewMRTHeader(timestamp uint32, t MRTType, subtype MRTSubTyper, l uint32) (*MRTHeader, error) {
	return &MRTHeader{
		Timestamp: timestamp,
		Type:      t,
		SubType:   subtype.ToUint16(),
		Len:       l,
	}, nil
}

func (h *MRTHeader) GetTime() time.Time {
	t := int64(h.Timestamp)
	return time.Unix(t, 0)
}

type MRTMessage struct {
	Header MRTHeader
	Body   Body
}

func (m *MRTMessage) Serialize() ([]byte, error) {
	buf, err := m.Body.Serialize()
	if err != nil {
		return nil, err
	}
	m.Header.Len = uint32(len(buf))
	bbuf, err := m.Header.Serialize()
	if err != nil {
		return nil, err
	}
	return append(bbuf, buf...), nil
}

func NewMRTMessage(timestamp uint32, t MRTType, subtype MRTSubTyper, body Body) (*MRTMessage, error) {
	header, err := NewMRTHeader(timestamp, t, subtype, 0)
	if err != nil {
		return nil, err
	}
	return &MRTMessage{
		Header: *header,
		Body:   body,
	}, nil
}

type Body interface {
	DecodeFromBytes([]byte) error
	Serialize() ([]byte, error)
}

type Peer struct {
	Type      uint8
	BgpId     net.IP
	IpAddress net.IP
	AS        uint32
}

func (p *Peer) DecodeFromBytes(data []byte) ([]byte, error) {
	notAllBytesAvail := fmt.Errorf("not all Peer bytes are available")
	if len(data) < 5 {
		return nil, notAllBytesAvail
	}
	p.Type = uint8(data[0])
	p.BgpId = net.IP(data[1:5])
	data = data[5:]

	if p.Type&1 > 0 {
		if len(data) < 16 {
			return nil, notAllBytesAvail
		}
		p.IpAddress = net.IP(data[:16])
		data = data[16:]
	} else {
		if len(data) < 4 {
			return nil, notAllBytesAvail
		}
		p.IpAddress = net.IP(data[:4])
		data = data[4:]
	}

	if p.Type&(1<<1) > 0 {
		if len(data) < 4 {
			return nil, notAllBytesAvail
		}
		p.AS = binary.BigEndian.Uint32(data[:4])
		data = data[4:]
	} else {
		if len(data) < 2 {
			return nil, notAllBytesAvail
		}
		p.AS = uint32(binary.BigEndian.Uint16(data[:2]))
		data = data[2:]
	}

	return data, nil
}

func (p *Peer) Serialize() ([]byte, error) {
	var err error
	var bbuf []byte
	buf := make([]byte, 5)
	buf[0] = uint8(p.Type)
	copy(buf[1:], p.BgpId.To4())
	if p.Type&1 > 0 {
		buf = append(buf, p.IpAddress.To16()...)
	} else {
		buf = append(buf, p.IpAddress.To4()...)
	}
	if p.Type&(1<<1) > 0 {
		bbuf, err = packValues([]interface{}{p.AS})
	} else {
		if p.AS > uint32(math.MaxUint16) {
			return nil, fmt.Errorf("AS number is beyond 2 octet. %d > %d", p.AS, math.MaxUint16)
		}
		bbuf, err = packValues([]interface{}{uint16(p.AS)})
	}
	if err != nil {
		return nil, err
	}
	return append(buf, bbuf...), nil
}

func NewPeer(bgpid string, ipaddr string, asn uint32, isAS4 bool) *Peer {
	t := 0
	addr := net.ParseIP(ipaddr).To4()
	if addr == nil {
		t |= 1
		addr = net.ParseIP(ipaddr).To16()
	}
	if isAS4 {
		t |= (1 << 1)
	}
	return &Peer{
		Type:      uint8(t),
		BgpId:     net.ParseIP(bgpid).To4(),
		IpAddress: addr,
		AS:        asn,
	}
}

func (p *Peer) String() string {
	return fmt.Sprintf("PEER ENTRY: ID [%s] Addr [%s] AS [%d]", p.BgpId, p.IpAddress, p.AS)
}

type PeerIndexTable struct {
	CollectorBgpId net.IP
	ViewName       string
	Peers          []*Peer
}

func (t *PeerIndexTable) DecodeFromBytes(data []byte) error {
	notAllBytesAvail := fmt.Errorf("not all PeerIndexTable bytes are available")
	if len(data) < 6 {
		return notAllBytesAvail
	}
	t.CollectorBgpId = net.IP(data[:4])
	viewLen := binary.BigEndian.Uint16(data[4:6])
	if len(data) < 6+int(viewLen) {
		return notAllBytesAvail
	}
	t.ViewName = string(data[6 : 6+viewLen])

	data = data[6+viewLen:]

	if len(data) < 2 {
		return notAllBytesAvail
	}
	peerNum := binary.BigEndian.Uint16(data[:2])
	data = data[2:]
	t.Peers = make([]*Peer, 0, peerNum)
	var err error
	for i := 0; i < int(peerNum); i++ {
		p := &Peer{}
		data, err = p.DecodeFromBytes(data)
		if err != nil {
			return err
		}
		t.Peers = append(t.Peers, p)
	}

	return nil
}

func (t *PeerIndexTable) Serialize() ([]byte, error) {
	buf := make([]byte, 8+len(t.ViewName))
	copy(buf, t.CollectorBgpId.To4())
	binary.BigEndian.PutUint16(buf[4:], uint16(len(t.ViewName)))
	copy(buf[6:], t.ViewName)
	binary.BigEndian.PutUint16(buf[6+len(t.ViewName):], uint16(len(t.Peers)))
	for _, peer := range t.Peers {
		bbuf, err := peer.Serialize()
		if err != nil {
			return nil, err
		}
		buf = append(buf, bbuf...)
	}
	return buf, nil
}

func NewPeerIndexTable(bgpid string, viewname string, peers []*Peer) *PeerIndexTable {
	return &PeerIndexTable{
		CollectorBgpId: net.ParseIP(bgpid).To4(),
		ViewName:       viewname,
		Peers:          peers,
	}
}

func (t *PeerIndexTable) String() string {
	return fmt.Sprintf("PEER_INDEX_TABLE: CollectorBgpId [%s] ViewName [%s] Peers [%s]", t.CollectorBgpId, t.ViewName, t.Peers)
}

type RibEntry struct {
	PeerIndex      uint16
	OriginatedTime uint32
	PathIdentifier uint32
	PathAttributes []bgp.PathAttributeInterface
	isAddPath      bool
}

func (e *RibEntry) DecodeFromBytes(data []byte) ([]byte, error) {
	notAllBytesAvail := fmt.Errorf("not all RibEntry bytes are available")
	if len(data) < 8 {
		return nil, notAllBytesAvail
	}
	e.PeerIndex = binary.BigEndian.Uint16(data[:2])
	e.OriginatedTime = binary.BigEndian.Uint32(data[2:6])
	if e.isAddPath {
		e.PathIdentifier = binary.BigEndian.Uint32(data[6:10])
		data = data[10:]
	} else {
		data = data[6:]
	}
	totalLen := binary.BigEndian.Uint16(data[:2])
	data = data[2:]
	for attrLen := totalLen; attrLen > 0; {
		p, err := bgp.GetPathAttribute(data)
		if err != nil {
			return nil, err
		}
		err = p.DecodeFromBytes(data)
		if err != nil {
			return nil, err
		}
		attrLen -= uint16(p.Len())
		if len(data) < p.Len() {
			return nil, notAllBytesAvail
		}
		data = data[p.Len():]
		e.PathAttributes = append(e.PathAttributes, p)
	}
	return data, nil
}

func (e *RibEntry) Serialize() ([]byte, error) {
	pbuf := make([]byte, 0)
	totalLen := 0
	for _, pattr := range e.PathAttributes {
		// TODO special modification is needed for MP_REACH_NLRI
		// but also Quagga doesn't implement this.
		//
		// RFC 6396 4.3.4
		// There is one exception to the encoding of BGP attributes for the BGP
		// MP_REACH_NLRI attribute (BGP Type Code 14).
		// Since the AFI, SAFI, and NLRI information is already encoded
		// in the RIB Entry Header or RIB_GENERIC Entry Header,
		// only the Next Hop Address Length and Next Hop Address fields are included.

		pb, err := pattr.Serialize()
		if err != nil {
			return nil, err
		}
		pbuf = append(pbuf, pb...)
		totalLen += len(pb)
	}
	var buf []byte
	if e.isAddPath {
		buf = make([]byte, 12)
		binary.BigEndian.PutUint16(buf, e.PeerIndex)
		binary.BigEndian.PutUint32(buf[2:], e.OriginatedTime)
		binary.BigEndian.PutUint32(buf[6:], e.PathIdentifier)
		binary.BigEndian.PutUint16(buf[10:], uint16(totalLen))
	} else {
		buf = make([]byte, 8)
		binary.BigEndian.PutUint16(buf, e.PeerIndex)
		binary.BigEndian.PutUint32(buf[2:], e.OriginatedTime)
		binary.BigEndian.PutUint16(buf[6:], uint16(totalLen))
	}
	buf = append(buf, pbuf...)
	return buf, nil
}

func NewRibEntry(index uint16, time uint32, pathId uint32, pathAttrs []bgp.PathAttributeInterface, isAddPath bool) *RibEntry {
	return &RibEntry{
		PeerIndex:      index,
		OriginatedTime: time,
		PathIdentifier: pathId,
		PathAttributes: pathAttrs,
		isAddPath:      isAddPath,
	}
}

func (e *RibEntry) String() string {
	if e.isAddPath {
		return fmt.Sprintf("RIB_ENTRY: PeerIndex [%d] OriginatedTime [%d] PathIdentifier[%d] PathAttributes [%v]", e.PeerIndex, e.OriginatedTime, e.PathIdentifier, e.PathAttributes)
	} else {
		return fmt.Sprintf("RIB_ENTRY: PeerIndex [%d] OriginatedTime [%d] PathAttributes [%v]", e.PeerIndex, e.OriginatedTime, e.PathAttributes)
	}

}

type Rib struct {
	SequenceNumber uint32
	Prefix         bgp.AddrPrefixInterface
	Entries        []*RibEntry
	RouteFamily    bgp.RouteFamily
	isAddPath      bool
}

func (u *Rib) DecodeFromBytes(data []byte) error {
	if len(data) < 4 {
		return fmt.Errorf("Not all RibIpv4Unicast message bytes available")
	}
	u.SequenceNumber = binary.BigEndian.Uint32(data[:4])
	data = data[4:]
	afi, safi := bgp.RouteFamilyToAfiSafi(u.RouteFamily)
	if afi == 0 && safi == 0 {
		afi = binary.BigEndian.Uint16(data[:2])
		safi = data[2]
		data = data[3:]
	}
	prefix, err := bgp.NewPrefixFromRouteFamily(afi, safi)
	if err != nil {
		return err
	}
	err = prefix.DecodeFromBytes(data)
	if err != nil {
		return err
	}
	u.Prefix = prefix
	data = data[prefix.Len():]
	entryNum := binary.BigEndian.Uint16(data[:2])
	data = data[2:]
	u.Entries = make([]*RibEntry, 0, entryNum)
	for i := 0; i < int(entryNum); i++ {
		e := &RibEntry{
			isAddPath: u.isAddPath,
		}
		data, err = e.DecodeFromBytes(data)
		if err != nil {
			return err
		}
		u.Entries = append(u.Entries, e)
	}
	return nil
}

func (u *Rib) Serialize() ([]byte, error) {
	buf := make([]byte, 4)
	binary.BigEndian.PutUint32(buf, u.SequenceNumber)
	rf := bgp.AfiSafiToRouteFamily(u.Prefix.AFI(), u.Prefix.SAFI())
	switch rf {
	case bgp.RF_IPv4_UC, bgp.RF_IPv4_MC, bgp.RF_IPv6_UC, bgp.RF_IPv6_MC:
	default:
		bbuf := make([]byte, 2)
		binary.BigEndian.PutUint16(bbuf, u.Prefix.AFI())
		buf = append(buf, bbuf...)
		buf = append(buf, u.Prefix.SAFI())
	}
	bbuf, err := u.Prefix.Serialize()
	if err != nil {
		return nil, err
	}
	buf = append(buf, bbuf...)
	bbuf, err = packValues([]interface{}{uint16(len(u.Entries))})
	if err != nil {
		return nil, err
	}
	buf = append(buf, bbuf...)
	for _, entry := range u.Entries {
		bbuf, err = entry.Serialize()
		if err != nil {
			return nil, err
		}
		buf = append(buf, bbuf...)
	}
	return buf, nil
}

func NewRib(seq uint32, prefix bgp.AddrPrefixInterface, entries []*RibEntry) *Rib {
	rf := bgp.AfiSafiToRouteFamily(prefix.AFI(), prefix.SAFI())
	return &Rib{
		SequenceNumber: seq,
		Prefix:         prefix,
		Entries:        entries,
		RouteFamily:    rf,
		isAddPath:      entries[0].isAddPath,
	}
}

func (u *Rib) String() string {
	return fmt.Sprintf("RIB: Seq [%d] Prefix [%s] Entries [%s]", u.SequenceNumber, u.Prefix, u.Entries)
}

type GeoPeer struct {
	Type      uint8
	BgpId     net.IP
	Latitude  float32
	Longitude float32
}

func (p *GeoPeer) DecodeFromBytes(data []byte) ([]byte, error) {
	if len(data) < 13 {
		return nil, fmt.Errorf("not all GeoPeer bytes are available")
	}
	// Peer IP Address and Peer AS should not be included
	p.Type = uint8(data[0])
	if p.Type != uint8(0) {
		return nil, fmt.Errorf("unsupported peer type for GeoPeer: %d", p.Type)
	}
	p.BgpId = net.IP(data[1:5])
	p.Latitude = math.Float32frombits(binary.BigEndian.Uint32(data[5:9]))
	p.Longitude = math.Float32frombits(binary.BigEndian.Uint32(data[9:13]))
	return data[13:], nil
}

func (p *GeoPeer) Serialize() ([]byte, error) {
	buf := make([]byte, 13)
	buf[0] = uint8(0) // Peer IP Address and Peer AS should not be included
	bgpId := p.BgpId.To4()
	if bgpId == nil {
		return nil, fmt.Errorf("invalid BgpId: %s", p.BgpId)
	}
	copy(buf[1:5], bgpId)
	binary.BigEndian.PutUint32(buf[5:9], math.Float32bits(p.Latitude))
	binary.BigEndian.PutUint32(buf[9:13], math.Float32bits(p.Longitude))
	return buf, nil
}

func NewGeoPeer(bgpid string, latitude float32, longitude float32) *GeoPeer {
	return &GeoPeer{
		Type:      0, // Peer IP Address and Peer AS should not be included
		BgpId:     net.ParseIP(bgpid).To4(),
		Latitude:  latitude,
		Longitude: longitude,
	}
}

func (p *GeoPeer) String() string {
	return fmt.Sprintf("PEER ENTRY: ID [%s] Latitude [%f] Longitude [%f]", p.BgpId, p.Latitude, p.Longitude)
}

type GeoPeerTable struct {
	CollectorBgpId     net.IP
	CollectorLatitude  float32
	CollectorLongitude float32
	Peers              []*GeoPeer
}

func (t *GeoPeerTable) DecodeFromBytes(data []byte) error {
	if len(data) < 14 {
		return fmt.Errorf("not all GeoPeerTable bytes are available")
	}
	t.CollectorBgpId = net.IP(data[0:4])
	t.CollectorLatitude = math.Float32frombits(binary.BigEndian.Uint32(data[4:8]))
	t.CollectorLongitude = math.Float32frombits(binary.BigEndian.Uint32(data[8:12]))
	peerCount := binary.BigEndian.Uint16(data[12:14])
	data = data[14:]
	t.Peers = make([]*GeoPeer, 0, peerCount)
	var err error
	for i := 0; i < int(peerCount); i++ {
		p := &GeoPeer{}
		if data, err = p.DecodeFromBytes(data); err != nil {
			return err
		}
		t.Peers = append(t.Peers, p)
	}
	return nil
}

func (t *GeoPeerTable) Serialize() ([]byte, error) {
	buf := make([]byte, 14)
	collectorBgpId := t.CollectorBgpId.To4()
	if collectorBgpId == nil {
		return nil, fmt.Errorf("invalid CollectorBgpId: %s", t.CollectorBgpId)
	}
	copy(buf[0:4], collectorBgpId)
	binary.BigEndian.PutUint32(buf[4:8], math.Float32bits(t.CollectorLatitude))
	binary.BigEndian.PutUint32(buf[8:12], math.Float32bits(t.CollectorLongitude))
	binary.BigEndian.PutUint16(buf[12:14], uint16(len(t.Peers)))
	for _, peer := range t.Peers {
		pbuf, err := peer.Serialize()
		if err != nil {
			return nil, err
		}
		buf = append(buf, pbuf...)
	}
	return buf, nil
}

func NewGeoPeerTable(bgpid string, latitude float32, longitude float32, peers []*GeoPeer) *GeoPeerTable {
	return &GeoPeerTable{
		CollectorBgpId:     net.ParseIP(bgpid).To4(),
		CollectorLatitude:  latitude,
		CollectorLongitude: longitude,
		Peers:              peers,
	}
}

func (t *GeoPeerTable) String() string {
	return fmt.Sprintf("GEO_PEER_TABLE: CollectorBgpId [%s] CollectorLatitude [%f] CollectorLongitude [%f] Peers [%s]", t.CollectorBgpId, t.CollectorLatitude, t.CollectorLongitude, t.Peers)
}

type BGP4MPHeader struct {
	PeerAS         uint32
	LocalAS        uint32
	InterfaceIndex uint16
	AddressFamily  uint16
	PeerIpAddress  net.IP
	LocalIpAddress net.IP
	isAS4          bool
}

func (m *BGP4MPHeader) decodeFromBytes(data []byte) ([]byte, error) {
	if m.isAS4 && len(data) < 8 {
		return nil, fmt.Errorf("Not all BGP4MPMessageAS4 bytes available")
	} else if !m.isAS4 && len(data) < 4 {
		return nil, fmt.Errorf("Not all BGP4MPMessageAS bytes available")
	}

	if m.isAS4 {
		m.PeerAS = binary.BigEndian.Uint32(data[:4])
		m.LocalAS = binary.BigEndian.Uint32(data[4:8])
		data = data[8:]
	} else {
		m.PeerAS = uint32(binary.BigEndian.Uint16(data[:2]))
		m.LocalAS = uint32(binary.BigEndian.Uint16(data[2:4]))
		data = data[4:]
	}
	m.InterfaceIndex = binary.BigEndian.Uint16(data[:2])
	m.AddressFamily = binary.BigEndian.Uint16(data[2:4])
	switch m.AddressFamily {
	case bgp.AFI_IP:
		m.PeerIpAddress = net.IP(data[4:8]).To4()
		m.LocalIpAddress = net.IP(data[8:12]).To4()
		data = data[12:]
	case bgp.AFI_IP6:
		m.PeerIpAddress = net.IP(data[4:20])
		m.LocalIpAddress = net.IP(data[20:36])
		data = data[36:]
	default:
		return nil, fmt.Errorf("unsupported address family: %d", m.AddressFamily)
	}
	return data, nil
}

func (m *BGP4MPHeader) serialize() ([]byte, error) {
	var values []interface{}
	if m.isAS4 {
		values = []interface{}{m.PeerAS, m.LocalAS, m.InterfaceIndex, m.AddressFamily}
	} else {
		values = []interface{}{uint16(m.PeerAS), uint16(m.LocalAS), m.InterfaceIndex, m.AddressFamily}
	}
	buf, err := packValues(values)
	if err != nil {
		return nil, err
	}
	var bbuf []byte
	switch m.AddressFamily {
	case bgp.AFI_IP:
		bbuf = make([]byte, 8)
		copy(bbuf, m.PeerIpAddress.To4())
		copy(bbuf[4:], m.LocalIpAddress.To4())
	case bgp.AFI_IP6:
		bbuf = make([]byte, 32)
		copy(bbuf, m.PeerIpAddress)
		copy(bbuf[16:], m.LocalIpAddress)
	default:
		return nil, fmt.Errorf("unsupported address family: %d", m.AddressFamily)
	}
	return append(buf, bbuf...), nil
}

func newBGP4MPHeader(peeras, localas uint32, intfindex uint16, peerip, localip string, isAS4 bool) (*BGP4MPHeader, error) {
	var af uint16
	paddr := net.ParseIP(peerip).To4()
	laddr := net.ParseIP(localip).To4()
	if paddr != nil && laddr != nil {
		af = bgp.AFI_IP
	} else {
		paddr = net.ParseIP(peerip).To16()
		laddr = net.ParseIP(localip).To16()
		if paddr != nil && laddr != nil {
			af = bgp.AFI_IP6
		} else {
			return nil, fmt.Errorf("Peer IP Address and Local IP Address must have the same address family")
		}
	}
	return &BGP4MPHeader{
		PeerAS:         peeras,
		LocalAS:        localas,
		InterfaceIndex: intfindex,
		AddressFamily:  af,
		PeerIpAddress:  paddr,
		LocalIpAddress: laddr,
		isAS4:          isAS4,
	}, nil
}

type BGP4MPStateChange struct {
	*BGP4MPHeader
	OldState BGPState
	NewState BGPState
}

func (m *BGP4MPStateChange) DecodeFromBytes(data []byte) error {
	rest, err := m.decodeFromBytes(data)
	if err != nil {
		return err
	}
	if len(rest) < 4 {
		return fmt.Errorf("Not all BGP4MPStateChange bytes available")
	}
	m.OldState = BGPState(binary.BigEndian.Uint16(rest[:2]))
	m.NewState = BGPState(binary.BigEndian.Uint16(rest[2:4]))
	return nil
}

func (m *BGP4MPStateChange) Serialize() ([]byte, error) {
	buf, err := m.serialize()
	if err != nil {
		return nil, err
	}
	bbuf, err := packValues([]interface{}{m.OldState, m.NewState})
	if err != nil {
		return nil, err
	}
	return append(buf, bbuf...), nil
}

func NewBGP4MPStateChange(peeras, localas uint32, intfindex uint16, peerip, localip string, isAS4 bool, oldstate, newstate BGPState) *BGP4MPStateChange {
	header, _ := newBGP4MPHeader(peeras, localas, intfindex, peerip, localip, isAS4)
	return &BGP4MPStateChange{
		BGP4MPHeader: header,
		OldState:     oldstate,
		NewState:     newstate,
	}
}

type BGP4MPMessage struct {
	*BGP4MPHeader
	BGPMessage        *bgp.BGPMessage
	BGPMessagePayload []byte
	isLocal           bool
	isAddPath         bool
}

func (m *BGP4MPMessage) DecodeFromBytes(data []byte) error {
	rest, err := m.decodeFromBytes(data)
	if err != nil {
		return err
	}

	if len(rest) < bgp.BGP_HEADER_LENGTH {
		return fmt.Errorf("Not all BGP4MPMessageAS4 bytes available")
	}

	msg, err := bgp.ParseBGPMessage(rest)
	if err != nil {
		return err
	}
	m.BGPMessage = msg
	return nil
}

func (m *BGP4MPMessage) Serialize() ([]byte, error) {
	buf, err := m.serialize()
	if err != nil {
		return nil, err
	}
	if m.BGPMessagePayload != nil {
		return append(buf, m.BGPMessagePayload...), nil
	}
	bbuf, err := m.BGPMessage.Serialize()
	if err != nil {
		return nil, err
	}
	return append(buf, bbuf...), nil
}

func NewBGP4MPMessage(peeras, localas uint32, intfindex uint16, peerip, localip string, isAS4 bool, msg *bgp.BGPMessage) *BGP4MPMessage {
	header, _ := newBGP4MPHeader(peeras, localas, intfindex, peerip, localip, isAS4)
	return &BGP4MPMessage{
		BGP4MPHeader: header,
		BGPMessage:   msg,
	}
}

func NewBGP4MPMessageLocal(peeras, localas uint32, intfindex uint16, peerip, localip string, isAS4 bool, msg *bgp.BGPMessage) *BGP4MPMessage {
	header, _ := newBGP4MPHeader(peeras, localas, intfindex, peerip, localip, isAS4)
	return &BGP4MPMessage{
		BGP4MPHeader: header,
		BGPMessage:   msg,
		isLocal:      true,
	}
}

func NewBGP4MPMessageAddPath(peeras, localas uint32, intfindex uint16, peerip, localip string, isAS4 bool, msg *bgp.BGPMessage) *BGP4MPMessage {
	header, _ := newBGP4MPHeader(peeras, localas, intfindex, peerip, localip, isAS4)
	return &BGP4MPMessage{
		BGP4MPHeader: header,
		BGPMessage:   msg,
		isAddPath:    true,
	}
}

func NewBGP4MPMessageLocalAddPath(peeras, localas uint32, intfindex uint16, peerip, localip string, isAS4 bool, msg *bgp.BGPMessage) *BGP4MPMessage {
	header, _ := newBGP4MPHeader(peeras, localas, intfindex, peerip, localip, isAS4)
	return &BGP4MPMessage{
		BGP4MPHeader: header,
		BGPMessage:   msg,
		isLocal:      true,
		isAddPath:    true,
	}
}

func (m *BGP4MPMessage) String() string {
	title := "BGP4MP_MSG"
	if m.isAS4 {
		title += "_AS4"
	}
	if m.isLocal {
		title += "_LOCAL"
	}
	if m.isAddPath {
		title += "_ADDPATH"
	}
	return fmt.Sprintf("%s: PeerAS [%d] LocalAS [%d] InterfaceIndex [%d] PeerIP [%s] LocalIP [%s] BGPMessage [%v]", title, m.PeerAS, m.LocalAS, m.InterfaceIndex, m.PeerIpAddress, m.LocalIpAddress, m.BGPMessage)
}

//This function can be passed into a bufio.Scanner.Split() to read buffered mrt msgs
func SplitMrt(data []byte, atEOF bool) (advance int, token []byte, err error) {
	if atEOF && len(data) == 0 {
		return 0, nil, nil
	}
	if cap(data) < MRT_COMMON_HEADER_LEN { // read more
		return 0, nil, nil
	}
	//this reads the data
	hdr := &MRTHeader{}
	errh := hdr.DecodeFromBytes(data[:MRT_COMMON_HEADER_LEN])
	if errh != nil {
		return 0, nil, errh
	}
	totlen := int(hdr.Len + MRT_COMMON_HEADER_LEN)
	if len(data) < totlen { //need to read more
		return 0, nil, nil
	}
	return totlen, data[0:totlen], nil
}

func ParseMRTBody(h *MRTHeader, data []byte) (*MRTMessage, error) {
	if len(data) < int(h.Len) {
		return nil, fmt.Errorf("Not all MRT message bytes available. expected: %d, actual: %d", int(h.Len), len(data))
	}
	msg := &MRTMessage{Header: *h}
	switch h.Type {
	case TABLE_DUMPv2:
		subType := MRTSubTypeTableDumpv2(h.SubType)
		rf := bgp.RouteFamily(0)
		isAddPath := false
		switch subType {
		case PEER_INDEX_TABLE:
			msg.Body = &PeerIndexTable{}
		case RIB_IPV4_UNICAST:
			rf = bgp.RF_IPv4_UC
		case RIB_IPV4_MULTICAST:
			rf = bgp.RF_IPv4_MC
		case RIB_IPV6_UNICAST:
			rf = bgp.RF_IPv6_UC
		case RIB_IPV6_MULTICAST:
			rf = bgp.RF_IPv6_MC
		case RIB_GENERIC:
		case GEO_PEER_TABLE:
			msg.Body = &GeoPeerTable{}
		case RIB_IPV4_UNICAST_ADDPATH:
			rf = bgp.RF_IPv4_UC
			isAddPath = true
		case RIB_IPV4_MULTICAST_ADDPATH:
			rf = bgp.RF_IPv4_MC
			isAddPath = true
		case RIB_IPV6_UNICAST_ADDPATH:
			rf = bgp.RF_IPv6_UC
			isAddPath = true
		case RIB_IPV6_MULTICAST_ADDPATH:
			rf = bgp.RF_IPv6_MC
			isAddPath = true
		case RIB_GENERIC_ADDPATH:
			isAddPath = true
		default:
			return nil, fmt.Errorf("unsupported table dumpv2 subtype: %v\n", subType)
		}

		if msg.Body == nil {
			msg.Body = &Rib{
				RouteFamily: rf,
				isAddPath:   isAddPath,
			}
		}
	case BGP4MP:
		subType := MRTSubTypeBGP4MP(h.SubType)
		isAS4 := true
		switch subType {
		case STATE_CHANGE:
			isAS4 = false
			fallthrough
		case STATE_CHANGE_AS4:
			msg.Body = &BGP4MPStateChange{
				BGP4MPHeader: &BGP4MPHeader{isAS4: isAS4},
			}
		case MESSAGE:
			isAS4 = false
			fallthrough
		case MESSAGE_AS4:
			msg.Body = &BGP4MPMessage{
				BGP4MPHeader: &BGP4MPHeader{isAS4: isAS4},
			}
		case MESSAGE_LOCAL:
			isAS4 = false
			fallthrough
		case MESSAGE_AS4_LOCAL:
			msg.Body = &BGP4MPMessage{
				BGP4MPHeader: &BGP4MPHeader{isAS4: isAS4},
				isLocal:      true,
			}
		case MESSAGE_ADDPATH:
			isAS4 = false
			fallthrough
		case MESSAGE_AS4_ADDPATH:
			msg.Body = &BGP4MPMessage{
				BGP4MPHeader: &BGP4MPHeader{isAS4: isAS4},
				isAddPath:    true,
			}
		case MESSAGE_LOCAL_ADDPATH:
			isAS4 = false
			fallthrough
		case MESSAGE_AS4_LOCAL_ADDPATH:
			msg.Body = &BGP4MPMessage{
				BGP4MPHeader: &BGP4MPHeader{isAS4: isAS4},
				isLocal:      true,
				isAddPath:    true,
			}
		default:
			return nil, fmt.Errorf("unsupported bgp4mp subtype: %v\n", subType)
		}
	default:
		return nil, fmt.Errorf("unsupported type: %v\n", h.Type)
	}
	err := msg.Body.DecodeFromBytes(data)
	if err != nil {
		return nil, err
	}
	return msg, nil
}