summaryrefslogtreecommitdiffhomepage
path: root/pkg/packet/bgp/sr_policy.go
blob: e7baa069c41efa139a15bbdd797e5d0dc27726ba (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
package bgp

import (
	"encoding/binary"
	"encoding/json"
	"fmt"
	"net"
	"strconv"

	api "github.com/osrg/gobgp/api"
)

type SRPolicyNLRI struct {
	PrefixDefault
	rf            RouteFamily
	Length        uint8
	Distinguisher uint32
	Color         uint32
	Endpoint      []byte
}

const (
	// SRPolicyIPv4NLRILen defines IPv4 SR Policy NLRI portion length in bits
	SRPolicyIPv4NLRILen = 96
	// SRPolicyIPv6NLRILen defines IPv6 SR Policy NLRI portion length in bits
	SRPolicyIPv6NLRILen = 192
)

func (s *SRPolicyNLRI) Flat() map[string]string {
	return map[string]string{}
}

func (s *SRPolicyNLRI) decodeFromBytes(rf RouteFamily, data []byte, options ...*MarshallingOption) error {
	if IsAddPathEnabled(true, rf, options) {
		var err error
		data, err = s.decodePathIdentifier(data)
		if err != nil {
			return err
		}
	}
	switch data[0] {
	case SRPolicyIPv4NLRILen:
		s.rf = RF_SR_POLICY_IPv4
	case SRPolicyIPv6NLRILen:
		s.rf = RF_SR_POLICY_IPv6
	default:
		msg := fmt.Sprintf("Invalid length %d for SR Policy NLRI", len(data))
		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, msg)
	}
	p := 0
	s.Length = data[p] / 8
	p++
	s.Distinguisher = binary.BigEndian.Uint32(data[p : p+4])
	p += 4
	s.Color = binary.BigEndian.Uint32(data[p : p+4])
	p += 4
	s.Endpoint = data[p:]

	return nil
}

func (s *SRPolicyNLRI) Serialize(options ...*MarshallingOption) ([]byte, error) {
	buf := make([]byte, 1+s.Length)
	p := 0
	buf[0] = s.Length * 8
	p++
	binary.BigEndian.PutUint32(buf[p:p+4], s.Distinguisher)
	p += 4
	binary.BigEndian.PutUint32(buf[p:p+4], s.Color)
	p += 4
	copy(buf[p:], s.Endpoint)
	if IsAddPathEnabled(false, s.rf, options) {
		id, err := s.serializeIdentifier()
		if err != nil {
			return nil, err
		}
		return append(id, buf...), nil
	}
	return buf, nil
}

func (s *SRPolicyNLRI) AFI() uint16 {
	afi, _ := RouteFamilyToAfiSafi(s.rf)
	return afi
}

func (s *SRPolicyNLRI) SAFI() uint8 {
	_, safi := RouteFamilyToAfiSafi(s.rf)
	return safi
}

func (s *SRPolicyNLRI) Len(options ...*MarshallingOption) int {
	buf, _ := s.Serialize(options...)
	return len(buf)
}

func (s *SRPolicyNLRI) String() string {
	afi, _ := RouteFamilyToAfiSafi(s.rf)
	var endp string
	switch afi {
	case AFI_IP:
		endp = net.IP(s.Endpoint).To4().String()
	case AFI_IP6:
		endp = net.IP(s.Endpoint).To16().String()
	default:
		endp = "[" + string(s.Endpoint) + "]"
	}
	return fmt.Sprintf("{ Length: %d (bytes), Distinguisher: %d, Color %d, Endpoint: %s }", s.Length, s.Distinguisher, s.Color, endp)
}

func (s *SRPolicyNLRI) MarshalJSON() ([]byte, error) {
	return json.Marshal(struct {
		Length        uint8  `json:"length"`
		Distinguisher uint32 `json:"distinguisher"`
		Color         uint32 `json:"color"`
		Endpoint      string `json:"endpoint"`
	}{
		Length:        s.Length,
		Distinguisher: s.Distinguisher,
		Color:         s.Color,
		Endpoint:      string(s.Endpoint),
	})
}

type SRPolicyIPv4 struct {
	SRPolicyNLRI
}

func (s *SRPolicyIPv4) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
	return s.decodeFromBytes(s.rf, data)
}

func NewSRPolicyIPv4(l uint32, d uint32, c uint32, ep []byte) *SRPolicyIPv4 {
	return &SRPolicyIPv4{
		SRPolicyNLRI: SRPolicyNLRI{
			rf:            RF_SR_POLICY_IPv4,
			Length:        uint8(l / 8),
			Distinguisher: d,
			Color:         c,
			Endpoint:      ep,
		},
	}
}

type SRPolicyIPv6 struct {
	SRPolicyNLRI
}

func (s *SRPolicyIPv6) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
	return s.decodeFromBytes(s.rf, data)
}

func NewSRPolicyIPv6(l uint32, d uint32, c uint32, ep []byte) *SRPolicyIPv6 {
	return &SRPolicyIPv6{
		SRPolicyNLRI: SRPolicyNLRI{
			rf:            RF_SR_POLICY_IPv6,
			Length:        uint8(l / 8),
			Distinguisher: d,
			Color:         c,
			Endpoint:      ep,
		},
	}
}

type TunnelEncapSubTLVSRPreference struct {
	TunnelEncapSubTLV
	Flags      uint8
	Preference uint32
}

func (t *TunnelEncapSubTLVSRPreference) DecodeFromBytes(data []byte) error {
	value, err := t.TunnelEncapSubTLV.DecodeFromBytes(data)
	if err != nil {
		return err
	}
	// Second byte carries the length of SR Preference SubTLV
	if t.Length != 6 {
		msg := fmt.Sprintf("Invalid TunnelEncapSubTLVSRPreference length: %d", t.Length)
		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, msg)
	}
	t.Flags = value[0]
	t.Preference = binary.BigEndian.Uint32(value[2:6])
	return nil
}

func (t *TunnelEncapSubTLVSRPreference) Serialize() ([]byte, error) {
	buf := make([]byte, 6)
	buf[0] = t.Flags
	binary.BigEndian.PutUint32(buf[2:6], t.Preference)
	return t.TunnelEncapSubTLV.Serialize(buf[:])
}

func (t *TunnelEncapSubTLVSRPreference) String() string {
	return fmt.Sprintf("{Flags: 0x%02x, Preference: %d}", t.Flags, t.Preference)
}

func (t *TunnelEncapSubTLVSRPreference) MarshalJSON() ([]byte, error) {
	return json.Marshal(struct {
		Type       EncapSubTLVType `json:"type"`
		Flags      uint8           `json:"flags"`
		Preference uint32          `json:"preference"`
	}{
		Type:       t.Type,
		Flags:      t.Flags,
		Preference: t.Preference,
	})
}

func NewTunnelEncapSubTLVSRPreference(flags uint32, preference uint32) *TunnelEncapSubTLVSRPreference {
	return &TunnelEncapSubTLVSRPreference{
		TunnelEncapSubTLV: TunnelEncapSubTLV{
			Type:   ENCAP_SUBTLV_TYPE_SRPREFERENCE,
			Length: 6,
		},
		Flags:      uint8(flags),
		Preference: preference,
	}
}

type TunnelEncapSubTLVSRPriority struct {
	TunnelEncapSubTLV
	Priority uint8
}

func (t *TunnelEncapSubTLVSRPriority) DecodeFromBytes(data []byte) error {
	value, err := t.TunnelEncapSubTLV.DecodeFromBytes(data)
	if err != nil {
		return err
	}
	// Second byte carries the length of SR Preference SubTLV
	if t.Length != 2 {
		msg := fmt.Sprintf("Invalid TunnelEncapSubTLVSRPriority length: %d", t.Length)
		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, msg)
	}
	t.Priority = value[0]
	return nil
}

func (t *TunnelEncapSubTLVSRPriority) Serialize() ([]byte, error) {
	buf := make([]byte, 1+1)
	buf[0] = t.Priority
	return t.TunnelEncapSubTLV.Serialize(buf[:])
}

func (t *TunnelEncapSubTLVSRPriority) String() string {
	return fmt.Sprintf("{Priority: %d}", t.Priority)
}

func (t *TunnelEncapSubTLVSRPriority) MarshalJSON() ([]byte, error) {
	return json.Marshal(struct {
		Type     EncapSubTLVType `json:"type"`
		Priority uint8           `json:"priority"`
	}{
		Type:     t.Type,
		Priority: t.Priority,
	})
}

func NewTunnelEncapSubTLVSRPriority(priority uint8) *TunnelEncapSubTLVSRPriority {
	return &TunnelEncapSubTLVSRPriority{
		TunnelEncapSubTLV: TunnelEncapSubTLV{
			Type:   ENCAP_SUBTLV_TYPE_SRPRIORITY,
			Length: 2,
		},
		Priority: priority,
	}
}

type TunnelEncapSubTLVSRCandidatePathName struct {
	TunnelEncapSubTLV
	CandidatePathName string
}

func (t *TunnelEncapSubTLVSRCandidatePathName) DecodeFromBytes(data []byte) error {
	value, err := t.TunnelEncapSubTLV.DecodeFromBytes(data)
	if err != nil {
		return err
	}
	// Skip Reserved byte
	t.CandidatePathName = string(value[1:t.TunnelEncapSubTLV.Len()])
	return nil
}

func (t *TunnelEncapSubTLVSRCandidatePathName) Serialize() ([]byte, error) {
	buf := make([]byte, 1+len(t.CandidatePathName))
	copy(buf[1:], t.CandidatePathName)
	return t.TunnelEncapSubTLV.Serialize(buf[:])
}

func (t *TunnelEncapSubTLVSRCandidatePathName) String() string {
	return fmt.Sprintf("{Candidate Path Name: %s}", t.CandidatePathName)
}

func (t *TunnelEncapSubTLVSRCandidatePathName) MarshalJSON() ([]byte, error) {
	return json.Marshal(struct {
		Type              EncapSubTLVType `json:"type"`
		CandidatePathName string          `json:"candidate_path_name"`
	}{
		Type:              t.Type,
		CandidatePathName: t.CandidatePathName,
	})
}

func NewTunnelEncapSubTLVSRCandidatePathName(cpn string) *TunnelEncapSubTLVSRCandidatePathName {
	return &TunnelEncapSubTLVSRCandidatePathName{
		TunnelEncapSubTLV: TunnelEncapSubTLV{
			Type:   ENCAP_SUBTLV_TYPE_SRCANDIDATE_PATH_NAME,
			Length: uint16(len(cpn) + 1), // length of Candidate Path name string + 1 Reserved byte
		},
		CandidatePathName: cpn,
	}
}

type SRENLPValue uint8

const (
	// ENLPType1 Indicates to push an IPv4 Explicit NULL label on an unlabeled IPv4
	// packet, but do not push an IPv6 Explicit NULL label on an
	// unlabeled IPv6 packet.
	ENLPType1 SRENLPValue = 1
	// ENLPType2 Indicates to push an IPv6 Explicit NULL label on an unlabeled IPv6
	// packet, but do not push an IPv4 Explicit NULL label on an
	// unlabeled IPv4 packet.
	ENLPType2 SRENLPValue = 2
	// ENLPType3 Indicates to push an IPv4 Explicit NULL label on an unlabeled IPv4
	// packet, and push an IPv6 Explicit NULL label on an unlabeled
	// IPv6 packet.
	ENLPType3 SRENLPValue = 3
	// ENLPType4 Indicates to not push an Explicit NULL label.
	ENLPType4 SRENLPValue = 4
)

type TunnelEncapSubTLVSRENLP struct {
	TunnelEncapSubTLV
	Flags uint8
	ENLP  SRENLPValue
}

func (t *TunnelEncapSubTLVSRENLP) DecodeFromBytes(data []byte) error {
	value, err := t.TunnelEncapSubTLV.DecodeFromBytes(data)
	if err != nil {
		return err
	}
	// Second byte carries the length of SR Preference SubTLV
	if t.Length != 3 {
		msg := fmt.Sprintf("Invalid TunnelEncapSubTLVSRENLP length: %d", t.Length)
		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, msg)
	}
	t.Flags = value[0]
	switch SRENLPValue(value[2]) {
	case ENLPType1:
	case ENLPType2:
	case ENLPType3:
	case ENLPType4:
	default:
		msg := fmt.Sprintf("Invalid ENLP Type: %d", value[2])
		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, msg)
	}
	t.ENLP = SRENLPValue(value[2])
	return nil
}

func (t *TunnelEncapSubTLVSRENLP) Serialize() ([]byte, error) {
	buf := make([]byte, t.Length)
	buf[0] = t.Flags
	buf[2] = byte(t.ENLP)
	return t.TunnelEncapSubTLV.Serialize(buf[:])
}

func (t *TunnelEncapSubTLVSRENLP) String() string {
	return fmt.Sprintf("{Flags: 0x%02x, ENLP Type: %d}", t.Flags, t.ENLP)
}

func (t *TunnelEncapSubTLVSRENLP) MarshalJSON() ([]byte, error) {
	return json.Marshal(struct {
		Type  EncapSubTLVType `json:"type"`
		Flags uint8           `json:"flags"`
		ENLP  uint8           `json:"enlp"`
	}{
		Type:  t.Type,
		Flags: t.Flags,
		ENLP:  uint8(t.ENLP),
	})
}

func NewTunnelEncapSubTLVSRENLP(flags uint32, enlp SRENLPValue) *TunnelEncapSubTLVSRENLP {
	return &TunnelEncapSubTLVSRENLP{
		TunnelEncapSubTLV: TunnelEncapSubTLV{
			Type:   ENCAP_SUBTLV_TYPE_SRENLP,
			Length: 3,
		},
		Flags: uint8(flags),
		ENLP:  enlp,
	}
}

type BSID struct {
	Value []byte
}

func (b *BSID) String() string {
	switch len(b.Value) {
	case 0:
		return "n/a"
	case 4:
		bsid := binary.BigEndian.Uint32(b.Value)
		bsid >>= 12
		return strconv.Itoa(int(bsid))
	case 16:
		return net.IP(b.Value).To16().String()
	default:
		return "invalid"
	}
}

func (b *BSID) Serialize() []byte {
	return b.Value
}
func (b *BSID) Len() int {
	return len(b.Value)
}

func NewBSID(v []byte) (*BSID, error) {
	var bsid *BSID
	switch len(v) {
	case 0:
	case 4:
		t := binary.BigEndian.Uint32(v)
		t <<= 12
		bsid = &BSID{
			Value: make([]byte, len(v)),
		}
		binary.BigEndian.PutUint32(bsid.Value, t)
	case 16:
		bsid = &BSID{
			Value: make([]byte, len(v)),
		}
		copy(bsid.Value, v)
	default:
		return nil, fmt.Errorf("invalid length %d", len(v))
	}

	return bsid, nil
}

type TunnelEncapSubTLVSRBSID struct {
	TunnelEncapSubTLV
	Flags uint8
	BSID  *BSID
}

func (t *TunnelEncapSubTLVSRBSID) DecodeFromBytes(data []byte) error {
	value, err := t.TunnelEncapSubTLV.DecodeFromBytes(data)
	if err != nil {
		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, err.Error())
	}
	// Check Sub TLV length, only 3 possible length are allowed
	switch t.Length {
	case 2: // No BSID, do not initializing BSID struct
	case 6:
		fallthrough
	case 18:
		t.BSID = &BSID{
			Value: make([]byte, t.Length-2),
		}
		copy(t.BSID.Value, value[2:t.Length])
	default:
		msg := fmt.Sprintf("Invalid TunnelEncapSubTLVSRBSID length: %d", t.Length)
		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, msg)
	}
	t.Flags = value[0]
	return nil
}

func (t *TunnelEncapSubTLVSRBSID) Serialize() ([]byte, error) {
	l := 2
	if t.BSID != nil {
		l += t.BSID.Len()
	}
	buf := make([]byte, l) // 1st byte Flags, 2nd byte Reserved, 3rd+ BSID
	buf[0] = t.Flags
	if t.BSID != nil {
		bsid := t.BSID.Serialize()
		copy(buf[2:], bsid)
	}
	return t.TunnelEncapSubTLV.Serialize(buf[:])
}

func (t *TunnelEncapSubTLVSRBSID) String() string {
	return fmt.Sprintf("{S-Flag: %t, I-Flag: %t, BSID: %s}", t.Flags&0x80 == 0x80, t.Flags&0x40 == 0x40, t.BSID.String())
}

func (t *TunnelEncapSubTLVSRBSID) MarshalJSON() ([]byte, error) {
	return json.Marshal(struct {
		Type  EncapSubTLVType `json:"type"`
		Flags uint8           `json:"flags"`
		BSID  string          `json:"binding_sid,omitempty"`
	}{
		Type:  t.Type,
		Flags: t.Flags,
		BSID:  t.BSID.String(),
	})
}

type TunnelEncapSubTLVSRv6BSID struct {
	TunnelEncapSubTLV
	Flags uint8
	BSID  *BSID
	EPBAS *SRv6EndpointBehaviorStructure
}

func (t *TunnelEncapSubTLVSRv6BSID) DecodeFromBytes(data []byte) error {
	value, err := t.TunnelEncapSubTLV.DecodeFromBytes(data)
	if err != nil {
		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, err.Error())
	}
	t.Flags = value[0]
	t.BSID, err = NewBSID(value[2:t.Length])
	if err != nil {
		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, err.Error())
	}
	return nil
}

func (t *TunnelEncapSubTLVSRv6BSID) Serialize() ([]byte, error) {
	buf := make([]byte, t.Length)
	buf[0] = t.Flags
	copy(buf[2:t.BSID.Len()], t.BSID.Serialize())
	return t.TunnelEncapSubTLV.Serialize(buf[:])
}

func (t *TunnelEncapSubTLVSRv6BSID) String() string {
	return fmt.Sprintf("{S-Flag: %t, I-Flag: %t, B-Flag: %t, BSID: %s}", t.Flags&0x80 == 0x80, t.Flags&0x40 == 0x40, t.Flags&0x20 == 0x20, t.BSID.String())
}

func (t *TunnelEncapSubTLVSRv6BSID) MarshalJSON() ([]byte, error) {
	return json.Marshal(struct {
		Type  EncapSubTLVType `json:"type"`
		Flags uint8           `json:"flags"`
		BSID  string          `json:"binding_sid,omitempty"`
	}{
		Type:  t.Type,
		Flags: t.Flags,
		BSID:  t.BSID.String(),
	})
}

// SegmentType defines a type of Segment in Segment List
type SegmentType int

const (
	// TypeA Segment Sub-TLV encodes a single SR-MPLS SID
	TypeA SegmentType = 1
	// TypeB Segment Sub-TLV encodes a single SRv6 SID.
	TypeB SegmentType = 13
	// TypeC Segment Sub-TLV encodes an IPv4 node address, SR Algorithm
	// and an optional SR-MPLS SID
	TypeC SegmentType = 3
	// TypeD Segment Sub-TLV encodes an IPv6 node address, SR Algorithm
	// and an optional SR-MPLS SID.
	TypeD SegmentType = 4
	// TypeE Segment Sub-TLV encodes an IPv4 node address, a local
	// interface Identifier (Local Interface ID) and an optional SR-MPLS
	// SID.
	TypeE SegmentType = 5
	// TypeF Segment Sub-TLV encodes an adjacency local address, an
	// adjacency remote address and an optional SR-MPLS SID.
	TypeF SegmentType = 6
	// TypeG Segment Sub-TLV encodes an IPv6 Link Local adjacency with
	// IPv6 local node address, a local interface identifier (Local
	// Interface ID), IPv6 remote node address , a remote interface
	// identifier (Remote Interface ID) and an optional SR-MPLS SID.
	TypeG SegmentType = 7
	// TypeH Segment Sub-TLV encodes an adjacency local address, an
	// adjacency remote address and an optional SR-MPLS SID.
	TypeH SegmentType = 8
	// TypeI Segment Sub-TLV encodes an IPv6 node address, SR Algorithm
	// and an optional SRv6 SID.
	TypeI SegmentType = 14
	// TypeJ Segment Sub-TLV encodes an IPv6 Link Local adjacency with
	// local node address, a local interface identifier (Local Interface
	// ID), remote IPv6 node address, a remote interface identifier (Remote
	// Interface ID) and an optional SRv6 SID.
	TypeJ SegmentType = 15
	// TypeK Segment Sub-TLV encodes an adjacency local address, an
	// adjacency remote address and an optional SRv6 SID.
	TypeK SegmentType = 16
)

// Weight sub-TLV specifies the weight associated to a given segment list.
type SegmentListWeight struct {
	TunnelEncapSubTLV
	Flags  uint8
	Weight uint32
}

func (s *SegmentListWeight) DecodeFromBytes(data []byte) error {
	value, err := s.TunnelEncapSubTLV.DecodeFromBytes(data)
	if err != nil {
		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, err.Error())
	}
	s.Flags = value[0]
	s.Weight = binary.BigEndian.Uint32(value[2:6])
	return nil
}
func (s *SegmentListWeight) Serialize() ([]byte, error) {
	buf := make([]byte, 6)
	buf[0] = s.Flags
	binary.BigEndian.PutUint32(buf[2:6], s.Weight)
	return s.TunnelEncapSubTLV.Serialize(buf)
}
func (s *SegmentListWeight) String() string {
	return fmt.Sprintf("{Flags: 0x%02x, Weight: %d}", s.Flags, s.Weight)
}

func (s *SegmentListWeight) MarshalJSON() ([]byte, error) {
	return json.Marshal(struct {
		Type   EncapSubTLVType `json:"type"`
		Flags  uint8           `json:"flags"`
		Weight uint32          `json:"weight,omitempty"`
	}{
		Type:   s.Type,
		Flags:  s.Flags,
		Weight: s.Weight,
	})
}

type SegmentTypeA struct {
	TunnelEncapSubTLV
	Flags uint8
	Label uint32
}

func (s *SegmentTypeA) DecodeFromBytes(data []byte) error {
	value, err := s.TunnelEncapSubTLV.DecodeFromBytes(data)
	if err != nil {
		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, err.Error())
	}
	s.Flags = value[0]
	s.Label = binary.BigEndian.Uint32(value[2:6])
	return nil
}
func (s *SegmentTypeA) Serialize() ([]byte, error) {
	buf := make([]byte, 6)
	buf[0] = s.Flags
	binary.BigEndian.PutUint32(buf[2:6], s.Label)
	return s.TunnelEncapSubTLV.Serialize(buf)
}
func (s *SegmentTypeA) String() string {
	return fmt.Sprintf("{V-flag: %t, A-flag:, %t S-flag: %t, B-flag: %t, Label: %d TC: %d S: %t TTL: %d}",
		s.Flags&0x80 == 0x80, s.Flags&0x40 == 0x40, s.Flags&0x20 == 0x20, s.Flags&0x10 == 0x10,
		s.Label>>12, s.Label&0x00000e00>>9, s.Label&0x00000100 == 0x00000100, s.Label&0x000000ff)
}

func (s *SegmentTypeA) MarshalJSON() ([]byte, error) {
	return json.Marshal(struct {
		Type  EncapSubTLVType `json:"type"`
		VFlag bool            `json:"v_flag"`
		AFlag bool            `json:"a_flag"`
		SFlag bool            `json:"s_flag"`
		BFlag bool            `json:"b_flag"`
		Label uint32          `json:"label"`
		TC    uint8           `json:"tc"`
		S     bool            `json:"s"`
		TTL   uint8           `json:"ttl"`
	}{
		Type:  s.Type,
		VFlag: s.Flags&0x80 == 0x80,
		AFlag: s.Flags&0x40 == 0x40,
		SFlag: s.Flags&0x20 == 0x20,
		BFlag: s.Flags&0x10 == 0x10,
		Label: s.Label >> 12,
		TC:    uint8(s.Label & 0x00000e00 >> 9),
		S:     s.Label&0x00000100 == 0x00000100,
		TTL:   uint8(s.Label & 0x000000ff),
	})
}

type SRv6EndpointBehaviorStructure struct {
	Behavior api.SRv6Behavior
	BlockLen uint8
	NodeLen  uint8
	FuncLen  uint8
	ArgLen   uint8
}

type SegmentTypeB struct {
	TunnelEncapSubTLV
	Flags uint8
	SID   []byte
	EP    *SRv6EndpointBehaviorStructure
}

func (s *SegmentTypeB) DecodeFromBytes(data []byte) error {
	value, err := s.TunnelEncapSubTLV.DecodeFromBytes(data)
	if err != nil {
		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, err.Error())
	}
	s.Flags = value[0]
	return nil
}
func (s *SegmentTypeB) Serialize() ([]byte, error) {
	buf := make([]byte, 6)
	buf[0] = s.Flags
	return s.TunnelEncapSubTLV.Serialize(buf)
}
func (s *SegmentTypeB) String() string {

	return fmt.Sprintf("{V-flag: %t, A-flag:, %t S-flag: %t, B-flag: %t}",
		s.Flags&0x80 == 0x80, s.Flags&0x40 == 0x40, s.Flags&0x20 == 0x20, s.Flags&0x10 == 0x10)
}

func (s *SegmentTypeB) MarshalJSON() ([]byte, error) {
	return json.Marshal(struct {
		Type  EncapSubTLVType `json:"type"`
		VFlag bool            `json:"v_flag"`
		AFlag bool            `json:"a_flag"`
		SFlag bool            `json:"s_flag"`
		BFlag bool            `json:"b_flag"`
	}{
		Type:  s.Type,
		VFlag: s.Flags&0x80 == 0x80,
		AFlag: s.Flags&0x40 == 0x40,
		SFlag: s.Flags&0x20 == 0x20,
		BFlag: s.Flags&0x10 == 0x10,
	})
}

const (
	// SegmentListSubTLVWeight defines code for Segment List's Weight sub-TLV
	SegmentListSubTLVWeight = 9
)

type TunnelEncapSubTLVSRSegmentList struct {
	TunnelEncapSubTLV
	Weight   *SegmentListWeight
	Segments []TunnelEncapSubTLVInterface
}

func (t *TunnelEncapSubTLVSRSegmentList) DecodeFromBytes(data []byte) error {
	value, err := t.TunnelEncapSubTLV.DecodeFromBytes(data)
	if err != nil {
		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, err.Error())
	}
	// Skip reserved byte to access inner SubTLV type
	value = value[1:]
	segments := make([]TunnelEncapSubTLVInterface, 0)
	p := 0
	for p < t.TunnelEncapSubTLV.Len()-4 {
		var segment TunnelEncapSubTLVInterface
		switch SegmentType(value[0]) {
		case SegmentListSubTLVWeight:
			t.Weight = &SegmentListWeight{}
			if err := t.Weight.DecodeFromBytes(value); err != nil {
				return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, err.Error())
			}
			p += t.Weight.TunnelEncapSubTLV.Len()
			value = value[t.Weight.TunnelEncapSubTLV.Len():]
			continue
		case TypeA:
			segment = &SegmentTypeA{}
			if err := segment.DecodeFromBytes(value); err != nil {
				return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, err.Error())
			}
		case TypeB:
			fallthrough
		case TypeC:
			fallthrough
		case TypeD:
			fallthrough
		case TypeE:
			fallthrough
		case TypeF:
			fallthrough
		case TypeG:
			fallthrough
		case TypeH:
			fallthrough
		case TypeI:
			fallthrough
		case TypeJ:
			fallthrough
		case TypeK:
			msg := fmt.Sprintf("Invalid SR Policy Segment SubTLV %d is not yet supported", value[0])
			return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, msg)
		default:
			msg := fmt.Sprintf("Invalid SR Policy Segment List SubTLV %d", value[0])
			return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, msg)
		}
		segments = append(segments, segment)
		p += segment.Len()
		value = value[segment.Len():]
	}
	if len(segments) == 0 {
		t.Segments = nil
	} else {
		t.Segments = segments
	}
	return nil
}

func (t *TunnelEncapSubTLVSRSegmentList) Serialize() ([]byte, error) {
	buf := make([]byte, 0)
	// Add reserved byte
	buf = append(buf, 0x0)
	if t.Weight != nil {
		wbuf, err := t.Weight.Serialize()
		if err != nil {
			return nil, err
		}
		buf = append(buf, wbuf...)
	}
	for _, s := range t.Segments {
		sbuf, err := s.Serialize()
		if err != nil {
			return nil, err
		}
		buf = append(buf, sbuf...)
	}
	return t.TunnelEncapSubTLV.Serialize(buf[:])
}

func (t *TunnelEncapSubTLVSRSegmentList) String() string {
	msg := "{"
	if t.Weight != nil {
		msg += "Weight: " + t.Weight.String() + ","
	}
	msg += "Segment List: [ "
	for _, s := range t.Segments {
		msg += s.String() + ","
	}
	msg += " ] }"
	return msg
}

func (t *TunnelEncapSubTLVSRSegmentList) MarshalJSON() ([]byte, error) {
	return json.Marshal(struct {
		Type     EncapSubTLVType `json:"type"`
		Weight   *SegmentListWeight
		Segments []TunnelEncapSubTLVInterface
	}{
		Type:     t.Type,
		Weight:   t.Weight,
		Segments: t.Segments,
	})
}