github.com/osrg/gobgp/v3@v3.30.0/pkg/packet/bgp/bgp.go (about)

     1  // Copyright (C) 2014 Nippon Telegraph and Telephone Corporation.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //    http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
    12  // implied.
    13  // See the License for the specific language governing permissions and
    14  // limitations under the License.
    15  
    16  package bgp
    17  
    18  import (
    19  	"bytes"
    20  	"encoding/binary"
    21  	"encoding/json"
    22  	"errors"
    23  	"fmt"
    24  	"math"
    25  	"net"
    26  	"reflect"
    27  	"regexp"
    28  	"sort"
    29  	"strconv"
    30  	"strings"
    31  	"sync"
    32  )
    33  
    34  type MarshallingOption struct {
    35  	AddPath        map[RouteFamily]BGPAddPathMode
    36  	Attributes     map[BGPAttrType]bool
    37  	ImplicitPrefix AddrPrefixInterface
    38  }
    39  
    40  // GetImplicitPrefix gets the implicit prefix associated with decoding/serialisation. This is used for
    41  // the MRT representation of MP_REACH_NLRI (see RFC 6396 4.3.4).
    42  func GetImplicitPrefix(options []*MarshallingOption) AddrPrefixInterface {
    43  	for _, opt := range options {
    44  		if opt != nil && opt.ImplicitPrefix != nil {
    45  			return opt.ImplicitPrefix
    46  		}
    47  	}
    48  
    49  	return nil
    50  }
    51  
    52  func IsAddPathEnabled(decode bool, f RouteFamily, options []*MarshallingOption) bool {
    53  	for _, opt := range options {
    54  		if opt == nil {
    55  			continue
    56  		}
    57  		if o := opt.AddPath; o != nil {
    58  			if decode && o[f]&BGP_ADD_PATH_RECEIVE > 0 {
    59  				return true
    60  			} else if !decode && o[f]&BGP_ADD_PATH_SEND > 0 {
    61  				return true
    62  			}
    63  		}
    64  	}
    65  	return false
    66  }
    67  func IsAttributePresent(attr BGPAttrType, options []*MarshallingOption) bool {
    68  	for _, opt := range options {
    69  		if opt == nil {
    70  			continue
    71  		}
    72  		if o := opt.Attributes; o != nil {
    73  			_, ok := o[attr]
    74  			return ok
    75  		}
    76  	}
    77  	return false
    78  }
    79  
    80  const (
    81  	AFI_IP     = 1
    82  	AFI_IP6    = 2
    83  	AFI_L2VPN  = 25
    84  	AFI_LS     = 16388
    85  	AFI_OPAQUE = 16397
    86  )
    87  
    88  const (
    89  	SAFI_UNICAST                  = 1
    90  	SAFI_MULTICAST                = 2
    91  	SAFI_MPLS_LABEL               = 4
    92  	SAFI_ENCAPSULATION            = 7
    93  	SAFI_VPLS                     = 65
    94  	SAFI_EVPN                     = 70
    95  	SAFI_LS                       = 71
    96  	SAFI_SRPOLICY                 = 73
    97  	SAFI_MUP                      = 85
    98  	SAFI_MPLS_VPN                 = 128
    99  	SAFI_MPLS_VPN_MULTICAST       = 129
   100  	SAFI_ROUTE_TARGET_CONSTRAINTS = 132
   101  	SAFI_FLOW_SPEC_UNICAST        = 133
   102  	SAFI_FLOW_SPEC_VPN            = 134
   103  	SAFI_KEY_VALUE                = 241
   104  )
   105  
   106  const (
   107  	BGP_ORIGIN_ATTR_TYPE_IGP        uint8 = 0
   108  	BGP_ORIGIN_ATTR_TYPE_EGP        uint8 = 1
   109  	BGP_ORIGIN_ATTR_TYPE_INCOMPLETE uint8 = 2
   110  )
   111  
   112  const (
   113  	BGP_ASPATH_ATTR_TYPE_SET        = 1
   114  	BGP_ASPATH_ATTR_TYPE_SEQ        = 2
   115  	BGP_ASPATH_ATTR_TYPE_CONFED_SEQ = 3
   116  	BGP_ASPATH_ATTR_TYPE_CONFED_SET = 4
   117  )
   118  
   119  const (
   120  	BGP_ATTR_NHLEN_IPV6_GLOBAL        = 16
   121  	BGP_ATTR_NHLEN_IPV6_GLOBAL_AND_LL = 32
   122  )
   123  
   124  // RFC7153 5.1. Registries for the "Type" Field
   125  // RANGE	REGISTRATION PROCEDURES
   126  // 0x00-0x3F	Transitive First Come First Served
   127  // 0x40-0x7F	Non-Transitive First Come First Served
   128  // 0x80-0x8F	Transitive Experimental Use
   129  // 0x90-0xBF	Transitive Standards Action
   130  // 0xC0-0xCF	Non-Transitive Experimental Use
   131  // 0xD0-0xFF	Non-Transitive Standards Action
   132  type ExtendedCommunityAttrType uint8
   133  
   134  const (
   135  	EC_TYPE_TRANSITIVE_TWO_OCTET_AS_SPECIFIC      ExtendedCommunityAttrType = 0x00
   136  	EC_TYPE_TRANSITIVE_IP6_SPECIFIC               ExtendedCommunityAttrType = 0x00 // RFC5701
   137  	EC_TYPE_TRANSITIVE_IP4_SPECIFIC               ExtendedCommunityAttrType = 0x01
   138  	EC_TYPE_TRANSITIVE_FOUR_OCTET_AS_SPECIFIC     ExtendedCommunityAttrType = 0x02
   139  	EC_TYPE_TRANSITIVE_OPAQUE                     ExtendedCommunityAttrType = 0x03
   140  	EC_TYPE_TRANSITIVE_QOS_MARKING                ExtendedCommunityAttrType = 0x04
   141  	EC_TYPE_COS_CAPABILITY                        ExtendedCommunityAttrType = 0x05
   142  	EC_TYPE_EVPN                                  ExtendedCommunityAttrType = 0x06
   143  	EC_TYPE_FLOWSPEC_REDIRECT_MIRROR              ExtendedCommunityAttrType = 0x08
   144  	EC_TYPE_MUP                                   ExtendedCommunityAttrType = 0x0c
   145  	EC_TYPE_NON_TRANSITIVE_TWO_OCTET_AS_SPECIFIC  ExtendedCommunityAttrType = 0x40
   146  	EC_TYPE_NON_TRANSITIVE_LINK_BANDWIDTH         ExtendedCommunityAttrType = 0x40
   147  	EC_TYPE_NON_TRANSITIVE_IP6_SPECIFIC           ExtendedCommunityAttrType = 0x40 // RFC5701
   148  	EC_TYPE_NON_TRANSITIVE_IP4_SPECIFIC           ExtendedCommunityAttrType = 0x41
   149  	EC_TYPE_NON_TRANSITIVE_FOUR_OCTET_AS_SPECIFIC ExtendedCommunityAttrType = 0x42
   150  	EC_TYPE_NON_TRANSITIVE_OPAQUE                 ExtendedCommunityAttrType = 0x43
   151  	EC_TYPE_NON_TRANSITIVE_QOS_MARKING            ExtendedCommunityAttrType = 0x44
   152  	EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL       ExtendedCommunityAttrType = 0x80
   153  	EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL2      ExtendedCommunityAttrType = 0x81 // RFC7674
   154  	EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL3      ExtendedCommunityAttrType = 0x82 // RFC7674
   155  )
   156  
   157  // RFC7153 5.2. Registries for the "Sub-Type" Field
   158  // RANGE	REGISTRATION PROCEDURES
   159  // 0x00-0xBF	First Come First Served
   160  // 0xC0-0xFF	IETF Review
   161  type ExtendedCommunityAttrSubType uint8
   162  
   163  const (
   164  	EC_SUBTYPE_ROUTE_TARGET            ExtendedCommunityAttrSubType = 0x02 // EC_TYPE: 0x00, 0x01, 0x02
   165  	EC_SUBTYPE_ROUTE_ORIGIN            ExtendedCommunityAttrSubType = 0x03 // EC_TYPE: 0x00, 0x01, 0x02
   166  	EC_SUBTYPE_LINK_BANDWIDTH          ExtendedCommunityAttrSubType = 0x04 // EC_TYPE: 0x40
   167  	EC_SUBTYPE_GENERIC                 ExtendedCommunityAttrSubType = 0x04 // EC_TYPE: 0x02, 0x42
   168  	EC_SUBTYPE_OSPF_DOMAIN_ID          ExtendedCommunityAttrSubType = 0x05 // EC_TYPE: 0x00, 0x01, 0x02
   169  	EC_SUBTYPE_OSPF_ROUTE_ID           ExtendedCommunityAttrSubType = 0x07 // EC_TYPE: 0x01
   170  	EC_SUBTYPE_BGP_DATA_COLLECTION     ExtendedCommunityAttrSubType = 0x08 // EC_TYPE: 0x00, 0x02
   171  	EC_SUBTYPE_SOURCE_AS               ExtendedCommunityAttrSubType = 0x09 // EC_TYPE: 0x00, 0x02
   172  	EC_SUBTYPE_L2VPN_ID                ExtendedCommunityAttrSubType = 0x0A // EC_TYPE: 0x00, 0x01
   173  	EC_SUBTYPE_VRF_ROUTE_IMPORT        ExtendedCommunityAttrSubType = 0x0B // EC_TYPE: 0x01
   174  	EC_SUBTYPE_CISCO_VPN_DISTINGUISHER ExtendedCommunityAttrSubType = 0x10 // EC_TYPE: 0x00, 0x01, 0x02
   175  
   176  	EC_SUBTYPE_OSPF_ROUTE_TYPE ExtendedCommunityAttrSubType = 0x06 // EC_TYPE: 0x03
   177  	EC_SUBTYPE_COLOR           ExtendedCommunityAttrSubType = 0x0B // EC_TYPE: 0x03
   178  	EC_SUBTYPE_ENCAPSULATION   ExtendedCommunityAttrSubType = 0x0C // EC_TYPE: 0x03
   179  	EC_SUBTYPE_DEFAULT_GATEWAY ExtendedCommunityAttrSubType = 0x0D // EC_TYPE: 0x03
   180  
   181  	EC_SUBTYPE_ORIGIN_VALIDATION ExtendedCommunityAttrSubType = 0x00 // EC_TYPE: 0x43
   182  
   183  	EC_SUBTYPE_MUP_DIRECT_SEG ExtendedCommunityAttrSubType = 0x00 // EC_TYPE: 0x0c
   184  
   185  	EC_SUBTYPE_FLOWSPEC_TRAFFIC_RATE   ExtendedCommunityAttrSubType = 0x06 // EC_TYPE: 0x80
   186  	EC_SUBTYPE_FLOWSPEC_TRAFFIC_ACTION ExtendedCommunityAttrSubType = 0x07 // EC_TYPE: 0x80
   187  	EC_SUBTYPE_FLOWSPEC_REDIRECT       ExtendedCommunityAttrSubType = 0x08 // EC_TYPE: 0x80
   188  	EC_SUBTYPE_FLOWSPEC_TRAFFIC_REMARK ExtendedCommunityAttrSubType = 0x09 // EC_TYPE: 0x80
   189  	EC_SUBTYPE_L2_INFO                 ExtendedCommunityAttrSubType = 0x0A // EC_TYPE: 0x80
   190  	EC_SUBTYPE_FLOWSPEC_REDIRECT_IP6   ExtendedCommunityAttrSubType = 0x0B // EC_TYPE: 0x80
   191  
   192  	EC_SUBTYPE_MAC_MOBILITY  ExtendedCommunityAttrSubType = 0x00 // EC_TYPE: 0x06
   193  	EC_SUBTYPE_ESI_LABEL     ExtendedCommunityAttrSubType = 0x01 // EC_TYPE: 0x06
   194  	EC_SUBTYPE_ES_IMPORT     ExtendedCommunityAttrSubType = 0x02 // EC_TYPE: 0x06
   195  	EC_SUBTYPE_ROUTER_MAC    ExtendedCommunityAttrSubType = 0x03 // EC_TYPE: 0x06
   196  	EC_SUBTYPE_L2_ATTRIBUTES ExtendedCommunityAttrSubType = 0x04 // EC_TYPE: 0x06
   197  
   198  	EC_SUBTYPE_UUID_BASED_RT ExtendedCommunityAttrSubType = 0x11
   199  )
   200  
   201  // RFC6624
   202  type Layer2EncapsulationType uint8
   203  
   204  const (
   205  	LAYER2ENCAPSULATION_TYPE_FRAMERELAY      Layer2EncapsulationType = 1
   206  	LAYER2ENCAPSULATION_TYPE_ATM_AAL5        Layer2EncapsulationType = 2
   207  	LAYER2ENCAPSULATION_TYPE_ATM_TRANSPARENT Layer2EncapsulationType = 3
   208  	LAYER2ENCAPSULATION_TYPE_ETHERNET_VLAN   Layer2EncapsulationType = 4
   209  	LAYER2ENCAPSULATION_TYPE_ETHERNET_RAW    Layer2EncapsulationType = 5
   210  	LAYER2ENCAPSULATION_TYPE_CISCO_HDLC      Layer2EncapsulationType = 6
   211  	LAYER2ENCAPSULATION_TYPE_PPP             Layer2EncapsulationType = 7
   212  	LAYER2ENCAPSULATION_TYPE_SONET           Layer2EncapsulationType = 8
   213  	LAYER2ENCAPSULATION_TYPE_ATM_VCC         Layer2EncapsulationType = 9
   214  	LAYER2ENCAPSULATION_TYPE_ATM_VPC         Layer2EncapsulationType = 10
   215  	LAYER2ENCAPSULATION_TYPE_IP_LAYER2       Layer2EncapsulationType = 11
   216  	LAYER2ENCAPSULATION_TYPE_VPLS            Layer2EncapsulationType = 19
   217  )
   218  
   219  func (l Layer2EncapsulationType) String() string {
   220  	switch l {
   221  	case LAYER2ENCAPSULATION_TYPE_FRAMERELAY:
   222  		return "framerelay"
   223  	case LAYER2ENCAPSULATION_TYPE_ATM_AAL5:
   224  		return "atm-aal5"
   225  	case LAYER2ENCAPSULATION_TYPE_ATM_TRANSPARENT:
   226  		return "atm-transparent"
   227  	case LAYER2ENCAPSULATION_TYPE_ETHERNET_VLAN:
   228  		return "ethernet-vlan"
   229  	case LAYER2ENCAPSULATION_TYPE_ETHERNET_RAW:
   230  		return "ethernet-raw"
   231  	case LAYER2ENCAPSULATION_TYPE_CISCO_HDLC:
   232  		return "cisco-hdlc"
   233  	case LAYER2ENCAPSULATION_TYPE_PPP:
   234  		return "ppp"
   235  	case LAYER2ENCAPSULATION_TYPE_SONET:
   236  		return "sonet"
   237  	case LAYER2ENCAPSULATION_TYPE_ATM_VCC:
   238  		return "atm-vcc"
   239  	case LAYER2ENCAPSULATION_TYPE_ATM_VPC:
   240  		return "atm-vpc"
   241  	case LAYER2ENCAPSULATION_TYPE_IP_LAYER2:
   242  		return "ip-layer2"
   243  	case LAYER2ENCAPSULATION_TYPE_VPLS:
   244  		return "vpls"
   245  	default:
   246  		return fmt.Sprintf("Layer2EncapsulationType(%d)", uint8(l))
   247  	}
   248  }
   249  
   250  type TunnelType uint16
   251  
   252  const (
   253  	TUNNEL_TYPE_L2TP3       TunnelType = 1
   254  	TUNNEL_TYPE_GRE         TunnelType = 2
   255  	TUNNEL_TYPE_IP_IN_IP    TunnelType = 7
   256  	TUNNEL_TYPE_VXLAN       TunnelType = 8
   257  	TUNNEL_TYPE_NVGRE       TunnelType = 9
   258  	TUNNEL_TYPE_MPLS        TunnelType = 10
   259  	TUNNEL_TYPE_MPLS_IN_GRE TunnelType = 11
   260  	TUNNEL_TYPE_VXLAN_GRE   TunnelType = 12
   261  	TUNNEL_TYPE_MPLS_IN_UDP TunnelType = 13
   262  	TUNNEL_TYPE_SR_POLICY   TunnelType = 15
   263  	TUNNEL_TYPE_GENEVE      TunnelType = 19
   264  )
   265  
   266  func (p TunnelType) String() string {
   267  	switch p {
   268  	case TUNNEL_TYPE_L2TP3:
   269  		return "l2tp3"
   270  	case TUNNEL_TYPE_GRE:
   271  		return "gre"
   272  	case TUNNEL_TYPE_IP_IN_IP:
   273  		return "ip-in-ip"
   274  	case TUNNEL_TYPE_VXLAN:
   275  		return "vxlan"
   276  	case TUNNEL_TYPE_NVGRE:
   277  		return "nvgre"
   278  	case TUNNEL_TYPE_MPLS:
   279  		return "mpls"
   280  	case TUNNEL_TYPE_MPLS_IN_GRE:
   281  		return "mpls-in-gre"
   282  	case TUNNEL_TYPE_VXLAN_GRE:
   283  		return "vxlan-gre"
   284  	case TUNNEL_TYPE_MPLS_IN_UDP:
   285  		return "mpls-in-udp"
   286  	case TUNNEL_TYPE_SR_POLICY:
   287  		return "sr-policy"
   288  	case TUNNEL_TYPE_GENEVE:
   289  		return "geneve"
   290  	default:
   291  		return fmt.Sprintf("TunnelType(%d)", uint8(p))
   292  	}
   293  }
   294  
   295  type PmsiTunnelType uint8
   296  
   297  const (
   298  	PMSI_TUNNEL_TYPE_NO_TUNNEL      PmsiTunnelType = 0
   299  	PMSI_TUNNEL_TYPE_RSVP_TE_P2MP   PmsiTunnelType = 1
   300  	PMSI_TUNNEL_TYPE_MLDP_P2MP      PmsiTunnelType = 2
   301  	PMSI_TUNNEL_TYPE_PIM_SSM_TREE   PmsiTunnelType = 3
   302  	PMSI_TUNNEL_TYPE_PIM_SM_TREE    PmsiTunnelType = 4
   303  	PMSI_TUNNEL_TYPE_BIDIR_PIM_TREE PmsiTunnelType = 5
   304  	PMSI_TUNNEL_TYPE_INGRESS_REPL   PmsiTunnelType = 6
   305  	PMSI_TUNNEL_TYPE_MLDP_MP2MP     PmsiTunnelType = 7
   306  )
   307  
   308  func (p PmsiTunnelType) String() string {
   309  	switch p {
   310  	case PMSI_TUNNEL_TYPE_NO_TUNNEL:
   311  		return "no-tunnel"
   312  	case PMSI_TUNNEL_TYPE_RSVP_TE_P2MP:
   313  		return "rsvp-te-p2mp"
   314  	case PMSI_TUNNEL_TYPE_MLDP_P2MP:
   315  		return "mldp-p2mp"
   316  	case PMSI_TUNNEL_TYPE_PIM_SSM_TREE:
   317  		return "pim-ssm-tree"
   318  	case PMSI_TUNNEL_TYPE_PIM_SM_TREE:
   319  		return "pim-sm-tree"
   320  	case PMSI_TUNNEL_TYPE_BIDIR_PIM_TREE:
   321  		return "bidir-pim-tree"
   322  	case PMSI_TUNNEL_TYPE_INGRESS_REPL:
   323  		return "ingress-repl"
   324  	case PMSI_TUNNEL_TYPE_MLDP_MP2MP:
   325  		return "mldp-mp2mp"
   326  	default:
   327  		return fmt.Sprintf("PmsiTunnelType(%d)", uint8(p))
   328  	}
   329  }
   330  
   331  type EncapSubTLVType uint8
   332  
   333  const (
   334  	ENCAP_SUBTLV_TYPE_ENCAPSULATION         EncapSubTLVType = 1
   335  	ENCAP_SUBTLV_TYPE_PROTOCOL              EncapSubTLVType = 2
   336  	ENCAP_SUBTLV_TYPE_COLOR                 EncapSubTLVType = 4
   337  	ENCAP_SUBTLV_TYPE_EGRESS_ENDPOINT       EncapSubTLVType = 6
   338  	ENCAP_SUBTLV_TYPE_UDP_DEST_PORT         EncapSubTLVType = 8
   339  	ENCAP_SUBTLV_TYPE_SRPREFERENCE          EncapSubTLVType = 12
   340  	ENCAP_SUBTLV_TYPE_SRBINDING_SID         EncapSubTLVType = 13
   341  	ENCAP_SUBTLV_TYPE_SRENLP                EncapSubTLVType = 14
   342  	ENCAP_SUBTLV_TYPE_SRPRIORITY            EncapSubTLVType = 15
   343  	ENCAP_SUBTLV_TYPE_SRSEGMENT_LIST        EncapSubTLVType = 128
   344  	ENCAP_SUBTLV_TYPE_SRCANDIDATE_PATH_NAME EncapSubTLVType = 129
   345  )
   346  
   347  const (
   348  	_ = iota
   349  	BGP_MSG_OPEN
   350  	BGP_MSG_UPDATE
   351  	BGP_MSG_NOTIFICATION
   352  	BGP_MSG_KEEPALIVE
   353  	BGP_MSG_ROUTE_REFRESH
   354  )
   355  
   356  const (
   357  	BGP_OPT_CAPABILITY = 2
   358  )
   359  
   360  type BGPCapabilityCode uint8
   361  
   362  const (
   363  	BGP_CAP_MULTIPROTOCOL               BGPCapabilityCode = 1
   364  	BGP_CAP_ROUTE_REFRESH               BGPCapabilityCode = 2
   365  	BGP_CAP_CARRYING_LABEL_INFO         BGPCapabilityCode = 4
   366  	BGP_CAP_EXTENDED_NEXTHOP            BGPCapabilityCode = 5
   367  	BGP_CAP_GRACEFUL_RESTART            BGPCapabilityCode = 64
   368  	BGP_CAP_FOUR_OCTET_AS_NUMBER        BGPCapabilityCode = 65
   369  	BGP_CAP_ADD_PATH                    BGPCapabilityCode = 69
   370  	BGP_CAP_ENHANCED_ROUTE_REFRESH      BGPCapabilityCode = 70
   371  	BGP_CAP_LONG_LIVED_GRACEFUL_RESTART BGPCapabilityCode = 71
   372  	BGP_CAP_FQDN                        BGPCapabilityCode = 73
   373  	BGP_CAP_SOFT_VERSION                BGPCapabilityCode = 75
   374  	BGP_CAP_ROUTE_REFRESH_CISCO         BGPCapabilityCode = 128
   375  )
   376  
   377  var CapNameMap = map[BGPCapabilityCode]string{
   378  	BGP_CAP_MULTIPROTOCOL:               "multiprotocol",
   379  	BGP_CAP_ROUTE_REFRESH:               "route-refresh",
   380  	BGP_CAP_CARRYING_LABEL_INFO:         "carrying-label-info",
   381  	BGP_CAP_GRACEFUL_RESTART:            "graceful-restart",
   382  	BGP_CAP_EXTENDED_NEXTHOP:            "extended-nexthop",
   383  	BGP_CAP_FOUR_OCTET_AS_NUMBER:        "4-octet-as",
   384  	BGP_CAP_ADD_PATH:                    "add-path",
   385  	BGP_CAP_ENHANCED_ROUTE_REFRESH:      "enhanced-route-refresh",
   386  	BGP_CAP_ROUTE_REFRESH_CISCO:         "cisco-route-refresh",
   387  	BGP_CAP_LONG_LIVED_GRACEFUL_RESTART: "long-lived-graceful-restart",
   388  	BGP_CAP_FQDN:                        "fqdn",
   389  	BGP_CAP_SOFT_VERSION:                "software-version",
   390  }
   391  
   392  func (c BGPCapabilityCode) String() string {
   393  	if n, y := CapNameMap[c]; y {
   394  		return n
   395  	}
   396  	return fmt.Sprintf("UnknownCapability(%d)", c)
   397  }
   398  
   399  var (
   400  	// Used parsing RouteDistinguisher
   401  	_regexpRouteDistinguisher = regexp.MustCompile(`^((\d+)\.(\d+)\.(\d+)\.(\d+)|((\d+)\.)?(\d+)|([\w]+:[\w:]*:[\w]+)):(\d+)$`)
   402  
   403  	// Used for operator and value for the FlowSpec numeric type
   404  	// Example:
   405  	// re.FindStringSubmatch("&==80")
   406  	// >>> ["&==80" "&" "==" "80"]
   407  	_regexpFlowSpecNumericType = regexp.MustCompile(`(&?)(==|=|>|>=|<|<=|!|!=|=!)?(\d+|-\d|true|false)`)
   408  
   409  	// - "=!" is used in the old style format of "tcp-flags" and "fragment".
   410  	// - The value field should be one of the followings:
   411  	//     * Decimal value (e.g., 80)
   412  	//     * Combination of the small letters, decimals, "-" and "+"
   413  	//       (e.g., tcp, ipv4, is-fragment+first-fragment)
   414  	//     * Capital letters (e.g., SA)
   415  	_regexpFlowSpecOperator      = regexp.MustCompile(`&|=|>|<|!|[\w\-+]+`)
   416  	_regexpFlowSpecOperatorValue = regexp.MustCompile(`[\w\-+]+`)
   417  
   418  	// Note: "(-*)" and "(.*)" catch the invalid flags
   419  	// Example: In this case, "Z" is unsupported flag type.
   420  	// re.FindStringSubmatch("&==-SZU")
   421  	// >>> ["&==-SZU" "&" "==" "-" "S" "ZU"]
   422  	_regexpFlowSpecTCPFlag = regexp.MustCompile("(&?)(==|=|!|!=|=!)?(-*)([FSRPAUCE]+)(.*)")
   423  
   424  	// Note: "(.*)" catches the invalid flags
   425  	// re.FindStringSubmatch("&!=+first-fragment+last-fragment+invalid-fragment")
   426  	// >>> ["&!=+first-fragment+last-fragment+invalid-fragment" "&" "!=" "+first-fragment+last-fragment" "+last-fragment" "+" "last" "+invalid-fragment"]
   427  	_regexpFlowSpecFragment = regexp.MustCompile(`(&?)(==|=|!|!=|=!)?(((\+)?(dont|is|first|last|not-a)-fragment)+)(.*)`)
   428  
   429  	// re.FindStringSubmatch("192.168.0.0/24")
   430  	// >>> ["192.168.0.0/24" "192.168.0.0" "/24" "24"]
   431  	// re.FindStringSubmatch("192.168.0.1")
   432  	// >>> ["192.168.0.1" "192.168.0.1" "" ""]
   433  	_regexpFindIPv4Prefix = regexp.MustCompile(`^([\d.]+)(/(\d{1,2}))?`)
   434  
   435  	// re.FindStringSubmatch("2001:dB8::/64")
   436  	// >>> ["2001:dB8::/64" "2001:dB8::" "/64" "64" "" ""]
   437  	// re.FindStringSubmatch("2001:dB8::/64/8")
   438  	// >>> ["2001:dB8::/64/8" "2001:dB8::" "/64" "64" "/8" "8"]
   439  	// re.FindStringSubmatch("2001:dB8::1")
   440  	// >>> ["2001:dB8::1" "2001:dB8::1" "" "" "" ""]
   441  	_regexpFindIPv6Prefix = regexp.MustCompile(`^([a-fA-F\d:.]+)(/(\d{1,3}))?(/(\d{1,3}))?`)
   442  )
   443  
   444  type ParameterCapabilityInterface interface {
   445  	DecodeFromBytes([]byte) error
   446  	Serialize() ([]byte, error)
   447  	Len() int
   448  	Code() BGPCapabilityCode
   449  }
   450  
   451  type DefaultParameterCapability struct {
   452  	CapCode  BGPCapabilityCode `json:"code"`
   453  	CapLen   uint8             `json:"-"`
   454  	CapValue []byte            `json:"value,omitempty"`
   455  }
   456  
   457  func (c *DefaultParameterCapability) Code() BGPCapabilityCode {
   458  	return c.CapCode
   459  }
   460  
   461  func (c *DefaultParameterCapability) DecodeFromBytes(data []byte) error {
   462  	c.CapCode = BGPCapabilityCode(data[0])
   463  	c.CapLen = data[1]
   464  	if len(data) < 2+int(c.CapLen) {
   465  		return NewMessageError(BGP_ERROR_OPEN_MESSAGE_ERROR, BGP_ERROR_SUB_UNSUPPORTED_CAPABILITY, nil, "Not all OptionParameterCapability bytes available")
   466  	}
   467  	if c.CapLen > 0 {
   468  		c.CapValue = data[2 : 2+c.CapLen]
   469  	}
   470  	return nil
   471  }
   472  
   473  func (c *DefaultParameterCapability) Serialize() ([]byte, error) {
   474  	c.CapLen = uint8(len(c.CapValue))
   475  	buf := make([]byte, 2+len(c.CapValue))
   476  	buf[0] = uint8(c.CapCode)
   477  	buf[1] = c.CapLen
   478  	copy(buf[2:], c.CapValue)
   479  	return buf, nil
   480  }
   481  
   482  func (c *DefaultParameterCapability) Len() int {
   483  	return int(c.CapLen + 2)
   484  }
   485  
   486  type CapMultiProtocol struct {
   487  	DefaultParameterCapability
   488  	CapValue RouteFamily
   489  }
   490  
   491  func (c *CapMultiProtocol) DecodeFromBytes(data []byte) error {
   492  	c.DefaultParameterCapability.DecodeFromBytes(data)
   493  	data = data[2:]
   494  	if len(data) < 4 {
   495  		return NewMessageError(BGP_ERROR_OPEN_MESSAGE_ERROR, BGP_ERROR_SUB_UNSUPPORTED_CAPABILITY, nil, "Not all CapabilityMultiProtocol bytes available")
   496  	}
   497  	c.CapValue = AfiSafiToRouteFamily(binary.BigEndian.Uint16(data[0:2]), data[3])
   498  	return nil
   499  }
   500  
   501  func (c *CapMultiProtocol) Serialize() ([]byte, error) {
   502  	buf := make([]byte, 4)
   503  	afi, safi := RouteFamilyToAfiSafi(c.CapValue)
   504  	binary.BigEndian.PutUint16(buf[0:], afi)
   505  	buf[3] = safi
   506  	c.DefaultParameterCapability.CapValue = buf
   507  	return c.DefaultParameterCapability.Serialize()
   508  }
   509  
   510  func (c *CapMultiProtocol) MarshalJSON() ([]byte, error) {
   511  	return json.Marshal(struct {
   512  		Code  BGPCapabilityCode `json:"code"`
   513  		Value RouteFamily       `json:"value"`
   514  	}{
   515  		Code:  c.Code(),
   516  		Value: c.CapValue,
   517  	})
   518  }
   519  
   520  func NewCapMultiProtocol(rf RouteFamily) *CapMultiProtocol {
   521  	return &CapMultiProtocol{
   522  		DefaultParameterCapability{
   523  			CapCode: BGP_CAP_MULTIPROTOCOL,
   524  		},
   525  		rf,
   526  	}
   527  }
   528  
   529  type CapRouteRefresh struct {
   530  	DefaultParameterCapability
   531  }
   532  
   533  func NewCapRouteRefresh() *CapRouteRefresh {
   534  	return &CapRouteRefresh{
   535  		DefaultParameterCapability{
   536  			CapCode: BGP_CAP_ROUTE_REFRESH,
   537  		},
   538  	}
   539  }
   540  
   541  type CapCarryingLabelInfo struct {
   542  	DefaultParameterCapability
   543  }
   544  
   545  func NewCapCarryingLabelInfo() *CapCarryingLabelInfo {
   546  	return &CapCarryingLabelInfo{
   547  		DefaultParameterCapability{
   548  			CapCode: BGP_CAP_CARRYING_LABEL_INFO,
   549  		},
   550  	}
   551  }
   552  
   553  type CapExtendedNexthopTuple struct {
   554  	NLRIAFI    uint16
   555  	NLRISAFI   uint16
   556  	NexthopAFI uint16
   557  }
   558  
   559  func (c *CapExtendedNexthopTuple) MarshalJSON() ([]byte, error) {
   560  	return json.Marshal(struct {
   561  		NLRIAddressFamily    RouteFamily `json:"nlri_address_family"`
   562  		NexthopAddressFamily uint16      `json:"nexthop_address_family"`
   563  	}{
   564  		NLRIAddressFamily:    AfiSafiToRouteFamily(c.NLRIAFI, uint8(c.NLRISAFI)),
   565  		NexthopAddressFamily: c.NexthopAFI,
   566  	})
   567  }
   568  
   569  func NewCapExtendedNexthopTuple(af RouteFamily, nexthop uint16) *CapExtendedNexthopTuple {
   570  	afi, safi := RouteFamilyToAfiSafi(af)
   571  	return &CapExtendedNexthopTuple{
   572  		NLRIAFI:    afi,
   573  		NLRISAFI:   uint16(safi),
   574  		NexthopAFI: nexthop,
   575  	}
   576  }
   577  
   578  type CapExtendedNexthop struct {
   579  	DefaultParameterCapability
   580  	Tuples []*CapExtendedNexthopTuple
   581  }
   582  
   583  func (c *CapExtendedNexthop) DecodeFromBytes(data []byte) error {
   584  	c.DefaultParameterCapability.DecodeFromBytes(data)
   585  	data = data[2:]
   586  	capLen := int(c.CapLen)
   587  	if capLen%6 != 0 || capLen < 6 || len(data) < capLen {
   588  		return NewMessageError(BGP_ERROR_OPEN_MESSAGE_ERROR, BGP_ERROR_SUB_UNSUPPORTED_CAPABILITY, nil, "Not all CapabilityExtendedNexthop bytes available")
   589  	}
   590  
   591  	c.Tuples = []*CapExtendedNexthopTuple{}
   592  	for capLen >= 6 {
   593  		t := &CapExtendedNexthopTuple{
   594  			binary.BigEndian.Uint16(data[0:2]),
   595  			binary.BigEndian.Uint16(data[2:4]),
   596  			binary.BigEndian.Uint16(data[4:6]),
   597  		}
   598  		c.Tuples = append(c.Tuples, t)
   599  		data = data[6:]
   600  		capLen -= 6
   601  	}
   602  	return nil
   603  }
   604  
   605  func (c *CapExtendedNexthop) Serialize() ([]byte, error) {
   606  	buf := make([]byte, len(c.Tuples)*6)
   607  	for i, t := range c.Tuples {
   608  		binary.BigEndian.PutUint16(buf[i*6:i*6+2], t.NLRIAFI)
   609  		binary.BigEndian.PutUint16(buf[i*6+2:i*6+4], t.NLRISAFI)
   610  		binary.BigEndian.PutUint16(buf[i*6+4:i*6+6], t.NexthopAFI)
   611  	}
   612  	c.DefaultParameterCapability.CapValue = buf
   613  	return c.DefaultParameterCapability.Serialize()
   614  }
   615  
   616  func (c *CapExtendedNexthop) MarshalJSON() ([]byte, error) {
   617  	return json.Marshal(struct {
   618  		Code   BGPCapabilityCode          `json:"code"`
   619  		Tuples []*CapExtendedNexthopTuple `json:"tuples"`
   620  	}{
   621  		Code:   c.Code(),
   622  		Tuples: c.Tuples,
   623  	})
   624  }
   625  
   626  func NewCapExtendedNexthop(tuples []*CapExtendedNexthopTuple) *CapExtendedNexthop {
   627  	return &CapExtendedNexthop{
   628  		DefaultParameterCapability{
   629  			CapCode: BGP_CAP_EXTENDED_NEXTHOP,
   630  		},
   631  		tuples,
   632  	}
   633  }
   634  
   635  type CapGracefulRestartTuple struct {
   636  	AFI   uint16
   637  	SAFI  uint8
   638  	Flags uint8
   639  }
   640  
   641  func (c *CapGracefulRestartTuple) MarshalJSON() ([]byte, error) {
   642  	return json.Marshal(struct {
   643  		RouteFamily RouteFamily `json:"route_family"`
   644  		Flags       uint8       `json:"flags"`
   645  	}{
   646  		RouteFamily: AfiSafiToRouteFamily(c.AFI, c.SAFI),
   647  		Flags:       c.Flags,
   648  	})
   649  }
   650  
   651  func NewCapGracefulRestartTuple(rf RouteFamily, forward bool) *CapGracefulRestartTuple {
   652  	afi, safi := RouteFamilyToAfiSafi(rf)
   653  	flags := 0
   654  	if forward {
   655  		flags = 0x80
   656  	}
   657  	return &CapGracefulRestartTuple{
   658  		AFI:   afi,
   659  		SAFI:  safi,
   660  		Flags: uint8(flags),
   661  	}
   662  }
   663  
   664  type CapGracefulRestart struct {
   665  	DefaultParameterCapability
   666  	Flags  uint8
   667  	Time   uint16
   668  	Tuples []*CapGracefulRestartTuple
   669  }
   670  
   671  func (c *CapGracefulRestart) DecodeFromBytes(data []byte) error {
   672  	c.DefaultParameterCapability.DecodeFromBytes(data)
   673  	data = data[2:]
   674  	if len(data) < 2 {
   675  		return NewMessageError(BGP_ERROR_OPEN_MESSAGE_ERROR, BGP_ERROR_SUB_UNSUPPORTED_CAPABILITY, nil, "Not all CapabilityGracefulRestart bytes available")
   676  	}
   677  	restart := binary.BigEndian.Uint16(data[0:2])
   678  	c.Flags = uint8(restart >> 12)
   679  	c.Time = restart & 0xfff
   680  	data = data[2:]
   681  
   682  	valueLen := int(c.CapLen) - 2
   683  
   684  	if valueLen >= 4 && len(data) >= valueLen {
   685  		c.Tuples = make([]*CapGracefulRestartTuple, 0, valueLen/4)
   686  
   687  		for i := valueLen; i >= 4; i -= 4 {
   688  			t := &CapGracefulRestartTuple{binary.BigEndian.Uint16(data[0:2]),
   689  				data[2], data[3]}
   690  			c.Tuples = append(c.Tuples, t)
   691  			data = data[4:]
   692  		}
   693  	}
   694  	return nil
   695  }
   696  
   697  func (c *CapGracefulRestart) Serialize() ([]byte, error) {
   698  	buf := make([]byte, 2, 2+4*len(c.Tuples))
   699  	binary.BigEndian.PutUint16(buf[0:], uint16(c.Flags)<<12|c.Time)
   700  	var tbuf [4]byte
   701  	for _, t := range c.Tuples {
   702  		binary.BigEndian.PutUint16(tbuf[0:2], t.AFI)
   703  		tbuf[2] = t.SAFI
   704  		tbuf[3] = t.Flags
   705  		buf = append(buf, tbuf[:]...)
   706  	}
   707  	c.DefaultParameterCapability.CapValue = buf
   708  	return c.DefaultParameterCapability.Serialize()
   709  }
   710  
   711  func (c *CapGracefulRestart) MarshalJSON() ([]byte, error) {
   712  	return json.Marshal(struct {
   713  		Code   BGPCapabilityCode          `json:"code"`
   714  		Flags  uint8                      `json:"flags"`
   715  		Time   uint16                     `json:"time"`
   716  		Tuples []*CapGracefulRestartTuple `json:"tuples"`
   717  	}{
   718  		Code:   c.Code(),
   719  		Flags:  c.Flags,
   720  		Time:   c.Time,
   721  		Tuples: c.Tuples,
   722  	})
   723  }
   724  
   725  func NewCapGracefulRestart(restarting, notification bool, time uint16, tuples []*CapGracefulRestartTuple) *CapGracefulRestart {
   726  	flags := 0
   727  	if restarting {
   728  		flags = 0x08
   729  	}
   730  	if notification {
   731  		flags |= 0x04
   732  	}
   733  	return &CapGracefulRestart{
   734  		DefaultParameterCapability: DefaultParameterCapability{
   735  			CapCode: BGP_CAP_GRACEFUL_RESTART,
   736  		},
   737  		Flags:  uint8(flags),
   738  		Time:   time,
   739  		Tuples: tuples,
   740  	}
   741  }
   742  
   743  type CapFourOctetASNumber struct {
   744  	DefaultParameterCapability
   745  	CapValue uint32
   746  }
   747  
   748  func (c *CapFourOctetASNumber) DecodeFromBytes(data []byte) error {
   749  	c.DefaultParameterCapability.DecodeFromBytes(data)
   750  	data = data[2:]
   751  	if len(data) < 4 {
   752  		return NewMessageError(BGP_ERROR_OPEN_MESSAGE_ERROR, BGP_ERROR_SUB_UNSUPPORTED_CAPABILITY, nil, "Not all CapabilityFourOctetASNumber bytes available")
   753  	}
   754  	c.CapValue = binary.BigEndian.Uint32(data[0:4])
   755  	return nil
   756  }
   757  
   758  func (c *CapFourOctetASNumber) Serialize() ([]byte, error) {
   759  	buf := make([]byte, 4)
   760  	binary.BigEndian.PutUint32(buf, c.CapValue)
   761  	c.DefaultParameterCapability.CapValue = buf
   762  	return c.DefaultParameterCapability.Serialize()
   763  }
   764  
   765  func (c *CapFourOctetASNumber) MarshalJSON() ([]byte, error) {
   766  	return json.Marshal(struct {
   767  		Code  BGPCapabilityCode `json:"code"`
   768  		Value uint32            `json:"value"`
   769  	}{
   770  		Code:  c.Code(),
   771  		Value: c.CapValue,
   772  	})
   773  }
   774  
   775  func NewCapFourOctetASNumber(asnum uint32) *CapFourOctetASNumber {
   776  	return &CapFourOctetASNumber{
   777  		DefaultParameterCapability{
   778  			CapCode: BGP_CAP_FOUR_OCTET_AS_NUMBER,
   779  		},
   780  		asnum,
   781  	}
   782  }
   783  
   784  type BGPAddPathMode uint8
   785  
   786  const (
   787  	BGP_ADD_PATH_NONE BGPAddPathMode = iota
   788  	BGP_ADD_PATH_RECEIVE
   789  	BGP_ADD_PATH_SEND
   790  	BGP_ADD_PATH_BOTH
   791  )
   792  
   793  func (m BGPAddPathMode) String() string {
   794  	switch m {
   795  	case BGP_ADD_PATH_NONE:
   796  		return "none"
   797  	case BGP_ADD_PATH_RECEIVE:
   798  		return "receive"
   799  	case BGP_ADD_PATH_SEND:
   800  		return "send"
   801  	case BGP_ADD_PATH_BOTH:
   802  		return "receive/send"
   803  	default:
   804  		return fmt.Sprintf("unknown(%d)", m)
   805  	}
   806  }
   807  
   808  type CapAddPathTuple struct {
   809  	RouteFamily RouteFamily
   810  	Mode        BGPAddPathMode
   811  }
   812  
   813  func (t *CapAddPathTuple) MarshalJSON() ([]byte, error) {
   814  	return json.Marshal(struct {
   815  		RouteFamily RouteFamily `json:"family"`
   816  		Mode        uint8       `json:"mode"`
   817  	}{
   818  		RouteFamily: t.RouteFamily,
   819  		Mode:        uint8(t.Mode),
   820  	})
   821  }
   822  
   823  func NewCapAddPathTuple(family RouteFamily, mode BGPAddPathMode) *CapAddPathTuple {
   824  	return &CapAddPathTuple{
   825  		RouteFamily: family,
   826  		Mode:        mode,
   827  	}
   828  }
   829  
   830  type CapAddPath struct {
   831  	DefaultParameterCapability
   832  	Tuples []*CapAddPathTuple
   833  }
   834  
   835  func (c *CapAddPath) DecodeFromBytes(data []byte) error {
   836  	c.DefaultParameterCapability.DecodeFromBytes(data)
   837  	data = data[2:]
   838  	capLen := int(c.CapLen)
   839  	if capLen%4 != 0 || capLen < 4 || len(data) < capLen {
   840  		return NewMessageError(BGP_ERROR_OPEN_MESSAGE_ERROR, BGP_ERROR_SUB_UNSUPPORTED_CAPABILITY, nil, "Not all CapabilityAddPath bytes available")
   841  	}
   842  
   843  	c.Tuples = []*CapAddPathTuple{}
   844  	for capLen >= 4 {
   845  		t := &CapAddPathTuple{
   846  			RouteFamily: AfiSafiToRouteFamily(binary.BigEndian.Uint16(data[:2]), data[2]),
   847  			Mode:        BGPAddPathMode(data[3]),
   848  		}
   849  		c.Tuples = append(c.Tuples, t)
   850  		data = data[4:]
   851  		capLen -= 4
   852  	}
   853  	return nil
   854  }
   855  
   856  func (c *CapAddPath) Serialize() ([]byte, error) {
   857  	buf := make([]byte, len(c.Tuples)*4)
   858  	for i, t := range c.Tuples {
   859  		afi, safi := RouteFamilyToAfiSafi(t.RouteFamily)
   860  		binary.BigEndian.PutUint16(buf[i*4:i*4+2], afi)
   861  		buf[i*4+2] = safi
   862  		buf[i*4+3] = byte(t.Mode)
   863  	}
   864  	c.DefaultParameterCapability.CapValue = buf
   865  	return c.DefaultParameterCapability.Serialize()
   866  }
   867  
   868  func (c *CapAddPath) MarshalJSON() ([]byte, error) {
   869  	return json.Marshal(struct {
   870  		Code   BGPCapabilityCode  `json:"code"`
   871  		Tuples []*CapAddPathTuple `json:"tuples"`
   872  	}{
   873  		Code:   c.Code(),
   874  		Tuples: c.Tuples,
   875  	})
   876  }
   877  
   878  func NewCapAddPath(tuples []*CapAddPathTuple) *CapAddPath {
   879  	return &CapAddPath{
   880  		DefaultParameterCapability: DefaultParameterCapability{
   881  			CapCode: BGP_CAP_ADD_PATH,
   882  		},
   883  		Tuples: tuples,
   884  	}
   885  }
   886  
   887  type CapEnhancedRouteRefresh struct {
   888  	DefaultParameterCapability
   889  }
   890  
   891  func NewCapEnhancedRouteRefresh() *CapEnhancedRouteRefresh {
   892  	return &CapEnhancedRouteRefresh{
   893  		DefaultParameterCapability{
   894  			CapCode: BGP_CAP_ENHANCED_ROUTE_REFRESH,
   895  		},
   896  	}
   897  }
   898  
   899  type CapRouteRefreshCisco struct {
   900  	DefaultParameterCapability
   901  }
   902  
   903  func NewCapRouteRefreshCisco() *CapRouteRefreshCisco {
   904  	return &CapRouteRefreshCisco{
   905  		DefaultParameterCapability{
   906  			CapCode: BGP_CAP_ROUTE_REFRESH_CISCO,
   907  		},
   908  	}
   909  }
   910  
   911  type CapLongLivedGracefulRestartTuple struct {
   912  	AFI         uint16
   913  	SAFI        uint8
   914  	Flags       uint8
   915  	RestartTime uint32
   916  }
   917  
   918  func (c *CapLongLivedGracefulRestartTuple) MarshalJSON() ([]byte, error) {
   919  	return json.Marshal(struct {
   920  		RouteFamily RouteFamily `json:"route_family"`
   921  		Flags       uint8       `json:"flags"`
   922  		RestartTime uint32      `json:"restart_time"`
   923  	}{
   924  		RouteFamily: AfiSafiToRouteFamily(c.AFI, c.SAFI),
   925  		Flags:       c.Flags,
   926  		RestartTime: c.RestartTime,
   927  	})
   928  }
   929  
   930  func NewCapLongLivedGracefulRestartTuple(rf RouteFamily, forward bool, restartTime uint32) *CapLongLivedGracefulRestartTuple {
   931  	afi, safi := RouteFamilyToAfiSafi(rf)
   932  	flags := 0
   933  	if forward {
   934  		flags = 0x80
   935  	}
   936  	return &CapLongLivedGracefulRestartTuple{
   937  		AFI:         afi,
   938  		SAFI:        safi,
   939  		Flags:       uint8(flags),
   940  		RestartTime: restartTime,
   941  	}
   942  }
   943  
   944  type CapLongLivedGracefulRestart struct {
   945  	DefaultParameterCapability
   946  	Tuples []*CapLongLivedGracefulRestartTuple
   947  }
   948  
   949  func (c *CapLongLivedGracefulRestart) DecodeFromBytes(data []byte) error {
   950  	c.DefaultParameterCapability.DecodeFromBytes(data)
   951  	data = data[2:]
   952  
   953  	valueLen := int(c.CapLen)
   954  	if valueLen%7 != 0 || len(data) < valueLen {
   955  		return NewMessageError(BGP_ERROR_OPEN_MESSAGE_ERROR, BGP_ERROR_SUB_UNSUPPORTED_CAPABILITY, nil, "invalid length of long lived graceful restart capablity")
   956  	}
   957  	for i := valueLen; i >= 7; i -= 7 {
   958  		t := &CapLongLivedGracefulRestartTuple{
   959  			binary.BigEndian.Uint16(data),
   960  			data[2],
   961  			data[3],
   962  			uint32(data[4])<<16 | uint32(data[5])<<8 | uint32(data[6]),
   963  		}
   964  		c.Tuples = append(c.Tuples, t)
   965  		data = data[7:]
   966  	}
   967  	return nil
   968  }
   969  
   970  func (c *CapLongLivedGracefulRestart) Serialize() ([]byte, error) {
   971  	buf := make([]byte, 7*len(c.Tuples))
   972  	for idx, t := range c.Tuples {
   973  		binary.BigEndian.PutUint16(buf[idx*7:], t.AFI)
   974  		buf[idx*7+2] = t.SAFI
   975  		buf[idx*7+3] = t.Flags
   976  		buf[idx*7+4] = uint8((t.RestartTime >> 16) & 0xff)
   977  		buf[idx*7+5] = uint8((t.RestartTime >> 8) & 0xff)
   978  		buf[idx*7+6] = uint8(t.RestartTime & 0xff)
   979  	}
   980  	c.DefaultParameterCapability.CapValue = buf
   981  	return c.DefaultParameterCapability.Serialize()
   982  }
   983  
   984  func (c *CapLongLivedGracefulRestart) MarshalJSON() ([]byte, error) {
   985  	return json.Marshal(struct {
   986  		Code   BGPCapabilityCode                   `json:"code"`
   987  		Tuples []*CapLongLivedGracefulRestartTuple `json:"tuples"`
   988  	}{
   989  		Code:   c.Code(),
   990  		Tuples: c.Tuples,
   991  	})
   992  }
   993  
   994  func NewCapLongLivedGracefulRestart(tuples []*CapLongLivedGracefulRestartTuple) *CapLongLivedGracefulRestart {
   995  	return &CapLongLivedGracefulRestart{
   996  		DefaultParameterCapability: DefaultParameterCapability{
   997  			CapCode: BGP_CAP_LONG_LIVED_GRACEFUL_RESTART,
   998  		},
   999  		Tuples: tuples,
  1000  	}
  1001  }
  1002  
  1003  type CapFQDN struct {
  1004  	DefaultParameterCapability
  1005  	HostNameLen   uint8
  1006  	HostName      string
  1007  	DomainNameLen uint8
  1008  	DomainName    string
  1009  }
  1010  
  1011  func (c *CapFQDN) DecodeFromBytes(data []byte) error {
  1012  	c.DefaultParameterCapability.DecodeFromBytes(data)
  1013  	data = data[2:]
  1014  	if len(data) < 2 {
  1015  		return NewMessageError(BGP_ERROR_OPEN_MESSAGE_ERROR, BGP_ERROR_SUB_UNSUPPORTED_CAPABILITY, nil, "Not all CapabilityFQDN bytes allowed")
  1016  	}
  1017  	rest := len(data)
  1018  	if rest < 1 {
  1019  		return NewMessageError(BGP_ERROR_OPEN_MESSAGE_ERROR, BGP_ERROR_SUB_UNSUPPORTED_CAPABILITY, nil, "Not all CapabilityFQDN bytes allowed")
  1020  	}
  1021  	hostNameLen := uint8(data[0])
  1022  	rest -= 1
  1023  	c.HostNameLen = hostNameLen
  1024  	if rest < int(hostNameLen) {
  1025  		return NewMessageError(BGP_ERROR_OPEN_MESSAGE_ERROR, BGP_ERROR_SUB_UNSUPPORTED_CAPABILITY, nil, "Not all CapabilityFQDN bytes allowed")
  1026  	}
  1027  	c.HostName = string(data[1 : c.HostNameLen+1])
  1028  	rest -= int(hostNameLen)
  1029  	if rest < 1 {
  1030  		return NewMessageError(BGP_ERROR_OPEN_MESSAGE_ERROR, BGP_ERROR_SUB_UNSUPPORTED_CAPABILITY, nil, "Not all CapabilityFQDN bytes allowed")
  1031  	}
  1032  	rest -= 1
  1033  	domainNameLen := uint8(data[c.HostNameLen+1])
  1034  	if rest < int(domainNameLen) {
  1035  		return NewMessageError(BGP_ERROR_OPEN_MESSAGE_ERROR, BGP_ERROR_SUB_UNSUPPORTED_CAPABILITY, nil, "Not all CapabilityFQDN bytes allowed")
  1036  	}
  1037  	c.DomainNameLen = domainNameLen
  1038  	c.DomainName = string(data[c.HostNameLen+2:])
  1039  	return nil
  1040  }
  1041  
  1042  func (c *CapFQDN) Serialize() ([]byte, error) {
  1043  	buf := make([]byte, c.HostNameLen+c.DomainNameLen+2)
  1044  	buf[0] = c.HostNameLen
  1045  	copy(buf[1:c.HostNameLen+1], c.HostName)
  1046  	buf[c.HostNameLen+1] = c.DomainNameLen
  1047  	copy(buf[c.HostNameLen+2:], c.DomainName)
  1048  	c.DefaultParameterCapability.CapValue = buf
  1049  	return c.DefaultParameterCapability.Serialize()
  1050  }
  1051  
  1052  func (c *CapFQDN) MarshalJSON() ([]byte, error) {
  1053  	return json.Marshal(struct {
  1054  		HostNameLen   uint8  `json:"hostname_len"`
  1055  		HostName      string `json:"hostname"`
  1056  		DomainNameLen uint8  `json:"domainname_len"`
  1057  		DomainName    string `json:"domainname"`
  1058  	}{
  1059  		HostNameLen:   c.HostNameLen,
  1060  		HostName:      c.HostName,
  1061  		DomainNameLen: c.DomainNameLen,
  1062  		DomainName:    c.DomainName,
  1063  	})
  1064  }
  1065  
  1066  func NewCapFQDN(hostname string, domainname string) *CapFQDN {
  1067  	if len(hostname) > 64 {
  1068  		hostname = hostname[:64]
  1069  	}
  1070  	if len(domainname) > 64 {
  1071  		domainname = domainname[:64]
  1072  	}
  1073  	return &CapFQDN{
  1074  		DefaultParameterCapability{
  1075  			CapCode: BGP_CAP_FQDN,
  1076  		},
  1077  		uint8(len(hostname)),
  1078  		hostname,
  1079  		uint8(len(domainname)),
  1080  		domainname,
  1081  	}
  1082  }
  1083  
  1084  type CapSoftwareVersion struct {
  1085  	DefaultParameterCapability
  1086  	SoftwareVersionLen uint8
  1087  	SoftwareVersion    string
  1088  }
  1089  
  1090  func (c *CapSoftwareVersion) DecodeFromBytes(data []byte) error {
  1091  	c.DefaultParameterCapability.DecodeFromBytes(data)
  1092  	data = data[2:]
  1093  	if len(data) < 2 {
  1094  		return NewMessageError(BGP_ERROR_OPEN_MESSAGE_ERROR, BGP_ERROR_SUB_UNSUPPORTED_CAPABILITY, nil, "Not all CapabilitySoftwareVersion bytes allowed")
  1095  	}
  1096  	softwareVersionLen := uint8(data[0])
  1097  	if len(data[1:]) < int(softwareVersionLen) || softwareVersionLen > 64 {
  1098  		return NewMessageError(BGP_ERROR_OPEN_MESSAGE_ERROR, BGP_ERROR_SUB_UNSUPPORTED_CAPABILITY, nil, "invalid length of software version capablity")
  1099  	}
  1100  	c.SoftwareVersionLen = softwareVersionLen
  1101  	c.SoftwareVersion = string(data[1:c.SoftwareVersionLen])
  1102  	return nil
  1103  }
  1104  
  1105  func (c *CapSoftwareVersion) Serialize() ([]byte, error) {
  1106  	buf := make([]byte, c.SoftwareVersionLen+1)
  1107  	buf[0] = c.SoftwareVersionLen
  1108  	copy(buf[1:], []byte(c.SoftwareVersion))
  1109  	c.DefaultParameterCapability.CapValue = buf
  1110  	return c.DefaultParameterCapability.Serialize()
  1111  }
  1112  
  1113  func (c *CapSoftwareVersion) MarshalJSON() ([]byte, error) {
  1114  	return json.Marshal(struct {
  1115  		SoftwareVersionLen uint8  `json:"software_version_len"`
  1116  		SoftwareVersion    string `json:"software_version"`
  1117  	}{
  1118  		SoftwareVersionLen: c.SoftwareVersionLen,
  1119  		SoftwareVersion:    c.SoftwareVersion,
  1120  	})
  1121  }
  1122  
  1123  func NewCapSoftwareVersion(version string) *CapSoftwareVersion {
  1124  	if len(version) > 64 {
  1125  		version = version[:64]
  1126  	}
  1127  
  1128  	return &CapSoftwareVersion{
  1129  		DefaultParameterCapability{
  1130  			CapCode: BGP_CAP_SOFT_VERSION,
  1131  		},
  1132  		uint8(len(version)),
  1133  		version,
  1134  	}
  1135  }
  1136  
  1137  type CapUnknown struct {
  1138  	DefaultParameterCapability
  1139  }
  1140  
  1141  func NewCapUnknown(code BGPCapabilityCode, value []byte) *CapUnknown {
  1142  	return &CapUnknown{
  1143  		DefaultParameterCapability{
  1144  			CapCode:  code,
  1145  			CapValue: value,
  1146  		},
  1147  	}
  1148  }
  1149  
  1150  func DecodeCapability(data []byte) (ParameterCapabilityInterface, error) {
  1151  	if len(data) < 2 {
  1152  		return nil, NewMessageError(BGP_ERROR_OPEN_MESSAGE_ERROR, BGP_ERROR_SUB_UNSUPPORTED_CAPABILITY, nil, "Not all ParameterCapability bytes available")
  1153  	}
  1154  	var c ParameterCapabilityInterface
  1155  	switch BGPCapabilityCode(data[0]) {
  1156  	case BGP_CAP_MULTIPROTOCOL:
  1157  		c = &CapMultiProtocol{}
  1158  	case BGP_CAP_ROUTE_REFRESH:
  1159  		c = &CapRouteRefresh{}
  1160  	case BGP_CAP_CARRYING_LABEL_INFO:
  1161  		c = &CapCarryingLabelInfo{}
  1162  	case BGP_CAP_EXTENDED_NEXTHOP:
  1163  		c = &CapExtendedNexthop{}
  1164  	case BGP_CAP_GRACEFUL_RESTART:
  1165  		c = &CapGracefulRestart{}
  1166  	case BGP_CAP_FOUR_OCTET_AS_NUMBER:
  1167  		c = &CapFourOctetASNumber{}
  1168  	case BGP_CAP_ADD_PATH:
  1169  		c = &CapAddPath{}
  1170  	case BGP_CAP_ENHANCED_ROUTE_REFRESH:
  1171  		c = &CapEnhancedRouteRefresh{}
  1172  	case BGP_CAP_ROUTE_REFRESH_CISCO:
  1173  		c = &CapRouteRefreshCisco{}
  1174  	case BGP_CAP_LONG_LIVED_GRACEFUL_RESTART:
  1175  		c = &CapLongLivedGracefulRestart{}
  1176  	case BGP_CAP_FQDN:
  1177  		c = &CapFQDN{}
  1178  	case BGP_CAP_SOFT_VERSION:
  1179  		c = &CapSoftwareVersion{}
  1180  	default:
  1181  		c = &CapUnknown{}
  1182  	}
  1183  	err := c.DecodeFromBytes(data)
  1184  	return c, err
  1185  }
  1186  
  1187  type OptionParameterInterface interface {
  1188  	Serialize() ([]byte, error)
  1189  }
  1190  
  1191  type OptionParameterCapability struct {
  1192  	ParamType  uint8
  1193  	ParamLen   uint8
  1194  	Capability []ParameterCapabilityInterface
  1195  }
  1196  
  1197  func (o *OptionParameterCapability) DecodeFromBytes(data []byte) error {
  1198  	if uint8(len(data)) < o.ParamLen {
  1199  		return NewMessageError(BGP_ERROR_OPEN_MESSAGE_ERROR, BGP_ERROR_SUB_UNSUPPORTED_OPTIONAL_PARAMETER, nil, "Not all OptionParameterCapability bytes available")
  1200  	}
  1201  	for len(data) >= 2 {
  1202  		c, err := DecodeCapability(data)
  1203  		if err != nil {
  1204  			return err
  1205  		}
  1206  		o.Capability = append(o.Capability, c)
  1207  		if c.Len() == 0 || len(data) < c.Len() {
  1208  			return NewMessageError(BGP_ERROR_MESSAGE_HEADER_ERROR, BGP_ERROR_SUB_BAD_MESSAGE_LENGTH, nil, "Bad capability length")
  1209  		}
  1210  		data = data[c.Len():]
  1211  	}
  1212  	return nil
  1213  }
  1214  
  1215  func (o *OptionParameterCapability) Serialize() ([]byte, error) {
  1216  	buf := make([]byte, 2)
  1217  	buf[0] = o.ParamType
  1218  	for _, p := range o.Capability {
  1219  		pbuf, err := p.Serialize()
  1220  		if err != nil {
  1221  			return nil, err
  1222  		}
  1223  		buf = append(buf, pbuf...)
  1224  	}
  1225  	o.ParamLen = uint8(len(buf) - 2)
  1226  	buf[1] = o.ParamLen
  1227  	return buf, nil
  1228  }
  1229  
  1230  func NewOptionParameterCapability(capability []ParameterCapabilityInterface) *OptionParameterCapability {
  1231  	return &OptionParameterCapability{
  1232  		ParamType:  BGP_OPT_CAPABILITY,
  1233  		Capability: capability,
  1234  	}
  1235  }
  1236  
  1237  type OptionParameterUnknown struct {
  1238  	ParamType uint8
  1239  	ParamLen  uint8
  1240  	Value     []byte
  1241  }
  1242  
  1243  func (o *OptionParameterUnknown) Serialize() ([]byte, error) {
  1244  	buf := make([]byte, 2+len(o.Value))
  1245  	buf[0] = o.ParamType
  1246  	if o.ParamLen == 0 {
  1247  		o.ParamLen = uint8(len(o.Value))
  1248  	}
  1249  	buf[1] = o.ParamLen
  1250  	copy(buf[2:], o.Value)
  1251  	return buf, nil
  1252  }
  1253  
  1254  type BGPOpen struct {
  1255  	Version     uint8
  1256  	MyAS        uint16
  1257  	HoldTime    uint16
  1258  	ID          net.IP
  1259  	OptParamLen uint8
  1260  	OptParams   []OptionParameterInterface
  1261  }
  1262  
  1263  func (msg *BGPOpen) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
  1264  	if len(data) < 10 {
  1265  		return NewMessageError(BGP_ERROR_MESSAGE_HEADER_ERROR, BGP_ERROR_SUB_BAD_MESSAGE_LENGTH, nil, "Not all BGP Open message bytes available")
  1266  	}
  1267  	msg.Version = data[0]
  1268  	msg.MyAS = binary.BigEndian.Uint16(data[1:3])
  1269  	msg.HoldTime = binary.BigEndian.Uint16(data[3:5])
  1270  	msg.ID = net.IP(data[5:9]).To4()
  1271  	msg.OptParamLen = data[9]
  1272  	data = data[10:]
  1273  	if len(data) < int(msg.OptParamLen) {
  1274  		return NewMessageError(BGP_ERROR_MESSAGE_HEADER_ERROR, BGP_ERROR_SUB_BAD_MESSAGE_LENGTH, nil, "Not all BGP Open message bytes available")
  1275  	}
  1276  
  1277  	msg.OptParams = []OptionParameterInterface{}
  1278  	for rest := msg.OptParamLen; rest > 0; {
  1279  		if rest < 2 {
  1280  			return NewMessageError(BGP_ERROR_MESSAGE_HEADER_ERROR, BGP_ERROR_SUB_BAD_MESSAGE_LENGTH, nil, "Malformed BGP Open message")
  1281  		}
  1282  		paramtype := data[0]
  1283  		paramlen := data[1]
  1284  		if paramlen >= 254 || rest < paramlen+2 {
  1285  			return NewMessageError(BGP_ERROR_MESSAGE_HEADER_ERROR, BGP_ERROR_SUB_BAD_MESSAGE_LENGTH, nil, "Malformed BGP Open message")
  1286  		}
  1287  		rest -= paramlen + 2
  1288  
  1289  		if paramtype == BGP_OPT_CAPABILITY {
  1290  			p := &OptionParameterCapability{}
  1291  			p.ParamType = paramtype
  1292  			p.ParamLen = paramlen
  1293  			p.DecodeFromBytes(data[2 : 2+paramlen])
  1294  			msg.OptParams = append(msg.OptParams, p)
  1295  		} else {
  1296  			p := &OptionParameterUnknown{}
  1297  			p.ParamType = paramtype
  1298  			p.ParamLen = paramlen
  1299  			p.Value = data[2 : 2+paramlen]
  1300  			msg.OptParams = append(msg.OptParams, p)
  1301  		}
  1302  		data = data[2+paramlen:]
  1303  	}
  1304  	return nil
  1305  }
  1306  
  1307  func (msg *BGPOpen) Serialize(options ...*MarshallingOption) ([]byte, error) {
  1308  	buf := make([]byte, 10)
  1309  	buf[0] = msg.Version
  1310  	binary.BigEndian.PutUint16(buf[1:3], msg.MyAS)
  1311  	binary.BigEndian.PutUint16(buf[3:5], msg.HoldTime)
  1312  	copy(buf[5:9], msg.ID.To4())
  1313  	pbuf := make([]byte, 0)
  1314  	for _, p := range msg.OptParams {
  1315  		onepbuf, err := p.Serialize()
  1316  		if err != nil {
  1317  			return nil, err
  1318  		}
  1319  		pbuf = append(pbuf, onepbuf...)
  1320  	}
  1321  	msg.OptParamLen = uint8(len(pbuf))
  1322  	buf[9] = msg.OptParamLen
  1323  	return append(buf, pbuf...), nil
  1324  }
  1325  
  1326  func NewBGPOpenMessage(myas uint16, holdtime uint16, id string, optparams []OptionParameterInterface) *BGPMessage {
  1327  	return &BGPMessage{
  1328  		Header: BGPHeader{Type: BGP_MSG_OPEN},
  1329  		Body:   &BGPOpen{4, myas, holdtime, net.ParseIP(id).To4(), 0, optparams},
  1330  	}
  1331  }
  1332  
  1333  type AddrPrefixInterface interface {
  1334  	DecodeFromBytes([]byte, ...*MarshallingOption) error
  1335  	Serialize(...*MarshallingOption) ([]byte, error)
  1336  	AFI() uint16
  1337  	SAFI() uint8
  1338  	Len(...*MarshallingOption) int
  1339  	String() string
  1340  	MarshalJSON() ([]byte, error)
  1341  	// Create a flat map to describe attributes and their
  1342  	// values. This can be used to create structured outputs.
  1343  	Flat() map[string]string
  1344  	PathIdentifier() uint32
  1345  	SetPathIdentifier(uint32)
  1346  	PathLocalIdentifier() uint32
  1347  	SetPathLocalIdentifier(uint32)
  1348  }
  1349  
  1350  func LabelString(nlri AddrPrefixInterface) string {
  1351  	label := ""
  1352  	switch n := nlri.(type) {
  1353  	case *LabeledIPAddrPrefix:
  1354  		label = n.Labels.String()
  1355  	case *LabeledIPv6AddrPrefix:
  1356  		label = n.Labels.String()
  1357  	case *LabeledVPNIPAddrPrefix:
  1358  		label = n.Labels.String()
  1359  	case *LabeledVPNIPv6AddrPrefix:
  1360  		label = n.Labels.String()
  1361  	case *EVPNNLRI:
  1362  		switch route := n.RouteTypeData.(type) {
  1363  		case *EVPNEthernetAutoDiscoveryRoute:
  1364  			label = fmt.Sprintf("[%d]", route.Label)
  1365  		case *EVPNMacIPAdvertisementRoute:
  1366  			ls := make([]string, len(route.Labels))
  1367  			for i, l := range route.Labels {
  1368  				ls[i] = strconv.Itoa(int(l))
  1369  			}
  1370  			label = fmt.Sprintf("[%s]", strings.Join(ls, ","))
  1371  		case *EVPNIPPrefixRoute:
  1372  			label = fmt.Sprintf("[%d]", route.Label)
  1373  		}
  1374  	}
  1375  	return label
  1376  }
  1377  
  1378  type PrefixDefault struct {
  1379  	mu      sync.Mutex
  1380  	id      uint32
  1381  	localId uint32
  1382  }
  1383  
  1384  func (p *PrefixDefault) PathIdentifier() uint32 {
  1385  	p.mu.Lock()
  1386  	defer p.mu.Unlock()
  1387  
  1388  	return p.id
  1389  }
  1390  
  1391  func (p *PrefixDefault) SetPathIdentifier(id uint32) {
  1392  	p.mu.Lock()
  1393  	defer p.mu.Unlock()
  1394  
  1395  	p.id = id
  1396  }
  1397  
  1398  func (p *PrefixDefault) PathLocalIdentifier() uint32 {
  1399  	p.mu.Lock()
  1400  	defer p.mu.Unlock()
  1401  
  1402  	return p.localId
  1403  }
  1404  
  1405  func (p *PrefixDefault) SetPathLocalIdentifier(id uint32) {
  1406  	p.mu.Lock()
  1407  	defer p.mu.Unlock()
  1408  
  1409  	p.localId = id
  1410  }
  1411  
  1412  func (p *PrefixDefault) decodePathIdentifier(data []byte) ([]byte, error) {
  1413  	if len(data) < 4 {
  1414  		code := uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR)
  1415  		subcode := uint8(BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST)
  1416  		return nil, NewMessageError(code, subcode, nil, "prefix misses path identifier field")
  1417  	}
  1418  	p.SetPathIdentifier(binary.BigEndian.Uint32(data[:4]))
  1419  	return data[4:], nil
  1420  }
  1421  
  1422  func (p *PrefixDefault) serializeIdentifier() ([]byte, error) {
  1423  	buf := make([]byte, 4)
  1424  	binary.BigEndian.PutUint32(buf, p.PathLocalIdentifier())
  1425  	return buf, nil
  1426  }
  1427  
  1428  type IPAddrPrefixDefault struct {
  1429  	PrefixDefault
  1430  	Length uint8
  1431  	Prefix net.IP
  1432  }
  1433  
  1434  func (r *IPAddrPrefixDefault) decodePrefix(data []byte, bitlen uint8, addrlen uint8) error {
  1435  	bytelen := (int(bitlen) + 7) / 8
  1436  	if len(data) < bytelen {
  1437  		eCode := uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR)
  1438  		eSubCode := uint8(BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST)
  1439  		return NewMessageError(eCode, eSubCode, nil, "network bytes is short")
  1440  	}
  1441  	if bitlen > addrlen*8 {
  1442  		eCode := uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR)
  1443  		eSubCode := uint8(BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST)
  1444  		return NewMessageError(eCode, eSubCode, nil, "network bit length is too long")
  1445  	}
  1446  	b := make([]byte, addrlen)
  1447  	copy(b, data[:bytelen])
  1448  	// clear trailing bits in the last byte. rfc doesn't require
  1449  	// this but some bgp implementations need this...
  1450  	rem := bitlen % 8
  1451  	if rem != 0 {
  1452  		mask := 0xff00 >> rem
  1453  		lastByte := b[bytelen-1] & byte(mask)
  1454  		b[bytelen-1] = lastByte
  1455  	}
  1456  	r.Prefix = b
  1457  	return nil
  1458  }
  1459  
  1460  func (r *IPAddrPrefixDefault) serializePrefix(bitLen uint8) ([]byte, error) {
  1461  	byteLen := (int(bitLen) + 7) / 8
  1462  	buf := make([]byte, byteLen)
  1463  	copy(buf, r.Prefix)
  1464  	return buf, nil
  1465  }
  1466  
  1467  func (r *IPAddrPrefixDefault) String() string {
  1468  	return r.Prefix.String() + "/" + strconv.FormatUint(uint64(r.Length), 10)
  1469  }
  1470  
  1471  func (r *IPAddrPrefixDefault) MarshalJSON() ([]byte, error) {
  1472  	return json.Marshal(struct {
  1473  		Prefix string `json:"prefix"`
  1474  	}{
  1475  		Prefix: r.String(),
  1476  	})
  1477  }
  1478  
  1479  type IPAddrPrefix struct {
  1480  	IPAddrPrefixDefault
  1481  	addrlen uint8
  1482  }
  1483  
  1484  func (r *IPAddrPrefix) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
  1485  	if r.addrlen == 0 {
  1486  		r.addrlen = 4
  1487  	}
  1488  	f := RF_IPv4_UC
  1489  	if r.addrlen == 16 {
  1490  		f = RF_IPv6_UC
  1491  	}
  1492  	if IsAddPathEnabled(true, f, options) {
  1493  		var err error
  1494  		data, err = r.decodePathIdentifier(data)
  1495  		if err != nil {
  1496  			return err
  1497  		}
  1498  	}
  1499  	if len(data) < 1 {
  1500  		eCode := uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR)
  1501  		eSubCode := uint8(BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST)
  1502  		return NewMessageError(eCode, eSubCode, nil, "prefix misses length field")
  1503  	}
  1504  	r.Length = data[0]
  1505  	return r.decodePrefix(data[1:], r.Length, r.addrlen)
  1506  }
  1507  
  1508  func (r *IPAddrPrefix) Serialize(options ...*MarshallingOption) ([]byte, error) {
  1509  	f := RF_IPv4_UC
  1510  	if r.addrlen == 16 {
  1511  		f = RF_IPv6_UC
  1512  	}
  1513  	var buf []byte
  1514  	if IsAddPathEnabled(false, f, options) {
  1515  		var err error
  1516  		buf, err = r.serializeIdentifier()
  1517  		if err != nil {
  1518  			return nil, err
  1519  		}
  1520  	}
  1521  	buf = append(buf, r.Length)
  1522  	pbuf, err := r.serializePrefix(r.Length)
  1523  	if err != nil {
  1524  		return nil, err
  1525  	}
  1526  	return append(buf, pbuf...), nil
  1527  }
  1528  
  1529  func (r *IPAddrPrefix) AFI() uint16 {
  1530  	return AFI_IP
  1531  }
  1532  
  1533  func (r *IPAddrPrefix) SAFI() uint8 {
  1534  	return SAFI_UNICAST
  1535  }
  1536  
  1537  func (r *IPAddrPrefix) Len(options ...*MarshallingOption) int {
  1538  	return 1 + ((int(r.Length) + 7) / 8)
  1539  }
  1540  
  1541  func NewIPAddrPrefix(length uint8, prefix string) *IPAddrPrefix {
  1542  	p := &IPAddrPrefix{
  1543  		IPAddrPrefixDefault{
  1544  			Length: length,
  1545  		},
  1546  		4,
  1547  	}
  1548  	p.IPAddrPrefixDefault.decodePrefix(net.ParseIP(prefix).To4(), length, 4)
  1549  	return p
  1550  }
  1551  
  1552  func isIPv4MappedIPv6(ip net.IP) bool {
  1553  	return len(ip) == net.IPv6len && ip.To4() != nil
  1554  }
  1555  
  1556  type IPv6AddrPrefix struct {
  1557  	IPAddrPrefix
  1558  }
  1559  
  1560  func (r *IPv6AddrPrefix) AFI() uint16 {
  1561  	return AFI_IP6
  1562  }
  1563  
  1564  func (r *IPv6AddrPrefix) String() string {
  1565  	prefix := r.Prefix.String()
  1566  	if isIPv4MappedIPv6(r.Prefix) {
  1567  		prefix = "::ffff:" + prefix
  1568  	}
  1569  	return prefix + "/" + strconv.FormatUint(uint64(r.Length), 10)
  1570  }
  1571  
  1572  func NewIPv6AddrPrefix(length uint8, prefix string) *IPv6AddrPrefix {
  1573  	p := &IPv6AddrPrefix{
  1574  		IPAddrPrefix{
  1575  			IPAddrPrefixDefault{
  1576  				Length: length,
  1577  			},
  1578  			16,
  1579  		},
  1580  	}
  1581  	p.IPAddrPrefixDefault.decodePrefix(net.ParseIP(prefix), length, 16)
  1582  	return p
  1583  }
  1584  
  1585  const (
  1586  	BGP_RD_TWO_OCTET_AS = iota
  1587  	BGP_RD_IPV4_ADDRESS
  1588  	BGP_RD_FOUR_OCTET_AS
  1589  	BGP_RD_EOR
  1590  )
  1591  
  1592  type RouteDistinguisherInterface interface {
  1593  	DecodeFromBytes([]byte) error
  1594  	Serialize() ([]byte, error)
  1595  	Len() int
  1596  	String() string
  1597  	MarshalJSON() ([]byte, error)
  1598  }
  1599  
  1600  type DefaultRouteDistinguisher struct {
  1601  	Type uint16
  1602  }
  1603  
  1604  func (rd *DefaultRouteDistinguisher) serialize(value []byte) ([]byte, error) {
  1605  	buf := make([]byte, 8)
  1606  	binary.BigEndian.PutUint16(buf, rd.Type)
  1607  	copy(buf[2:], value)
  1608  	return buf, nil
  1609  }
  1610  
  1611  func (rd *DefaultRouteDistinguisher) Len() int {
  1612  	return 8
  1613  }
  1614  
  1615  type RouteDistinguisherTwoOctetAS struct {
  1616  	DefaultRouteDistinguisher
  1617  	Admin    uint16
  1618  	Assigned uint32
  1619  }
  1620  
  1621  func (rd *RouteDistinguisherTwoOctetAS) DecodeFromBytes(data []byte) error {
  1622  	rd.Admin = binary.BigEndian.Uint16(data[0:2])
  1623  	rd.Assigned = binary.BigEndian.Uint32(data[2:6])
  1624  	return nil
  1625  }
  1626  
  1627  func (rd *RouteDistinguisherTwoOctetAS) Serialize() ([]byte, error) {
  1628  	buf := make([]byte, 6)
  1629  	binary.BigEndian.PutUint16(buf[0:2], rd.Admin)
  1630  	binary.BigEndian.PutUint32(buf[2:6], rd.Assigned)
  1631  	return rd.serialize(buf)
  1632  }
  1633  
  1634  func (rd *RouteDistinguisherTwoOctetAS) String() string {
  1635  	return fmt.Sprintf("%d:%d", rd.Admin, rd.Assigned)
  1636  }
  1637  
  1638  func (rd *RouteDistinguisherTwoOctetAS) MarshalJSON() ([]byte, error) {
  1639  	return json.Marshal(struct {
  1640  		Type     uint16 `json:"type"`
  1641  		Admin    uint16 `json:"admin"`
  1642  		Assigned uint32 `json:"assigned"`
  1643  	}{
  1644  		Type:     rd.Type,
  1645  		Admin:    rd.Admin,
  1646  		Assigned: rd.Assigned,
  1647  	})
  1648  }
  1649  
  1650  func NewRouteDistinguisherTwoOctetAS(admin uint16, assigned uint32) *RouteDistinguisherTwoOctetAS {
  1651  	return &RouteDistinguisherTwoOctetAS{
  1652  		DefaultRouteDistinguisher: DefaultRouteDistinguisher{
  1653  			Type: BGP_RD_TWO_OCTET_AS,
  1654  		},
  1655  		Admin:    admin,
  1656  		Assigned: assigned,
  1657  	}
  1658  }
  1659  
  1660  type RouteDistinguisherIPAddressAS struct {
  1661  	DefaultRouteDistinguisher
  1662  	Admin    net.IP
  1663  	Assigned uint16
  1664  }
  1665  
  1666  func (rd *RouteDistinguisherIPAddressAS) DecodeFromBytes(data []byte) error {
  1667  	rd.Admin = data[0:4]
  1668  	rd.Assigned = binary.BigEndian.Uint16(data[4:6])
  1669  	return nil
  1670  }
  1671  
  1672  func (rd *RouteDistinguisherIPAddressAS) Serialize() ([]byte, error) {
  1673  	buf := make([]byte, 6)
  1674  	copy(buf[0:4], rd.Admin.To4())
  1675  	binary.BigEndian.PutUint16(buf[4:6], rd.Assigned)
  1676  	return rd.serialize(buf)
  1677  }
  1678  
  1679  func (rd *RouteDistinguisherIPAddressAS) String() string {
  1680  	return fmt.Sprintf("%s:%d", rd.Admin.String(), rd.Assigned)
  1681  }
  1682  
  1683  func (rd *RouteDistinguisherIPAddressAS) MarshalJSON() ([]byte, error) {
  1684  	return json.Marshal(struct {
  1685  		Type     uint16 `json:"type"`
  1686  		Admin    string `json:"admin"`
  1687  		Assigned uint16 `json:"assigned"`
  1688  	}{
  1689  		Type:     rd.Type,
  1690  		Admin:    rd.Admin.String(),
  1691  		Assigned: rd.Assigned,
  1692  	})
  1693  }
  1694  
  1695  func NewRouteDistinguisherIPAddressAS(admin string, assigned uint16) *RouteDistinguisherIPAddressAS {
  1696  	return &RouteDistinguisherIPAddressAS{
  1697  		DefaultRouteDistinguisher: DefaultRouteDistinguisher{
  1698  			Type: BGP_RD_IPV4_ADDRESS,
  1699  		},
  1700  		Admin:    net.ParseIP(admin).To4(),
  1701  		Assigned: assigned,
  1702  	}
  1703  }
  1704  
  1705  type RouteDistinguisherFourOctetAS struct {
  1706  	DefaultRouteDistinguisher
  1707  	Admin    uint32
  1708  	Assigned uint16
  1709  }
  1710  
  1711  func (rd *RouteDistinguisherFourOctetAS) DecodeFromBytes(data []byte) error {
  1712  	rd.Admin = binary.BigEndian.Uint32(data[0:4])
  1713  	rd.Assigned = binary.BigEndian.Uint16(data[4:6])
  1714  	return nil
  1715  }
  1716  
  1717  func (rd *RouteDistinguisherFourOctetAS) Serialize() ([]byte, error) {
  1718  	buf := make([]byte, 6)
  1719  	binary.BigEndian.PutUint32(buf[0:4], rd.Admin)
  1720  	binary.BigEndian.PutUint16(buf[4:6], rd.Assigned)
  1721  	return rd.serialize(buf)
  1722  }
  1723  
  1724  func (rd *RouteDistinguisherFourOctetAS) String() string {
  1725  	fst := rd.Admin >> 16 & 0xffff
  1726  	snd := rd.Admin & 0xffff
  1727  	return fmt.Sprintf("%d.%d:%d", fst, snd, rd.Assigned)
  1728  }
  1729  
  1730  func (rd *RouteDistinguisherFourOctetAS) MarshalJSON() ([]byte, error) {
  1731  	return json.Marshal(struct {
  1732  		Type     uint16 `json:"type"`
  1733  		Admin    uint32 `json:"admin"`
  1734  		Assigned uint16 `json:"assigned"`
  1735  	}{
  1736  		Type:     rd.Type,
  1737  		Admin:    rd.Admin,
  1738  		Assigned: rd.Assigned,
  1739  	})
  1740  }
  1741  
  1742  func NewRouteDistinguisherFourOctetAS(admin uint32, assigned uint16) *RouteDistinguisherFourOctetAS {
  1743  	return &RouteDistinguisherFourOctetAS{
  1744  		DefaultRouteDistinguisher: DefaultRouteDistinguisher{
  1745  			Type: BGP_RD_FOUR_OCTET_AS,
  1746  		},
  1747  		Admin:    admin,
  1748  		Assigned: assigned,
  1749  	}
  1750  }
  1751  
  1752  type RouteDistinguisherUnknown struct {
  1753  	DefaultRouteDistinguisher
  1754  	Value []byte
  1755  }
  1756  
  1757  func (rd *RouteDistinguisherUnknown) DecodeFromBytes(data []byte) error {
  1758  	rd.Value = data[0:6]
  1759  	return nil
  1760  }
  1761  
  1762  func (rd *RouteDistinguisherUnknown) Serialize() ([]byte, error) {
  1763  	return rd.DefaultRouteDistinguisher.serialize(rd.Value)
  1764  }
  1765  
  1766  func (rd *RouteDistinguisherUnknown) String() string {
  1767  	return fmt.Sprintf("%v", rd.Value)
  1768  }
  1769  
  1770  func (rd *RouteDistinguisherUnknown) MarshalJSON() ([]byte, error) {
  1771  	return json.Marshal(struct {
  1772  		Type  uint16 `json:"type"`
  1773  		Value []byte `json:"value"`
  1774  	}{
  1775  		Type:  rd.Type,
  1776  		Value: rd.Value,
  1777  	})
  1778  }
  1779  
  1780  func GetRouteDistinguisher(data []byte) RouteDistinguisherInterface {
  1781  	typ := binary.BigEndian.Uint16(data[0:2])
  1782  	switch typ {
  1783  	case BGP_RD_TWO_OCTET_AS:
  1784  		return NewRouteDistinguisherTwoOctetAS(binary.BigEndian.Uint16(data[2:4]), binary.BigEndian.Uint32(data[4:8]))
  1785  	case BGP_RD_IPV4_ADDRESS:
  1786  		return NewRouteDistinguisherIPAddressAS(net.IP(data[2:6]).String(), binary.BigEndian.Uint16(data[6:8]))
  1787  	case BGP_RD_FOUR_OCTET_AS:
  1788  		return NewRouteDistinguisherFourOctetAS(binary.BigEndian.Uint32(data[2:6]), binary.BigEndian.Uint16(data[6:8]))
  1789  	}
  1790  	rd := &RouteDistinguisherUnknown{
  1791  		DefaultRouteDistinguisher: DefaultRouteDistinguisher{
  1792  			Type: typ,
  1793  		},
  1794  	}
  1795  	return rd
  1796  }
  1797  
  1798  func parseRdAndRt(input string) ([]string, error) {
  1799  	elems := _regexpRouteDistinguisher.FindStringSubmatch(input)
  1800  	if len(elems) != 11 {
  1801  		return nil, fmt.Errorf("failed to parse RD %q", input)
  1802  	}
  1803  	return elems, nil
  1804  }
  1805  
  1806  func ParseRouteDistinguisher(rd string) (RouteDistinguisherInterface, error) {
  1807  	elems, err := parseRdAndRt(rd)
  1808  	if err != nil {
  1809  		return nil, err
  1810  	}
  1811  	assigned, _ := strconv.ParseUint(elems[10], 10, 32)
  1812  	ip := net.ParseIP(elems[1])
  1813  	switch {
  1814  	case ip.To4() != nil:
  1815  		return NewRouteDistinguisherIPAddressAS(elems[1], uint16(assigned)), nil
  1816  	case elems[6] == "" && elems[7] == "":
  1817  		asn, _ := strconv.ParseUint(elems[8], 10, 16)
  1818  		return NewRouteDistinguisherTwoOctetAS(uint16(asn), uint32(assigned)), nil
  1819  	default:
  1820  		fst, _ := strconv.ParseUint(elems[7], 10, 16)
  1821  		snd, _ := strconv.ParseUint(elems[8], 10, 16)
  1822  		asn := fst<<16 | snd
  1823  		return NewRouteDistinguisherFourOctetAS(uint32(asn), uint16(assigned)), nil
  1824  	}
  1825  }
  1826  
  1827  // ParseVPNPrefix parses VPNv4/VPNv6 prefix.
  1828  func ParseVPNPrefix(prefix string) (RouteDistinguisherInterface, net.IP, *net.IPNet, error) {
  1829  	elems := strings.SplitN(prefix, ":", 3)
  1830  	if len(elems) < 3 {
  1831  		return nil, nil, nil, fmt.Errorf("invalid VPN prefix format: %q", prefix)
  1832  	}
  1833  
  1834  	rd, err := ParseRouteDistinguisher(elems[0] + ":" + elems[1])
  1835  	if err != nil {
  1836  		return nil, nil, nil, err
  1837  	}
  1838  
  1839  	addr, network, err := net.ParseCIDR(elems[2])
  1840  	return rd, addr, network, err
  1841  }
  1842  
  1843  // ContainsCIDR checks if one IPNet is a subnet of another.
  1844  func ContainsCIDR(n1, n2 *net.IPNet) bool {
  1845  	ones1, _ := n1.Mask.Size()
  1846  	ones2, _ := n2.Mask.Size()
  1847  	return ones1 <= ones2 && n1.Contains(n2.IP)
  1848  }
  1849  
  1850  //
  1851  // RFC3107 Carrying Label Information in BGP-4
  1852  //
  1853  // 3. Carrying Label Mapping Information
  1854  //
  1855  // b) Label:
  1856  //
  1857  // The Label field carries one or more labels (that corresponds to
  1858  // the stack of labels [MPLS-ENCAPS(RFC3032)]). Each label is encoded as
  1859  // 4 octets, where the high-order 20 bits contain the label value, and
  1860  // the low order bit contains "Bottom of Stack"
  1861  //
  1862  // RFC3032 MPLS Label Stack Encoding
  1863  //
  1864  // 2.1. Encoding the Label Stack
  1865  //
  1866  //  0       1       2               3
  1867  //  0 ... 9 0 ... 9 0 1 2 3 4 ... 9 0 1
  1868  // +-----+-+-+---+-+-+-+-+-+-----+-+-+-+
  1869  // |     Label     | Exp |S|    TTL    |
  1870  // +-----+-+-+---+-+-+-+-+-+-----+-+-+-+
  1871  //
  1872  
  1873  // RFC3107 Carrying Label Information in BGP-4
  1874  //
  1875  // 3. Carrying Label Mapping Information
  1876  //
  1877  // The label information carried (as part of NLRI) in the Withdrawn
  1878  // Routes field should be set to 0x800000.
  1879  const WITHDRAW_LABEL = uint32(0x800000)
  1880  const ZERO_LABEL = uint32(0) // some platform uses this as withdraw label
  1881  
  1882  type MPLSLabelStack struct {
  1883  	Labels []uint32
  1884  }
  1885  
  1886  func (l *MPLSLabelStack) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
  1887  	labels := []uint32{}
  1888  	foundBottom := false
  1889  	bottomExpected := true
  1890  	if IsAttributePresent(BGP_ATTR_TYPE_PREFIX_SID, options) {
  1891  		// If Update carries Prefix SID attribute then one should not rely on BoS for the label stack processing,
  1892  		// the first and only label carries transposed variable part of the SRv6 SID.
  1893  		bottomExpected = false
  1894  	}
  1895  	for len(data) >= 3 {
  1896  		label := uint32(data[0])<<16 | uint32(data[1])<<8 | uint32(data[2])
  1897  		if label == WITHDRAW_LABEL || label == ZERO_LABEL {
  1898  			l.Labels = []uint32{label}
  1899  			return nil
  1900  		}
  1901  		data = data[3:]
  1902  		labels = append(labels, label>>4)
  1903  		if !bottomExpected {
  1904  			// Faking found bottom.
  1905  			foundBottom = true
  1906  			break
  1907  		}
  1908  		if label&1 == 1 {
  1909  			foundBottom = true
  1910  			break
  1911  		}
  1912  	}
  1913  
  1914  	if !foundBottom {
  1915  		l.Labels = []uint32{}
  1916  		return nil
  1917  	}
  1918  	l.Labels = labels
  1919  	return nil
  1920  }
  1921  
  1922  func (l *MPLSLabelStack) Serialize(options ...*MarshallingOption) ([]byte, error) {
  1923  	buf := make([]byte, len(l.Labels)*3)
  1924  	for i, label := range l.Labels {
  1925  		if label == WITHDRAW_LABEL {
  1926  			return []byte{128, 0, 0}, nil
  1927  		}
  1928  		label = label << 4
  1929  		buf[i*3] = byte((label >> 16) & 0xff)
  1930  		buf[i*3+1] = byte((label >> 8) & 0xff)
  1931  		buf[i*3+2] = byte(label & 0xff)
  1932  	}
  1933  	buf[len(buf)-1] |= 1
  1934  	return buf, nil
  1935  }
  1936  
  1937  func (l *MPLSLabelStack) Len() int { return 3 * len(l.Labels) }
  1938  
  1939  func (l *MPLSLabelStack) String() string {
  1940  	if len(l.Labels) == 0 {
  1941  		return ""
  1942  	}
  1943  	s := bytes.NewBuffer(make([]byte, 0, 64))
  1944  	s.WriteString("[")
  1945  	ss := make([]string, 0, len(l.Labels))
  1946  	for _, label := range l.Labels {
  1947  		ss = append(ss, fmt.Sprintf("%d", label))
  1948  	}
  1949  	s.WriteString(strings.Join(ss, ", "))
  1950  	s.WriteString("]")
  1951  	return s.String()
  1952  }
  1953  
  1954  func NewMPLSLabelStack(labels ...uint32) *MPLSLabelStack {
  1955  	if len(labels) == 0 {
  1956  		labels = []uint32{0}
  1957  	}
  1958  	return &MPLSLabelStack{labels}
  1959  }
  1960  
  1961  func ParseMPLSLabelStack(buf string) (*MPLSLabelStack, error) {
  1962  	elems := strings.Split(buf, "/")
  1963  	labels := make([]uint32, 0, len(elems))
  1964  	if len(elems) == 0 {
  1965  		goto ERR
  1966  	}
  1967  	for _, elem := range elems {
  1968  		i, err := strconv.ParseUint(elem, 10, 32)
  1969  		if err != nil {
  1970  			goto ERR
  1971  		}
  1972  		if i > ((1 << 20) - 1) {
  1973  			goto ERR
  1974  		}
  1975  		labels = append(labels, uint32(i))
  1976  	}
  1977  	return NewMPLSLabelStack(labels...), nil
  1978  ERR:
  1979  	return nil, NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "invalid mpls label stack format")
  1980  }
  1981  
  1982  //
  1983  // RFC3107 Carrying Label Information in BGP-4
  1984  //
  1985  // 3. Carrying Label Mapping Information
  1986  //
  1987  // +----------------------+
  1988  // |   Length (1 octet)   |
  1989  // +----------------------+
  1990  // |   Label (3 octets)   |
  1991  // +----------------------+
  1992  // .......................
  1993  // +----------------------+
  1994  // |   Prefix (variable)  |
  1995  // +----------------------+
  1996  //
  1997  // RFC4364 BGP/MPLS IP VPNs
  1998  //
  1999  // 4.3.4. How VPN-IPv4 NLRI Is Carried in BGP
  2000  //
  2001  // The labeled VPN-IPv4 NLRI itself is encoded as specified in
  2002  // [MPLS-BGP(RFC3107)], where the prefix consists of an 8-byte RD
  2003  // followed by an IPv4 prefix.
  2004  //
  2005  
  2006  type LabeledVPNIPAddrPrefix struct {
  2007  	IPAddrPrefixDefault
  2008  	Labels  MPLSLabelStack
  2009  	RD      RouteDistinguisherInterface
  2010  	addrlen uint8
  2011  }
  2012  
  2013  func (l *LabeledVPNIPAddrPrefix) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
  2014  	f := RF_IPv4_VPN
  2015  	if l.addrlen == 16 {
  2016  		f = RF_IPv6_VPN
  2017  	}
  2018  	if IsAddPathEnabled(true, f, options) {
  2019  		var err error
  2020  		data, err = l.decodePathIdentifier(data)
  2021  		if err != nil {
  2022  			return err
  2023  		}
  2024  	}
  2025  	if len(data) < 1 {
  2026  		return NewMessageError(uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR), uint8(BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST), nil, "prefix misses length field")
  2027  	}
  2028  	l.Length = uint8(data[0])
  2029  	data = data[1:]
  2030  	l.Labels.DecodeFromBytes(data, options...)
  2031  	if int(l.Length)-8*(l.Labels.Len()) < 0 {
  2032  		l.Labels.Labels = []uint32{}
  2033  	}
  2034  	data = data[l.Labels.Len():]
  2035  	l.RD = GetRouteDistinguisher(data)
  2036  	rdLen := l.RD.Len()
  2037  	if len(data) < rdLen {
  2038  		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "bad labeled VPN-IPv4 NLRI length")
  2039  	}
  2040  	data = data[l.RD.Len():]
  2041  	restbits := int(l.Length) - 8*(l.Labels.Len()+l.RD.Len())
  2042  	return l.decodePrefix(data, uint8(restbits), l.addrlen)
  2043  }
  2044  
  2045  func (l *LabeledVPNIPAddrPrefix) Serialize(options ...*MarshallingOption) ([]byte, error) {
  2046  	f := RF_IPv4_VPN
  2047  	if l.addrlen == 16 {
  2048  		f = RF_IPv6_VPN
  2049  	}
  2050  	var buf []byte
  2051  	if IsAddPathEnabled(false, f, options) {
  2052  		var err error
  2053  		buf, err = l.serializeIdentifier()
  2054  		if err != nil {
  2055  			return nil, err
  2056  		}
  2057  	}
  2058  	buf = append(buf, l.Length)
  2059  	lbuf, err := l.Labels.Serialize(options...)
  2060  	if err != nil {
  2061  		return nil, err
  2062  	}
  2063  	buf = append(buf, lbuf...)
  2064  	rbuf, err := l.RD.Serialize()
  2065  	if err != nil {
  2066  		return nil, err
  2067  	}
  2068  	buf = append(buf, rbuf...)
  2069  	restbits := int(l.Length) - 8*(l.Labels.Len()+l.RD.Len())
  2070  	pbuf, err := l.serializePrefix(uint8(restbits))
  2071  	if err != nil {
  2072  		return nil, err
  2073  	}
  2074  	buf = append(buf, pbuf...)
  2075  	return buf, nil
  2076  }
  2077  
  2078  func (l *LabeledVPNIPAddrPrefix) AFI() uint16 {
  2079  	return AFI_IP
  2080  }
  2081  
  2082  func (l *LabeledVPNIPAddrPrefix) SAFI() uint8 {
  2083  	return SAFI_MPLS_VPN
  2084  }
  2085  
  2086  func (l *LabeledVPNIPAddrPrefix) IPPrefixLen() uint8 {
  2087  	return l.Length - 8*uint8(l.Labels.Len()+l.RD.Len())
  2088  }
  2089  
  2090  func (l *LabeledVPNIPAddrPrefix) Len(options ...*MarshallingOption) int {
  2091  	return 1 + l.Labels.Len() + l.RD.Len() + int((l.IPPrefixLen()+7)/8)
  2092  }
  2093  
  2094  func (l *LabeledVPNIPAddrPrefix) String() string {
  2095  	return l.RD.String() + ":" + l.IPPrefix()
  2096  }
  2097  
  2098  func (l *LabeledVPNIPAddrPrefix) IPPrefix() string {
  2099  	masklen := l.IPAddrPrefixDefault.Length - uint8(8*(l.Labels.Len()+l.RD.Len()))
  2100  	return l.IPAddrPrefixDefault.Prefix.String() + "/" + strconv.FormatUint(uint64(masklen), 10)
  2101  }
  2102  
  2103  func (l *LabeledVPNIPAddrPrefix) MarshalJSON() ([]byte, error) {
  2104  	masklen := l.IPAddrPrefixDefault.Length - uint8(8*(l.Labels.Len()+l.RD.Len()))
  2105  	return json.Marshal(struct {
  2106  		Prefix string                      `json:"prefix"`
  2107  		Labels []uint32                    `json:"labels"`
  2108  		RD     RouteDistinguisherInterface `json:"rd"`
  2109  	}{
  2110  		Prefix: fmt.Sprintf("%s/%d", l.IPAddrPrefixDefault.Prefix, masklen),
  2111  		Labels: l.Labels.Labels,
  2112  		RD:     l.RD,
  2113  	})
  2114  }
  2115  
  2116  func NewLabeledVPNIPAddrPrefix(length uint8, prefix string, label MPLSLabelStack, rd RouteDistinguisherInterface) *LabeledVPNIPAddrPrefix {
  2117  	rdlen := 0
  2118  	if rd != nil {
  2119  		rdlen = rd.Len()
  2120  	}
  2121  	return &LabeledVPNIPAddrPrefix{
  2122  		IPAddrPrefixDefault{
  2123  			Length: length + uint8(8*(label.Len()+rdlen)),
  2124  			Prefix: net.ParseIP(prefix).To4(),
  2125  		},
  2126  		label,
  2127  		rd,
  2128  		4,
  2129  	}
  2130  }
  2131  
  2132  type LabeledVPNIPv6AddrPrefix struct {
  2133  	LabeledVPNIPAddrPrefix
  2134  }
  2135  
  2136  func (l *LabeledVPNIPv6AddrPrefix) AFI() uint16 {
  2137  	return AFI_IP6
  2138  }
  2139  
  2140  func NewLabeledVPNIPv6AddrPrefix(length uint8, prefix string, label MPLSLabelStack, rd RouteDistinguisherInterface) *LabeledVPNIPv6AddrPrefix {
  2141  	rdlen := 0
  2142  	if rd != nil {
  2143  		rdlen = rd.Len()
  2144  	}
  2145  	return &LabeledVPNIPv6AddrPrefix{
  2146  		LabeledVPNIPAddrPrefix{
  2147  			IPAddrPrefixDefault{
  2148  				Length: length + uint8(8*(label.Len()+rdlen)),
  2149  				Prefix: net.ParseIP(prefix),
  2150  			},
  2151  			label,
  2152  			rd,
  2153  			16,
  2154  		},
  2155  	}
  2156  }
  2157  
  2158  type LabeledIPAddrPrefix struct {
  2159  	IPAddrPrefixDefault
  2160  	Labels  MPLSLabelStack
  2161  	addrlen uint8
  2162  }
  2163  
  2164  func (r *LabeledIPAddrPrefix) AFI() uint16 {
  2165  	return AFI_IP
  2166  }
  2167  
  2168  func (r *LabeledIPAddrPrefix) SAFI() uint8 {
  2169  	return SAFI_MPLS_LABEL
  2170  }
  2171  
  2172  func (l *LabeledIPAddrPrefix) IPPrefixLen() uint8 {
  2173  	return l.Length - 8*uint8(l.Labels.Len())
  2174  }
  2175  
  2176  func (l *LabeledIPAddrPrefix) Len(options ...*MarshallingOption) int {
  2177  	return 1 + l.Labels.Len() + int((l.IPPrefixLen()+7)/8)
  2178  }
  2179  
  2180  func (l *LabeledIPAddrPrefix) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
  2181  	f := RF_IPv4_MPLS
  2182  	if l.addrlen == 16 {
  2183  		f = RF_IPv6_MPLS
  2184  	}
  2185  	if IsAddPathEnabled(true, f, options) {
  2186  		var err error
  2187  		data, err = l.decodePathIdentifier(data)
  2188  		if err != nil {
  2189  			return err
  2190  		}
  2191  	}
  2192  	l.Length = uint8(data[0])
  2193  	data = data[1:]
  2194  	l.Labels.DecodeFromBytes(data)
  2195  
  2196  	if int(l.Length)-8*(l.Labels.Len()) < 0 {
  2197  		l.Labels.Labels = []uint32{}
  2198  	}
  2199  	restbits := int(l.Length) - 8*(l.Labels.Len())
  2200  	data = data[l.Labels.Len():]
  2201  	return l.decodePrefix(data, uint8(restbits), l.addrlen)
  2202  }
  2203  
  2204  func (l *LabeledIPAddrPrefix) Serialize(options ...*MarshallingOption) ([]byte, error) {
  2205  	f := RF_IPv4_MPLS
  2206  	if l.addrlen == 16 {
  2207  		f = RF_IPv6_MPLS
  2208  	}
  2209  	var buf []byte
  2210  	if IsAddPathEnabled(false, f, options) {
  2211  		var err error
  2212  		buf, err = l.serializeIdentifier()
  2213  		if err != nil {
  2214  			return nil, err
  2215  		}
  2216  	}
  2217  	buf = append(buf, l.Length)
  2218  	restbits := int(l.Length) - 8*(l.Labels.Len())
  2219  	lbuf, err := l.Labels.Serialize()
  2220  	if err != nil {
  2221  		return nil, err
  2222  	}
  2223  	buf = append(buf, lbuf...)
  2224  	pbuf, err := l.serializePrefix(uint8(restbits))
  2225  	if err != nil {
  2226  		return nil, err
  2227  	}
  2228  	buf = append(buf, pbuf...)
  2229  	return buf, nil
  2230  }
  2231  
  2232  func (l *LabeledIPAddrPrefix) String() string {
  2233  	prefix := l.Prefix.String()
  2234  	if isIPv4MappedIPv6(l.Prefix) {
  2235  		prefix = "::ffff:" + prefix
  2236  	}
  2237  	masklen := int(l.Length) - l.Labels.Len()*8
  2238  	return prefix + "/" + strconv.FormatUint(uint64(masklen), 10)
  2239  }
  2240  
  2241  func (l *LabeledIPAddrPrefix) MarshalJSON() ([]byte, error) {
  2242  	return json.Marshal(struct {
  2243  		Prefix string   `json:"prefix"`
  2244  		Labels []uint32 `json:"labels"`
  2245  	}{
  2246  		Prefix: l.String(),
  2247  		Labels: l.Labels.Labels,
  2248  	})
  2249  }
  2250  
  2251  func NewLabeledIPAddrPrefix(length uint8, prefix string, label MPLSLabelStack) *LabeledIPAddrPrefix {
  2252  	return &LabeledIPAddrPrefix{
  2253  		IPAddrPrefixDefault{
  2254  			Length: length + uint8(label.Len()*8),
  2255  			Prefix: net.ParseIP(prefix).To4(),
  2256  		},
  2257  		label,
  2258  		4,
  2259  	}
  2260  }
  2261  
  2262  type LabeledIPv6AddrPrefix struct {
  2263  	LabeledIPAddrPrefix
  2264  }
  2265  
  2266  func (l *LabeledIPv6AddrPrefix) AFI() uint16 {
  2267  	return AFI_IP6
  2268  }
  2269  
  2270  func NewLabeledIPv6AddrPrefix(length uint8, prefix string, label MPLSLabelStack) *LabeledIPv6AddrPrefix {
  2271  	return &LabeledIPv6AddrPrefix{
  2272  		LabeledIPAddrPrefix{
  2273  			IPAddrPrefixDefault{
  2274  				Length: length + uint8(label.Len()*8),
  2275  				Prefix: net.ParseIP(prefix),
  2276  			},
  2277  			label,
  2278  			16,
  2279  		},
  2280  	}
  2281  }
  2282  
  2283  type RouteTargetMembershipNLRI struct {
  2284  	PrefixDefault
  2285  	Length      uint8
  2286  	AS          uint32
  2287  	RouteTarget ExtendedCommunityInterface
  2288  }
  2289  
  2290  func (n *RouteTargetMembershipNLRI) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
  2291  	if IsAddPathEnabled(true, RF_RTC_UC, options) {
  2292  		var err error
  2293  		data, err = n.decodePathIdentifier(data)
  2294  		if err != nil {
  2295  			return err
  2296  		}
  2297  	}
  2298  	if len(data) < 1 {
  2299  		return NewMessageError(uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR), uint8(BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST), nil, "prefix misses length field")
  2300  	}
  2301  	n.Length = data[0]
  2302  	data = data[1 : n.Length/8+1]
  2303  	if len(data) == 0 {
  2304  		return nil
  2305  	} else if len(data) != 12 {
  2306  		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "Not all RouteTargetMembershipNLRI bytes available")
  2307  	}
  2308  	n.AS = binary.BigEndian.Uint32(data[0:4])
  2309  	rt, err := ParseExtended(data[4:])
  2310  	n.RouteTarget = rt
  2311  	if err != nil {
  2312  		return err
  2313  	}
  2314  	return nil
  2315  }
  2316  
  2317  func (n *RouteTargetMembershipNLRI) Serialize(options ...*MarshallingOption) ([]byte, error) {
  2318  	var buf []byte
  2319  	if IsAddPathEnabled(false, RF_RTC_UC, options) {
  2320  		var err error
  2321  		buf, err = n.serializeIdentifier()
  2322  		if err != nil {
  2323  			return nil, err
  2324  		}
  2325  	}
  2326  	if n.RouteTarget == nil {
  2327  		return append(buf, 0), nil
  2328  	}
  2329  	offset := len(buf)
  2330  	buf = append(buf, make([]byte, 5)...)
  2331  	buf[offset] = 96
  2332  	binary.BigEndian.PutUint32(buf[offset+1:], n.AS)
  2333  	ebuf, err := n.RouteTarget.Serialize()
  2334  	if err != nil {
  2335  		return nil, err
  2336  	}
  2337  	return append(buf, ebuf...), nil
  2338  }
  2339  
  2340  func (n *RouteTargetMembershipNLRI) AFI() uint16 {
  2341  	return AFI_IP
  2342  }
  2343  
  2344  func (n *RouteTargetMembershipNLRI) SAFI() uint8 {
  2345  	return SAFI_ROUTE_TARGET_CONSTRAINTS
  2346  }
  2347  
  2348  func (n *RouteTargetMembershipNLRI) Len(options ...*MarshallingOption) int {
  2349  	if n.AS == 0 && n.RouteTarget == nil {
  2350  		return 1
  2351  	}
  2352  	return 13
  2353  }
  2354  
  2355  func (n *RouteTargetMembershipNLRI) String() string {
  2356  	target := "default"
  2357  	if n.RouteTarget != nil {
  2358  		target = n.RouteTarget.String()
  2359  	}
  2360  	return strconv.FormatUint(uint64(n.AS), 10) + ":" + target
  2361  }
  2362  
  2363  func (n *RouteTargetMembershipNLRI) MarshalJSON() ([]byte, error) {
  2364  	return json.Marshal(struct {
  2365  		Prefix string `json:"prefix"`
  2366  	}{
  2367  		Prefix: n.String(),
  2368  	})
  2369  }
  2370  
  2371  func NewRouteTargetMembershipNLRI(as uint32, target ExtendedCommunityInterface) *RouteTargetMembershipNLRI {
  2372  	l := 12 * 8
  2373  	if as == 0 && target == nil {
  2374  		l = 1
  2375  	}
  2376  	return &RouteTargetMembershipNLRI{
  2377  		Length:      uint8(l),
  2378  		AS:          as,
  2379  		RouteTarget: target,
  2380  	}
  2381  }
  2382  
  2383  //go:generate stringer -type=ESIType
  2384  type ESIType uint8
  2385  
  2386  const (
  2387  	ESI_ARBITRARY ESIType = iota
  2388  	ESI_LACP
  2389  	ESI_MSTP
  2390  	ESI_MAC
  2391  	ESI_ROUTERID
  2392  	ESI_AS
  2393  )
  2394  
  2395  type EthernetSegmentIdentifier struct {
  2396  	Type  ESIType
  2397  	Value []byte
  2398  }
  2399  
  2400  func (esi *EthernetSegmentIdentifier) DecodeFromBytes(data []byte) error {
  2401  	if len(data) < 10 {
  2402  		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("invalid %s length", esi.Type.String()))
  2403  	}
  2404  	esi.Type = ESIType(data[0])
  2405  	esi.Value = data[1:10]
  2406  	switch esi.Type {
  2407  	case ESI_LACP, ESI_MSTP, ESI_ROUTERID, ESI_AS:
  2408  		if esi.Value[8] != 0x00 {
  2409  			return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("invalid %s. last octet must be 0x00 (0x%02x)", esi.Type.String(), esi.Value[8]))
  2410  		}
  2411  	}
  2412  	return nil
  2413  }
  2414  
  2415  func (esi *EthernetSegmentIdentifier) Serialize() ([]byte, error) {
  2416  	buf := make([]byte, 10)
  2417  	buf[0] = uint8(esi.Type)
  2418  	copy(buf[1:], esi.Value)
  2419  	return buf, nil
  2420  }
  2421  
  2422  func isZeroBuf(buf []byte) bool {
  2423  	for _, b := range buf {
  2424  		if b != 0 {
  2425  			return false
  2426  		}
  2427  	}
  2428  	return true
  2429  }
  2430  
  2431  func (esi *EthernetSegmentIdentifier) String() string {
  2432  	toHexArray := func(data []byte) string {
  2433  		// Converts byte slice into the colon separated hex values and the
  2434  		// number of elements are 9 at most (excluding Type field).
  2435  		values := make([]string, 0, 9)
  2436  		for _, v := range data {
  2437  			values = append(values, fmt.Sprintf("%02x", v))
  2438  		}
  2439  		return strings.Join(values, ":")
  2440  	}
  2441  
  2442  	s := bytes.NewBuffer(make([]byte, 0, 64))
  2443  	s.WriteString(fmt.Sprintf("%s | ", esi.Type.String()))
  2444  	switch esi.Type {
  2445  	case ESI_LACP:
  2446  		s.WriteString(fmt.Sprintf("system mac %s, ", net.HardwareAddr(esi.Value[:6]).String()))
  2447  		s.WriteString(fmt.Sprintf("port key %d", binary.BigEndian.Uint16(esi.Value[6:8])))
  2448  	case ESI_MSTP:
  2449  		s.WriteString(fmt.Sprintf("bridge mac %s, ", net.HardwareAddr(esi.Value[:6]).String()))
  2450  		s.WriteString(fmt.Sprintf("priority %d", binary.BigEndian.Uint16(esi.Value[6:8])))
  2451  	case ESI_MAC:
  2452  		s.WriteString(fmt.Sprintf("system mac %s, ", net.HardwareAddr(esi.Value[:6]).String()))
  2453  		s.WriteString(fmt.Sprintf("local discriminator %d", uint32(esi.Value[6])<<16|uint32(esi.Value[7])<<8|uint32(esi.Value[8])))
  2454  	case ESI_ROUTERID:
  2455  		s.WriteString(fmt.Sprintf("router id %s, ", net.IP(esi.Value[:4])))
  2456  		s.WriteString(fmt.Sprintf("local discriminator %d", binary.BigEndian.Uint32(esi.Value[4:8])))
  2457  	case ESI_AS:
  2458  		s.WriteString(fmt.Sprintf("as %d, ", binary.BigEndian.Uint32(esi.Value[:4])))
  2459  		s.WriteString(fmt.Sprintf("local discriminator %d", binary.BigEndian.Uint32(esi.Value[4:8])))
  2460  	case ESI_ARBITRARY:
  2461  		if isZeroBuf(esi.Value) {
  2462  			return "single-homed"
  2463  		}
  2464  		fallthrough
  2465  	default:
  2466  		s.WriteString(toHexArray(esi.Value))
  2467  	}
  2468  	return s.String()
  2469  }
  2470  
  2471  // Decode Ethernet Segment Identifier (ESI) from string slice.
  2472  //
  2473  // The first element of args should be the Type field (e.g., "ARBITRARY",
  2474  // "arbitrary", "ESI_ARBITRARY" or "esi_arbitrary") and "single-homed" is
  2475  // the special keyword for all zeroed ESI.
  2476  // For the "ARBITRARY" Value field (Type 0), it should be the colon separated
  2477  // hex values and the number of elements should be 9 at most.
  2478  //
  2479  //	e.g.) args := []string{"ARBITRARY", "11:22:33:44:55:66:77:88:99"}
  2480  //
  2481  // For the other types, the Value field format is the similar to the string
  2482  // format of ESI.
  2483  //
  2484  //	e.g.) args := []string{"lacp", "aa:bb:cc:dd:ee:ff", "100"}
  2485  func ParseEthernetSegmentIdentifier(args []string) (EthernetSegmentIdentifier, error) {
  2486  	esi := EthernetSegmentIdentifier{}
  2487  	argLen := len(args)
  2488  	if argLen == 0 || args[0] == "single-homed" {
  2489  		return esi, nil
  2490  	}
  2491  
  2492  	typeStr := strings.TrimPrefix(strings.ToUpper(args[0]), "ESI_")
  2493  	switch typeStr {
  2494  	case "ARBITRARY":
  2495  		esi.Type = ESI_ARBITRARY
  2496  	case "LACP":
  2497  		esi.Type = ESI_LACP
  2498  	case "MSTP":
  2499  		esi.Type = ESI_MSTP
  2500  	case "MAC":
  2501  		esi.Type = ESI_MAC
  2502  	case "ROUTERID":
  2503  		esi.Type = ESI_ROUTERID
  2504  	case "AS":
  2505  		esi.Type = ESI_AS
  2506  	default:
  2507  		typ, err := strconv.ParseUint(args[0], 10, 8)
  2508  		if err != nil {
  2509  			return esi, fmt.Errorf("invalid esi type: %s", args[0])
  2510  		}
  2511  		esi.Type = ESIType(typ)
  2512  	}
  2513  
  2514  	invalidEsiValuesError := fmt.Errorf("invalid esi values for type %s: %s", esi.Type.String(), args[1:])
  2515  	esi.Value = make([]byte, 9)
  2516  	switch esi.Type {
  2517  	case ESI_LACP:
  2518  		fallthrough
  2519  	case ESI_MSTP:
  2520  		if argLen < 3 {
  2521  			return esi, invalidEsiValuesError
  2522  		}
  2523  		// MAC
  2524  		mac, err := net.ParseMAC(args[1])
  2525  		if err != nil {
  2526  			return esi, invalidEsiValuesError
  2527  		}
  2528  		copy(esi.Value[0:6], mac)
  2529  		// Port Key or Bridge Priority
  2530  		i, err := strconv.ParseUint(args[2], 10, 16)
  2531  		if err != nil {
  2532  			return esi, invalidEsiValuesError
  2533  		}
  2534  		binary.BigEndian.PutUint16(esi.Value[6:8], uint16(i))
  2535  	case ESI_MAC:
  2536  		if argLen < 3 {
  2537  			return esi, invalidEsiValuesError
  2538  		}
  2539  		// MAC
  2540  		mac, err := net.ParseMAC(args[1])
  2541  		if err != nil {
  2542  			return esi, invalidEsiValuesError
  2543  		}
  2544  		copy(esi.Value[0:6], mac)
  2545  		// Local Discriminator
  2546  		i, err := strconv.ParseUint(args[2], 10, 32)
  2547  		if err != nil {
  2548  			return esi, invalidEsiValuesError
  2549  		}
  2550  		iBuf := make([]byte, 4)
  2551  		binary.BigEndian.PutUint32(iBuf, uint32(i))
  2552  		copy(esi.Value[6:9], iBuf[1:4])
  2553  	case ESI_ROUTERID:
  2554  		if argLen < 3 {
  2555  			return esi, invalidEsiValuesError
  2556  		}
  2557  		// Router ID
  2558  		ip := net.ParseIP(args[1])
  2559  		if ip == nil || ip.To4() == nil {
  2560  			return esi, invalidEsiValuesError
  2561  		}
  2562  		copy(esi.Value[0:4], ip.To4())
  2563  		// Local Discriminator
  2564  		i, err := strconv.ParseUint(args[2], 10, 32)
  2565  		if err != nil {
  2566  			return esi, invalidEsiValuesError
  2567  		}
  2568  		binary.BigEndian.PutUint32(esi.Value[4:8], uint32(i))
  2569  	case ESI_AS:
  2570  		if argLen < 3 {
  2571  			return esi, invalidEsiValuesError
  2572  		}
  2573  		// AS
  2574  		as, err := strconv.ParseUint(args[1], 10, 32)
  2575  		if err != nil {
  2576  			return esi, invalidEsiValuesError
  2577  		}
  2578  		binary.BigEndian.PutUint32(esi.Value[0:4], uint32(as))
  2579  		// Local Discriminator
  2580  		i, err := strconv.ParseUint(args[2], 10, 32)
  2581  		if err != nil {
  2582  			return esi, invalidEsiValuesError
  2583  		}
  2584  		binary.BigEndian.PutUint32(esi.Value[4:8], uint32(i))
  2585  	case ESI_ARBITRARY:
  2586  		fallthrough
  2587  	default:
  2588  		if argLen < 2 {
  2589  			// Assumes the Value field is omitted
  2590  			break
  2591  		}
  2592  		values := make([]byte, 0, 9)
  2593  		for _, e := range strings.SplitN(args[1], ":", 9) {
  2594  			v, err := strconv.ParseUint(e, 16, 16)
  2595  			if err != nil {
  2596  				return esi, invalidEsiValuesError
  2597  			}
  2598  			values = append(values, byte(v))
  2599  		}
  2600  		copy(esi.Value, values)
  2601  	}
  2602  
  2603  	return esi, nil
  2604  }
  2605  
  2606  //
  2607  // I-D bess-evpn-overlay-01
  2608  //
  2609  // 5.1.3 Constructing EVPN BGP Routes
  2610  //
  2611  // For the balance of this memo, the MPLS label field will be
  2612  // referred to as the VNI/VSID field. The VNI/VSID field is used for
  2613  // both local and global VNIs/VSIDs, and for either case the entire 24-
  2614  // bit field is used to encode the VNI/VSID value.
  2615  //
  2616  // We can't use type MPLSLabelStack for EVPN NLRI, because EVPN NLRI's MPLS
  2617  // field can be filled with VXLAN VNI. In that case, we must avoid modifying
  2618  // bottom of stack bit.
  2619  //
  2620  
  2621  func labelDecode(data []byte) (uint32, error) {
  2622  	if len(data) < 3 {
  2623  		return 0, NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "Not all Label bytes available")
  2624  	}
  2625  	return uint32(data[0])<<16 | uint32(data[1])<<8 | uint32(data[2]), nil
  2626  }
  2627  
  2628  func labelSerialize(label uint32) ([]byte, error) {
  2629  	if label > 0xffffff {
  2630  		return nil, NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("Out of range Label: %d", label))
  2631  	}
  2632  	buf := make([]byte, 3)
  2633  	buf[0] = byte((label >> 16) & 0xff)
  2634  	buf[1] = byte((label >> 8) & 0xff)
  2635  	buf[2] = byte(label & 0xff)
  2636  	return buf, nil
  2637  }
  2638  
  2639  type EVPNEthernetAutoDiscoveryRoute struct {
  2640  	RD    RouteDistinguisherInterface
  2641  	ESI   EthernetSegmentIdentifier
  2642  	ETag  uint32
  2643  	Label uint32
  2644  }
  2645  
  2646  func (er *EVPNEthernetAutoDiscoveryRoute) Len() int {
  2647  	// RD(8) + ESI(10) + ETag(4) + Label(3)
  2648  	return 25
  2649  }
  2650  
  2651  func (er *EVPNEthernetAutoDiscoveryRoute) DecodeFromBytes(data []byte) error {
  2652  	er.RD = GetRouteDistinguisher(data)
  2653  	rdLen := er.RD.Len()
  2654  	if len(data) < rdLen+14 { // 14 is 10 for
  2655  		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "bad Ethernet Auto-discovery Route length")
  2656  	}
  2657  	data = data[er.RD.Len():]
  2658  	err := er.ESI.DecodeFromBytes(data)
  2659  	if err != nil {
  2660  		return err
  2661  	}
  2662  	data = data[10:]
  2663  	er.ETag = binary.BigEndian.Uint32(data[0:4])
  2664  	data = data[4:]
  2665  	if er.Label, err = labelDecode(data); err != nil {
  2666  		return err
  2667  	}
  2668  	return nil
  2669  }
  2670  
  2671  func (er *EVPNEthernetAutoDiscoveryRoute) Serialize() ([]byte, error) {
  2672  	var buf []byte
  2673  	var err error
  2674  	if er.RD != nil {
  2675  		buf, err = er.RD.Serialize()
  2676  		if err != nil {
  2677  			return nil, err
  2678  		}
  2679  	} else {
  2680  		buf = make([]byte, 8)
  2681  	}
  2682  	tbuf, err := er.ESI.Serialize()
  2683  	if err != nil {
  2684  		return nil, err
  2685  	}
  2686  	buf = append(buf, tbuf...)
  2687  
  2688  	var tagBuf [4]byte
  2689  	binary.BigEndian.PutUint32(tagBuf[:4], er.ETag)
  2690  	buf = append(buf, tagBuf[:4]...)
  2691  
  2692  	tbuf, err = labelSerialize(er.Label)
  2693  	if err != nil {
  2694  		return nil, err
  2695  	}
  2696  	buf = append(buf, tbuf...)
  2697  
  2698  	return buf, nil
  2699  }
  2700  
  2701  func (er *EVPNEthernetAutoDiscoveryRoute) String() string {
  2702  	// RFC7432: BGP MPLS-Based Ethernet VPN
  2703  	// 7.1. Ethernet Auto-discovery Route
  2704  	// For the purpose of BGP route key processing, only the Ethernet
  2705  	// Segment Identifier and the Ethernet Tag ID are considered to be part
  2706  	// of the prefix in the NLRI.  The MPLS Label field is to be treated as
  2707  	// a route attribute as opposed to being part of the route.
  2708  	return fmt.Sprintf("[type:A-D][rd:%s][esi:%s][etag:%d]", er.RD, er.ESI.String(), er.ETag)
  2709  }
  2710  
  2711  func (er *EVPNEthernetAutoDiscoveryRoute) MarshalJSON() ([]byte, error) {
  2712  	return json.Marshal(struct {
  2713  		RD    RouteDistinguisherInterface `json:"rd"`
  2714  		ESI   string                      `json:"esi"`
  2715  		Etag  uint32                      `json:"etag"`
  2716  		Label uint32                      `json:"label"`
  2717  	}{
  2718  		RD:    er.RD,
  2719  		ESI:   er.ESI.String(),
  2720  		Etag:  er.ETag,
  2721  		Label: er.Label,
  2722  	})
  2723  }
  2724  
  2725  func (er *EVPNEthernetAutoDiscoveryRoute) rd() RouteDistinguisherInterface {
  2726  	return er.RD
  2727  }
  2728  
  2729  func NewEVPNEthernetAutoDiscoveryRoute(rd RouteDistinguisherInterface, esi EthernetSegmentIdentifier, etag uint32, label uint32) *EVPNNLRI {
  2730  	return NewEVPNNLRI(EVPN_ROUTE_TYPE_ETHERNET_AUTO_DISCOVERY, &EVPNEthernetAutoDiscoveryRoute{
  2731  		RD:    rd,
  2732  		ESI:   esi,
  2733  		ETag:  etag,
  2734  		Label: label,
  2735  	})
  2736  }
  2737  
  2738  type EVPNMacIPAdvertisementRoute struct {
  2739  	RD               RouteDistinguisherInterface
  2740  	ESI              EthernetSegmentIdentifier
  2741  	ETag             uint32
  2742  	MacAddressLength uint8
  2743  	MacAddress       net.HardwareAddr
  2744  	IPAddressLength  uint8
  2745  	IPAddress        net.IP
  2746  	Labels           []uint32
  2747  }
  2748  
  2749  func (er *EVPNMacIPAdvertisementRoute) Len() int {
  2750  	// RD(8) + ESI(10) + ETag(4) + MacAddressLength(1) + MacAddress(6)
  2751  	// + IPAddressLength(1) + IPAddress(0, 4 or 16) + Labels(3 or 6)
  2752  	return 30 + int(er.IPAddressLength)/8 + len(er.Labels)*3
  2753  }
  2754  
  2755  func (er *EVPNMacIPAdvertisementRoute) DecodeFromBytes(data []byte) error {
  2756  	er.RD = GetRouteDistinguisher(data)
  2757  	rdLen := er.RD.Len()
  2758  	if len(data) < rdLen {
  2759  		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "bad length of MAC/IP Advertisement Route")
  2760  	}
  2761  	data = data[er.RD.Len():]
  2762  	err := er.ESI.DecodeFromBytes(data)
  2763  	if err != nil {
  2764  		return err
  2765  	}
  2766  	data = data[10:]
  2767  	er.ETag = binary.BigEndian.Uint32(data[0:4])
  2768  	data = data[4:]
  2769  	er.MacAddressLength = data[0]
  2770  	er.MacAddress = net.HardwareAddr(data[1:7])
  2771  	er.IPAddressLength = data[7]
  2772  	data = data[8:]
  2773  	if er.IPAddressLength == 32 || er.IPAddressLength == 128 {
  2774  		er.IPAddress = net.IP(data[0:((er.IPAddressLength) / 8)])
  2775  	} else if er.IPAddressLength != 0 {
  2776  		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("Invalid IP address length: %d", er.IPAddressLength))
  2777  	}
  2778  	data = data[(er.IPAddressLength / 8):]
  2779  	var label uint32
  2780  	if label, err = labelDecode(data); err != nil {
  2781  		return err
  2782  	}
  2783  	er.Labels = append(er.Labels, label)
  2784  	data = data[3:]
  2785  	if len(data) == 3 {
  2786  		if label, err = labelDecode(data); err != nil {
  2787  			return err
  2788  		}
  2789  		er.Labels = append(er.Labels, label)
  2790  	}
  2791  	return nil
  2792  }
  2793  
  2794  func (er *EVPNMacIPAdvertisementRoute) Serialize() ([]byte, error) {
  2795  	var buf []byte
  2796  	var err error
  2797  	if er.RD != nil {
  2798  		buf, err = er.RD.Serialize()
  2799  		if err != nil {
  2800  			return nil, err
  2801  		}
  2802  	} else {
  2803  		buf = make([]byte, 8)
  2804  	}
  2805  
  2806  	esi, err := er.ESI.Serialize()
  2807  	if err != nil {
  2808  		return nil, err
  2809  	}
  2810  
  2811  	buf = append(buf, esi...)
  2812  	var tbuf [7]byte
  2813  	binary.BigEndian.PutUint32(tbuf[:4], er.ETag)
  2814  	buf = append(buf, tbuf[:4]...)
  2815  	tbuf[0] = er.MacAddressLength
  2816  	copy(tbuf[1:], er.MacAddress)
  2817  	buf = append(buf, tbuf[:7]...)
  2818  
  2819  	buf = append(buf, er.IPAddressLength)
  2820  	switch er.IPAddressLength {
  2821  	case 0:
  2822  		// IP address omitted
  2823  	case 32:
  2824  		buf = append(buf, []byte(er.IPAddress.To4())...)
  2825  	case 128:
  2826  		buf = append(buf, []byte(er.IPAddress.To16())...)
  2827  	default:
  2828  		return nil, fmt.Errorf("invalid IP address length: %d", er.IPAddressLength)
  2829  	}
  2830  
  2831  	for _, l := range er.Labels {
  2832  		label, err := labelSerialize(l)
  2833  		if err != nil {
  2834  			return nil, err
  2835  		}
  2836  		buf = append(buf, label...)
  2837  	}
  2838  	return buf, nil
  2839  }
  2840  
  2841  func (er *EVPNMacIPAdvertisementRoute) String() string {
  2842  	// RFC7432: BGP MPLS-Based Ethernet VPN
  2843  	// 7.2. MAC/IP Advertisement Route
  2844  	// For the purpose of BGP route key processing, only the Ethernet Tag
  2845  	// ID, MAC Address Length, MAC Address, IP Address Length, and IP
  2846  	// Address fields are considered to be part of the prefix in the NLRI.
  2847  	// The Ethernet Segment Identifier, MPLS Label1, and MPLS Label2 fields
  2848  	// are to be treated as route attributes as opposed to being part of the
  2849  	// "route".
  2850  	return fmt.Sprintf("[type:macadv][rd:%s][etag:%d][mac:%s][ip:%s]", er.RD, er.ETag, er.MacAddress, er.IPAddress)
  2851  }
  2852  
  2853  func (er *EVPNMacIPAdvertisementRoute) MarshalJSON() ([]byte, error) {
  2854  	return json.Marshal(struct {
  2855  		RD         RouteDistinguisherInterface `json:"rd"`
  2856  		ESI        string                      `json:"esi"`
  2857  		Etag       uint32                      `json:"etag"`
  2858  		MacAddress string                      `json:"mac"`
  2859  		IPAddress  string                      `json:"ip"`
  2860  		Labels     []uint32                    `json:"labels"`
  2861  	}{
  2862  		RD:         er.RD,
  2863  		ESI:        er.ESI.String(),
  2864  		Etag:       er.ETag,
  2865  		MacAddress: er.MacAddress.String(),
  2866  		IPAddress:  er.IPAddress.String(),
  2867  		Labels:     er.Labels,
  2868  	})
  2869  }
  2870  
  2871  func (er *EVPNMacIPAdvertisementRoute) rd() RouteDistinguisherInterface {
  2872  	return er.RD
  2873  }
  2874  
  2875  func NewEVPNMacIPAdvertisementRoute(rd RouteDistinguisherInterface, esi EthernetSegmentIdentifier, etag uint32, macAddress string, ipAddress string, labels []uint32) *EVPNNLRI {
  2876  	mac, _ := net.ParseMAC(macAddress)
  2877  	var ipLen uint8
  2878  	ip := net.ParseIP(ipAddress)
  2879  	if ip != nil {
  2880  		if ipv4 := ip.To4(); ipv4 != nil {
  2881  			ipLen = 32
  2882  			ip = ipv4
  2883  		} else {
  2884  			ipLen = 128
  2885  		}
  2886  	}
  2887  	return NewEVPNNLRI(EVPN_ROUTE_TYPE_MAC_IP_ADVERTISEMENT, &EVPNMacIPAdvertisementRoute{
  2888  		RD:               rd,
  2889  		ESI:              esi,
  2890  		ETag:             etag,
  2891  		MacAddressLength: 48,
  2892  		MacAddress:       mac,
  2893  		IPAddressLength:  ipLen,
  2894  		IPAddress:        ip,
  2895  		Labels:           labels,
  2896  	})
  2897  }
  2898  
  2899  type EVPNMulticastEthernetTagRoute struct {
  2900  	RD              RouteDistinguisherInterface
  2901  	ETag            uint32
  2902  	IPAddressLength uint8
  2903  	IPAddress       net.IP
  2904  }
  2905  
  2906  func (er *EVPNMulticastEthernetTagRoute) Len() int {
  2907  	// RD(8) + ETag(4) + IPAddressLength(1) + IPAddress(4 or 16)
  2908  	return 13 + int(er.IPAddressLength)/8
  2909  }
  2910  
  2911  func (er *EVPNMulticastEthernetTagRoute) DecodeFromBytes(data []byte) error {
  2912  	er.RD = GetRouteDistinguisher(data)
  2913  	rdLen := er.RD.Len()
  2914  	if len(data) < rdLen+4 {
  2915  		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "invalid length of multicast ethernet tag route")
  2916  	}
  2917  	data = data[er.RD.Len():]
  2918  	er.ETag = binary.BigEndian.Uint32(data[0:4])
  2919  	er.IPAddressLength = data[4]
  2920  	data = data[5:]
  2921  	if er.IPAddressLength == 32 || er.IPAddressLength == 128 {
  2922  		er.IPAddress = net.IP(data[:er.IPAddressLength/8])
  2923  	} else {
  2924  		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("Invalid IP address length: %d", er.IPAddressLength))
  2925  	}
  2926  	return nil
  2927  }
  2928  
  2929  func (er *EVPNMulticastEthernetTagRoute) Serialize() ([]byte, error) {
  2930  	var buf []byte
  2931  	var err error
  2932  	if er.RD != nil {
  2933  		buf, err = er.RD.Serialize()
  2934  		if err != nil {
  2935  			return nil, err
  2936  		}
  2937  	} else {
  2938  		buf = make([]byte, 8)
  2939  	}
  2940  	var tbuf [4]byte
  2941  	binary.BigEndian.PutUint32(tbuf[:4], er.ETag)
  2942  	buf = append(buf, tbuf[:4]...)
  2943  	buf = append(buf, er.IPAddressLength)
  2944  	switch er.IPAddressLength {
  2945  	case 32:
  2946  		buf = append(buf, []byte(er.IPAddress.To4())...)
  2947  	case 128:
  2948  		buf = append(buf, []byte(er.IPAddress.To16())...)
  2949  	default:
  2950  		return nil, fmt.Errorf("invalid IP address length: %d", er.IPAddressLength)
  2951  	}
  2952  	return buf, nil
  2953  }
  2954  
  2955  func (er *EVPNMulticastEthernetTagRoute) String() string {
  2956  	// RFC7432: BGP MPLS-Based Ethernet VPN
  2957  	// 7.3. Inclusive Multicast Ethernet Tag Route
  2958  	// ...(snip)... For the purpose of BGP route key
  2959  	// processing, only the Ethernet Tag ID, IP Address Length, and
  2960  	// Originating Router's IP Address fields are considered to be part of
  2961  	// the prefix in the NLRI.
  2962  	return fmt.Sprintf("[type:multicast][rd:%s][etag:%d][ip:%s]", er.RD, er.ETag, er.IPAddress)
  2963  }
  2964  
  2965  func (er *EVPNMulticastEthernetTagRoute) MarshalJSON() ([]byte, error) {
  2966  	return json.Marshal(struct {
  2967  		RD        RouteDistinguisherInterface `json:"rd"`
  2968  		Etag      uint32                      `json:"etag"`
  2969  		IPAddress string                      `json:"ip"`
  2970  	}{
  2971  		RD:        er.RD,
  2972  		Etag:      er.ETag,
  2973  		IPAddress: er.IPAddress.String(),
  2974  	})
  2975  }
  2976  
  2977  func (er *EVPNMulticastEthernetTagRoute) rd() RouteDistinguisherInterface {
  2978  	return er.RD
  2979  }
  2980  
  2981  func NewEVPNMulticastEthernetTagRoute(rd RouteDistinguisherInterface, etag uint32, ipAddress string) *EVPNNLRI {
  2982  	ipLen := uint8(32)
  2983  	ip := net.ParseIP(ipAddress)
  2984  	if ipv4 := ip.To4(); ipv4 != nil {
  2985  		ip = ipv4
  2986  	} else {
  2987  		ipLen = 128
  2988  	}
  2989  	return NewEVPNNLRI(EVPN_INCLUSIVE_MULTICAST_ETHERNET_TAG, &EVPNMulticastEthernetTagRoute{
  2990  		RD:              rd,
  2991  		ETag:            etag,
  2992  		IPAddressLength: ipLen,
  2993  		IPAddress:       ip,
  2994  	})
  2995  }
  2996  
  2997  type EVPNEthernetSegmentRoute struct {
  2998  	RD              RouteDistinguisherInterface
  2999  	ESI             EthernetSegmentIdentifier
  3000  	IPAddressLength uint8
  3001  	IPAddress       net.IP
  3002  }
  3003  
  3004  func (er *EVPNEthernetSegmentRoute) Len() int {
  3005  	// RD(8) + ESI(10) + IPAddressLength(1) + IPAddress(4 or 16)
  3006  	return 19 + int(er.IPAddressLength)/8
  3007  }
  3008  
  3009  func (er *EVPNEthernetSegmentRoute) DecodeFromBytes(data []byte) error {
  3010  	er.RD = GetRouteDistinguisher(data)
  3011  	rdLen := er.RD.Len()
  3012  	if len(data) < rdLen {
  3013  		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "invalid Ethernet Segment Route length")
  3014  	}
  3015  	data = data[er.RD.Len():]
  3016  	er.ESI.DecodeFromBytes(data)
  3017  	data = data[10:]
  3018  	er.IPAddressLength = data[0]
  3019  	data = data[1:]
  3020  	if er.IPAddressLength == 32 || er.IPAddressLength == 128 {
  3021  		er.IPAddress = net.IP(data[:er.IPAddressLength/8])
  3022  	} else {
  3023  		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("Invalid IP address length: %d", er.IPAddressLength))
  3024  	}
  3025  	return nil
  3026  }
  3027  
  3028  func (er *EVPNEthernetSegmentRoute) Serialize() ([]byte, error) {
  3029  	var buf []byte
  3030  	var err error
  3031  	if er.RD != nil {
  3032  		buf, err = er.RD.Serialize()
  3033  		if err != nil {
  3034  			return nil, err
  3035  		}
  3036  	} else {
  3037  		buf = make([]byte, 8)
  3038  	}
  3039  	tbuf, err := er.ESI.Serialize()
  3040  	if err != nil {
  3041  		return nil, err
  3042  	}
  3043  	buf = append(buf, tbuf...)
  3044  	buf = append(buf, er.IPAddressLength)
  3045  	switch er.IPAddressLength {
  3046  	case 32:
  3047  		buf = append(buf, []byte(er.IPAddress.To4())...)
  3048  	case 128:
  3049  		buf = append(buf, []byte(er.IPAddress.To16())...)
  3050  	default:
  3051  		return nil, fmt.Errorf("invalid IP address length: %d", er.IPAddressLength)
  3052  	}
  3053  	return buf, nil
  3054  }
  3055  
  3056  func (er *EVPNEthernetSegmentRoute) String() string {
  3057  	// RFC7432: BGP MPLS-Based Ethernet VPN
  3058  	// 7.4. Ethernet Segment Route
  3059  	// For the purpose of BGP route key processing, only the Ethernet
  3060  	// Segment ID, IP Address Length, and Originating Router's IP Address
  3061  	// fields are considered to be part of the prefix in the NLRI.
  3062  	return fmt.Sprintf("[type:esi][rd:%s][esi:%s][ip:%s]", er.RD, er.ESI.String(), er.IPAddress)
  3063  }
  3064  
  3065  func (er *EVPNEthernetSegmentRoute) MarshalJSON() ([]byte, error) {
  3066  	return json.Marshal(struct {
  3067  		RD        RouteDistinguisherInterface `json:"rd"`
  3068  		ESI       string                      `json:"esi"`
  3069  		IPAddress string                      `json:"ip"`
  3070  	}{
  3071  		RD:        er.RD,
  3072  		ESI:       er.ESI.String(),
  3073  		IPAddress: er.IPAddress.String(),
  3074  	})
  3075  }
  3076  
  3077  func (er *EVPNEthernetSegmentRoute) rd() RouteDistinguisherInterface {
  3078  	return er.RD
  3079  }
  3080  
  3081  func NewEVPNEthernetSegmentRoute(rd RouteDistinguisherInterface, esi EthernetSegmentIdentifier, ipAddress string) *EVPNNLRI {
  3082  	ipLen := uint8(32)
  3083  	ip := net.ParseIP(ipAddress)
  3084  	if ipv4 := ip.To4(); ipv4 != nil {
  3085  		ip = ipv4
  3086  	} else {
  3087  		ipLen = 128
  3088  	}
  3089  	return NewEVPNNLRI(EVPN_ETHERNET_SEGMENT_ROUTE, &EVPNEthernetSegmentRoute{
  3090  		RD:              rd,
  3091  		ESI:             esi,
  3092  		IPAddressLength: ipLen,
  3093  		IPAddress:       ip,
  3094  	})
  3095  }
  3096  
  3097  type EVPNIPPrefixRoute struct {
  3098  	RD             RouteDistinguisherInterface
  3099  	ESI            EthernetSegmentIdentifier
  3100  	ETag           uint32
  3101  	IPPrefixLength uint8
  3102  	IPPrefix       net.IP
  3103  	GWIPAddress    net.IP
  3104  	Label          uint32
  3105  }
  3106  
  3107  func (er *EVPNIPPrefixRoute) Len() int {
  3108  	if er.IPPrefix.To4() != nil {
  3109  		return 34
  3110  	}
  3111  	return 58
  3112  }
  3113  
  3114  func (er *EVPNIPPrefixRoute) DecodeFromBytes(data []byte) error {
  3115  	addrLen := net.IPv4len
  3116  	switch len(data) {
  3117  	case 34:
  3118  		// RD(8) + ESI(10) + ETag(4) + IPPrefixLength(1) + IPv4 Prefix(4) + GW IPv4(4) + Label(3)
  3119  	case 58:
  3120  		// RD(8) + ESI(10) + ETag(4) + IPPrefixLength(1) + IPv6 Prefix(16) + GW IPv6(16) + Label(3)
  3121  		addrLen = net.IPv6len
  3122  	default:
  3123  		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "Not all EVPN IP Prefix Route bytes available")
  3124  	}
  3125  
  3126  	er.RD = GetRouteDistinguisher(data[0:8])
  3127  
  3128  	err := er.ESI.DecodeFromBytes(data[8:18])
  3129  	if err != nil {
  3130  		return err
  3131  	}
  3132  
  3133  	er.ETag = binary.BigEndian.Uint32(data[18:22])
  3134  
  3135  	er.IPPrefixLength = data[22]
  3136  
  3137  	offset := 23 // RD(8) + ESI(10) + ETag(4) + IPPrefixLength(1)
  3138  	er.IPPrefix = data[offset : offset+addrLen]
  3139  	offset += addrLen
  3140  
  3141  	er.GWIPAddress = data[offset : offset+addrLen]
  3142  	offset += addrLen
  3143  
  3144  	if er.Label, err = labelDecode(data[offset : offset+3]); err != nil {
  3145  		return err
  3146  	}
  3147  	// offset += 3
  3148  
  3149  	return nil
  3150  }
  3151  
  3152  func (er *EVPNIPPrefixRoute) Serialize() ([]byte, error) {
  3153  	buf := make([]byte, 23) // RD(8) + ESI(10) + ETag(4) + IPPrefixLength(1)
  3154  
  3155  	if er.RD != nil {
  3156  		tbuf, err := er.RD.Serialize()
  3157  		if err != nil {
  3158  			return nil, err
  3159  		}
  3160  		copy(buf[0:8], tbuf)
  3161  	}
  3162  
  3163  	tbuf, err := er.ESI.Serialize()
  3164  	if err != nil {
  3165  		return nil, err
  3166  	}
  3167  	copy(buf[8:18], tbuf)
  3168  
  3169  	binary.BigEndian.PutUint32(buf[18:22], er.ETag)
  3170  
  3171  	buf[22] = er.IPPrefixLength
  3172  
  3173  	if er.IPPrefix == nil {
  3174  		return nil, NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "IP Prefix is nil")
  3175  	} else if er.IPPrefix.To4() != nil {
  3176  		buf = append(buf, er.IPPrefix.To4()...)
  3177  		if er.GWIPAddress == nil {
  3178  			// draft-ietf-bess-evpn-prefix-advertisement: IP Prefix Advertisement in EVPN
  3179  			// The GW IP field SHOULD be zero if it is not used as an Overlay Index.
  3180  			er.GWIPAddress = net.IPv4zero
  3181  		}
  3182  		buf = append(buf, er.GWIPAddress.To4()...)
  3183  	} else {
  3184  		buf = append(buf, er.IPPrefix.To16()...)
  3185  		if er.GWIPAddress == nil {
  3186  			er.GWIPAddress = net.IPv6zero
  3187  		}
  3188  		buf = append(buf, er.GWIPAddress.To16()...)
  3189  	}
  3190  
  3191  	tbuf, err = labelSerialize(er.Label)
  3192  	if err != nil {
  3193  		return nil, err
  3194  	}
  3195  	buf = append(buf, tbuf...)
  3196  
  3197  	return buf, nil
  3198  }
  3199  
  3200  func (er *EVPNIPPrefixRoute) String() string {
  3201  	// draft-ietf-bess-evpn-prefix-advertisement: IP Prefix Advertisement in EVPN
  3202  	// 3.1 IP Prefix Route Encoding
  3203  	// The RD, Eth-Tag ID, IP Prefix Length and IP Prefix will be part of
  3204  	// the route key used by BGP to compare routes. The rest of the fields
  3205  	// will not be part of the route key.
  3206  	return fmt.Sprintf("[type:Prefix][rd:%s][etag:%d][prefix:%s/%d]", er.RD, er.ETag, er.IPPrefix, er.IPPrefixLength)
  3207  }
  3208  
  3209  func (er *EVPNIPPrefixRoute) MarshalJSON() ([]byte, error) {
  3210  	return json.Marshal(struct {
  3211  		RD      RouteDistinguisherInterface `json:"rd"`
  3212  		ESI     string                      `json:"esi"`
  3213  		Etag    uint32                      `json:"etag"`
  3214  		Prefix  string                      `json:"prefix"`
  3215  		Gateway string                      `json:"gateway"`
  3216  		Label   uint32                      `json:"label"`
  3217  	}{
  3218  		RD:      er.RD,
  3219  		ESI:     er.ESI.String(),
  3220  		Etag:    er.ETag,
  3221  		Prefix:  fmt.Sprintf("%s/%d", er.IPPrefix, er.IPPrefixLength),
  3222  		Gateway: er.GWIPAddress.String(),
  3223  		Label:   er.Label,
  3224  	})
  3225  }
  3226  
  3227  func (er *EVPNIPPrefixRoute) rd() RouteDistinguisherInterface {
  3228  	return er.RD
  3229  }
  3230  
  3231  func NewEVPNIPPrefixRoute(rd RouteDistinguisherInterface, esi EthernetSegmentIdentifier, etag uint32, ipPrefixLength uint8, ipPrefix string, gateway string, label uint32) *EVPNNLRI {
  3232  	ip := net.ParseIP(ipPrefix)
  3233  	gw := net.ParseIP(gateway)
  3234  	if ipv4 := ip.To4(); ipv4 != nil {
  3235  		ip = ipv4
  3236  		gw = gw.To4()
  3237  	}
  3238  	return NewEVPNNLRI(EVPN_IP_PREFIX, &EVPNIPPrefixRoute{
  3239  		RD:             rd,
  3240  		ESI:            esi,
  3241  		ETag:           etag,
  3242  		IPPrefixLength: ipPrefixLength,
  3243  		IPPrefix:       ip,
  3244  		GWIPAddress:    gw,
  3245  		Label:          label,
  3246  	})
  3247  }
  3248  
  3249  type EVPNIPMSIRoute struct {
  3250  	RD   RouteDistinguisherInterface
  3251  	ETag uint32
  3252  	EC   ExtendedCommunityInterface
  3253  }
  3254  
  3255  func (er *EVPNIPMSIRoute) Len() int {
  3256  	// RD(8) + ETag(4) + EC(8)
  3257  	return 20
  3258  }
  3259  
  3260  func (er *EVPNIPMSIRoute) DecodeFromBytes(data []byte) error {
  3261  
  3262  	er.RD = GetRouteDistinguisher(data[0:8])
  3263  
  3264  	data = data[er.RD.Len():]
  3265  	er.ETag = binary.BigEndian.Uint32(data[0:4])
  3266  
  3267  	data = data[4:]
  3268  	ec, err := ParseExtended(data[0:8])
  3269  	if err != nil {
  3270  		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "Parse extended community interface failed")
  3271  	}
  3272  	er.EC = ec
  3273  	return nil
  3274  }
  3275  
  3276  func (er *EVPNIPMSIRoute) Serialize() ([]byte, error) {
  3277  	buf := make([]byte, 20)
  3278  
  3279  	if er.RD != nil {
  3280  		tbuf, err := er.RD.Serialize()
  3281  		if err != nil {
  3282  			return nil, err
  3283  		}
  3284  		copy(buf[0:8], tbuf)
  3285  	}
  3286  
  3287  	binary.BigEndian.PutUint32(buf[8:12], er.ETag)
  3288  
  3289  	ec, err := er.EC.Serialize()
  3290  	if err != nil {
  3291  		return nil, err
  3292  	}
  3293  
  3294  	return append(buf, ec...), nil
  3295  }
  3296  
  3297  func (er *EVPNIPMSIRoute) String() string {
  3298  	ec := "default"
  3299  	if er.EC != nil {
  3300  		ec = er.EC.String()
  3301  	}
  3302  	return fmt.Sprintf("[type:I-PMSI][rd:%s][etag:%d][EC:%s]", er.RD, er.ETag, ec)
  3303  }
  3304  
  3305  func (er *EVPNIPMSIRoute) MarshalJSON() ([]byte, error) {
  3306  	return json.Marshal(struct {
  3307  		RD   RouteDistinguisherInterface `json:"rd"`
  3308  		ETag uint32                      `json:"etag"`
  3309  		EC   string                      `json:"ec"`
  3310  	}{
  3311  		RD:   er.RD,
  3312  		ETag: er.ETag,
  3313  		EC:   er.EC.String(),
  3314  	})
  3315  }
  3316  
  3317  func (er *EVPNIPMSIRoute) rd() RouteDistinguisherInterface {
  3318  	return er.RD
  3319  }
  3320  
  3321  func NewEVPNIPMSIRoute(rd RouteDistinguisherInterface, etag uint32, ec ExtendedCommunityInterface) *EVPNNLRI {
  3322  
  3323  	return NewEVPNNLRI(EVPN_I_PMSI, &EVPNIPMSIRoute{
  3324  		RD:   rd,
  3325  		ETag: etag,
  3326  		EC:   ec,
  3327  	})
  3328  }
  3329  
  3330  type EVPNRouteTypeInterface interface {
  3331  	Len() int
  3332  	DecodeFromBytes([]byte) error
  3333  	Serialize() ([]byte, error)
  3334  	String() string
  3335  	rd() RouteDistinguisherInterface
  3336  	MarshalJSON() ([]byte, error)
  3337  }
  3338  
  3339  func getEVPNRouteType(t uint8) (EVPNRouteTypeInterface, error) {
  3340  	switch t {
  3341  	case EVPN_ROUTE_TYPE_ETHERNET_AUTO_DISCOVERY:
  3342  		return &EVPNEthernetAutoDiscoveryRoute{}, nil
  3343  	case EVPN_ROUTE_TYPE_MAC_IP_ADVERTISEMENT:
  3344  		return &EVPNMacIPAdvertisementRoute{}, nil
  3345  	case EVPN_INCLUSIVE_MULTICAST_ETHERNET_TAG:
  3346  		return &EVPNMulticastEthernetTagRoute{}, nil
  3347  	case EVPN_ETHERNET_SEGMENT_ROUTE:
  3348  		return &EVPNEthernetSegmentRoute{}, nil
  3349  	case EVPN_IP_PREFIX:
  3350  		return &EVPNIPPrefixRoute{}, nil
  3351  	}
  3352  	return nil, NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("Unknown EVPN Route type: %d", t))
  3353  }
  3354  
  3355  const (
  3356  	EVPN_ROUTE_TYPE_ETHERNET_AUTO_DISCOVERY = 1
  3357  	EVPN_ROUTE_TYPE_MAC_IP_ADVERTISEMENT    = 2
  3358  	EVPN_INCLUSIVE_MULTICAST_ETHERNET_TAG   = 3
  3359  	EVPN_ETHERNET_SEGMENT_ROUTE             = 4
  3360  	EVPN_IP_PREFIX                          = 5
  3361  	EVPN_I_PMSI                             = 9
  3362  )
  3363  
  3364  type EVPNNLRI struct {
  3365  	PrefixDefault
  3366  	RouteType     uint8
  3367  	Length        uint8
  3368  	RouteTypeData EVPNRouteTypeInterface
  3369  }
  3370  
  3371  func (n *EVPNNLRI) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
  3372  	if IsAddPathEnabled(true, RF_EVPN, options) {
  3373  		var err error
  3374  		data, err = n.decodePathIdentifier(data)
  3375  		if err != nil {
  3376  			return err
  3377  		}
  3378  	}
  3379  	if len(data) < 2 {
  3380  		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "Not all EVPNNLRI bytes available")
  3381  	}
  3382  	n.RouteType = data[0]
  3383  	n.Length = data[1]
  3384  	data = data[2:]
  3385  	if len(data) < int(n.Length) {
  3386  		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "Not all EVPNNLRI Route type bytes available")
  3387  	}
  3388  	r, err := getEVPNRouteType(n.RouteType)
  3389  	if err != nil {
  3390  		return err
  3391  	}
  3392  	n.RouteTypeData = r
  3393  	return n.RouteTypeData.DecodeFromBytes(data[:n.Length])
  3394  }
  3395  
  3396  func (n *EVPNNLRI) Serialize(options ...*MarshallingOption) ([]byte, error) {
  3397  	var buf []byte
  3398  	if IsAddPathEnabled(false, RF_EVPN, options) {
  3399  		var err error
  3400  		buf, err = n.serializeIdentifier()
  3401  		if err != nil {
  3402  			return nil, err
  3403  		}
  3404  	}
  3405  	offset := len(buf)
  3406  	buf = append(buf, make([]byte, 2)...)
  3407  	buf[offset] = n.RouteType
  3408  	tbuf, err := n.RouteTypeData.Serialize()
  3409  	buf[offset+1] = n.Length
  3410  	if err != nil {
  3411  		return nil, err
  3412  	}
  3413  	return append(buf, tbuf...), nil
  3414  }
  3415  
  3416  func (n *EVPNNLRI) AFI() uint16 {
  3417  	return AFI_L2VPN
  3418  }
  3419  
  3420  func (n *EVPNNLRI) SAFI() uint8 {
  3421  	return SAFI_EVPN
  3422  }
  3423  
  3424  func (n *EVPNNLRI) Len(options ...*MarshallingOption) int {
  3425  	return int(n.Length) + 2
  3426  }
  3427  
  3428  func (n *EVPNNLRI) String() string {
  3429  	if n.RouteTypeData != nil {
  3430  		return n.RouteTypeData.String()
  3431  	}
  3432  	return strconv.FormatUint(uint64(n.RouteType), 10) + ":" + strconv.FormatUint(uint64(n.Length), 10)
  3433  }
  3434  
  3435  func (n *EVPNNLRI) MarshalJSON() ([]byte, error) {
  3436  	return json.Marshal(struct {
  3437  		Type  uint8                  `json:"type"`
  3438  		Value EVPNRouteTypeInterface `json:"value"`
  3439  	}{
  3440  		Type:  n.RouteType,
  3441  		Value: n.RouteTypeData,
  3442  	})
  3443  }
  3444  
  3445  func (n *EVPNNLRI) RD() RouteDistinguisherInterface {
  3446  	return n.RouteTypeData.rd()
  3447  }
  3448  
  3449  func NewEVPNNLRI(routeType uint8, routeTypeData EVPNRouteTypeInterface) *EVPNNLRI {
  3450  	var l uint8
  3451  	if routeTypeData != nil {
  3452  		l = uint8(routeTypeData.Len())
  3453  	}
  3454  	return &EVPNNLRI{
  3455  		RouteType:     routeType,
  3456  		Length:        l,
  3457  		RouteTypeData: routeTypeData,
  3458  	}
  3459  }
  3460  
  3461  type EncapNLRI struct {
  3462  	IPAddrPrefixDefault
  3463  	addrlen uint8
  3464  }
  3465  
  3466  func (n *EncapNLRI) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
  3467  	if n.addrlen == 0 {
  3468  		n.addrlen = 4
  3469  	}
  3470  	f := RF_IPv4_ENCAP
  3471  	if n.addrlen == 16 {
  3472  		f = RF_IPv6_ENCAP
  3473  	}
  3474  	if IsAddPathEnabled(true, f, options) {
  3475  		var err error
  3476  		data, err = n.decodePathIdentifier(data)
  3477  		if err != nil {
  3478  			return err
  3479  		}
  3480  	}
  3481  	if len(data) < 4 {
  3482  		eCode := uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR)
  3483  		eSubCode := uint8(BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST)
  3484  		return NewMessageError(eCode, eSubCode, nil, "prefix misses length field")
  3485  	}
  3486  	n.Length = data[0]
  3487  	if n.addrlen == 0 {
  3488  		n.addrlen = 4
  3489  	}
  3490  	return n.decodePrefix(data[1:], n.Length, n.addrlen)
  3491  }
  3492  
  3493  func (n *EncapNLRI) Serialize(options ...*MarshallingOption) ([]byte, error) {
  3494  	var buf []byte
  3495  	f := RF_IPv4_ENCAP
  3496  	if n.addrlen == 16 {
  3497  		f = RF_IPv6_ENCAP
  3498  	}
  3499  	if IsAddPathEnabled(false, f, options) {
  3500  		var err error
  3501  		buf, err = n.serializeIdentifier()
  3502  		if err != nil {
  3503  			return nil, err
  3504  		}
  3505  	}
  3506  	if n.Prefix.To4() != nil {
  3507  		buf = append(buf, net.IPv4len*8)
  3508  		n.Prefix = n.Prefix.To4()
  3509  	} else {
  3510  		buf = append(buf, net.IPv6len*8)
  3511  	}
  3512  	n.Length = buf[len(buf)-1]
  3513  	pbuf, err := n.serializePrefix(n.Length)
  3514  	if err != nil {
  3515  		return nil, err
  3516  	}
  3517  	return append(buf, pbuf...), nil
  3518  }
  3519  
  3520  func (n *EncapNLRI) String() string {
  3521  	return n.Prefix.String()
  3522  }
  3523  
  3524  func (n *EncapNLRI) AFI() uint16 {
  3525  	return AFI_IP
  3526  }
  3527  
  3528  func (n *EncapNLRI) SAFI() uint8 {
  3529  	return SAFI_ENCAPSULATION
  3530  }
  3531  
  3532  func (n *EncapNLRI) Len(options ...*MarshallingOption) int {
  3533  	return 1 + len(n.Prefix)
  3534  }
  3535  
  3536  func NewEncapNLRI(endpoint string) *EncapNLRI {
  3537  	return &EncapNLRI{
  3538  		IPAddrPrefixDefault{Length: 32, Prefix: net.ParseIP(endpoint).To4()},
  3539  		4,
  3540  	}
  3541  }
  3542  
  3543  type Encapv6NLRI struct {
  3544  	EncapNLRI
  3545  }
  3546  
  3547  func (n *Encapv6NLRI) AFI() uint16 {
  3548  	return AFI_IP6
  3549  }
  3550  
  3551  func NewEncapv6NLRI(endpoint string) *Encapv6NLRI {
  3552  	return &Encapv6NLRI{
  3553  		EncapNLRI{
  3554  			IPAddrPrefixDefault{Length: 128, Prefix: net.ParseIP(endpoint)},
  3555  			16,
  3556  		},
  3557  	}
  3558  }
  3559  
  3560  type BGPFlowSpecType uint8
  3561  
  3562  const (
  3563  	FLOW_SPEC_TYPE_UNKNOWN BGPFlowSpecType = iota
  3564  	FLOW_SPEC_TYPE_DST_PREFIX
  3565  	FLOW_SPEC_TYPE_SRC_PREFIX
  3566  	FLOW_SPEC_TYPE_IP_PROTO
  3567  	FLOW_SPEC_TYPE_PORT
  3568  	FLOW_SPEC_TYPE_DST_PORT
  3569  	FLOW_SPEC_TYPE_SRC_PORT
  3570  	FLOW_SPEC_TYPE_ICMP_TYPE
  3571  	FLOW_SPEC_TYPE_ICMP_CODE
  3572  	FLOW_SPEC_TYPE_TCP_FLAG
  3573  	FLOW_SPEC_TYPE_PKT_LEN
  3574  	FLOW_SPEC_TYPE_DSCP
  3575  	FLOW_SPEC_TYPE_FRAGMENT
  3576  	FLOW_SPEC_TYPE_LABEL
  3577  	FLOW_SPEC_TYPE_ETHERNET_TYPE // 14
  3578  	FLOW_SPEC_TYPE_SRC_MAC
  3579  	FLOW_SPEC_TYPE_DST_MAC
  3580  	FLOW_SPEC_TYPE_LLC_DSAP
  3581  	FLOW_SPEC_TYPE_LLC_SSAP
  3582  	FLOW_SPEC_TYPE_LLC_CONTROL
  3583  	FLOW_SPEC_TYPE_SNAP
  3584  	FLOW_SPEC_TYPE_VID
  3585  	FLOW_SPEC_TYPE_COS
  3586  	FLOW_SPEC_TYPE_INNER_VID
  3587  	FLOW_SPEC_TYPE_INNER_COS
  3588  )
  3589  
  3590  var FlowSpecNameMap = map[BGPFlowSpecType]string{
  3591  	FLOW_SPEC_TYPE_UNKNOWN:       "unknown",
  3592  	FLOW_SPEC_TYPE_DST_PREFIX:    "destination",
  3593  	FLOW_SPEC_TYPE_SRC_PREFIX:    "source",
  3594  	FLOW_SPEC_TYPE_IP_PROTO:      "protocol",
  3595  	FLOW_SPEC_TYPE_PORT:          "port",
  3596  	FLOW_SPEC_TYPE_DST_PORT:      "destination-port",
  3597  	FLOW_SPEC_TYPE_SRC_PORT:      "source-port",
  3598  	FLOW_SPEC_TYPE_ICMP_TYPE:     "icmp-type",
  3599  	FLOW_SPEC_TYPE_ICMP_CODE:     "icmp-code",
  3600  	FLOW_SPEC_TYPE_TCP_FLAG:      "tcp-flags",
  3601  	FLOW_SPEC_TYPE_PKT_LEN:       "packet-length",
  3602  	FLOW_SPEC_TYPE_DSCP:          "dscp",
  3603  	FLOW_SPEC_TYPE_FRAGMENT:      "fragment",
  3604  	FLOW_SPEC_TYPE_LABEL:         "label",
  3605  	FLOW_SPEC_TYPE_ETHERNET_TYPE: "ether-type",
  3606  	FLOW_SPEC_TYPE_SRC_MAC:       "source-mac",
  3607  	FLOW_SPEC_TYPE_DST_MAC:       "destination-mac",
  3608  	FLOW_SPEC_TYPE_LLC_DSAP:      "llc-dsap",
  3609  	FLOW_SPEC_TYPE_LLC_SSAP:      "llc-ssap",
  3610  	FLOW_SPEC_TYPE_LLC_CONTROL:   "llc-control",
  3611  	FLOW_SPEC_TYPE_SNAP:          "snap",
  3612  	FLOW_SPEC_TYPE_VID:           "vid",
  3613  	FLOW_SPEC_TYPE_COS:           "cos",
  3614  	FLOW_SPEC_TYPE_INNER_VID:     "inner-vid",
  3615  	FLOW_SPEC_TYPE_INNER_COS:     "inner-cos",
  3616  }
  3617  
  3618  var FlowSpecValueMap = map[string]BGPFlowSpecType{
  3619  	FlowSpecNameMap[FLOW_SPEC_TYPE_DST_PREFIX]:    FLOW_SPEC_TYPE_DST_PREFIX,
  3620  	FlowSpecNameMap[FLOW_SPEC_TYPE_SRC_PREFIX]:    FLOW_SPEC_TYPE_SRC_PREFIX,
  3621  	FlowSpecNameMap[FLOW_SPEC_TYPE_IP_PROTO]:      FLOW_SPEC_TYPE_IP_PROTO,
  3622  	FlowSpecNameMap[FLOW_SPEC_TYPE_PORT]:          FLOW_SPEC_TYPE_PORT,
  3623  	FlowSpecNameMap[FLOW_SPEC_TYPE_DST_PORT]:      FLOW_SPEC_TYPE_DST_PORT,
  3624  	FlowSpecNameMap[FLOW_SPEC_TYPE_SRC_PORT]:      FLOW_SPEC_TYPE_SRC_PORT,
  3625  	FlowSpecNameMap[FLOW_SPEC_TYPE_ICMP_TYPE]:     FLOW_SPEC_TYPE_ICMP_TYPE,
  3626  	FlowSpecNameMap[FLOW_SPEC_TYPE_ICMP_CODE]:     FLOW_SPEC_TYPE_ICMP_CODE,
  3627  	FlowSpecNameMap[FLOW_SPEC_TYPE_TCP_FLAG]:      FLOW_SPEC_TYPE_TCP_FLAG,
  3628  	FlowSpecNameMap[FLOW_SPEC_TYPE_PKT_LEN]:       FLOW_SPEC_TYPE_PKT_LEN,
  3629  	FlowSpecNameMap[FLOW_SPEC_TYPE_DSCP]:          FLOW_SPEC_TYPE_DSCP,
  3630  	FlowSpecNameMap[FLOW_SPEC_TYPE_FRAGMENT]:      FLOW_SPEC_TYPE_FRAGMENT,
  3631  	FlowSpecNameMap[FLOW_SPEC_TYPE_LABEL]:         FLOW_SPEC_TYPE_LABEL,
  3632  	FlowSpecNameMap[FLOW_SPEC_TYPE_ETHERNET_TYPE]: FLOW_SPEC_TYPE_ETHERNET_TYPE,
  3633  	FlowSpecNameMap[FLOW_SPEC_TYPE_SRC_MAC]:       FLOW_SPEC_TYPE_SRC_MAC,
  3634  	FlowSpecNameMap[FLOW_SPEC_TYPE_DST_MAC]:       FLOW_SPEC_TYPE_DST_MAC,
  3635  	FlowSpecNameMap[FLOW_SPEC_TYPE_LLC_DSAP]:      FLOW_SPEC_TYPE_LLC_DSAP,
  3636  	FlowSpecNameMap[FLOW_SPEC_TYPE_LLC_SSAP]:      FLOW_SPEC_TYPE_LLC_SSAP,
  3637  	FlowSpecNameMap[FLOW_SPEC_TYPE_LLC_CONTROL]:   FLOW_SPEC_TYPE_LLC_CONTROL,
  3638  	FlowSpecNameMap[FLOW_SPEC_TYPE_SNAP]:          FLOW_SPEC_TYPE_SNAP,
  3639  	FlowSpecNameMap[FLOW_SPEC_TYPE_VID]:           FLOW_SPEC_TYPE_VID,
  3640  	FlowSpecNameMap[FLOW_SPEC_TYPE_COS]:           FLOW_SPEC_TYPE_COS,
  3641  	FlowSpecNameMap[FLOW_SPEC_TYPE_INNER_VID]:     FLOW_SPEC_TYPE_INNER_VID,
  3642  	FlowSpecNameMap[FLOW_SPEC_TYPE_INNER_COS]:     FLOW_SPEC_TYPE_INNER_COS,
  3643  }
  3644  
  3645  // Joins the given and args into a single string and normalize it.
  3646  // Example:
  3647  // args := []string{"  &  <=80", " tcp  != udp ", " =!   SA   & =U!  F", " =  is-fragment+last-fragment"}
  3648  // fmt.Printf("%q", normalizeFlowSpecOpValues(args))
  3649  // >>> ["<=80" "tcp" "!=udp" "=!SA" "&=U" "!F" "=is-fragment+last-fragment"]
  3650  func normalizeFlowSpecOpValues(args []string) []string {
  3651  	// Extracts keywords from the given args.
  3652  	sub := ""
  3653  	subs := make([]string, 0)
  3654  	for _, s := range _regexpFlowSpecOperator.FindAllString(strings.Join(args, " "), -1) {
  3655  		sub += s
  3656  		if _regexpFlowSpecOperatorValue.MatchString(s) {
  3657  			subs = append(subs, sub)
  3658  			sub = ""
  3659  		}
  3660  	}
  3661  
  3662  	// RFC5575 says "It should be unset in the first operator byte of a
  3663  	// sequence".
  3664  	if len(subs) > 0 {
  3665  		subs[0] = strings.TrimPrefix(subs[0], "&")
  3666  	}
  3667  
  3668  	return subs
  3669  }
  3670  
  3671  // Parses the FlowSpec numeric operator using the given submatch which should be
  3672  // the return value of func (*Regexp) FindStringSubmatch.
  3673  func parseFlowSpecNumericOperator(submatch []string) (operator uint8, err error) {
  3674  	if submatch[1] == "&" {
  3675  		operator = DEC_NUM_OP_AND
  3676  	}
  3677  	value, ok := DECNumOpValueMap[submatch[2]]
  3678  	if !ok {
  3679  		return 0, fmt.Errorf("invalid numeric operator: %s%s", submatch[1], submatch[2])
  3680  	}
  3681  	operator |= uint8(value)
  3682  	return operator, nil
  3683  }
  3684  
  3685  // Parses the pairs of operator and value for the FlowSpec numeric type. The
  3686  // given validationFunc is applied to evaluate whether the parsed value is
  3687  // valid or not (e.g., if exceeds range or not).
  3688  // Note: Each of the args should be formatted in single pair of operator and
  3689  // value before calling this function.
  3690  // e.g.) "&==100", ">=200" or "&<300"
  3691  func parseFlowSpecNumericOpValues(typ BGPFlowSpecType, args []string, validationFunc func(uint64) error) (FlowSpecComponentInterface, error) {
  3692  	argsLen := len(args)
  3693  	items := make([]*FlowSpecComponentItem, 0, argsLen)
  3694  	for idx, arg := range args {
  3695  		m := _regexpFlowSpecNumericType.FindStringSubmatch(arg)
  3696  		if len(m) < 4 {
  3697  			return nil, fmt.Errorf("invalid argument for %s: %s in %q", typ.String(), arg, args)
  3698  		}
  3699  		operator, err := parseFlowSpecNumericOperator(m)
  3700  		if err != nil {
  3701  			return nil, err
  3702  		}
  3703  		// "true" and "false" is operator, but here handles them as value.
  3704  		var value uint64
  3705  		switch m[3] {
  3706  		case "true", "false":
  3707  			if idx != argsLen-1 {
  3708  				return nil, fmt.Errorf("%s should be the last of each rule", m[3])
  3709  			}
  3710  			operator = uint8(DECNumOpValueMap[m[3]])
  3711  		default:
  3712  			if value, err = strconv.ParseUint(m[3], 10, 64); err != nil {
  3713  				return nil, fmt.Errorf("invalid numeric value: %s", m[3])
  3714  			}
  3715  			if err = validationFunc(value); err != nil {
  3716  				return nil, err
  3717  			}
  3718  		}
  3719  		items = append(items, NewFlowSpecComponentItem(operator, value))
  3720  	}
  3721  
  3722  	// Marks end-of-list bit
  3723  	items[argsLen-1].Op |= uint8(DEC_NUM_OP_END)
  3724  
  3725  	return NewFlowSpecComponent(typ, items), nil
  3726  }
  3727  
  3728  func flowSpecNumeric1ByteParser(_ RouteFamily, typ BGPFlowSpecType, args []string) (FlowSpecComponentInterface, error) {
  3729  	args = normalizeFlowSpecOpValues(args)
  3730  
  3731  	f := func(i uint64) error {
  3732  		if i <= 0xff { // 1 byte
  3733  			return nil
  3734  		}
  3735  		return fmt.Errorf("%s range exceeded", typ.String())
  3736  	}
  3737  
  3738  	return parseFlowSpecNumericOpValues(typ, args, f)
  3739  }
  3740  
  3741  func flowSpecNumeric2BytesParser(_ RouteFamily, typ BGPFlowSpecType, args []string) (FlowSpecComponentInterface, error) {
  3742  	args = normalizeFlowSpecOpValues(args)
  3743  
  3744  	f := func(i uint64) error {
  3745  		if i <= 0xffff { // 2 bytes
  3746  			return nil
  3747  		}
  3748  		return fmt.Errorf("%s range exceeded", typ.String())
  3749  	}
  3750  
  3751  	return parseFlowSpecNumericOpValues(typ, args, f)
  3752  }
  3753  
  3754  // Parses the FlowSpec bitmask operand using the given submatch which should be
  3755  // the return value of func (*Regexp) FindStringSubmatch.
  3756  func parseFlowSpecBitmaskOperand(submatch []string) (operand uint8, err error) {
  3757  	if submatch[1] == "&" {
  3758  		operand = BITMASK_FLAG_OP_AND
  3759  	}
  3760  	value, ok := BitmaskFlagOpValueMap[submatch[2]]
  3761  	if !ok {
  3762  		return 0, fmt.Errorf("invalid bitmask operand: %s%s", submatch[1], submatch[2])
  3763  	}
  3764  	operand |= uint8(value)
  3765  	return operand, nil
  3766  }
  3767  
  3768  func flowSpecPrefixParser(rf RouteFamily, typ BGPFlowSpecType, args []string) (FlowSpecComponentInterface, error) {
  3769  	// args[0]: IP Prefix or IP Address (suppose prefix length is 32)
  3770  	// args[1]: Offset in bit (IPv6 only)
  3771  	//
  3772  	// Example:
  3773  	// - IPv4 Prefix
  3774  	//   args := []string{"192.168.0.0/24"}
  3775  	// - IPv4 Address
  3776  	//   args := []string{"192.168.0.1"}
  3777  	// - IPv6 Prefix
  3778  	//   args := []string{"2001:db8:1::/64"}
  3779  	// - IPv6 Prefix with offset
  3780  	//   args := []string{"0:db8:1::/64/16"}
  3781  	//   args := []string{"0:db8:1::/64", "16"}
  3782  	// - IPv6 Address
  3783  	//   args := []string{"2001:db8:1::1"}
  3784  	// - IPv6 Address with offset
  3785  	//   args := []string{"0:db8:1::1", "16"}
  3786  	afi, _ := RouteFamilyToAfiSafi(rf)
  3787  	switch afi {
  3788  	case AFI_IP:
  3789  		if len(args) > 1 {
  3790  			return nil, errors.New("cannot specify offset for ipv4 prefix")
  3791  		}
  3792  		invalidIPv4PrefixError := fmt.Errorf("invalid ipv4 prefix: %s", args[0])
  3793  		m := _regexpFindIPv4Prefix.FindStringSubmatch(args[0])
  3794  		if len(m) < 4 {
  3795  			return nil, invalidIPv4PrefixError
  3796  		}
  3797  		prefix := net.ParseIP(m[1])
  3798  		if prefix.To4() == nil {
  3799  			return nil, invalidIPv4PrefixError
  3800  		}
  3801  		var prefixLen uint64 = 32
  3802  		if m[3] != "" {
  3803  			var err error
  3804  			prefixLen, err = strconv.ParseUint(m[3], 10, 8)
  3805  			if err != nil || prefixLen > 32 {
  3806  				return nil, invalidIPv4PrefixError
  3807  			}
  3808  		}
  3809  		switch typ {
  3810  		case FLOW_SPEC_TYPE_DST_PREFIX:
  3811  			return NewFlowSpecDestinationPrefix(NewIPAddrPrefix(uint8(prefixLen), prefix.String())), nil
  3812  		case FLOW_SPEC_TYPE_SRC_PREFIX:
  3813  			return NewFlowSpecSourcePrefix(NewIPAddrPrefix(uint8(prefixLen), prefix.String())), nil
  3814  		}
  3815  		return nil, fmt.Errorf("invalid traffic filtering rule type: %s", typ.String())
  3816  	case AFI_IP6:
  3817  		if len(args) > 2 {
  3818  			return nil, fmt.Errorf("invalid arguments for ipv6 prefix: %q", args)
  3819  		}
  3820  		invalidIPv6PrefixError := fmt.Errorf("invalid ipv6 prefix: %s", args[0])
  3821  		m := _regexpFindIPv6Prefix.FindStringSubmatch(args[0])
  3822  		if len(m) < 4 {
  3823  			return nil, invalidIPv6PrefixError
  3824  		}
  3825  		prefix := net.ParseIP(m[1])
  3826  		if prefix.To16() == nil {
  3827  			return nil, invalidIPv6PrefixError
  3828  		}
  3829  		var prefixLen uint64 = 128
  3830  		if m[3] != "" {
  3831  			var err error
  3832  			prefixLen, err = strconv.ParseUint(m[3], 10, 8)
  3833  			if err != nil || prefixLen > 128 {
  3834  				return nil, invalidIPv6PrefixError
  3835  			}
  3836  		}
  3837  		var offset uint64
  3838  		if len(args) == 1 && m[5] != "" {
  3839  			var err error
  3840  			offset, err = strconv.ParseUint(m[5], 10, 8)
  3841  			if err != nil || offset > 128 {
  3842  				return nil, fmt.Errorf("invalid ipv6 prefix offset: %s", m[5])
  3843  			}
  3844  		} else if len(args) == 2 {
  3845  			if m[5] != "" {
  3846  				return nil, fmt.Errorf("multiple ipv6 prefix offset arguments detected: %q", args)
  3847  			}
  3848  			var err error
  3849  			offset, err = strconv.ParseUint(args[1], 10, 8)
  3850  			if err != nil || offset > 128 {
  3851  				return nil, fmt.Errorf("invalid ipv6 prefix offset: %s", args[1])
  3852  			}
  3853  		}
  3854  		switch typ {
  3855  		case FLOW_SPEC_TYPE_DST_PREFIX:
  3856  			return NewFlowSpecDestinationPrefix6(NewIPv6AddrPrefix(uint8(prefixLen), prefix.String()), uint8(offset)), nil
  3857  		case FLOW_SPEC_TYPE_SRC_PREFIX:
  3858  			return NewFlowSpecSourcePrefix6(NewIPv6AddrPrefix(uint8(prefixLen), prefix.String()), uint8(offset)), nil
  3859  		}
  3860  		return nil, fmt.Errorf("invalid traffic filtering rule type: %s", typ.String())
  3861  	}
  3862  	return nil, fmt.Errorf("invalid address family: %s", rf.String())
  3863  }
  3864  
  3865  func flowSpecIpProtoParser(_ RouteFamily, typ BGPFlowSpecType, args []string) (FlowSpecComponentInterface, error) {
  3866  	// args: List of pairs of Operator and IP protocol type
  3867  	//
  3868  	// Example:
  3869  	// - TCP or UDP
  3870  	//   args := []string{"tcp", "==udp"}
  3871  	// - Not TCP and not UDP
  3872  	//   args := []string{"!=tcp", "&!=udp"}
  3873  	args = normalizeFlowSpecOpValues(args)
  3874  	s := strings.Join(args, " ")
  3875  	for i, name := range ProtocolNameMap {
  3876  		s = strings.Replace(s, name, fmt.Sprintf("%d", i), -1)
  3877  	}
  3878  	args = strings.Split(s, " ")
  3879  
  3880  	f := func(i uint64) error {
  3881  		if i <= 0xff { // 1 byte
  3882  			return nil
  3883  		}
  3884  		return fmt.Errorf("%s range exceeded", typ.String())
  3885  	}
  3886  
  3887  	return parseFlowSpecNumericOpValues(typ, args, f)
  3888  }
  3889  
  3890  func flowSpecTcpFlagParser(_ RouteFamily, typ BGPFlowSpecType, args []string) (FlowSpecComponentInterface, error) {
  3891  	// args: List of pairs of Operand and TCP Flags
  3892  	//
  3893  	// Example:
  3894  	// - SYN or SYN/ACK
  3895  	//   args := []string{"==S", "==SA"}
  3896  	// - Not FIN and not URG
  3897  	//   args := []string{"!=F", "&!=U"}
  3898  	args = normalizeFlowSpecOpValues(args)
  3899  
  3900  	argsLen := len(args)
  3901  	items := make([]*FlowSpecComponentItem, 0, argsLen)
  3902  
  3903  	for _, arg := range args {
  3904  		m := _regexpFlowSpecTCPFlag.FindStringSubmatch(arg)
  3905  		if len(m) < 6 {
  3906  			return nil, fmt.Errorf("invalid argument for %s: %s in %q", typ.String(), arg, args)
  3907  		} else if mLast := m[len(m)-1]; mLast != "" || m[3] != "" {
  3908  			return nil, fmt.Errorf("invalid argument for %s: %s in %q", typ.String(), arg, args)
  3909  		}
  3910  		operand, err := parseFlowSpecBitmaskOperand(m)
  3911  		if err != nil {
  3912  			return nil, err
  3913  		}
  3914  		var value uint64
  3915  		for flag, name := range TCPFlagNameMap {
  3916  			if strings.Contains(m[4], name) {
  3917  				value |= uint64(flag)
  3918  			}
  3919  		}
  3920  		items = append(items, NewFlowSpecComponentItem(operand, value))
  3921  	}
  3922  
  3923  	// Marks end-of-list bit
  3924  	items[argsLen-1].Op |= BITMASK_FLAG_OP_END
  3925  
  3926  	return NewFlowSpecComponent(typ, items), nil
  3927  }
  3928  
  3929  func flowSpecDscpParser(_ RouteFamily, typ BGPFlowSpecType, args []string) (FlowSpecComponentInterface, error) {
  3930  	args = normalizeFlowSpecOpValues(args)
  3931  
  3932  	f := func(i uint64) error {
  3933  		if i < 64 { // 6 bits
  3934  			return nil
  3935  		}
  3936  		return fmt.Errorf("%s range exceeded", typ.String())
  3937  	}
  3938  
  3939  	return parseFlowSpecNumericOpValues(typ, args, f)
  3940  }
  3941  
  3942  func flowSpecFragmentParser(_ RouteFamily, typ BGPFlowSpecType, args []string) (FlowSpecComponentInterface, error) {
  3943  	// args: List of pairs of Operator and Fragment flags
  3944  	//
  3945  	// Example:
  3946  	// - is-fragment or last-fragment
  3947  	//   args := []string{"==is-fragment", "==last-fragment"}
  3948  	// - is-fragment and last-fragment (exact match)
  3949  	//   args := []string{"==is-fragment+last-fragment"}
  3950  	args = normalizeFlowSpecOpValues(args)
  3951  
  3952  	argsLen := len(args)
  3953  	items := make([]*FlowSpecComponentItem, 0, argsLen)
  3954  
  3955  	for _, arg := range args {
  3956  		m := _regexpFlowSpecFragment.FindStringSubmatch(arg)
  3957  		if len(m) < 4 {
  3958  			return nil, fmt.Errorf("invalid argument for %s: %s in %q", typ.String(), arg, args)
  3959  		} else if mLast := m[len(m)-1]; mLast != "" {
  3960  			return nil, fmt.Errorf("invalid argument for %s: %s in %q", typ.String(), arg, args)
  3961  		}
  3962  		operand, err := parseFlowSpecBitmaskOperand(m)
  3963  		if err != nil {
  3964  			return nil, err
  3965  		}
  3966  		var value uint64
  3967  		// Example:
  3968  		// m[3] = "first-fragment+last-fragment"
  3969  		for flag, name := range FragmentFlagNameMap {
  3970  			if strings.Contains(m[3], name) {
  3971  				value |= uint64(flag)
  3972  			}
  3973  		}
  3974  		items = append(items, NewFlowSpecComponentItem(operand, value))
  3975  	}
  3976  
  3977  	// Marks end-of-list bit
  3978  	items[argsLen-1].Op |= BITMASK_FLAG_OP_END
  3979  
  3980  	return NewFlowSpecComponent(typ, items), nil
  3981  }
  3982  
  3983  func flowSpecLabelParser(rf RouteFamily, typ BGPFlowSpecType, args []string) (FlowSpecComponentInterface, error) {
  3984  	afi, _ := RouteFamilyToAfiSafi(rf)
  3985  	if afi == AFI_IP {
  3986  		return nil, fmt.Errorf("%s is not supported for ipv4", typ.String())
  3987  	}
  3988  
  3989  	args = normalizeFlowSpecOpValues(args)
  3990  
  3991  	f := func(i uint64) error {
  3992  		if i <= 0xfffff { // 20 bits
  3993  			return nil
  3994  		}
  3995  		return errors.New("flow label range exceeded")
  3996  	}
  3997  
  3998  	return parseFlowSpecNumericOpValues(typ, args, f)
  3999  }
  4000  
  4001  func flowSpecEtherTypeParser(rf RouteFamily, typ BGPFlowSpecType, args []string) (FlowSpecComponentInterface, error) {
  4002  	// args: List of pairs of Operator and Ether Types
  4003  	//
  4004  	// Example:
  4005  	// - ARP or IPv4
  4006  	//   args := []string{"==arp", "==ipv4"}
  4007  	// - Not IPv4 and not IPv6
  4008  	//   args := []string{"!=ipv4", "&!=ipv6"}
  4009  	if rf != RF_FS_L2_VPN {
  4010  		return nil, fmt.Errorf("%s is supported for only l2vpn", typ.String())
  4011  	}
  4012  
  4013  	args = normalizeFlowSpecOpValues(args)
  4014  	s := strings.Join(args, " ")
  4015  	for i, name := range EthernetTypeNameMap {
  4016  		s = strings.Replace(s, name, fmt.Sprintf("%d", i), -1)
  4017  	}
  4018  	args = strings.Split(s, " ")
  4019  
  4020  	f := func(i uint64) error {
  4021  		if i <= 0xffff { // 2 bytes
  4022  			return nil
  4023  		}
  4024  		return fmt.Errorf("%s range exceeded", typ.String())
  4025  	}
  4026  
  4027  	return parseFlowSpecNumericOpValues(typ, args, f)
  4028  }
  4029  
  4030  func flowSpecMacParser(rf RouteFamily, typ BGPFlowSpecType, args []string) (FlowSpecComponentInterface, error) {
  4031  	// args[0]: MAC address
  4032  	if rf != RF_FS_L2_VPN {
  4033  		return nil, fmt.Errorf("%s is supported for only l2vpn", typ.String())
  4034  	}
  4035  
  4036  	mac, err := net.ParseMAC(args[0])
  4037  	if err != nil {
  4038  		return nil, fmt.Errorf("invalid mac address: %s", args[0])
  4039  	}
  4040  
  4041  	switch typ {
  4042  	case FLOW_SPEC_TYPE_DST_MAC:
  4043  		return NewFlowSpecDestinationMac(mac), nil
  4044  	case FLOW_SPEC_TYPE_SRC_MAC:
  4045  		return NewFlowSpecSourceMac(mac), nil
  4046  	}
  4047  	return nil, fmt.Errorf("invalid traffic filtering rule type: %s", typ.String())
  4048  }
  4049  
  4050  func flowSpecLlcParser(rf RouteFamily, typ BGPFlowSpecType, args []string) (FlowSpecComponentInterface, error) {
  4051  	if rf != RF_FS_L2_VPN {
  4052  		return nil, fmt.Errorf("%s is supported for only l2vpn", typ.String())
  4053  	}
  4054  
  4055  	return flowSpecNumeric1ByteParser(rf, typ, args)
  4056  }
  4057  
  4058  func flowSpecSnapParser(rf RouteFamily, typ BGPFlowSpecType, args []string) (FlowSpecComponentInterface, error) {
  4059  	if rf != RF_FS_L2_VPN {
  4060  		return nil, fmt.Errorf("%s is supported for only l2vpn", typ.String())
  4061  	}
  4062  
  4063  	args = normalizeFlowSpecOpValues(args)
  4064  
  4065  	f := func(i uint64) error {
  4066  		if i <= 0xffffffffff { // 5 bytes
  4067  			return nil
  4068  		}
  4069  		return fmt.Errorf("%s range exceeded", typ.String())
  4070  	}
  4071  
  4072  	return parseFlowSpecNumericOpValues(typ, args, f)
  4073  }
  4074  
  4075  func flowSpecVlanIDParser(rf RouteFamily, typ BGPFlowSpecType, args []string) (FlowSpecComponentInterface, error) {
  4076  	if rf != RF_FS_L2_VPN {
  4077  		return nil, fmt.Errorf("%s is supported for only l2vpn", typ.String())
  4078  	}
  4079  
  4080  	args = normalizeFlowSpecOpValues(args)
  4081  	s := strings.Join(args, " ")
  4082  	for i, name := range EthernetTypeNameMap {
  4083  		s = strings.Replace(s, name, fmt.Sprintf("%d", i), -1)
  4084  	}
  4085  	args = strings.Split(s, " ")
  4086  
  4087  	f := func(i uint64) error {
  4088  		if i <= 4095 { // 12 bits
  4089  			return nil
  4090  		}
  4091  		return fmt.Errorf("%s range exceeded", typ.String())
  4092  	}
  4093  
  4094  	return parseFlowSpecNumericOpValues(typ, args, f)
  4095  }
  4096  
  4097  func flowSpecVlanCosParser(rf RouteFamily, typ BGPFlowSpecType, args []string) (FlowSpecComponentInterface, error) {
  4098  	if rf != RF_FS_L2_VPN {
  4099  		return nil, fmt.Errorf("%s is supported for only l2vpn", typ.String())
  4100  	}
  4101  
  4102  	args = normalizeFlowSpecOpValues(args)
  4103  	s := strings.Join(args, " ")
  4104  	for i, name := range EthernetTypeNameMap {
  4105  		s = strings.Replace(s, name, fmt.Sprintf("%d", i), -1)
  4106  	}
  4107  	args = strings.Split(s, " ")
  4108  
  4109  	f := func(i uint64) error {
  4110  		if i <= 7 { // 3 bits
  4111  			return nil
  4112  		}
  4113  		return fmt.Errorf("%s range exceeded", typ.String())
  4114  	}
  4115  
  4116  	return parseFlowSpecNumericOpValues(typ, args, f)
  4117  }
  4118  
  4119  var flowSpecParserMap = map[BGPFlowSpecType]func(RouteFamily, BGPFlowSpecType, []string) (FlowSpecComponentInterface, error){
  4120  	FLOW_SPEC_TYPE_DST_PREFIX:    flowSpecPrefixParser,
  4121  	FLOW_SPEC_TYPE_SRC_PREFIX:    flowSpecPrefixParser,
  4122  	FLOW_SPEC_TYPE_IP_PROTO:      flowSpecIpProtoParser,
  4123  	FLOW_SPEC_TYPE_PORT:          flowSpecNumeric2BytesParser,
  4124  	FLOW_SPEC_TYPE_DST_PORT:      flowSpecNumeric2BytesParser,
  4125  	FLOW_SPEC_TYPE_SRC_PORT:      flowSpecNumeric2BytesParser,
  4126  	FLOW_SPEC_TYPE_ICMP_TYPE:     flowSpecNumeric1ByteParser,
  4127  	FLOW_SPEC_TYPE_ICMP_CODE:     flowSpecNumeric1ByteParser,
  4128  	FLOW_SPEC_TYPE_TCP_FLAG:      flowSpecTcpFlagParser,
  4129  	FLOW_SPEC_TYPE_PKT_LEN:       flowSpecNumeric2BytesParser,
  4130  	FLOW_SPEC_TYPE_DSCP:          flowSpecDscpParser,
  4131  	FLOW_SPEC_TYPE_FRAGMENT:      flowSpecFragmentParser,
  4132  	FLOW_SPEC_TYPE_LABEL:         flowSpecLabelParser,
  4133  	FLOW_SPEC_TYPE_ETHERNET_TYPE: flowSpecEtherTypeParser,
  4134  	FLOW_SPEC_TYPE_DST_MAC:       flowSpecMacParser,
  4135  	FLOW_SPEC_TYPE_SRC_MAC:       flowSpecMacParser,
  4136  	FLOW_SPEC_TYPE_LLC_DSAP:      flowSpecLlcParser,
  4137  	FLOW_SPEC_TYPE_LLC_SSAP:      flowSpecLlcParser,
  4138  	FLOW_SPEC_TYPE_LLC_CONTROL:   flowSpecLlcParser,
  4139  	FLOW_SPEC_TYPE_SNAP:          flowSpecSnapParser,
  4140  	FLOW_SPEC_TYPE_VID:           flowSpecVlanIDParser,
  4141  	FLOW_SPEC_TYPE_COS:           flowSpecVlanCosParser,
  4142  	FLOW_SPEC_TYPE_INNER_VID:     flowSpecVlanIDParser,
  4143  	FLOW_SPEC_TYPE_INNER_COS:     flowSpecVlanCosParser,
  4144  }
  4145  
  4146  func extractFlowSpecArgs(args []string) map[BGPFlowSpecType][]string {
  4147  	m := make(map[BGPFlowSpecType][]string, len(FlowSpecValueMap))
  4148  	var typ BGPFlowSpecType
  4149  	for _, arg := range args {
  4150  		if t, ok := FlowSpecValueMap[arg]; ok {
  4151  			typ = t
  4152  			m[typ] = make([]string, 0)
  4153  		} else {
  4154  			m[typ] = append(m[typ], arg)
  4155  		}
  4156  	}
  4157  	return m
  4158  }
  4159  
  4160  func ParseFlowSpecComponents(rf RouteFamily, arg string) ([]FlowSpecComponentInterface, error) {
  4161  	_, safi := RouteFamilyToAfiSafi(rf)
  4162  	switch safi {
  4163  	case SAFI_FLOW_SPEC_UNICAST, SAFI_FLOW_SPEC_VPN:
  4164  		// Valid
  4165  	default:
  4166  		return nil, fmt.Errorf("invalid address family: %s", rf.String())
  4167  	}
  4168  
  4169  	typeArgs := extractFlowSpecArgs(strings.Split(arg, " "))
  4170  	rules := make([]FlowSpecComponentInterface, 0, len(typeArgs))
  4171  	for typ, args := range typeArgs {
  4172  		parser, ok := flowSpecParserMap[typ]
  4173  		if !ok {
  4174  			return nil, fmt.Errorf("unsupported traffic filtering rule type: %s", typ.String())
  4175  		}
  4176  		if len(args) == 0 {
  4177  			return nil, fmt.Errorf("specify traffic filtering rules for %s", typ.String())
  4178  		}
  4179  		rule, err := parser(rf, typ, args)
  4180  		if err != nil {
  4181  			return nil, err
  4182  		}
  4183  		rules = append(rules, rule)
  4184  	}
  4185  	return rules, nil
  4186  }
  4187  
  4188  func (t BGPFlowSpecType) String() string {
  4189  	name, ok := FlowSpecNameMap[t]
  4190  	if !ok {
  4191  		return fmt.Sprintf("%s(%d)", FlowSpecNameMap[FLOW_SPEC_TYPE_UNKNOWN], t)
  4192  	}
  4193  	return name
  4194  }
  4195  
  4196  type FlowSpecComponentInterface interface {
  4197  	DecodeFromBytes([]byte, ...*MarshallingOption) error
  4198  	Serialize(...*MarshallingOption) ([]byte, error)
  4199  	Len(...*MarshallingOption) int
  4200  	Type() BGPFlowSpecType
  4201  	String() string
  4202  }
  4203  
  4204  type flowSpecPrefix struct {
  4205  	Prefix AddrPrefixInterface
  4206  	typ    BGPFlowSpecType
  4207  }
  4208  
  4209  func (p *flowSpecPrefix) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
  4210  	p.typ = BGPFlowSpecType(data[0])
  4211  	return p.Prefix.DecodeFromBytes(data[1:], options...)
  4212  }
  4213  
  4214  func (p *flowSpecPrefix) Serialize(options ...*MarshallingOption) ([]byte, error) {
  4215  	bbuf, err := p.Prefix.Serialize(options...)
  4216  	if err != nil {
  4217  		return nil, err
  4218  	}
  4219  	buf := make([]byte, 1+len(bbuf))
  4220  	buf[0] = byte(p.Type())
  4221  	copy(buf[1:], bbuf)
  4222  	return buf, nil
  4223  }
  4224  
  4225  func (p *flowSpecPrefix) Len(options ...*MarshallingOption) int {
  4226  	buf, _ := p.Serialize(options...)
  4227  	return len(buf)
  4228  }
  4229  
  4230  func (p *flowSpecPrefix) Type() BGPFlowSpecType {
  4231  	return p.typ
  4232  }
  4233  
  4234  func (p *flowSpecPrefix) String() string {
  4235  	return fmt.Sprintf("[%s: %s]", p.Type(), p.Prefix.String())
  4236  }
  4237  
  4238  func (p *flowSpecPrefix) MarshalJSON() ([]byte, error) {
  4239  	return json.Marshal(struct {
  4240  		Type  BGPFlowSpecType     `json:"type"`
  4241  		Value AddrPrefixInterface `json:"value"`
  4242  	}{
  4243  		Type:  p.Type(),
  4244  		Value: p.Prefix,
  4245  	})
  4246  }
  4247  
  4248  type flowSpecPrefix6 struct {
  4249  	Prefix AddrPrefixInterface
  4250  	Offset uint8
  4251  	typ    BGPFlowSpecType
  4252  }
  4253  
  4254  // draft-ietf-idr-flow-spec-v6-06
  4255  // <type (1 octet), prefix length (1 octet), prefix offset(1 octet), prefix>
  4256  func (p *flowSpecPrefix6) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
  4257  	p.typ = BGPFlowSpecType(data[0])
  4258  	p.Offset = data[2]
  4259  	prefix := append([]byte{data[1]}, data[3:]...)
  4260  	return p.Prefix.DecodeFromBytes(prefix, options...)
  4261  }
  4262  
  4263  func (p *flowSpecPrefix6) Serialize(options ...*MarshallingOption) ([]byte, error) {
  4264  	buf := []byte{byte(p.Type())}
  4265  	bbuf, err := p.Prefix.Serialize(options...)
  4266  	if err != nil {
  4267  		return nil, err
  4268  	}
  4269  	buf = append(buf, bbuf[0])
  4270  	buf = append(buf, p.Offset)
  4271  	return append(buf, bbuf[1:]...), nil
  4272  }
  4273  
  4274  func (p *flowSpecPrefix6) Len(options ...*MarshallingOption) int {
  4275  	buf, _ := p.Serialize(options...)
  4276  	return len(buf)
  4277  }
  4278  
  4279  func (p *flowSpecPrefix6) Type() BGPFlowSpecType {
  4280  	return p.typ
  4281  }
  4282  
  4283  func (p *flowSpecPrefix6) String() string {
  4284  	return fmt.Sprintf("[%s: %s/%d]", p.Type(), p.Prefix.String(), p.Offset)
  4285  }
  4286  
  4287  func (p *flowSpecPrefix6) MarshalJSON() ([]byte, error) {
  4288  	return json.Marshal(struct {
  4289  		Type   BGPFlowSpecType     `json:"type"`
  4290  		Value  AddrPrefixInterface `json:"value"`
  4291  		Offset uint8               `json:"offset"`
  4292  	}{
  4293  		Type:   p.Type(),
  4294  		Value:  p.Prefix,
  4295  		Offset: p.Offset,
  4296  	})
  4297  }
  4298  
  4299  type FlowSpecDestinationPrefix struct {
  4300  	flowSpecPrefix
  4301  }
  4302  
  4303  func NewFlowSpecDestinationPrefix(prefix AddrPrefixInterface) *FlowSpecDestinationPrefix {
  4304  	return &FlowSpecDestinationPrefix{flowSpecPrefix{prefix, FLOW_SPEC_TYPE_DST_PREFIX}}
  4305  }
  4306  
  4307  type FlowSpecSourcePrefix struct {
  4308  	flowSpecPrefix
  4309  }
  4310  
  4311  func NewFlowSpecSourcePrefix(prefix AddrPrefixInterface) *FlowSpecSourcePrefix {
  4312  	return &FlowSpecSourcePrefix{flowSpecPrefix{prefix, FLOW_SPEC_TYPE_SRC_PREFIX}}
  4313  }
  4314  
  4315  type FlowSpecDestinationPrefix6 struct {
  4316  	flowSpecPrefix6
  4317  }
  4318  
  4319  func NewFlowSpecDestinationPrefix6(prefix AddrPrefixInterface, offset uint8) *FlowSpecDestinationPrefix6 {
  4320  	return &FlowSpecDestinationPrefix6{flowSpecPrefix6{prefix, offset, FLOW_SPEC_TYPE_DST_PREFIX}}
  4321  }
  4322  
  4323  type FlowSpecSourcePrefix6 struct {
  4324  	flowSpecPrefix6
  4325  }
  4326  
  4327  func NewFlowSpecSourcePrefix6(prefix AddrPrefixInterface, offset uint8) *FlowSpecSourcePrefix6 {
  4328  	return &FlowSpecSourcePrefix6{flowSpecPrefix6{prefix, offset, FLOW_SPEC_TYPE_SRC_PREFIX}}
  4329  }
  4330  
  4331  type flowSpecMac struct {
  4332  	Mac net.HardwareAddr
  4333  	typ BGPFlowSpecType
  4334  }
  4335  
  4336  func (p *flowSpecMac) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
  4337  	if len(data) < 2 || len(data) < 2+int(data[1]) {
  4338  		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "not all mac bits available")
  4339  	}
  4340  	p.typ = BGPFlowSpecType(data[0])
  4341  	p.Mac = net.HardwareAddr(data[2 : 2+int(data[1])])
  4342  	return nil
  4343  }
  4344  
  4345  func (p *flowSpecMac) Serialize(options ...*MarshallingOption) ([]byte, error) {
  4346  	if len(p.Mac) == 0 {
  4347  		return nil, errors.New("mac unset")
  4348  	}
  4349  	buf := make([]byte, 2+len(p.Mac))
  4350  	buf[0] = byte(p.Type())
  4351  	buf[1] = byte(len(p.Mac))
  4352  	copy(buf[2:], p.Mac)
  4353  	return buf, nil
  4354  }
  4355  
  4356  func (p *flowSpecMac) Len(options ...*MarshallingOption) int {
  4357  	return 2 + len(p.Mac)
  4358  }
  4359  
  4360  func (p *flowSpecMac) Type() BGPFlowSpecType {
  4361  	return p.typ
  4362  }
  4363  
  4364  func (p *flowSpecMac) String() string {
  4365  	return fmt.Sprintf("[%s: %s]", p.Type(), p.Mac.String())
  4366  }
  4367  
  4368  func (p *flowSpecMac) MarshalJSON() ([]byte, error) {
  4369  	return json.Marshal(struct {
  4370  		Type  BGPFlowSpecType `json:"type"`
  4371  		Value string          `json:"value"`
  4372  	}{
  4373  		Type:  p.Type(),
  4374  		Value: p.Mac.String(),
  4375  	})
  4376  }
  4377  
  4378  type FlowSpecSourceMac struct {
  4379  	flowSpecMac
  4380  }
  4381  
  4382  func NewFlowSpecSourceMac(mac net.HardwareAddr) *FlowSpecSourceMac {
  4383  	return &FlowSpecSourceMac{flowSpecMac{Mac: mac, typ: FLOW_SPEC_TYPE_SRC_MAC}}
  4384  }
  4385  
  4386  type FlowSpecDestinationMac struct {
  4387  	flowSpecMac
  4388  }
  4389  
  4390  func NewFlowSpecDestinationMac(mac net.HardwareAddr) *FlowSpecDestinationMac {
  4391  	return &FlowSpecDestinationMac{flowSpecMac{Mac: mac, typ: FLOW_SPEC_TYPE_DST_MAC}}
  4392  }
  4393  
  4394  type FlowSpecComponentItem struct {
  4395  	Op    uint8  `json:"op"`
  4396  	Value uint64 `json:"value"`
  4397  }
  4398  
  4399  func (v *FlowSpecComponentItem) Len() int {
  4400  	return 1 << ((uint32(v.Op) >> 4) & 0x3)
  4401  }
  4402  
  4403  func (v *FlowSpecComponentItem) Serialize() ([]byte, error) {
  4404  	order := uint32(math.Log2(float64(v.Len())))
  4405  	buf := make([]byte, 1+(1<<order))
  4406  	buf[0] = byte(uint32(v.Op) | order<<4)
  4407  	switch order {
  4408  	case 0:
  4409  		buf[1] = byte(v.Value)
  4410  	case 1:
  4411  		binary.BigEndian.PutUint16(buf[1:], uint16(v.Value))
  4412  	case 2:
  4413  		binary.BigEndian.PutUint32(buf[1:], uint32(v.Value))
  4414  	case 3:
  4415  		binary.BigEndian.PutUint64(buf[1:], uint64(v.Value))
  4416  	default:
  4417  		return nil, fmt.Errorf("invalid value size(too big): %d", v.Value)
  4418  	}
  4419  	return buf, nil
  4420  }
  4421  
  4422  func NewFlowSpecComponentItem(op uint8, value uint64) *FlowSpecComponentItem {
  4423  	v := &FlowSpecComponentItem{op, value}
  4424  	order := uint32(math.Log2(float64(v.Len())))
  4425  	// we don't know if not initialized properly or initialized to
  4426  	// zero...
  4427  	if order == 0 {
  4428  		order = func() uint32 {
  4429  			for i := 0; i < 3; i++ {
  4430  				if v.Value < (1 << ((1 << uint(i)) * 8)) {
  4431  					return uint32(i)
  4432  				}
  4433  			}
  4434  			// Return 8 octet order
  4435  			return 3
  4436  		}()
  4437  	}
  4438  	v.Op = uint8(uint32(v.Op) | order<<4)
  4439  	return v
  4440  }
  4441  
  4442  type FlowSpecComponent struct {
  4443  	Items []*FlowSpecComponentItem
  4444  	typ   BGPFlowSpecType
  4445  }
  4446  
  4447  func (p *FlowSpecComponent) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
  4448  	p.typ = BGPFlowSpecType(data[0])
  4449  	data = data[1:]
  4450  	p.Items = make([]*FlowSpecComponentItem, 0)
  4451  	for {
  4452  		if len(data) < 2 {
  4453  			return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "not all flowspec component bytes available")
  4454  		}
  4455  		op := data[0]
  4456  		end := op & 0x80
  4457  		l := 1 << ((op >> 4) & 0x3) // (min, max) = (1, 8)
  4458  		v := make([]byte, 8)
  4459  		copy(v[8-l:], data[1:1+l])
  4460  		i := binary.BigEndian.Uint64(v)
  4461  		item := &FlowSpecComponentItem{op, i}
  4462  		p.Items = append(p.Items, item)
  4463  		if end > 0 {
  4464  			break
  4465  		}
  4466  		data = data[1+l:]
  4467  	}
  4468  	return nil
  4469  }
  4470  
  4471  func (p *FlowSpecComponent) Serialize(options ...*MarshallingOption) ([]byte, error) {
  4472  	buf := []byte{byte(p.Type())}
  4473  	for _, v := range p.Items {
  4474  		bbuf, err := v.Serialize()
  4475  		if err != nil {
  4476  			return nil, err
  4477  		}
  4478  		buf = append(buf, bbuf...)
  4479  	}
  4480  	return buf, nil
  4481  }
  4482  
  4483  func (p *FlowSpecComponent) Len(options ...*MarshallingOption) int {
  4484  	l := 1
  4485  	for _, item := range p.Items {
  4486  		l += item.Len() + 1
  4487  	}
  4488  	return l
  4489  }
  4490  
  4491  func (p *FlowSpecComponent) Type() BGPFlowSpecType {
  4492  	return p.typ
  4493  }
  4494  
  4495  func formatRaw(op uint8, value uint64) string {
  4496  	return fmt.Sprintf("op:%b,value:%d", op, value)
  4497  }
  4498  
  4499  func formatNumeric(op uint8, value uint64) string {
  4500  	cmpFlag := DECNumOp(op & 0x7) // lower 3 bits
  4501  	if cmpFlag == DEC_NUM_OP_TRUE || cmpFlag == DEC_NUM_OP_FALSE {
  4502  		// Omit value field
  4503  		return DECNumOp(op).String()
  4504  	}
  4505  	return DECNumOp(op).String() + strconv.FormatUint(value, 10)
  4506  }
  4507  
  4508  func formatProto(op uint8, value uint64) string {
  4509  	cmpFlag := DECNumOp(op & 0x7) // lower 3 bits
  4510  	if cmpFlag == DEC_NUM_OP_TRUE || cmpFlag == DEC_NUM_OP_FALSE {
  4511  		// Omit value field
  4512  		return DECNumOp(op).String()
  4513  	}
  4514  	return DECNumOp(op).String() + Protocol(value).String()
  4515  }
  4516  
  4517  func formatTCPFlag(op uint8, value uint64) string {
  4518  	return BitmaskFlagOp(op).String() + TCPFlag(value).String()
  4519  }
  4520  
  4521  func formatFragment(op uint8, value uint64) string {
  4522  	return BitmaskFlagOp(op).String() + FragmentFlag(value).String()
  4523  }
  4524  
  4525  func formatEtherType(op uint8, value uint64) string {
  4526  	cmpFlag := DECNumOp(op & 0x7) // lower 3 bits
  4527  	if cmpFlag == DEC_NUM_OP_TRUE || cmpFlag == DEC_NUM_OP_FALSE {
  4528  		// Omit value field
  4529  		return DECNumOp(op).String()
  4530  	}
  4531  	return DECNumOp(op).String() + EthernetType(value).String()
  4532  }
  4533  
  4534  var flowSpecFormatMap = map[BGPFlowSpecType]func(op uint8, value uint64) string{
  4535  	FLOW_SPEC_TYPE_UNKNOWN:       formatRaw,
  4536  	FLOW_SPEC_TYPE_IP_PROTO:      formatProto,
  4537  	FLOW_SPEC_TYPE_PORT:          formatNumeric,
  4538  	FLOW_SPEC_TYPE_DST_PORT:      formatNumeric,
  4539  	FLOW_SPEC_TYPE_SRC_PORT:      formatNumeric,
  4540  	FLOW_SPEC_TYPE_ICMP_TYPE:     formatNumeric,
  4541  	FLOW_SPEC_TYPE_ICMP_CODE:     formatNumeric,
  4542  	FLOW_SPEC_TYPE_TCP_FLAG:      formatTCPFlag,
  4543  	FLOW_SPEC_TYPE_PKT_LEN:       formatNumeric,
  4544  	FLOW_SPEC_TYPE_DSCP:          formatNumeric,
  4545  	FLOW_SPEC_TYPE_FRAGMENT:      formatFragment,
  4546  	FLOW_SPEC_TYPE_LABEL:         formatNumeric,
  4547  	FLOW_SPEC_TYPE_ETHERNET_TYPE: formatEtherType,
  4548  	FLOW_SPEC_TYPE_LLC_DSAP:      formatNumeric,
  4549  	FLOW_SPEC_TYPE_LLC_SSAP:      formatNumeric,
  4550  	FLOW_SPEC_TYPE_LLC_CONTROL:   formatNumeric,
  4551  	FLOW_SPEC_TYPE_SNAP:          formatNumeric,
  4552  	FLOW_SPEC_TYPE_VID:           formatNumeric,
  4553  	FLOW_SPEC_TYPE_COS:           formatNumeric,
  4554  	FLOW_SPEC_TYPE_INNER_VID:     formatNumeric,
  4555  	FLOW_SPEC_TYPE_INNER_COS:     formatNumeric,
  4556  }
  4557  
  4558  func (p *FlowSpecComponent) String() string {
  4559  	f := flowSpecFormatMap[FLOW_SPEC_TYPE_UNKNOWN]
  4560  	if _, ok := flowSpecFormatMap[p.typ]; ok {
  4561  		f = flowSpecFormatMap[p.typ]
  4562  	}
  4563  
  4564  	items := make([]string, 0, len(p.Items))
  4565  	for _, i := range p.Items {
  4566  		items = append(items, f(i.Op, i.Value))
  4567  	}
  4568  	// Removes leading and tailing spaces
  4569  	value := strings.TrimSpace(strings.Join(items, ""))
  4570  
  4571  	return fmt.Sprintf("[%s: %s]", p.typ, value)
  4572  }
  4573  
  4574  func (p *FlowSpecComponent) MarshalJSON() ([]byte, error) {
  4575  	return json.Marshal(struct {
  4576  		Type  BGPFlowSpecType          `json:"type"`
  4577  		Value []*FlowSpecComponentItem `json:"value"`
  4578  	}{
  4579  		Type:  p.Type(),
  4580  		Value: p.Items,
  4581  	})
  4582  }
  4583  
  4584  func NewFlowSpecComponent(typ BGPFlowSpecType, items []*FlowSpecComponentItem) *FlowSpecComponent {
  4585  	// Set end-of-list bit on the last item and unset them on the others.
  4586  	for i, v := range items {
  4587  		if i == len(items)-1 {
  4588  			v.Op |= 0x80
  4589  		} else {
  4590  			v.Op &^= 0x80
  4591  		}
  4592  
  4593  	}
  4594  	return &FlowSpecComponent{
  4595  		Items: items,
  4596  		typ:   typ,
  4597  	}
  4598  }
  4599  
  4600  type FlowSpecUnknown struct {
  4601  	Value []byte
  4602  }
  4603  
  4604  func (p *FlowSpecUnknown) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
  4605  	p.Value = data
  4606  	return nil
  4607  }
  4608  
  4609  func (p *FlowSpecUnknown) Serialize(options ...*MarshallingOption) ([]byte, error) {
  4610  	return p.Value, nil
  4611  }
  4612  
  4613  func (p *FlowSpecUnknown) Len(options ...*MarshallingOption) int {
  4614  	return len(p.Value)
  4615  }
  4616  
  4617  func (p *FlowSpecUnknown) Type() BGPFlowSpecType {
  4618  	if len(p.Value) > 0 {
  4619  		return BGPFlowSpecType(p.Value[0])
  4620  	}
  4621  	return FLOW_SPEC_TYPE_UNKNOWN
  4622  }
  4623  
  4624  func (p *FlowSpecUnknown) String() string {
  4625  	return fmt.Sprintf("[unknown:%v]", p.Value)
  4626  }
  4627  
  4628  func (p *FlowSpecUnknown) MarshalJSON() ([]byte, error) {
  4629  	return json.Marshal(struct {
  4630  		Type  BGPFlowSpecType `json:"type"`
  4631  		Value string          `json:"value"`
  4632  	}{
  4633  		Type:  p.Type(),
  4634  		Value: string(p.Value),
  4635  	})
  4636  }
  4637  
  4638  type FlowSpecNLRI struct {
  4639  	PrefixDefault
  4640  	Value []FlowSpecComponentInterface
  4641  	rf    RouteFamily
  4642  	rd    RouteDistinguisherInterface
  4643  }
  4644  
  4645  func (n *FlowSpecNLRI) AFI() uint16 {
  4646  	afi, _ := RouteFamilyToAfiSafi(n.rf)
  4647  	return afi
  4648  }
  4649  
  4650  func (n *FlowSpecNLRI) SAFI() uint8 {
  4651  	_, safi := RouteFamilyToAfiSafi(n.rf)
  4652  	return safi
  4653  }
  4654  
  4655  func (n *FlowSpecNLRI) RD() RouteDistinguisherInterface {
  4656  	return n.rd
  4657  }
  4658  
  4659  func (n *FlowSpecNLRI) decodeFromBytes(rf RouteFamily, data []byte, options ...*MarshallingOption) error {
  4660  	if IsAddPathEnabled(true, rf, options) {
  4661  		var err error
  4662  		data, err = n.decodePathIdentifier(data)
  4663  		if err != nil {
  4664  			return err
  4665  		}
  4666  	}
  4667  	var length int
  4668  	if (data[0]>>4) == 0xf && len(data) > 2 {
  4669  		length = int(binary.BigEndian.Uint16(data[0:2]))
  4670  		data = data[2:]
  4671  	} else if len(data) > 1 {
  4672  		length = int(data[0])
  4673  		data = data[1:]
  4674  	} else {
  4675  		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "not all flowspec component bytes available")
  4676  	}
  4677  	if len(data) < length {
  4678  		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "not all flowspec component bytes available")
  4679  	}
  4680  
  4681  	n.rf = rf
  4682  
  4683  	if n.SAFI() == SAFI_FLOW_SPEC_VPN {
  4684  		if length < 8 {
  4685  			return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "not all flowspec component bytes available")
  4686  		}
  4687  		n.rd = GetRouteDistinguisher(data[:8])
  4688  		data = data[8:]
  4689  		length -= 8
  4690  	}
  4691  
  4692  	for l := length; l > 0; {
  4693  		if len(data) == 0 {
  4694  			return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "not all flowspec component bytes available")
  4695  		}
  4696  		t := BGPFlowSpecType(data[0])
  4697  		var i FlowSpecComponentInterface
  4698  		switch t {
  4699  		case FLOW_SPEC_TYPE_DST_PREFIX:
  4700  			switch {
  4701  			case rf>>16 == AFI_IP:
  4702  				i = NewFlowSpecDestinationPrefix(NewIPAddrPrefix(0, ""))
  4703  			case rf>>16 == AFI_IP6:
  4704  				i = NewFlowSpecDestinationPrefix6(NewIPv6AddrPrefix(0, ""), 0)
  4705  			default:
  4706  				return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("Invalid address family: %v", rf))
  4707  			}
  4708  		case FLOW_SPEC_TYPE_SRC_PREFIX:
  4709  			switch {
  4710  			case rf>>16 == AFI_IP:
  4711  				i = NewFlowSpecSourcePrefix(NewIPAddrPrefix(0, ""))
  4712  			case rf>>16 == AFI_IP6:
  4713  				i = NewFlowSpecSourcePrefix6(NewIPv6AddrPrefix(0, ""), 0)
  4714  			default:
  4715  				return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("Invalid address family: %v", rf))
  4716  			}
  4717  		case FLOW_SPEC_TYPE_SRC_MAC:
  4718  			switch rf {
  4719  			case RF_FS_L2_VPN:
  4720  				i = NewFlowSpecSourceMac(nil)
  4721  			default:
  4722  				return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("Invalid address family: %v", rf))
  4723  			}
  4724  		case FLOW_SPEC_TYPE_DST_MAC:
  4725  			switch rf {
  4726  			case RF_FS_L2_VPN:
  4727  				i = NewFlowSpecDestinationMac(nil)
  4728  			default:
  4729  				return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("Invalid address family: %v", rf))
  4730  			}
  4731  		case FLOW_SPEC_TYPE_IP_PROTO, FLOW_SPEC_TYPE_PORT, FLOW_SPEC_TYPE_DST_PORT, FLOW_SPEC_TYPE_SRC_PORT,
  4732  			FLOW_SPEC_TYPE_ICMP_TYPE, FLOW_SPEC_TYPE_ICMP_CODE, FLOW_SPEC_TYPE_TCP_FLAG, FLOW_SPEC_TYPE_PKT_LEN,
  4733  			FLOW_SPEC_TYPE_DSCP, FLOW_SPEC_TYPE_FRAGMENT, FLOW_SPEC_TYPE_LABEL, FLOW_SPEC_TYPE_ETHERNET_TYPE,
  4734  			FLOW_SPEC_TYPE_LLC_DSAP, FLOW_SPEC_TYPE_LLC_SSAP, FLOW_SPEC_TYPE_LLC_CONTROL, FLOW_SPEC_TYPE_SNAP,
  4735  			FLOW_SPEC_TYPE_VID, FLOW_SPEC_TYPE_COS, FLOW_SPEC_TYPE_INNER_VID, FLOW_SPEC_TYPE_INNER_COS:
  4736  			i = NewFlowSpecComponent(t, nil)
  4737  		default:
  4738  			i = &FlowSpecUnknown{}
  4739  		}
  4740  
  4741  		err := i.DecodeFromBytes(data, options...)
  4742  		if err != nil {
  4743  			i = &FlowSpecUnknown{data}
  4744  		}
  4745  		l -= i.Len(options...)
  4746  		data = data[i.Len(options...):]
  4747  		n.Value = append(n.Value, i)
  4748  	}
  4749  
  4750  	// Sort Traffic Filtering Rules in types order to avoid the unordered rules
  4751  	// are determined different.
  4752  	sort.SliceStable(n.Value, func(i, j int) bool { return n.Value[i].Type() < n.Value[j].Type() })
  4753  
  4754  	return nil
  4755  }
  4756  
  4757  func (n *FlowSpecNLRI) Serialize(options ...*MarshallingOption) ([]byte, error) {
  4758  	buf := make([]byte, 0, 32)
  4759  	if n.SAFI() == SAFI_FLOW_SPEC_VPN {
  4760  		if n.rd == nil {
  4761  			return nil, errors.New("RD is nil")
  4762  		}
  4763  		b, err := n.rd.Serialize()
  4764  		if err != nil {
  4765  			return nil, err
  4766  		}
  4767  		buf = append(buf, b...)
  4768  	}
  4769  	for _, v := range n.Value {
  4770  		b, err := v.Serialize(options...)
  4771  		if err != nil {
  4772  			return nil, err
  4773  		}
  4774  		buf = append(buf, b...)
  4775  	}
  4776  	length := n.Len(options...)
  4777  	if length > 0xfff {
  4778  		return nil, fmt.Errorf("too large: %d", length)
  4779  	} else if length < 0xf0 {
  4780  		length -= 1
  4781  		buf = append([]byte{byte(length)}, buf...)
  4782  	} else {
  4783  		length -= 2
  4784  		b := make([]byte, 2)
  4785  		binary.BigEndian.PutUint16(buf, uint16(length))
  4786  		buf = append(b, buf...)
  4787  	}
  4788  
  4789  	if IsAddPathEnabled(false, n.rf, options) {
  4790  		id, err := n.serializeIdentifier()
  4791  		if err != nil {
  4792  			return nil, err
  4793  		}
  4794  		return append(id, buf...), nil
  4795  	}
  4796  	return buf, nil
  4797  }
  4798  
  4799  func (n *FlowSpecNLRI) Len(options ...*MarshallingOption) int {
  4800  	l := 0
  4801  	if n.SAFI() == SAFI_FLOW_SPEC_VPN {
  4802  		l += n.RD().Len()
  4803  	}
  4804  	for _, v := range n.Value {
  4805  		l += v.Len(options...)
  4806  	}
  4807  	if l < 0xf0 {
  4808  		return l + 1
  4809  	} else {
  4810  		return l + 2
  4811  	}
  4812  }
  4813  
  4814  func (n *FlowSpecNLRI) String() string {
  4815  	buf := bytes.NewBuffer(make([]byte, 0, 32))
  4816  	if n.SAFI() == SAFI_FLOW_SPEC_VPN {
  4817  		buf.WriteString("[rd: ")
  4818  		buf.WriteString(n.rd.String())
  4819  		buf.WriteString("]")
  4820  	}
  4821  	for _, v := range n.Value {
  4822  		buf.WriteString(v.String())
  4823  	}
  4824  	return buf.String()
  4825  }
  4826  
  4827  func (n *FlowSpecNLRI) MarshalJSON() ([]byte, error) {
  4828  	if n.rd != nil {
  4829  		return json.Marshal(struct {
  4830  			RD    RouteDistinguisherInterface  `json:"rd"`
  4831  			Value []FlowSpecComponentInterface `json:"value"`
  4832  		}{
  4833  			RD:    n.rd,
  4834  			Value: n.Value,
  4835  		})
  4836  	}
  4837  	return json.Marshal(struct {
  4838  		Value []FlowSpecComponentInterface `json:"value"`
  4839  	}{
  4840  		Value: n.Value,
  4841  	})
  4842  
  4843  }
  4844  
  4845  // CompareFlowSpecNLRI(n, m) returns
  4846  // -1 when m has precedence
  4847  //
  4848  //	0 when n and m have same precedence
  4849  //	1 when n has precedence
  4850  func CompareFlowSpecNLRI(n, m *FlowSpecNLRI) (int, error) {
  4851  	family := AfiSafiToRouteFamily(n.AFI(), n.SAFI())
  4852  	if family != AfiSafiToRouteFamily(m.AFI(), m.SAFI()) {
  4853  		return 0, errors.New("address family mismatch")
  4854  	}
  4855  	longer := n.Value
  4856  	shorter := m.Value
  4857  	invert := 1
  4858  	if n.SAFI() == SAFI_FLOW_SPEC_VPN {
  4859  		k, _ := n.Serialize()
  4860  		l, _ := m.Serialize()
  4861  		if result := bytes.Compare(k, l); result != 0 {
  4862  			return result, nil
  4863  		}
  4864  	}
  4865  	if len(n.Value) < len(m.Value) {
  4866  		longer = m.Value
  4867  		shorter = n.Value
  4868  		invert = -1
  4869  	}
  4870  	for idx, v := range longer {
  4871  		if len(shorter) < idx+1 {
  4872  			return invert, nil
  4873  		}
  4874  		w := shorter[idx]
  4875  		if v.Type() < w.Type() {
  4876  			return invert, nil
  4877  		} else if v.Type() > w.Type() {
  4878  			return invert * -1, nil
  4879  		} else if v.Type() == FLOW_SPEC_TYPE_DST_PREFIX || v.Type() == FLOW_SPEC_TYPE_SRC_PREFIX {
  4880  			// RFC5575 5.1
  4881  			//
  4882  			// For IP prefix values (IP destination and source prefix) precedence is
  4883  			// given to the lowest IP value of the common prefix length; if the
  4884  			// common prefix is equal, then the most specific prefix has precedence.
  4885  			var p, q *IPAddrPrefixDefault
  4886  			var pCommon, qCommon uint64
  4887  			if n.AFI() == AFI_IP {
  4888  				if v.Type() == FLOW_SPEC_TYPE_DST_PREFIX {
  4889  					p = &v.(*FlowSpecDestinationPrefix).Prefix.(*IPAddrPrefix).IPAddrPrefixDefault
  4890  					q = &w.(*FlowSpecDestinationPrefix).Prefix.(*IPAddrPrefix).IPAddrPrefixDefault
  4891  				} else {
  4892  					p = &v.(*FlowSpecSourcePrefix).Prefix.(*IPAddrPrefix).IPAddrPrefixDefault
  4893  					q = &w.(*FlowSpecSourcePrefix).Prefix.(*IPAddrPrefix).IPAddrPrefixDefault
  4894  				}
  4895  				min := p.Length
  4896  				if q.Length < p.Length {
  4897  					min = q.Length
  4898  				}
  4899  				pCommon = uint64(binary.BigEndian.Uint32([]byte(p.Prefix.To4())) >> (32 - min))
  4900  				qCommon = uint64(binary.BigEndian.Uint32([]byte(q.Prefix.To4())) >> (32 - min))
  4901  			} else if n.AFI() == AFI_IP6 {
  4902  				if v.Type() == FLOW_SPEC_TYPE_DST_PREFIX {
  4903  					p = &v.(*FlowSpecDestinationPrefix6).Prefix.(*IPv6AddrPrefix).IPAddrPrefixDefault
  4904  					q = &w.(*FlowSpecDestinationPrefix6).Prefix.(*IPv6AddrPrefix).IPAddrPrefixDefault
  4905  				} else {
  4906  					p = &v.(*FlowSpecSourcePrefix6).Prefix.(*IPv6AddrPrefix).IPAddrPrefixDefault
  4907  					q = &w.(*FlowSpecSourcePrefix6).Prefix.(*IPv6AddrPrefix).IPAddrPrefixDefault
  4908  				}
  4909  				min := uint(p.Length)
  4910  				if q.Length < p.Length {
  4911  					min = uint(q.Length)
  4912  				}
  4913  				var mask uint
  4914  				if min-64 > 0 {
  4915  					mask = min - 64
  4916  				}
  4917  				pCommon = binary.BigEndian.Uint64([]byte(p.Prefix.To16()[:8])) >> mask
  4918  				qCommon = binary.BigEndian.Uint64([]byte(q.Prefix.To16()[:8])) >> mask
  4919  				if pCommon == qCommon && mask == 0 {
  4920  					mask = 64 - min
  4921  					pCommon = binary.BigEndian.Uint64([]byte(p.Prefix.To16()[8:])) >> mask
  4922  					qCommon = binary.BigEndian.Uint64([]byte(q.Prefix.To16()[8:])) >> mask
  4923  				}
  4924  			}
  4925  
  4926  			if pCommon < qCommon {
  4927  				return invert, nil
  4928  			} else if pCommon > qCommon {
  4929  				return invert * -1, nil
  4930  			} else if p.Length > q.Length {
  4931  				return invert, nil
  4932  			} else if p.Length < q.Length {
  4933  				return invert * -1, nil
  4934  			}
  4935  
  4936  		} else {
  4937  			// RFC5575 5.1
  4938  			//
  4939  			// For all other component types, unless otherwise specified, the
  4940  			// comparison is performed by comparing the component data as a binary
  4941  			// string using the memcmp() function as defined by the ISO C standard.
  4942  			// For strings of different lengths, the common prefix is compared.  If
  4943  			// equal, the longest string is considered to have higher precedence
  4944  			// than the shorter one.
  4945  			p, _ := v.Serialize()
  4946  			q, _ := w.Serialize()
  4947  			min := len(p)
  4948  			if len(q) < len(p) {
  4949  				min = len(q)
  4950  			}
  4951  			if result := bytes.Compare(p[:min], q[:min]); result < 0 {
  4952  				return invert, nil
  4953  			} else if result > 0 {
  4954  				return invert * -1, nil
  4955  			} else if len(p) > len(q) {
  4956  				return invert, nil
  4957  			} else if len(q) > len(p) {
  4958  				return invert * -1, nil
  4959  			}
  4960  		}
  4961  	}
  4962  	return 0, nil
  4963  }
  4964  
  4965  type FlowSpecIPv4Unicast struct {
  4966  	FlowSpecNLRI
  4967  }
  4968  
  4969  func (n *FlowSpecIPv4Unicast) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
  4970  	return n.decodeFromBytes(AfiSafiToRouteFamily(n.AFI(), n.SAFI()), data, options...)
  4971  }
  4972  
  4973  func NewFlowSpecIPv4Unicast(value []FlowSpecComponentInterface) *FlowSpecIPv4Unicast {
  4974  	sort.SliceStable(value, func(i, j int) bool { return value[i].Type() < value[j].Type() })
  4975  	return &FlowSpecIPv4Unicast{
  4976  		FlowSpecNLRI: FlowSpecNLRI{
  4977  			Value: value,
  4978  			rf:    RF_FS_IPv4_UC,
  4979  		},
  4980  	}
  4981  }
  4982  
  4983  type FlowSpecIPv4VPN struct {
  4984  	FlowSpecNLRI
  4985  }
  4986  
  4987  func (n *FlowSpecIPv4VPN) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
  4988  	return n.decodeFromBytes(AfiSafiToRouteFamily(n.AFI(), n.SAFI()), data, options...)
  4989  }
  4990  
  4991  func NewFlowSpecIPv4VPN(rd RouteDistinguisherInterface, value []FlowSpecComponentInterface) *FlowSpecIPv4VPN {
  4992  	sort.SliceStable(value, func(i, j int) bool { return value[i].Type() < value[j].Type() })
  4993  	return &FlowSpecIPv4VPN{
  4994  		FlowSpecNLRI: FlowSpecNLRI{
  4995  			Value: value,
  4996  			rf:    RF_FS_IPv4_VPN,
  4997  			rd:    rd,
  4998  		},
  4999  	}
  5000  }
  5001  
  5002  type FlowSpecIPv6Unicast struct {
  5003  	FlowSpecNLRI
  5004  }
  5005  
  5006  func (n *FlowSpecIPv6Unicast) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
  5007  	return n.decodeFromBytes(AfiSafiToRouteFamily(n.AFI(), n.SAFI()), data, options...)
  5008  }
  5009  
  5010  func NewFlowSpecIPv6Unicast(value []FlowSpecComponentInterface) *FlowSpecIPv6Unicast {
  5011  	sort.SliceStable(value, func(i, j int) bool { return value[i].Type() < value[j].Type() })
  5012  	return &FlowSpecIPv6Unicast{
  5013  		FlowSpecNLRI: FlowSpecNLRI{
  5014  			Value: value,
  5015  			rf:    RF_FS_IPv6_UC,
  5016  		},
  5017  	}
  5018  }
  5019  
  5020  type FlowSpecIPv6VPN struct {
  5021  	FlowSpecNLRI
  5022  }
  5023  
  5024  func (n *FlowSpecIPv6VPN) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
  5025  	return n.decodeFromBytes(AfiSafiToRouteFamily(n.AFI(), n.SAFI()), data, options...)
  5026  }
  5027  
  5028  func NewFlowSpecIPv6VPN(rd RouteDistinguisherInterface, value []FlowSpecComponentInterface) *FlowSpecIPv6VPN {
  5029  	sort.SliceStable(value, func(i, j int) bool { return value[i].Type() < value[j].Type() })
  5030  	return &FlowSpecIPv6VPN{
  5031  		FlowSpecNLRI: FlowSpecNLRI{
  5032  			Value: value,
  5033  			rf:    RF_FS_IPv6_VPN,
  5034  			rd:    rd,
  5035  		},
  5036  	}
  5037  }
  5038  
  5039  type FlowSpecL2VPN struct {
  5040  	FlowSpecNLRI
  5041  }
  5042  
  5043  func (n *FlowSpecL2VPN) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
  5044  	return n.decodeFromBytes(AfiSafiToRouteFamily(n.AFI(), n.SAFI()), data)
  5045  }
  5046  
  5047  func NewFlowSpecL2VPN(rd RouteDistinguisherInterface, value []FlowSpecComponentInterface) *FlowSpecL2VPN {
  5048  	sort.SliceStable(value, func(i, j int) bool { return value[i].Type() < value[j].Type() })
  5049  	return &FlowSpecL2VPN{
  5050  		FlowSpecNLRI: FlowSpecNLRI{
  5051  			Value: value,
  5052  			rf:    RF_FS_L2_VPN,
  5053  			rd:    rd,
  5054  		},
  5055  	}
  5056  }
  5057  
  5058  type OpaqueNLRI struct {
  5059  	PrefixDefault
  5060  	Length uint16
  5061  	Key    []byte
  5062  	Value  []byte
  5063  }
  5064  
  5065  func (n *OpaqueNLRI) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
  5066  	if len(data) < 2 {
  5067  		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "Not all OpaqueNLRI bytes available")
  5068  	}
  5069  	if IsAddPathEnabled(true, RF_OPAQUE, options) {
  5070  		var err error
  5071  		data, err = n.decodePathIdentifier(data)
  5072  		if err != nil {
  5073  			return err
  5074  		}
  5075  	}
  5076  	n.Length = binary.BigEndian.Uint16(data[0:2])
  5077  	if len(data)-2 < int(n.Length) {
  5078  		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "Not all OpaqueNLRI bytes available")
  5079  	}
  5080  	n.Key = data[2 : 2+n.Length]
  5081  	n.Value = data[2+n.Length:]
  5082  	return nil
  5083  }
  5084  
  5085  func (n *OpaqueNLRI) Serialize(options ...*MarshallingOption) ([]byte, error) {
  5086  	keyLen := len(n.Key)
  5087  	if keyLen > math.MaxUint16 {
  5088  		return nil, errors.New("key length too big")
  5089  	}
  5090  	buf := make([]byte, 2, 2+keyLen+len(n.Value))
  5091  	binary.BigEndian.PutUint16(buf[:2], uint16(keyLen))
  5092  	buf = append(buf, n.Key...)
  5093  	buf = append(buf, n.Value...)
  5094  	if IsAddPathEnabled(false, RF_OPAQUE, options) {
  5095  		id, err := n.serializeIdentifier()
  5096  		if err != nil {
  5097  			return nil, err
  5098  		}
  5099  		return append(id, buf...), nil
  5100  	}
  5101  	return buf, nil
  5102  }
  5103  
  5104  func (n *OpaqueNLRI) AFI() uint16 {
  5105  	return AFI_OPAQUE
  5106  }
  5107  
  5108  func (n *OpaqueNLRI) SAFI() uint8 {
  5109  	return SAFI_KEY_VALUE
  5110  }
  5111  
  5112  func (n *OpaqueNLRI) Len(options ...*MarshallingOption) int {
  5113  	return 2 + len(n.Key) + len(n.Value)
  5114  }
  5115  
  5116  func (n *OpaqueNLRI) String() string {
  5117  	return string(n.Key)
  5118  }
  5119  
  5120  func (n *OpaqueNLRI) MarshalJSON() ([]byte, error) {
  5121  	return json.Marshal(struct {
  5122  		Key   string `json:"key"`
  5123  		Value string `json:"value"`
  5124  	}{
  5125  		Key:   string(n.Key),
  5126  		Value: string(n.Value),
  5127  	})
  5128  }
  5129  
  5130  func NewOpaqueNLRI(key, value []byte) *OpaqueNLRI {
  5131  	return &OpaqueNLRI{
  5132  		Key:   key,
  5133  		Value: value,
  5134  	}
  5135  }
  5136  
  5137  type LsNLRIType uint16
  5138  
  5139  const (
  5140  	LS_NLRI_TYPE_UNKNOWN LsNLRIType = iota
  5141  	LS_NLRI_TYPE_NODE
  5142  	LS_NLRI_TYPE_LINK
  5143  	LS_NLRI_TYPE_PREFIX_IPV4
  5144  	LS_NLRI_TYPE_PREFIX_IPV6
  5145  )
  5146  
  5147  type LsNLRIInterface interface {
  5148  	DecodeFromBytes([]byte) error
  5149  	Serialize() ([]byte, error)
  5150  	Len() int
  5151  	Type() LsNLRIType
  5152  	String() string
  5153  }
  5154  
  5155  type LsProtocolID uint8
  5156  
  5157  const (
  5158  	LS_PROTOCOL_UNKNOWN = iota
  5159  	LS_PROTOCOL_ISIS_L1
  5160  	LS_PROTOCOL_ISIS_L2
  5161  	LS_PROTOCOL_OSPF_V2
  5162  	LS_PROTOCOL_DIRECT
  5163  	LS_PROTOCOL_STATIC
  5164  	LS_PROTOCOL_OSPF_V3
  5165  	LS_PROTOCOL_BGP
  5166  )
  5167  
  5168  func (l LsProtocolID) String() string {
  5169  	switch l {
  5170  	case LS_PROTOCOL_ISIS_L1:
  5171  		return "ISIS-L1"
  5172  	case LS_PROTOCOL_ISIS_L2:
  5173  		return "ISIS-L2"
  5174  	case LS_PROTOCOL_OSPF_V2:
  5175  		return "OSPFv2"
  5176  	case LS_PROTOCOL_DIRECT:
  5177  		return "DIRECT"
  5178  	case LS_PROTOCOL_STATIC:
  5179  		return "STATIC"
  5180  	case LS_PROTOCOL_OSPF_V3:
  5181  		return "OSPFv3"
  5182  	case LS_PROTOCOL_BGP:
  5183  		return "BGP"
  5184  	default:
  5185  		return fmt.Sprintf("LsProtocolID(%d)", uint8(l))
  5186  	}
  5187  }
  5188  
  5189  type LsNLRI struct {
  5190  	NLRIType   LsNLRIType
  5191  	Length     uint16
  5192  	ProtocolID LsProtocolID
  5193  	Identifier uint64
  5194  }
  5195  
  5196  const lsNLRIHdrLen = 9
  5197  
  5198  func (l *LsNLRI) DecodeFromBytes(data []byte) error {
  5199  	if len(data) < lsNLRIHdrLen {
  5200  		return malformedAttrListErr("Malformed NLRI")
  5201  	}
  5202  
  5203  	l.ProtocolID = LsProtocolID(data[0])
  5204  	l.Identifier = binary.BigEndian.Uint64(data[1:lsNLRIHdrLen])
  5205  
  5206  	return nil
  5207  }
  5208  
  5209  func (l *LsNLRI) Serialize(value []byte) ([]byte, error) {
  5210  	buf := make([]byte, lsNLRIHdrLen)
  5211  	buf[0] = uint8(l.ProtocolID)
  5212  	binary.BigEndian.PutUint64(buf[1:], l.Identifier)
  5213  	buf = append(buf, value...)
  5214  
  5215  	return buf, nil
  5216  }
  5217  
  5218  func (l *LsNLRI) Len() int {
  5219  	return int(l.Length)
  5220  }
  5221  
  5222  func (l *LsNLRI) Type() LsNLRIType {
  5223  	return l.NLRIType
  5224  }
  5225  
  5226  type LsNodeNLRI struct {
  5227  	LsNLRI
  5228  	LocalNodeDesc LsTLVInterface
  5229  }
  5230  
  5231  func (l *LsNodeNLRI) DecodeFromBytes(data []byte) error {
  5232  	if err := l.LsNLRI.DecodeFromBytes(data); err != nil {
  5233  		return nil
  5234  	}
  5235  
  5236  	tlv := data[lsNLRIHdrLen:]
  5237  	if len(tlv) < tlvHdrLen {
  5238  		return malformedAttrListErr("Malformed Node NLRI")
  5239  	}
  5240  
  5241  	tlvType := LsTLVType(binary.BigEndian.Uint16(tlv[:2]))
  5242  	if tlvType != LS_TLV_LOCAL_NODE_DESC {
  5243  		return malformedAttrListErr("Mandatory TLV missing")
  5244  	}
  5245  
  5246  	l.LocalNodeDesc = &LsTLVNodeDescriptor{}
  5247  	if err := l.LocalNodeDesc.DecodeFromBytes(tlv); err != nil {
  5248  		return malformedAttrListErr(fmt.Sprintf("Malformed Node NLRI: %v", err))
  5249  	}
  5250  
  5251  	return nil
  5252  }
  5253  
  5254  func (l *LsNodeNLRI) String() string {
  5255  	if l.LocalNodeDesc == nil {
  5256  		return "NODE { EMPTY }"
  5257  	}
  5258  
  5259  	local := l.LocalNodeDesc.(*LsTLVNodeDescriptor).Extract()
  5260  	return fmt.Sprintf("NODE { AS:%v BGP-LS ID:%v %v %v:%v }", local.Asn, local.BGPLsID, local.IGPRouterID, l.ProtocolID.String(), l.Identifier)
  5261  }
  5262  
  5263  func (l *LsNodeNLRI) Serialize() ([]byte, error) {
  5264  	if l.LocalNodeDesc == nil {
  5265  		return nil, errors.New("local node descriptor missing")
  5266  	}
  5267  	ser, err := l.LocalNodeDesc.Serialize()
  5268  	if err != nil {
  5269  		return nil, err
  5270  	}
  5271  
  5272  	return l.LsNLRI.Serialize(ser)
  5273  }
  5274  
  5275  func (l *LsNodeNLRI) MarshalJSON() ([]byte, error) {
  5276  	return json.Marshal(struct {
  5277  		Type      LsNLRIType       `json:"type"`
  5278  		LocalNode LsNodeDescriptor `json:"local_node_desc"`
  5279  	}{
  5280  		Type:      l.Type(),
  5281  		LocalNode: *l.LocalNodeDesc.(*LsTLVNodeDescriptor).Extract(),
  5282  	})
  5283  }
  5284  
  5285  type LsLinkDescriptor struct {
  5286  	LinkLocalID       *uint32
  5287  	LinkRemoteID      *uint32
  5288  	InterfaceAddrIPv4 *net.IP
  5289  	NeighborAddrIPv4  *net.IP
  5290  	InterfaceAddrIPv6 *net.IP
  5291  	NeighborAddrIPv6  *net.IP
  5292  }
  5293  
  5294  func (l *LsLinkDescriptor) ParseTLVs(tlvs []LsTLVInterface) {
  5295  	for _, tlv := range tlvs {
  5296  		switch v := tlv.(type) {
  5297  		case *LsTLVLinkID:
  5298  			l.LinkLocalID = &v.Local
  5299  			l.LinkRemoteID = &v.Remote
  5300  
  5301  		case *LsTLVIPv4InterfaceAddr:
  5302  			l.InterfaceAddrIPv4 = &v.IP
  5303  
  5304  		case *LsTLVIPv4NeighborAddr:
  5305  			l.NeighborAddrIPv4 = &v.IP
  5306  
  5307  		case *LsTLVIPv6InterfaceAddr:
  5308  			l.InterfaceAddrIPv6 = &v.IP
  5309  
  5310  		case *LsTLVIPv6NeighborAddr:
  5311  			l.NeighborAddrIPv6 = &v.IP
  5312  		}
  5313  	}
  5314  }
  5315  
  5316  func (l *LsLinkDescriptor) String() string {
  5317  	switch {
  5318  	case l.InterfaceAddrIPv4 != nil && l.NeighborAddrIPv4 != nil:
  5319  		return fmt.Sprintf("%v->%v", l.InterfaceAddrIPv4, l.NeighborAddrIPv4)
  5320  
  5321  	case l.InterfaceAddrIPv6 != nil && l.NeighborAddrIPv6 != nil:
  5322  		return fmt.Sprintf("%v->%v", l.InterfaceAddrIPv6, l.NeighborAddrIPv6)
  5323  
  5324  	case l.LinkLocalID != nil && l.LinkRemoteID != nil:
  5325  		return fmt.Sprintf("%v->%v", *l.LinkLocalID, *l.LinkRemoteID)
  5326  
  5327  	case l.InterfaceAddrIPv4 != nil:
  5328  		return fmt.Sprintf("%v->UNKNOWN", l.InterfaceAddrIPv4)
  5329  	case l.NeighborAddrIPv4 != nil:
  5330  		return fmt.Sprintf("UNKNOWN->%v", l.NeighborAddrIPv4)
  5331  
  5332  	case l.InterfaceAddrIPv6 != nil:
  5333  		return fmt.Sprintf("%v->UNKNOWN", l.InterfaceAddrIPv6)
  5334  	case l.NeighborAddrIPv6 != nil:
  5335  		return fmt.Sprintf("UNKNOWN->%v", l.NeighborAddrIPv6)
  5336  
  5337  	case l.LinkLocalID != nil:
  5338  		return fmt.Sprintf("%v->UNKNOWN", *l.LinkLocalID)
  5339  	case l.LinkRemoteID != nil:
  5340  		return fmt.Sprintf("UNKNOWN->%v", *l.LinkRemoteID)
  5341  
  5342  	default:
  5343  		return "UNKNOWN"
  5344  	}
  5345  }
  5346  
  5347  func NewLsLinkTLVs(ld *LsLinkDescriptor) []LsTLVInterface {
  5348  	tlvs := []LsTLVInterface{}
  5349  
  5350  	if ld.LinkLocalID != nil && ld.LinkRemoteID != nil {
  5351  		tlvs = append(tlvs, &LsTLVLinkID{
  5352  			// https://tools.ietf.org/html/rfc5307#section-1.1
  5353  			LsTLV: LsTLV{
  5354  				Type:   LS_TLV_LINK_ID,
  5355  				Length: 8,
  5356  			},
  5357  			Local:  *ld.LinkLocalID,
  5358  			Remote: *ld.LinkRemoteID,
  5359  		})
  5360  	}
  5361  
  5362  	if ld.InterfaceAddrIPv4 != nil {
  5363  		tlvs = append(tlvs, &LsTLVIPv4InterfaceAddr{
  5364  			LsTLV: LsTLV{
  5365  				Type:   LS_TLV_IPV4_INTERFACE_ADDR,
  5366  				Length: net.IPv4len,
  5367  			},
  5368  			IP: *ld.InterfaceAddrIPv4,
  5369  		})
  5370  	}
  5371  	if ld.NeighborAddrIPv4 != nil {
  5372  		tlvs = append(tlvs, &LsTLVIPv4NeighborAddr{
  5373  			LsTLV: LsTLV{
  5374  				Type:   LS_TLV_IPV4_NEIGHBOR_ADDR,
  5375  				Length: net.IPv4len,
  5376  			},
  5377  			IP: *ld.NeighborAddrIPv4,
  5378  		})
  5379  	}
  5380  	if ld.InterfaceAddrIPv6 != nil {
  5381  		tlvs = append(tlvs, &LsTLVIPv6InterfaceAddr{
  5382  			LsTLV: LsTLV{
  5383  				Type:   LS_TLV_IPV6_INTERFACE_ADDR,
  5384  				Length: net.IPv6len,
  5385  			},
  5386  			IP: *ld.InterfaceAddrIPv6,
  5387  		})
  5388  	}
  5389  	if ld.NeighborAddrIPv6 != nil {
  5390  		tlvs = append(tlvs, &LsTLVIPv6NeighborAddr{
  5391  			LsTLV: LsTLV{
  5392  				Type:   LS_TLV_IPV6_NEIGHBOR_ADDR,
  5393  				Length: net.IPv6len,
  5394  			},
  5395  			IP: *ld.NeighborAddrIPv6,
  5396  		})
  5397  	}
  5398  
  5399  	return tlvs
  5400  }
  5401  
  5402  type LsLinkNLRI struct {
  5403  	LsNLRI
  5404  	LocalNodeDesc  LsTLVInterface
  5405  	RemoteNodeDesc LsTLVInterface
  5406  	LinkDesc       []LsTLVInterface
  5407  }
  5408  
  5409  func (l *LsLinkNLRI) String() string {
  5410  	if l.LocalNodeDesc == nil || l.RemoteNodeDesc == nil {
  5411  		return "LINK { EMPTY }"
  5412  	}
  5413  	var local string
  5414  	var remote string
  5415  	if l.LsNLRI.ProtocolID == LS_PROTOCOL_BGP {
  5416  		local = l.LocalNodeDesc.(*LsTLVNodeDescriptor).Extract().BGPRouterID.String()
  5417  		remote = l.RemoteNodeDesc.(*LsTLVNodeDescriptor).Extract().BGPRouterID.String()
  5418  	} else {
  5419  		local = l.LocalNodeDesc.(*LsTLVNodeDescriptor).Extract().IGPRouterID
  5420  		remote = l.RemoteNodeDesc.(*LsTLVNodeDescriptor).Extract().IGPRouterID
  5421  	}
  5422  
  5423  	link := &LsLinkDescriptor{}
  5424  	link.ParseTLVs(l.LinkDesc)
  5425  
  5426  	return fmt.Sprintf("LINK { LOCAL_NODE: %v REMOTE_NODE: %v LINK: %v}", local, remote, link)
  5427  }
  5428  
  5429  func (l *LsLinkNLRI) DecodeFromBytes(data []byte) error {
  5430  	if err := l.LsNLRI.DecodeFromBytes(data); err != nil {
  5431  		return nil
  5432  	}
  5433  
  5434  	tlv := data[lsNLRIHdrLen:]
  5435  	m := make(map[LsTLVType]bool)
  5436  
  5437  	for len(tlv) >= tlvHdrLen {
  5438  		sub := &LsTLV{}
  5439  		_, err := sub.DecodeFromBytes(tlv)
  5440  		if err != nil {
  5441  			return err
  5442  		}
  5443  		m[sub.Type] = true
  5444  
  5445  		var subTLV LsTLVInterface
  5446  		switch sub.Type {
  5447  		case LS_TLV_LOCAL_NODE_DESC, LS_TLV_REMOTE_NODE_DESC:
  5448  			subTLV = &LsTLVNodeDescriptor{}
  5449  		case LS_TLV_LINK_ID:
  5450  			subTLV = &LsTLVLinkID{}
  5451  		case LS_TLV_IPV4_INTERFACE_ADDR:
  5452  			subTLV = &LsTLVIPv4InterfaceAddr{}
  5453  		case LS_TLV_IPV4_NEIGHBOR_ADDR:
  5454  			subTLV = &LsTLVIPv4NeighborAddr{}
  5455  		case LS_TLV_IPV6_INTERFACE_ADDR:
  5456  			subTLV = &LsTLVIPv6InterfaceAddr{}
  5457  		case LS_TLV_IPV6_NEIGHBOR_ADDR:
  5458  			subTLV = &LsTLVIPv6NeighborAddr{}
  5459  
  5460  		default:
  5461  			tlv = tlv[sub.Len():]
  5462  			l.Length -= uint16(sub.Len())
  5463  			continue
  5464  		}
  5465  
  5466  		if err := subTLV.DecodeFromBytes(tlv); err != nil {
  5467  			return err
  5468  		}
  5469  		tlv = tlv[subTLV.Len():]
  5470  
  5471  		switch sub.Type {
  5472  		case LS_TLV_LOCAL_NODE_DESC:
  5473  			l.LocalNodeDesc = subTLV
  5474  		case LS_TLV_REMOTE_NODE_DESC:
  5475  			l.RemoteNodeDesc = subTLV
  5476  		default:
  5477  			l.LinkDesc = append(l.LinkDesc, subTLV)
  5478  		}
  5479  	}
  5480  
  5481  	required := []LsTLVType{LS_TLV_LOCAL_NODE_DESC, LS_TLV_REMOTE_NODE_DESC}
  5482  	for _, tlv := range required {
  5483  		if _, ok := m[tlv]; !ok {
  5484  			return malformedAttrListErr("Required TLV missing")
  5485  		}
  5486  	}
  5487  
  5488  	return nil
  5489  }
  5490  
  5491  func (l *LsLinkNLRI) Serialize() ([]byte, error) {
  5492  	if l.LocalNodeDesc == nil || l.RemoteNodeDesc == nil {
  5493  		return nil, errors.New("required TLV missing")
  5494  	}
  5495  
  5496  	buf := make([]byte, 0)
  5497  	s, err := l.LocalNodeDesc.Serialize()
  5498  	if err != nil {
  5499  		return nil, err
  5500  	}
  5501  	buf = append(buf, s...)
  5502  
  5503  	s, err = l.RemoteNodeDesc.Serialize()
  5504  	if err != nil {
  5505  		return nil, err
  5506  	}
  5507  	buf = append(buf, s...)
  5508  
  5509  	for _, tlv := range l.LinkDesc {
  5510  		s, err := tlv.Serialize()
  5511  		if err != nil {
  5512  			return nil, err
  5513  		}
  5514  		buf = append(buf, s...)
  5515  	}
  5516  
  5517  	return l.LsNLRI.Serialize(buf)
  5518  }
  5519  
  5520  func (l *LsLinkNLRI) MarshalJSON() ([]byte, error) {
  5521  	linkDesc := &LsLinkDescriptor{}
  5522  	linkDesc.ParseTLVs(l.LinkDesc)
  5523  
  5524  	return json.Marshal(struct {
  5525  		Type       LsNLRIType       `json:"type"`
  5526  		LocalNode  LsNodeDescriptor `json:"local_node_desc"`
  5527  		RemoteNode LsNodeDescriptor `json:"remote_node_desc"`
  5528  		LinkDesc   LsLinkDescriptor `json:"link_desc"`
  5529  	}{
  5530  		Type:       l.Type(),
  5531  		LocalNode:  *l.LocalNodeDesc.(*LsTLVNodeDescriptor).Extract(),
  5532  		RemoteNode: *l.RemoteNodeDesc.(*LsTLVNodeDescriptor).Extract(),
  5533  		LinkDesc:   *linkDesc,
  5534  	})
  5535  }
  5536  
  5537  type LsPrefixDescriptor struct {
  5538  	IPReachability []net.IPNet
  5539  	OSPFRouteType  LsOspfRouteType
  5540  }
  5541  
  5542  func (l *LsPrefixDescriptor) ParseTLVs(tlvs []LsTLVInterface, ipv6 bool) {
  5543  	for _, tlv := range tlvs {
  5544  		switch v := tlv.(type) {
  5545  		case *LsTLVIPReachability:
  5546  			l.IPReachability = append(l.IPReachability, v.ToIPNet(ipv6))
  5547  
  5548  		case *LsTLVOspfRouteType:
  5549  			l.OSPFRouteType = v.RouteType
  5550  		}
  5551  	}
  5552  }
  5553  
  5554  type LsPrefixV4NLRI struct {
  5555  	LsNLRI
  5556  	LocalNodeDesc LsTLVInterface
  5557  	PrefixDesc    []LsTLVInterface
  5558  }
  5559  
  5560  func (l *LsPrefixV4NLRI) String() string {
  5561  	if l.LocalNodeDesc == nil {
  5562  		return "PREFIXv4 { EMPTY }"
  5563  	}
  5564  
  5565  	local := l.LocalNodeDesc.(*LsTLVNodeDescriptor).Extract()
  5566  	prefix := &LsPrefixDescriptor{}
  5567  	prefix.ParseTLVs(l.PrefixDesc, false)
  5568  	ips := make([]string, len(prefix.IPReachability))
  5569  	for i, ip := range prefix.IPReachability {
  5570  		ips[i] = ip.String()
  5571  	}
  5572  
  5573  	ospf := ""
  5574  	if prefix.OSPFRouteType != LS_OSPF_ROUTE_TYPE_UNKNOWN {
  5575  		ospf = fmt.Sprintf("OSPF_ROUTE_TYPE:%v ", prefix.OSPFRouteType)
  5576  	}
  5577  
  5578  	return fmt.Sprintf("PREFIXv4 { LOCAL_NODE: %s PREFIX: %v %s}", local.IGPRouterID, ips, ospf)
  5579  }
  5580  
  5581  func (l *LsPrefixV4NLRI) DecodeFromBytes(data []byte) error {
  5582  	if err := l.LsNLRI.DecodeFromBytes(data); err != nil {
  5583  		return nil
  5584  	}
  5585  
  5586  	tlv := data[lsNLRIHdrLen:]
  5587  	m := make(map[LsTLVType]bool)
  5588  
  5589  	for len(tlv) >= tlvHdrLen {
  5590  		sub := &LsTLV{}
  5591  		_, err := sub.DecodeFromBytes(tlv)
  5592  		if err != nil {
  5593  			return err
  5594  		}
  5595  		m[sub.Type] = true
  5596  
  5597  		var subTLV LsTLVInterface
  5598  		switch sub.Type {
  5599  		case LS_TLV_LOCAL_NODE_DESC:
  5600  			subTLV = &LsTLVNodeDescriptor{}
  5601  		case LS_TLV_OSPF_ROUTE_TYPE:
  5602  			subTLV = &LsTLVOspfRouteType{}
  5603  		case LS_TLV_IP_REACH_INFO:
  5604  			subTLV = &LsTLVIPReachability{}
  5605  
  5606  		default:
  5607  			tlv = tlv[sub.Len():]
  5608  			l.Length -= uint16(sub.Len())
  5609  			continue
  5610  		}
  5611  
  5612  		if err := subTLV.DecodeFromBytes(tlv); err != nil {
  5613  			return err
  5614  		}
  5615  		tlv = tlv[subTLV.Len():]
  5616  
  5617  		switch sub.Type {
  5618  		case LS_TLV_LOCAL_NODE_DESC:
  5619  			l.LocalNodeDesc = subTLV
  5620  		default:
  5621  			l.PrefixDesc = append(l.PrefixDesc, subTLV)
  5622  		}
  5623  	}
  5624  
  5625  	required := []LsTLVType{LS_TLV_IP_REACH_INFO, LS_TLV_LOCAL_NODE_DESC}
  5626  	for _, tlv := range required {
  5627  		if _, ok := m[tlv]; !ok {
  5628  			return malformedAttrListErr("Required TLV missing")
  5629  		}
  5630  	}
  5631  
  5632  	for _, tlv := range l.PrefixDesc {
  5633  		switch v := tlv.(type) {
  5634  		case *LsTLVIPReachability:
  5635  			if v.PrefixLength > 8*net.IPv4len {
  5636  				return malformedAttrListErr("Unexpected IP Reachability info")
  5637  			}
  5638  		}
  5639  	}
  5640  
  5641  	return nil
  5642  }
  5643  
  5644  func (l *LsPrefixV4NLRI) Serialize() ([]byte, error) {
  5645  	if l.LocalNodeDesc == nil {
  5646  		return nil, errors.New("required TLV missing")
  5647  	}
  5648  
  5649  	buf := make([]byte, 0)
  5650  	s, err := l.LocalNodeDesc.Serialize()
  5651  	if err != nil {
  5652  		return nil, err
  5653  	}
  5654  	buf = append(buf, s...)
  5655  
  5656  	for _, tlv := range l.PrefixDesc {
  5657  		s, err := tlv.Serialize()
  5658  		if err != nil {
  5659  			return nil, err
  5660  		}
  5661  		buf = append(buf, s...)
  5662  	}
  5663  
  5664  	return l.LsNLRI.Serialize(buf)
  5665  }
  5666  
  5667  func (l *LsPrefixV4NLRI) MarshalJSON() ([]byte, error) {
  5668  	prefixDesc := &LsPrefixDescriptor{}
  5669  	prefixDesc.ParseTLVs(l.PrefixDesc, false)
  5670  
  5671  	return json.Marshal(struct {
  5672  		Type       LsNLRIType         `json:"type"`
  5673  		LocalNode  LsNodeDescriptor   `json:"local_node_desc"`
  5674  		PrefixDesc LsPrefixDescriptor `json:"prefix_desc"`
  5675  	}{
  5676  		Type:       l.Type(),
  5677  		LocalNode:  *l.LocalNodeDesc.(*LsTLVNodeDescriptor).Extract(),
  5678  		PrefixDesc: *prefixDesc,
  5679  	})
  5680  }
  5681  
  5682  func NewLsPrefixTLVs(pd *LsPrefixDescriptor) []LsTLVInterface {
  5683  	lsTLVs := []LsTLVInterface{}
  5684  	for _, ipReach := range pd.IPReachability {
  5685  		prefixSize, _ := ipReach.Mask.Size()
  5686  		lenIpPrefix := (prefixSize-1)/8 + 1
  5687  		lenIpReach := uint16(lenIpPrefix + 1)
  5688  		var tlv *LsTLVIPReachability
  5689  
  5690  		if ipReach.IP.To4() != nil {
  5691  			ip := ipReach.IP.To4()
  5692  			tlv = &LsTLVIPReachability{
  5693  				LsTLV: LsTLV{
  5694  					Type:   LS_TLV_IP_REACH_INFO,
  5695  					Length: lenIpReach,
  5696  				},
  5697  				PrefixLength: uint8(prefixSize),
  5698  				Prefix:       []byte(ip)[:((lenIpPrefix-1)/8 + 1)],
  5699  			}
  5700  		} else if ipReach.IP.To16() != nil {
  5701  			ip := ipReach.IP.To16()
  5702  			tlv = &LsTLVIPReachability{
  5703  				LsTLV: LsTLV{
  5704  					Type:   LS_TLV_IP_REACH_INFO,
  5705  					Length: lenIpReach,
  5706  				},
  5707  				PrefixLength: uint8(prefixSize),
  5708  				Prefix:       []byte(ip)[:((lenIpPrefix-1)/8 + 1)],
  5709  			}
  5710  		}
  5711  		lsTLVs = append(lsTLVs, tlv)
  5712  	}
  5713  
  5714  	lsTLVs = append(lsTLVs,
  5715  		&LsTLVOspfRouteType{
  5716  			LsTLV: LsTLV{
  5717  				Type:   LS_TLV_OSPF_ROUTE_TYPE,
  5718  				Length: 1,
  5719  			},
  5720  			RouteType: pd.OSPFRouteType,
  5721  		})
  5722  	return lsTLVs
  5723  }
  5724  
  5725  type LsPrefixV6NLRI struct {
  5726  	LsNLRI
  5727  	LocalNodeDesc LsTLVInterface
  5728  	PrefixDesc    []LsTLVInterface
  5729  }
  5730  
  5731  func (l *LsPrefixV6NLRI) String() string {
  5732  	if l.LocalNodeDesc == nil {
  5733  		return "PREFIXv6 { EMPTY }"
  5734  	}
  5735  
  5736  	local := l.LocalNodeDesc.(*LsTLVNodeDescriptor).Extract()
  5737  	prefix := &LsPrefixDescriptor{}
  5738  	prefix.ParseTLVs(l.PrefixDesc, true)
  5739  	ips := []string{}
  5740  	for _, ip := range prefix.IPReachability {
  5741  		ips = append(ips, ip.String())
  5742  	}
  5743  
  5744  	ospf := ""
  5745  	if prefix.OSPFRouteType != LS_OSPF_ROUTE_TYPE_UNKNOWN {
  5746  		ospf = fmt.Sprintf("OSPF_ROUTE_TYPE:%v ", prefix.OSPFRouteType)
  5747  	}
  5748  
  5749  	return fmt.Sprintf("PREFIXv6 { LOCAL_NODE: %v PREFIX: %v %v}", local.IGPRouterID, ips, ospf)
  5750  }
  5751  
  5752  func (l *LsPrefixV6NLRI) DecodeFromBytes(data []byte) error {
  5753  	if err := l.LsNLRI.DecodeFromBytes(data); err != nil {
  5754  		return nil
  5755  	}
  5756  
  5757  	tlv := data[lsNLRIHdrLen:]
  5758  	m := make(map[LsTLVType]bool)
  5759  
  5760  	for len(tlv) >= tlvHdrLen {
  5761  		sub := &LsTLV{}
  5762  		_, err := sub.DecodeFromBytes(tlv)
  5763  		if err != nil {
  5764  			return err
  5765  		}
  5766  		m[sub.Type] = true
  5767  
  5768  		var subTLV LsTLVInterface
  5769  		switch sub.Type {
  5770  		case LS_TLV_LOCAL_NODE_DESC:
  5771  			subTLV = &LsTLVNodeDescriptor{}
  5772  		case LS_TLV_OSPF_ROUTE_TYPE:
  5773  			subTLV = &LsTLVOspfRouteType{}
  5774  		case LS_TLV_IP_REACH_INFO:
  5775  			subTLV = &LsTLVIPReachability{}
  5776  
  5777  		default:
  5778  			tlv = tlv[sub.Len():]
  5779  			l.Length -= uint16(sub.Len())
  5780  			continue
  5781  		}
  5782  
  5783  		if err := subTLV.DecodeFromBytes(tlv); err != nil {
  5784  			return err
  5785  		}
  5786  		tlv = tlv[subTLV.Len():]
  5787  
  5788  		switch sub.Type {
  5789  		case LS_TLV_LOCAL_NODE_DESC:
  5790  			l.LocalNodeDesc = subTLV
  5791  		default:
  5792  			l.PrefixDesc = append(l.PrefixDesc, subTLV)
  5793  		}
  5794  	}
  5795  
  5796  	required := []LsTLVType{LS_TLV_IP_REACH_INFO, LS_TLV_LOCAL_NODE_DESC}
  5797  	for _, tlv := range required {
  5798  		if _, ok := m[tlv]; !ok {
  5799  			return malformedAttrListErr("Required TLV missing")
  5800  		}
  5801  	}
  5802  
  5803  	return nil
  5804  }
  5805  
  5806  func (l *LsPrefixV6NLRI) Serialize() ([]byte, error) {
  5807  	if l.LocalNodeDesc == nil {
  5808  		return nil, errors.New("required TLV missing")
  5809  	}
  5810  
  5811  	buf := make([]byte, 0)
  5812  	s, err := l.LocalNodeDesc.Serialize()
  5813  	if err != nil {
  5814  		return nil, err
  5815  	}
  5816  	buf = append(buf, s...)
  5817  
  5818  	for _, tlv := range l.PrefixDesc {
  5819  		s, err := tlv.Serialize()
  5820  		if err != nil {
  5821  			return nil, err
  5822  		}
  5823  		buf = append(buf, s...)
  5824  	}
  5825  
  5826  	return l.LsNLRI.Serialize(buf)
  5827  }
  5828  
  5829  func (l *LsPrefixV6NLRI) MarshalJSON() ([]byte, error) {
  5830  	prefixDesc := &LsPrefixDescriptor{}
  5831  	prefixDesc.ParseTLVs(l.PrefixDesc, true)
  5832  
  5833  	return json.Marshal(struct {
  5834  		Type       LsNLRIType         `json:"type"`
  5835  		LocalNode  LsNodeDescriptor   `json:"local_node_desc"`
  5836  		PrefixDesc LsPrefixDescriptor `json:"prefix_desc"`
  5837  	}{
  5838  		Type:       l.Type(),
  5839  		LocalNode:  *l.LocalNodeDesc.(*LsTLVNodeDescriptor).Extract(),
  5840  		PrefixDesc: *prefixDesc,
  5841  	})
  5842  }
  5843  
  5844  type LsTLVType uint16
  5845  
  5846  // Based on https://www.iana.org/assignments/bgp-ls-parameters/bgp-ls-parameters.xhtml
  5847  const (
  5848  	LS_TLV_UNKNOWN LsTLVType = iota
  5849  
  5850  	LS_TLV_LOCAL_NODE_DESC     = 256
  5851  	LS_TLV_REMOTE_NODE_DESC    = 257
  5852  	LS_TLV_LINK_ID             = 258
  5853  	LS_TLV_IPV4_INTERFACE_ADDR = 259
  5854  	LS_TLV_IPV4_NEIGHBOR_ADDR  = 260
  5855  	LS_TLV_IPV6_INTERFACE_ADDR = 261
  5856  	LS_TLV_IPV6_NEIGHBOR_ADDR  = 262
  5857  	LS_TLV_MULTI_TOPO_ID       = 263
  5858  	LS_TLV_OSPF_ROUTE_TYPE     = 264
  5859  	LS_TLV_IP_REACH_INFO       = 265
  5860  
  5861  	LS_TLV_AS                       = 512
  5862  	LS_TLV_BGP_LS_ID                = 513
  5863  	LS_TLV_OSPF_AREA                = 514
  5864  	LS_TLV_IGP_ROUTER_ID            = 515
  5865  	LS_TLV_BGP_ROUTER_ID            = 516 // RFC9086
  5866  	LS_TLV_BGP_CONFEDERATION_MEMBER = 517 // RFC9086
  5867  
  5868  	LS_TLV_NODE_FLAG_BITS        = 1024
  5869  	LS_TLV_OPAQUE_NODE_ATTR      = 1025
  5870  	LS_TLV_NODE_NAME             = 1026
  5871  	LS_TLV_ISIS_AREA             = 1027
  5872  	LS_TLV_IPV4_LOCAL_ROUTER_ID  = 1028
  5873  	LS_TLV_IPV6_LOCAL_ROUTER_ID  = 1029
  5874  	LS_TLV_IPV4_REMOTE_ROUTER_ID = 1030
  5875  	LS_TLV_IPV6_REMOTE_ROUTER_ID = 1031
  5876  
  5877  	LS_TLV_SR_CAPABILITIES = 1034 // draft-ietf-idr-bgp-ls-segment-routing-ext
  5878  	LS_TLV_SR_ALGORITHM    = 1035 // draft-ietf-idr-bgp-ls-segment-routing-ext
  5879  	LS_TLV_SR_LOCAL_BLOCK  = 1036 // draft-ietf-idr-bgp-ls-segment-routing-ext
  5880  	LS_TLV_SRMS_PREFERENCE = 1037 // draft-ietf-idr-bgp-ls-segment-routing-ext, TODO
  5881  
  5882  	LS_TLV_ADMIN_GROUP              = 1088
  5883  	LS_TLV_MAX_LINK_BANDWIDTH       = 1089
  5884  	LS_TLV_MAX_RESERVABLE_BANDWIDTH = 1090
  5885  	LS_TLV_UNRESERVED_BANDWIDTH     = 1091
  5886  	LS_TLV_TE_DEFAULT_METRIC        = 1092
  5887  	LS_TLV_LINK_PROTECTION_TYPE     = 1093 // TODO
  5888  	LS_TLV_MPLS_PROTOCOL_MASK       = 1094 // TODO
  5889  	LS_TLV_IGP_METRIC               = 1095
  5890  	LS_TLV_SRLG                     = 1096
  5891  	LS_TLV_OPAQUE_LINK_ATTR         = 1097
  5892  	LS_TLV_LINK_NAME                = 1098
  5893  	LS_TLV_ADJACENCY_SID            = 1099 // draft-ietf-idr-bgp-ls-segment-routing-ext
  5894  	LS_TLV_LAN_ADJACENCY_SID        = 1100 // draft-ietf-idr-bgp-ls-segment-routing-ext, TODO
  5895  	LS_TLV_PEER_NODE_SID            = 1101 // RFC9086
  5896  	LS_TLV_PEER_ADJACENCY_SID       = 1102 // RFC9086
  5897  	LS_TLV_PEER_SET_SID             = 1103 // RFC9086
  5898  
  5899  	LS_TLV_RTM_CAPABILITY = 1105 // RFC8169, TODO
  5900  
  5901  	LS_TLV_IGP_FLAGS              = 1152
  5902  	LS_TLV_IGP_ROUTE_TAG          = 1153 // TODO
  5903  	LS_TLV_EXTENDED_ROUTE_TAG     = 1154 // TODO
  5904  	LS_TLV_PREFIX_METRIC          = 1155 // TODO
  5905  	LS_TLV_OSPF_FORWARDING_ADDR   = 1156 // TODO
  5906  	LS_TLV_OPAQUE_PREFIX_ATTR     = 1157
  5907  	LS_TLV_PREFIX_SID             = 1158 // draft-ietf-idr-bgp-ls-segment-routing-ext
  5908  	LS_TLV_RANGE                  = 1159 // draft-ietf-idr-bgp-ls-segment-routing-ext, TODO
  5909  	LS_TLV_SID_LABEL_TLV          = 1161 // draft-ietf-idr-bgp-ls-segment-routing-ext
  5910  	LS_TLV_PREFIX_ATTRIBUTE_FLAGS = 1170 // draft-ietf-idr-bgp-ls-segment-routing-ext, TODO
  5911  	LS_TLV_SOURCE_ROUTER_ID       = 1171 // draft-ietf-idr-bgp-ls-segment-routing-ext, TODO
  5912  	LS_TLV_L2_BUNDLE_MEMBER_TLV   = 1172 // draft-ietf-idr-bgp-ls-segment-routing-ext, TODO
  5913  )
  5914  
  5915  type LsTLVInterface interface {
  5916  	Len() int
  5917  	DecodeFromBytes([]byte) error
  5918  	Serialize() ([]byte, error)
  5919  	String() string
  5920  	MarshalJSON() ([]byte, error)
  5921  }
  5922  
  5923  func NewLsAttributeTLVs(lsAttr *LsAttribute) []LsTLVInterface {
  5924  	tlvs := []LsTLVInterface{}
  5925  
  5926  	if lsAttr.Node.Flags != nil {
  5927  		tlvs = append(tlvs, NewLsTLVNodeFlagbits(lsAttr.Node.Flags))
  5928  	}
  5929  	if lsAttr.Node.Opaque != nil {
  5930  		tlvs = append(tlvs, NewLsTLVOpaqueNodeAttr(lsAttr.Node.Opaque))
  5931  	}
  5932  	if lsAttr.Node.Name != nil {
  5933  		tlvs = append(tlvs, NewLsTLVNodeName(lsAttr.Node.Name))
  5934  	}
  5935  	if lsAttr.Node.IsisArea != nil {
  5936  		tlvs = append(tlvs, NewLsTLVIsisArea(lsAttr.Node.IsisArea))
  5937  	}
  5938  	if lsAttr.Node.LocalRouterID != (*net.IP)(nil) {
  5939  		tlvs = append(tlvs, NewLsTLVLocalIPv4RouterID(lsAttr.Node.LocalRouterID))
  5940  	}
  5941  	if lsAttr.Node.LocalRouterIDv6 != (*net.IP)(nil) {
  5942  		tlvs = append(tlvs, NewLsTLVLocalIPv6RouterID(lsAttr.Node.LocalRouterIDv6))
  5943  	}
  5944  	if lsAttr.Node.SrCapabilties != nil {
  5945  		tlvs = append(tlvs, NewLsTLVSrCapabilities(lsAttr.Node.SrCapabilties))
  5946  	}
  5947  	if lsAttr.Node.SrAlgorithms != nil {
  5948  		tlvs = append(tlvs, NewLsTLVSrAlgorithm(lsAttr.Node.SrAlgorithms))
  5949  	}
  5950  	if lsAttr.Node.SrLocalBlock != nil {
  5951  		tlvs = append(tlvs, NewLsTLVSrLocalBlock(lsAttr.Node.SrLocalBlock))
  5952  	}
  5953  
  5954  	if lsAttr.Link.Name != nil {
  5955  		tlvs = append(tlvs, NewLsTLVLinkName(lsAttr.Link.Name))
  5956  	}
  5957  	if lsAttr.Link.LocalRouterID != (*net.IP)(nil) {
  5958  		tlvs = append(tlvs, NewLsTLVLocalIPv4RouterID(lsAttr.Link.LocalRouterID))
  5959  	}
  5960  	if lsAttr.Link.LocalRouterIDv6 != (*net.IP)(nil) {
  5961  		tlvs = append(tlvs, NewLsTLVLocalIPv6RouterID(lsAttr.Link.LocalRouterIDv6))
  5962  	}
  5963  	if lsAttr.Link.RemoteRouterID != (*net.IP)(nil) {
  5964  		tlvs = append(tlvs, NewLsTLVRemoteIPv4RouterID(lsAttr.Link.RemoteRouterID))
  5965  	}
  5966  	if lsAttr.Link.RemoteRouterIDv6 != (*net.IP)(nil) {
  5967  		tlvs = append(tlvs, NewLsTLVRemoteIPv6RouterID(lsAttr.Link.RemoteRouterIDv6))
  5968  	}
  5969  	if lsAttr.Link.AdminGroup != nil {
  5970  		tlvs = append(tlvs, NewLsTLVAdminGroup(lsAttr.Link.AdminGroup))
  5971  	}
  5972  	if lsAttr.Link.DefaultTEMetric != nil {
  5973  		tlvs = append(tlvs, NewLsTLVTEDefaultMetric(lsAttr.Link.DefaultTEMetric))
  5974  	}
  5975  	if lsAttr.Link.IGPMetric != nil {
  5976  		tlvs = append(tlvs, NewLsTLVIGPMetric(lsAttr.Link.IGPMetric))
  5977  	}
  5978  	if lsAttr.Link.Opaque != nil {
  5979  		tlvs = append(tlvs, NewLsTLVOpaqueLinkAttr(lsAttr.Link.Opaque))
  5980  	}
  5981  	if lsAttr.Link.Bandwidth != nil {
  5982  		tlvs = append(tlvs, NewLsTLVMaxLinkBw(lsAttr.Link.Bandwidth))
  5983  	}
  5984  	if lsAttr.Link.ReservableBandwidth != nil {
  5985  		tlvs = append(tlvs, NewLsTLVMaxReservableLinkBw(lsAttr.Link.ReservableBandwidth))
  5986  	}
  5987  	if lsAttr.Link.UnreservedBandwidth != nil && *lsAttr.Link.UnreservedBandwidth != [8]float32{0, 0, 0, 0, 0, 0, 0, 0} {
  5988  		tlvs = append(tlvs, NewLsTLVUnreservedBw(lsAttr.Link.UnreservedBandwidth))
  5989  	}
  5990  	if lsAttr.Link.Srlgs != nil {
  5991  		tlvs = append(tlvs, NewLsTLVSrlg(lsAttr.Link.Srlgs))
  5992  	}
  5993  	if lsAttr.Link.SrAdjacencySID != nil {
  5994  		tlvs = append(tlvs, NewLsTLVAdjacencySID(lsAttr.Link.SrAdjacencySID))
  5995  	}
  5996  
  5997  	if lsAttr.Prefix.IGPFlags != nil {
  5998  		tlvs = append(tlvs, NewLsTLVIGPFlags(lsAttr.Prefix.IGPFlags))
  5999  	}
  6000  	if lsAttr.Prefix.Opaque != nil {
  6001  		tlvs = append(tlvs, NewLsTLVOpaquePrefixAttr(lsAttr.Prefix.Opaque))
  6002  	}
  6003  	if lsAttr.Prefix.SrPrefixSID != nil {
  6004  		tlvs = append(tlvs, NewLsTLVPrefixSID(lsAttr.Prefix.SrPrefixSID))
  6005  	}
  6006  
  6007  	if lsAttr.BgpPeerSegment.BgpPeerNodeSid != nil {
  6008  		tlvs = append(tlvs, NewLsTLVPeerNodeSID(lsAttr.BgpPeerSegment.BgpPeerNodeSid))
  6009  	}
  6010  	if lsAttr.BgpPeerSegment.BgpPeerAdjacencySid != nil {
  6011  		tlvs = append(tlvs, NewLsTLVPeerAdjacencySID(lsAttr.BgpPeerSegment.BgpPeerAdjacencySid))
  6012  	}
  6013  	if lsAttr.BgpPeerSegment.BgpPeerSetSid != nil {
  6014  		tlvs = append(tlvs, NewLsTLVPeerSetSID(lsAttr.BgpPeerSegment.BgpPeerSetSid))
  6015  	}
  6016  
  6017  	return tlvs
  6018  }
  6019  
  6020  type LsTLV struct {
  6021  	Type   LsTLVType
  6022  	Length uint16
  6023  }
  6024  
  6025  func malformedAttrListErr(s string) error {
  6026  	return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, s)
  6027  }
  6028  
  6029  const tlvHdrLen = 4
  6030  
  6031  func (l *LsTLV) Len() int {
  6032  	return int(l.Length) + tlvHdrLen
  6033  }
  6034  
  6035  func (l *LsTLV) Serialize(value []byte) ([]byte, error) {
  6036  	if len(value) != int(l.Length) {
  6037  		return nil, malformedAttrListErr("serialization failed: LS TLV malformed")
  6038  	}
  6039  
  6040  	buf := make([]byte, tlvHdrLen+len(value))
  6041  	binary.BigEndian.PutUint16(buf[:2], uint16(l.Type))
  6042  	binary.BigEndian.PutUint16(buf[2:4], uint16(l.Length))
  6043  	copy(buf[4:], value)
  6044  
  6045  	return buf, nil
  6046  }
  6047  
  6048  func (l *LsTLV) DecodeFromBytes(data []byte) ([]byte, error) {
  6049  	if len(data) < tlvHdrLen {
  6050  		return nil, malformedAttrListErr("decoding failed: LS TLV malformed")
  6051  	}
  6052  	l.Type = LsTLVType(binary.BigEndian.Uint16(data[:2]))
  6053  	l.Length = binary.BigEndian.Uint16(data[2:4])
  6054  
  6055  	if len(data) < l.Len() {
  6056  		return nil, malformedAttrListErr("decoding failed: LS TLV malformed")
  6057  	}
  6058  
  6059  	return data[tlvHdrLen:l.Len()], nil
  6060  }
  6061  
  6062  type LsTLVLinkID struct {
  6063  	LsTLV
  6064  	Local  uint32
  6065  	Remote uint32
  6066  }
  6067  
  6068  func (l *LsTLVLinkID) DecodeFromBytes(data []byte) error {
  6069  	value, err := l.LsTLV.DecodeFromBytes(data)
  6070  	if err != nil {
  6071  		return err
  6072  	}
  6073  
  6074  	if l.Type != LS_TLV_LINK_ID {
  6075  		return malformedAttrListErr("Unexpected TLV type")
  6076  	}
  6077  
  6078  	// https://tools.ietf.org/html/rfc5307#section-1.1
  6079  	if len(value) != 8 {
  6080  		return malformedAttrListErr("Incorrect Link ID length")
  6081  	}
  6082  
  6083  	l.Local = binary.BigEndian.Uint32(value[:4])
  6084  	l.Remote = binary.BigEndian.Uint32(value[4:])
  6085  
  6086  	return nil
  6087  }
  6088  
  6089  func (l *LsTLVLinkID) Serialize() ([]byte, error) {
  6090  	buf := make([]byte, 8)
  6091  	binary.BigEndian.PutUint32(buf[:4], l.Local)
  6092  	binary.BigEndian.PutUint32(buf[4:], l.Remote)
  6093  
  6094  	return l.LsTLV.Serialize(buf)
  6095  }
  6096  
  6097  func (l *LsTLVLinkID) String() string {
  6098  	return fmt.Sprintf("{Link ID Remote: %v Local: %v}", l.Local, l.Remote)
  6099  }
  6100  
  6101  func (l *LsTLVLinkID) MarshalJSON() ([]byte, error) {
  6102  	return json.Marshal(struct {
  6103  		Type   LsTLVType `json:"type"`
  6104  		Local  uint32    `json:"local_link_id"`
  6105  		Remote uint32    `json:"remote_link_id"`
  6106  	}{
  6107  		Type:   l.Type,
  6108  		Local:  l.Local,
  6109  		Remote: l.Remote,
  6110  	})
  6111  }
  6112  
  6113  type LsTLVIPv4InterfaceAddr struct {
  6114  	LsTLV
  6115  	IP net.IP
  6116  }
  6117  
  6118  func (l *LsTLVIPv4InterfaceAddr) DecodeFromBytes(data []byte) error {
  6119  	value, err := l.LsTLV.DecodeFromBytes(data)
  6120  	if err != nil {
  6121  		return err
  6122  	}
  6123  
  6124  	if l.Type != LS_TLV_IPV4_INTERFACE_ADDR {
  6125  		return malformedAttrListErr("Unexpected TLV type")
  6126  	}
  6127  
  6128  	// https://tools.ietf.org/html/rfc5305#section-3.2
  6129  	if len(value) != 4 {
  6130  		return malformedAttrListErr("Unexpected address size")
  6131  	}
  6132  
  6133  	l.IP = net.IP(value)
  6134  
  6135  	return nil
  6136  }
  6137  
  6138  func (l *LsTLVIPv4InterfaceAddr) Serialize() ([]byte, error) {
  6139  	return l.LsTLV.Serialize(l.IP)
  6140  }
  6141  
  6142  func (l *LsTLVIPv4InterfaceAddr) String() string {
  6143  	return fmt.Sprintf("{IPv4 Interface Address: %v}", l.IP)
  6144  }
  6145  
  6146  func (l *LsTLVIPv4InterfaceAddr) MarshalJSON() ([]byte, error) {
  6147  	return json.Marshal(struct {
  6148  		Type  LsTLVType `json:"type"`
  6149  		Value string    `json:"ipv4_interface_address"`
  6150  	}{
  6151  		Type:  l.Type,
  6152  		Value: fmt.Sprintf("%v", l.IP),
  6153  	})
  6154  }
  6155  
  6156  type LsTLVIPv4NeighborAddr struct {
  6157  	LsTLV
  6158  	IP net.IP
  6159  }
  6160  
  6161  func (l *LsTLVIPv4NeighborAddr) DecodeFromBytes(data []byte) error {
  6162  	value, err := l.LsTLV.DecodeFromBytes(data)
  6163  	if err != nil {
  6164  		return err
  6165  	}
  6166  
  6167  	if l.Type != LS_TLV_IPV4_NEIGHBOR_ADDR {
  6168  		return malformedAttrListErr("Unexpected TLV type")
  6169  	}
  6170  
  6171  	// https://tools.ietf.org/html/rfc5305#section-3.3
  6172  	if len(value) != 4 {
  6173  		return malformedAttrListErr("Unexpected address size")
  6174  	}
  6175  
  6176  	l.IP = net.IP(value)
  6177  
  6178  	return nil
  6179  }
  6180  
  6181  func (l *LsTLVIPv4NeighborAddr) Serialize() ([]byte, error) {
  6182  	return l.LsTLV.Serialize(l.IP)
  6183  }
  6184  
  6185  func (l *LsTLVIPv4NeighborAddr) String() string {
  6186  	return fmt.Sprintf("{IPv4 Neighbor Address: %v}", l.IP)
  6187  }
  6188  
  6189  func (l *LsTLVIPv4NeighborAddr) MarshalJSON() ([]byte, error) {
  6190  	return json.Marshal(struct {
  6191  		Type  LsTLVType `json:"type"`
  6192  		Value string    `json:"ipv4_neighbor_address"`
  6193  	}{
  6194  		Type:  l.Type,
  6195  		Value: fmt.Sprintf("%v", l.IP),
  6196  	})
  6197  }
  6198  
  6199  type LsTLVIPv6InterfaceAddr struct {
  6200  	LsTLV
  6201  	IP net.IP
  6202  }
  6203  
  6204  func (l *LsTLVIPv6InterfaceAddr) DecodeFromBytes(data []byte) error {
  6205  	value, err := l.LsTLV.DecodeFromBytes(data)
  6206  	if err != nil {
  6207  		return err
  6208  	}
  6209  
  6210  	if l.Type != LS_TLV_IPV6_INTERFACE_ADDR {
  6211  		return malformedAttrListErr("Unexpected TLV type")
  6212  	}
  6213  
  6214  	// https://tools.ietf.org/html/rfc6119#section-4.2
  6215  	if len(value) != 16 {
  6216  		return malformedAttrListErr("Unexpected address size")
  6217  	}
  6218  
  6219  	l.IP = net.IP(value)
  6220  
  6221  	if l.IP.IsLinkLocalUnicast() {
  6222  		return malformedAttrListErr("Unexpected link local address")
  6223  	}
  6224  
  6225  	return nil
  6226  }
  6227  
  6228  func (l *LsTLVIPv6InterfaceAddr) Serialize() ([]byte, error) {
  6229  	return l.LsTLV.Serialize(l.IP)
  6230  }
  6231  
  6232  func (l *LsTLVIPv6InterfaceAddr) String() string {
  6233  	return fmt.Sprintf("{IPv6 Interface Address: %v}", l.IP)
  6234  }
  6235  
  6236  func (l *LsTLVIPv6InterfaceAddr) MarshalJSON() ([]byte, error) {
  6237  	return json.Marshal(struct {
  6238  		Type  LsTLVType `json:"type"`
  6239  		Value string    `json:"ipv6_interface_address"`
  6240  	}{
  6241  		Type:  l.Type,
  6242  		Value: fmt.Sprintf("%v", l.IP),
  6243  	})
  6244  }
  6245  
  6246  type LsTLVIPv6NeighborAddr struct {
  6247  	LsTLV
  6248  	IP net.IP
  6249  }
  6250  
  6251  func (l *LsTLVIPv6NeighborAddr) DecodeFromBytes(data []byte) error {
  6252  	value, err := l.LsTLV.DecodeFromBytes(data)
  6253  	if err != nil {
  6254  		return err
  6255  	}
  6256  
  6257  	if l.Type != LS_TLV_IPV6_NEIGHBOR_ADDR {
  6258  		return malformedAttrListErr("Unexpected TLV type")
  6259  	}
  6260  
  6261  	// https://tools.ietf.org/html/rfc6119#section-4.3
  6262  	if len(value) != 16 {
  6263  		return malformedAttrListErr("Unexpected address size")
  6264  	}
  6265  
  6266  	l.IP = net.IP(value)
  6267  
  6268  	if l.IP.IsLinkLocalUnicast() {
  6269  		return malformedAttrListErr("Unexpected link local address")
  6270  	}
  6271  
  6272  	return nil
  6273  }
  6274  
  6275  func (l *LsTLVIPv6NeighborAddr) Serialize() ([]byte, error) {
  6276  	return l.LsTLV.Serialize(l.IP)
  6277  }
  6278  
  6279  func (l *LsTLVIPv6NeighborAddr) String() string {
  6280  	return fmt.Sprintf("{IPv6 Neighbor Address: %v}", l.IP)
  6281  }
  6282  
  6283  func (l *LsTLVIPv6NeighborAddr) MarshalJSON() ([]byte, error) {
  6284  	return json.Marshal(struct {
  6285  		Type  LsTLVType `json:"type"`
  6286  		Value string    `json:"ipv6_neighbor_address"`
  6287  	}{
  6288  		Type:  l.Type,
  6289  		Value: fmt.Sprintf("%v", l.IP),
  6290  	})
  6291  }
  6292  
  6293  // https://tools.ietf.org/html/rfc7752#section-3.3.1.1
  6294  type LsNodeFlags struct {
  6295  	Overload bool `json:"overload"`
  6296  	Attached bool `json:"attached"`
  6297  	External bool `json:"external"`
  6298  	ABR      bool `json:"abr"`
  6299  	Router   bool `json:"router"`
  6300  	V6       bool `json:"v6"`
  6301  }
  6302  
  6303  type LsTLVNodeFlagBits struct {
  6304  	LsTLV
  6305  	Flags uint8
  6306  }
  6307  
  6308  func NewLsTLVNodeFlagbits(l *LsNodeFlags) *LsTLVNodeFlagBits {
  6309  	var flags uint8
  6310  	if l.Overload {
  6311  		flags = flags & (1 >> 7)
  6312  	}
  6313  	if l.Attached {
  6314  		flags = flags & (1 >> 6)
  6315  	}
  6316  	if l.External {
  6317  		flags = flags & (1 >> 5)
  6318  	}
  6319  	if l.ABR {
  6320  		flags = flags & (1 >> 4)
  6321  	}
  6322  	if l.Router {
  6323  		flags = flags & (1 >> 3)
  6324  	}
  6325  	if l.V6 {
  6326  		flags = flags & (1 >> 2)
  6327  	}
  6328  	return &LsTLVNodeFlagBits{
  6329  		LsTLV: LsTLV{
  6330  			Type:   BGP_ASPATH_ATTR_TYPE_SET,
  6331  			Length: 2,
  6332  		},
  6333  		Flags: flags,
  6334  	}
  6335  }
  6336  
  6337  func (l *LsTLVNodeFlagBits) Extract() *LsNodeFlags {
  6338  	return &LsNodeFlags{
  6339  		Overload: (l.Flags & (1 << 7)) > 0,
  6340  		Attached: (l.Flags & (1 << 6)) > 0,
  6341  		External: (l.Flags & (1 << 5)) > 0,
  6342  		ABR:      (l.Flags & (1 << 4)) > 0,
  6343  		Router:   (l.Flags & (1 << 3)) > 0,
  6344  		V6:       (l.Flags & (1 << 2)) > 0,
  6345  	}
  6346  }
  6347  
  6348  func (l *LsTLVNodeFlagBits) DecodeFromBytes(data []byte) error {
  6349  	value, err := l.LsTLV.DecodeFromBytes(data)
  6350  	if err != nil {
  6351  		return err
  6352  	}
  6353  
  6354  	if l.Type != LS_TLV_NODE_FLAG_BITS {
  6355  		return malformedAttrListErr("Unexpected TLV type")
  6356  	}
  6357  
  6358  	if l.Length != 1 {
  6359  		return malformedAttrListErr("Node Flag Bits TLV malformed")
  6360  	}
  6361  
  6362  	l.Flags = value[0]
  6363  
  6364  	return nil
  6365  }
  6366  
  6367  func (l *LsTLVNodeFlagBits) Serialize() ([]byte, error) {
  6368  	return l.LsTLV.Serialize([]byte{l.Flags})
  6369  }
  6370  
  6371  func (l *LsTLVNodeFlagBits) String() string {
  6372  	flags := "XXVRBETO"
  6373  
  6374  	var buf bytes.Buffer
  6375  
  6376  	for i := 0; i < len(flags); i++ {
  6377  		if l.Flags&(1<<uint(i)) > 0 {
  6378  			buf.WriteString(flags[i : i+1])
  6379  		} else {
  6380  			buf.WriteString("*")
  6381  		}
  6382  	}
  6383  
  6384  	return fmt.Sprintf("{Node Flags: %s}", buf.String())
  6385  }
  6386  
  6387  func (l *LsTLVNodeFlagBits) MarshalJSON() ([]byte, error) {
  6388  	return json.Marshal(struct {
  6389  		Type  LsTLVType `json:"type"`
  6390  		Flags string    `json:"node_flags"`
  6391  	}{
  6392  		Type:  l.Type,
  6393  		Flags: l.String(),
  6394  	})
  6395  }
  6396  
  6397  type LsTLVNodeName struct {
  6398  	LsTLV
  6399  	Name string
  6400  }
  6401  
  6402  func NewLsTLVNodeName(l *string) *LsTLVNodeName {
  6403  	return &LsTLVNodeName{
  6404  		LsTLV: LsTLV{
  6405  			Type:   BGP_ASPATH_ATTR_TYPE_SET,
  6406  			Length: uint16(len(*l)),
  6407  		},
  6408  		Name: *l,
  6409  	}
  6410  }
  6411  
  6412  func (l *LsTLVNodeName) DecodeFromBytes(data []byte) error {
  6413  	value, err := l.LsTLV.DecodeFromBytes(data)
  6414  	if err != nil {
  6415  		return err
  6416  	}
  6417  
  6418  	if l.Type != LS_TLV_NODE_NAME {
  6419  		return malformedAttrListErr("Unexpected TLV type")
  6420  	}
  6421  
  6422  	// RFC5301, section 3.
  6423  	if l.Length < 1 || l.Length > 255 {
  6424  		return malformedAttrListErr("Incorrect Node Name")
  6425  	}
  6426  
  6427  	l.Name = string(value)
  6428  
  6429  	return nil
  6430  }
  6431  
  6432  func (l *LsTLVNodeName) Serialize() ([]byte, error) {
  6433  	return l.LsTLV.Serialize([]byte(l.Name))
  6434  }
  6435  
  6436  func (l *LsTLVNodeName) String() string {
  6437  	return fmt.Sprintf("{Node Name: %s}", l.Name)
  6438  }
  6439  
  6440  func (l *LsTLVNodeName) MarshalJSON() ([]byte, error) {
  6441  	return json.Marshal(struct {
  6442  		Type LsTLVType `json:"type"`
  6443  		Name string    `json:"node_name"`
  6444  	}{
  6445  		Type: l.Type,
  6446  		Name: l.Name,
  6447  	})
  6448  }
  6449  
  6450  type LsTLVIsisArea struct {
  6451  	LsTLV
  6452  	Area []byte
  6453  }
  6454  
  6455  func NewLsTLVIsisArea(l *[]byte) *LsTLVIsisArea {
  6456  	return &LsTLVIsisArea{
  6457  		LsTLV: LsTLV{
  6458  			Type:   BGP_ASPATH_ATTR_TYPE_SET,
  6459  			Length: uint16(len(*l)),
  6460  		},
  6461  		Area: *l,
  6462  	}
  6463  }
  6464  
  6465  func (l *LsTLVIsisArea) DecodeFromBytes(data []byte) error {
  6466  	value, err := l.LsTLV.DecodeFromBytes(data)
  6467  	if err != nil {
  6468  		return err
  6469  	}
  6470  
  6471  	if l.Type != LS_TLV_ISIS_AREA {
  6472  		return malformedAttrListErr("Unexpected TLV type")
  6473  	}
  6474  
  6475  	if len(value) < 1 || len(value) > 13 {
  6476  		return malformedAttrListErr("Incorrect ISIS Area size")
  6477  	}
  6478  
  6479  	l.Area = value
  6480  
  6481  	return nil
  6482  }
  6483  
  6484  func (l *LsTLVIsisArea) Serialize() ([]byte, error) {
  6485  	return l.LsTLV.Serialize(l.Area)
  6486  }
  6487  
  6488  func (l *LsTLVIsisArea) String() string {
  6489  	return fmt.Sprintf("{ISIS Area ID: %v}", l.Area)
  6490  }
  6491  
  6492  func (l *LsTLVIsisArea) MarshalJSON() ([]byte, error) {
  6493  	return json.Marshal(struct {
  6494  		Type LsTLVType `json:"type"`
  6495  		Area string    `json:"isis_area_id"`
  6496  	}{
  6497  		Type: l.Type,
  6498  		Area: fmt.Sprintf("%v", l.Area),
  6499  	})
  6500  }
  6501  
  6502  type LsTLVLocalIPv4RouterID struct {
  6503  	LsTLV
  6504  	IP net.IP
  6505  }
  6506  
  6507  func NewLsTLVLocalIPv4RouterID(l *net.IP) *LsTLVLocalIPv4RouterID {
  6508  	return &LsTLVLocalIPv4RouterID{
  6509  		LsTLV: LsTLV{
  6510  			Type:   BGP_ASPATH_ATTR_TYPE_SET,
  6511  			Length: 4,
  6512  		},
  6513  		IP: *l,
  6514  	}
  6515  }
  6516  
  6517  func (l *LsTLVLocalIPv4RouterID) DecodeFromBytes(data []byte) error {
  6518  	value, err := l.LsTLV.DecodeFromBytes(data)
  6519  	if err != nil {
  6520  		return err
  6521  	}
  6522  
  6523  	if l.Type != LS_TLV_IPV4_LOCAL_ROUTER_ID {
  6524  		return malformedAttrListErr("Unexpected TLV type")
  6525  	}
  6526  
  6527  	// https://tools.ietf.org/html/rfc5305#section-4.3
  6528  	if len(value) != 4 {
  6529  		return malformedAttrListErr("Unexpected address size")
  6530  	}
  6531  
  6532  	l.IP = net.IP(value)
  6533  
  6534  	return nil
  6535  }
  6536  
  6537  func (l *LsTLVLocalIPv4RouterID) Serialize() ([]byte, error) {
  6538  	return l.LsTLV.Serialize(l.IP)
  6539  }
  6540  
  6541  func (l *LsTLVLocalIPv4RouterID) String() string {
  6542  	return fmt.Sprintf("{Local RouterID IPv4: %v}", l.IP)
  6543  }
  6544  
  6545  func (l *LsTLVLocalIPv4RouterID) MarshalJSON() ([]byte, error) {
  6546  	return json.Marshal(struct {
  6547  		Type  LsTLVType `json:"type"`
  6548  		Value string    `json:"node_local_router_id_ipv4"`
  6549  	}{
  6550  		Type:  l.Type,
  6551  		Value: fmt.Sprintf("%v", l.IP),
  6552  	})
  6553  }
  6554  
  6555  type LsTLVRemoteIPv4RouterID struct {
  6556  	LsTLV
  6557  	IP net.IP
  6558  }
  6559  
  6560  func NewLsTLVRemoteIPv4RouterID(l *net.IP) *LsTLVRemoteIPv4RouterID {
  6561  	return &LsTLVRemoteIPv4RouterID{
  6562  		LsTLV: LsTLV{
  6563  			Type:   BGP_ASPATH_ATTR_TYPE_SET,
  6564  			Length: 4,
  6565  		},
  6566  		IP: *l,
  6567  	}
  6568  }
  6569  
  6570  func (l *LsTLVRemoteIPv4RouterID) DecodeFromBytes(data []byte) error {
  6571  	value, err := l.LsTLV.DecodeFromBytes(data)
  6572  	if err != nil {
  6573  		return err
  6574  	}
  6575  
  6576  	if l.Type != LS_TLV_IPV4_REMOTE_ROUTER_ID {
  6577  		return malformedAttrListErr("Unexpected TLV type")
  6578  	}
  6579  
  6580  	// https://tools.ietf.org/html/rfc5305#section-4.3
  6581  	if len(value) != 4 {
  6582  		return malformedAttrListErr("Unexpected address size")
  6583  	}
  6584  
  6585  	l.IP = net.IP(value)
  6586  
  6587  	return nil
  6588  }
  6589  
  6590  func (l *LsTLVRemoteIPv4RouterID) Serialize() ([]byte, error) {
  6591  	return l.LsTLV.Serialize(l.IP)
  6592  }
  6593  
  6594  func (l *LsTLVRemoteIPv4RouterID) String() string {
  6595  	return fmt.Sprintf("{Remote RouterID IPv4: %v}", l.IP)
  6596  }
  6597  
  6598  func (l *LsTLVRemoteIPv4RouterID) MarshalJSON() ([]byte, error) {
  6599  	return json.Marshal(struct {
  6600  		Type  LsTLVType `json:"type"`
  6601  		Value string    `json:"node_remote_router_id_ipv4"`
  6602  	}{
  6603  		Type:  l.Type,
  6604  		Value: fmt.Sprintf("%v", l.IP),
  6605  	})
  6606  }
  6607  
  6608  type LsTLVLocalIPv6RouterID struct {
  6609  	LsTLV
  6610  	IP net.IP
  6611  }
  6612  
  6613  func NewLsTLVLocalIPv6RouterID(l *net.IP) *LsTLVLocalIPv6RouterID {
  6614  	return &LsTLVLocalIPv6RouterID{
  6615  		LsTLV: LsTLV{
  6616  			Type:   BGP_ASPATH_ATTR_TYPE_SET,
  6617  			Length: 0,
  6618  		},
  6619  		IP: *l,
  6620  	}
  6621  }
  6622  
  6623  func (l *LsTLVLocalIPv6RouterID) DecodeFromBytes(data []byte) error {
  6624  	value, err := l.LsTLV.DecodeFromBytes(data)
  6625  	if err != nil {
  6626  		return err
  6627  	}
  6628  
  6629  	if l.Type != LS_TLV_IPV6_LOCAL_ROUTER_ID {
  6630  		return malformedAttrListErr("Unexpected TLV type")
  6631  	}
  6632  
  6633  	// https://tools.ietf.org/html/rfc6119#section-4.1
  6634  	if len(value) != 16 {
  6635  		return malformedAttrListErr("Unexpected address size")
  6636  	}
  6637  
  6638  	l.IP = net.IP(value)
  6639  
  6640  	return nil
  6641  }
  6642  
  6643  func (l *LsTLVLocalIPv6RouterID) Serialize() ([]byte, error) {
  6644  	return l.LsTLV.Serialize(l.IP)
  6645  }
  6646  
  6647  func (l *LsTLVLocalIPv6RouterID) String() string {
  6648  	return fmt.Sprintf("{Local RouterID IPv6: %v}", l.IP)
  6649  }
  6650  
  6651  func (l *LsTLVLocalIPv6RouterID) MarshalJSON() ([]byte, error) {
  6652  	return json.Marshal(struct {
  6653  		Type  LsTLVType `json:"type"`
  6654  		Value string    `json:"node_local_router_id_ipv6"`
  6655  	}{
  6656  		Type:  l.Type,
  6657  		Value: fmt.Sprintf("%v", l.IP),
  6658  	})
  6659  }
  6660  
  6661  type LsTLVRemoteIPv6RouterID struct {
  6662  	LsTLV
  6663  	IP net.IP
  6664  }
  6665  
  6666  func NewLsTLVRemoteIPv6RouterID(l *net.IP) *LsTLVRemoteIPv6RouterID {
  6667  	return &LsTLVRemoteIPv6RouterID{
  6668  		LsTLV: LsTLV{
  6669  			Type:   BGP_ASPATH_ATTR_TYPE_SET,
  6670  			Length: 4,
  6671  		},
  6672  		IP: *l,
  6673  	}
  6674  }
  6675  
  6676  func (l *LsTLVRemoteIPv6RouterID) DecodeFromBytes(data []byte) error {
  6677  	value, err := l.LsTLV.DecodeFromBytes(data)
  6678  	if err != nil {
  6679  		return err
  6680  	}
  6681  
  6682  	if l.Type != LS_TLV_IPV6_REMOTE_ROUTER_ID {
  6683  		return malformedAttrListErr("Unexpected TLV type")
  6684  	}
  6685  
  6686  	// https://tools.ietf.org/html/rfc6119#section-4.1
  6687  	if len(value) != 16 {
  6688  		return malformedAttrListErr("Unexpected address size")
  6689  	}
  6690  
  6691  	l.IP = net.IP(value)
  6692  
  6693  	return nil
  6694  }
  6695  
  6696  func (l *LsTLVRemoteIPv6RouterID) Serialize() ([]byte, error) {
  6697  	return l.LsTLV.Serialize(l.IP)
  6698  }
  6699  
  6700  func (l *LsTLVRemoteIPv6RouterID) String() string {
  6701  	return fmt.Sprintf("{Remote RouterID IPv6: %v}", l.IP)
  6702  }
  6703  
  6704  func (l *LsTLVRemoteIPv6RouterID) MarshalJSON() ([]byte, error) {
  6705  	return json.Marshal(struct {
  6706  		Type  LsTLVType `json:"type"`
  6707  		Value string    `json:"node_remote_router_id_ipv6"`
  6708  	}{
  6709  		Type:  l.Type,
  6710  		Value: fmt.Sprintf("%v", l.IP),
  6711  	})
  6712  }
  6713  
  6714  type LsTLVOpaqueNodeAttr struct {
  6715  	LsTLV
  6716  	Attr []byte
  6717  }
  6718  
  6719  func NewLsTLVOpaqueNodeAttr(l *[]byte) *LsTLVOpaqueNodeAttr {
  6720  	return &LsTLVOpaqueNodeAttr{
  6721  		LsTLV: LsTLV{
  6722  			Type:   BGP_ASPATH_ATTR_TYPE_SET,
  6723  			Length: uint16(len(*l)),
  6724  		},
  6725  		Attr: *l,
  6726  	}
  6727  }
  6728  
  6729  func (l *LsTLVOpaqueNodeAttr) DecodeFromBytes(data []byte) error {
  6730  	value, err := l.LsTLV.DecodeFromBytes(data)
  6731  	if err != nil {
  6732  		return err
  6733  	}
  6734  
  6735  	if l.Type != LS_TLV_OPAQUE_NODE_ATTR {
  6736  		return malformedAttrListErr("Unexpected TLV type")
  6737  	}
  6738  
  6739  	l.Attr = value
  6740  
  6741  	return nil
  6742  }
  6743  
  6744  func (l *LsTLVOpaqueNodeAttr) Serialize() ([]byte, error) {
  6745  	return l.LsTLV.Serialize(l.Attr)
  6746  }
  6747  
  6748  func (l *LsTLVOpaqueNodeAttr) String() string {
  6749  	return fmt.Sprintf("{Opaque attribute: %v}", l.Attr)
  6750  }
  6751  
  6752  func (l *LsTLVOpaqueNodeAttr) MarshalJSON() ([]byte, error) {
  6753  	return json.Marshal(struct {
  6754  		Type  LsTLVType `json:"type"`
  6755  		Value string    `json:"node_opaque_attribute"`
  6756  	}{
  6757  		Type:  l.Type,
  6758  		Value: fmt.Sprintf("%v", l.Attr),
  6759  	})
  6760  }
  6761  
  6762  type LsTLVAutonomousSystem struct {
  6763  	LsTLV
  6764  	ASN uint32
  6765  }
  6766  
  6767  func (l *LsTLVAutonomousSystem) DecodeFromBytes(data []byte) error {
  6768  	value, err := l.LsTLV.DecodeFromBytes(data)
  6769  	if err != nil {
  6770  		return err
  6771  	}
  6772  
  6773  	if l.Type != LS_TLV_AS {
  6774  		return malformedAttrListErr("Unexpected TLV type")
  6775  	}
  6776  
  6777  	// https://tools.ietf.org/html/rfc7752#section-3.2.1.4
  6778  	if len(value) != 4 {
  6779  		return malformedAttrListErr("Incorrect AS length")
  6780  	}
  6781  
  6782  	l.ASN = binary.BigEndian.Uint32(value)
  6783  
  6784  	return nil
  6785  }
  6786  
  6787  func (l *LsTLVAutonomousSystem) Serialize() ([]byte, error) {
  6788  	var buf [4]byte
  6789  	binary.BigEndian.PutUint32(buf[:4], l.ASN)
  6790  
  6791  	return l.LsTLV.Serialize(buf[:])
  6792  }
  6793  
  6794  func (l *LsTLVAutonomousSystem) String() string {
  6795  	return fmt.Sprintf("{ASN: %d}", l.ASN)
  6796  }
  6797  
  6798  func (l *LsTLVAutonomousSystem) MarshalJSON() ([]byte, error) {
  6799  	return json.Marshal(struct {
  6800  		Type LsTLVType `json:"type"`
  6801  		ASN  uint32    `json:"asn"`
  6802  	}{
  6803  		Type: l.Type,
  6804  		ASN:  l.ASN,
  6805  	})
  6806  }
  6807  
  6808  type LsTLVBgpLsID struct {
  6809  	LsTLV
  6810  	BGPLsID uint32
  6811  }
  6812  
  6813  func (l *LsTLVBgpLsID) DecodeFromBytes(data []byte) error {
  6814  	value, err := l.LsTLV.DecodeFromBytes(data)
  6815  	if err != nil {
  6816  		return err
  6817  	}
  6818  
  6819  	if l.Type != LS_TLV_BGP_LS_ID {
  6820  		return malformedAttrListErr("Unexpected TLV type")
  6821  	}
  6822  
  6823  	// https://tools.ietf.org/html/rfc7752#section-3.2.1.4
  6824  	if len(value) != 4 {
  6825  		return malformedAttrListErr("Incorrect BGP-LS ID length")
  6826  	}
  6827  
  6828  	l.BGPLsID = binary.BigEndian.Uint32(value)
  6829  
  6830  	return nil
  6831  }
  6832  
  6833  func (l *LsTLVBgpLsID) Serialize() ([]byte, error) {
  6834  	var buf [4]byte
  6835  	binary.BigEndian.PutUint32(buf[:4], l.BGPLsID)
  6836  
  6837  	return l.LsTLV.Serialize(buf[:4])
  6838  }
  6839  
  6840  func (l *LsTLVBgpLsID) String() string {
  6841  	return fmt.Sprintf("{BGP LS ID: %d}", l.BGPLsID)
  6842  }
  6843  
  6844  func (l *LsTLVBgpLsID) MarshalJSON() ([]byte, error) {
  6845  	return json.Marshal(struct {
  6846  		Type    LsTLVType `json:"type"`
  6847  		BgpLsID uint32    `json:"bgp_ls_id"`
  6848  	}{
  6849  		Type:    l.Type,
  6850  		BgpLsID: l.BGPLsID,
  6851  	})
  6852  }
  6853  
  6854  type LsTLVIgpRouterID struct {
  6855  	LsTLV
  6856  	RouterID []byte
  6857  }
  6858  
  6859  func (l *LsTLVIgpRouterID) DecodeFromBytes(data []byte) error {
  6860  	value, err := l.LsTLV.DecodeFromBytes(data)
  6861  	if err != nil {
  6862  		return err
  6863  	}
  6864  
  6865  	if l.Type != LS_TLV_IGP_ROUTER_ID {
  6866  		return malformedAttrListErr("Unexpected TLV type")
  6867  	}
  6868  
  6869  	// https://tools.ietf.org/html/rfc7752#section-3.2.1.4
  6870  	// 4, 6, 7, and 8 are the only valid values.
  6871  	switch len(value) {
  6872  	case 4, 6, 7, 8:
  6873  		break
  6874  	default:
  6875  		return malformedAttrListErr(fmt.Sprintf("Incorrect IGP Router ID length: %d", len(value)))
  6876  	}
  6877  
  6878  	l.RouterID = value
  6879  
  6880  	return nil
  6881  }
  6882  
  6883  func (l *LsTLVIgpRouterID) Serialize() ([]byte, error) {
  6884  	return l.LsTLV.Serialize(l.RouterID)
  6885  }
  6886  
  6887  func (l *LsTLVIgpRouterID) String() string {
  6888  	return fmt.Sprintf("{IGP Router ID: %v}", l.RouterID)
  6889  }
  6890  
  6891  func (l *LsTLVIgpRouterID) MarshalJSON() ([]byte, error) {
  6892  	return json.Marshal(struct {
  6893  		Type     LsTLVType `json:"type"`
  6894  		RouterID string    `json:"igp_router_id"`
  6895  	}{
  6896  		Type:     l.Type,
  6897  		RouterID: fmt.Sprintf("%v", l.RouterID),
  6898  	})
  6899  }
  6900  
  6901  type LsTLVOspfAreaID struct {
  6902  	LsTLV
  6903  	AreaID uint32
  6904  }
  6905  
  6906  func (l *LsTLVOspfAreaID) DecodeFromBytes(data []byte) error {
  6907  	value, err := l.LsTLV.DecodeFromBytes(data)
  6908  	if err != nil {
  6909  		return err
  6910  	}
  6911  
  6912  	if l.Type != LS_TLV_OSPF_AREA {
  6913  		return malformedAttrListErr("Unexpected TLV type")
  6914  	}
  6915  
  6916  	// https://tools.ietf.org/html/rfc7752#section-3.2.1.4
  6917  	if len(value) != 4 {
  6918  		return malformedAttrListErr("Incorrect OSPF Area ID length")
  6919  	}
  6920  
  6921  	l.AreaID = binary.BigEndian.Uint32(value)
  6922  
  6923  	return nil
  6924  }
  6925  
  6926  func (l *LsTLVOspfAreaID) Serialize() ([]byte, error) {
  6927  	var buf [4]byte
  6928  	binary.BigEndian.PutUint32(buf[:4], l.AreaID)
  6929  
  6930  	return l.LsTLV.Serialize(buf[:4])
  6931  }
  6932  
  6933  func (l *LsTLVOspfAreaID) String() string {
  6934  	return fmt.Sprintf("{OSPF Area ID: %d}", l.AreaID)
  6935  }
  6936  
  6937  func (l *LsTLVOspfAreaID) MarshalJSON() ([]byte, error) {
  6938  	return json.Marshal(struct {
  6939  		Type   LsTLVType `json:"type"`
  6940  		AreaID uint32    `json:"ospf_area_id"`
  6941  	}{
  6942  		Type:   l.Type,
  6943  		AreaID: l.AreaID,
  6944  	})
  6945  }
  6946  
  6947  type LsTLVBgpRouterID struct {
  6948  	LsTLV
  6949  	RouterID net.IP
  6950  }
  6951  
  6952  func (l *LsTLVBgpRouterID) DecodeFromBytes(data []byte) error {
  6953  	value, err := l.LsTLV.DecodeFromBytes(data)
  6954  	if err != nil {
  6955  		return err
  6956  	}
  6957  
  6958  	if l.Type != LS_TLV_BGP_ROUTER_ID {
  6959  		return malformedAttrListErr("Unexpected TLV type")
  6960  	}
  6961  
  6962  	// https://tools.ietf.org/html/rfc9086#section-4.1
  6963  	// 4 is the only valid value.
  6964  	if len(value) != 4 {
  6965  		return malformedAttrListErr(fmt.Sprintf("Incorrect BGP Router ID length: %d", len(value)))
  6966  	}
  6967  
  6968  	l.RouterID = net.IP(value)
  6969  
  6970  	return nil
  6971  }
  6972  
  6973  func (l *LsTLVBgpRouterID) Serialize() ([]byte, error) {
  6974  	tmpaddr := l.RouterID
  6975  	if tmpaddr.To4() != nil {
  6976  		var buf [4]byte
  6977  		copy(buf[:], l.RouterID.To4())
  6978  		return l.LsTLV.Serialize(buf[:])
  6979  	}
  6980  	var buf [16]byte
  6981  	copy(buf[:], l.RouterID.To16())
  6982  	return l.LsTLV.Serialize(buf[:])
  6983  }
  6984  
  6985  func (l *LsTLVBgpRouterID) String() string {
  6986  	return fmt.Sprintf("{BGP Router ID: %v}", l.RouterID)
  6987  }
  6988  
  6989  func (l *LsTLVBgpRouterID) MarshalJSON() ([]byte, error) {
  6990  	return json.Marshal(struct {
  6991  		Type     LsTLVType `json:"type"`
  6992  		RouterID string    `json:"bgp_router_id"`
  6993  	}{
  6994  		Type:     l.Type,
  6995  		RouterID: fmt.Sprintf("%v", l.RouterID),
  6996  	})
  6997  }
  6998  
  6999  type LsTLVBgpConfederationMember struct {
  7000  	LsTLV
  7001  	BgpConfederationMember uint32
  7002  }
  7003  
  7004  func (l *LsTLVBgpConfederationMember) DecodeFromBytes(data []byte) error {
  7005  	value, err := l.LsTLV.DecodeFromBytes(data)
  7006  	if err != nil {
  7007  		return err
  7008  	}
  7009  
  7010  	if l.Type != LS_TLV_BGP_CONFEDERATION_MEMBER {
  7011  		return malformedAttrListErr("Unexpected TLV type")
  7012  	}
  7013  
  7014  	// https://tools.ietf.org/html/rfc9086#section-4.3
  7015  	// 4 is the only valid value.
  7016  	if len(value) != 4 {
  7017  		return malformedAttrListErr(fmt.Sprintf("Incorrect BGP Confederation Member length: %d", len(value)))
  7018  	}
  7019  
  7020  	l.BgpConfederationMember = binary.BigEndian.Uint32(value)
  7021  
  7022  	return nil
  7023  }
  7024  
  7025  func (l *LsTLVBgpConfederationMember) Serialize() ([]byte, error) {
  7026  	var buf [4]byte
  7027  	binary.BigEndian.PutUint32(buf[:4], l.BgpConfederationMember)
  7028  
  7029  	return l.LsTLV.Serialize(buf[:4])
  7030  }
  7031  
  7032  func (l *LsTLVBgpConfederationMember) String() string {
  7033  	return fmt.Sprintf("{BGP Confederation Member: %d}", l.BgpConfederationMember)
  7034  }
  7035  
  7036  func (l *LsTLVBgpConfederationMember) MarshalJSON() ([]byte, error) {
  7037  	return json.Marshal(struct {
  7038  		Type                   LsTLVType `json:"type"`
  7039  		BgpConfederationMember uint32    `json:"bgp_confederation_member"`
  7040  	}{
  7041  		Type:                   l.Type,
  7042  		BgpConfederationMember: l.BgpConfederationMember,
  7043  	})
  7044  }
  7045  
  7046  type LsOspfRouteType uint8
  7047  
  7048  const (
  7049  	LS_OSPF_ROUTE_TYPE_UNKNOWN = iota
  7050  	LS_OSPF_ROUTE_TYPE_INTRA_AREA
  7051  	LS_OSPF_ROUTE_TYPE_INTER_AREA
  7052  	LS_OSPF_ROUTE_TYPE_EXTERNAL1
  7053  	LS_OSPF_ROUTE_TYPE_EXTERNAL2
  7054  	LS_OSPF_ROUTE_TYPE_NSSA1
  7055  	LS_OSPF_ROUTE_TYPE_NSSA2
  7056  )
  7057  
  7058  func (l LsOspfRouteType) String() string {
  7059  	switch l {
  7060  	case LS_OSPF_ROUTE_TYPE_INTRA_AREA:
  7061  		return "INTRA-AREA"
  7062  	case LS_OSPF_ROUTE_TYPE_INTER_AREA:
  7063  		return "INTER-AREA"
  7064  	case LS_OSPF_ROUTE_TYPE_EXTERNAL1:
  7065  		return "EXTERNAL1"
  7066  	case LS_OSPF_ROUTE_TYPE_EXTERNAL2:
  7067  		return "EXTERNAL2"
  7068  	case LS_OSPF_ROUTE_TYPE_NSSA1:
  7069  		return "NSSA1"
  7070  	case LS_OSPF_ROUTE_TYPE_NSSA2:
  7071  		return "NSSA2"
  7072  	default:
  7073  		return fmt.Sprintf("LsOspfRouteType(%d)", uint8(l))
  7074  	}
  7075  }
  7076  
  7077  type LsTLVOspfRouteType struct {
  7078  	LsTLV
  7079  	RouteType LsOspfRouteType
  7080  }
  7081  
  7082  func (l *LsTLVOspfRouteType) DecodeFromBytes(data []byte) error {
  7083  	value, err := l.LsTLV.DecodeFromBytes(data)
  7084  	if err != nil {
  7085  		return err
  7086  	}
  7087  
  7088  	if l.Type != LS_TLV_OSPF_ROUTE_TYPE {
  7089  		return malformedAttrListErr("Unexpected TLV type")
  7090  	}
  7091  
  7092  	// https://tools.ietf.org/html/rfc7752#section-3.2.3.1
  7093  	if len(value) != 1 {
  7094  		return malformedAttrListErr("Incorrect OSPF Route type length")
  7095  	}
  7096  
  7097  	if value[0] < byte(LS_OSPF_ROUTE_TYPE_INTRA_AREA) || value[0] > LS_OSPF_ROUTE_TYPE_NSSA2 {
  7098  		return malformedAttrListErr("Incorrect OSPF Route type")
  7099  	}
  7100  
  7101  	l.RouteType = LsOspfRouteType(value[0])
  7102  
  7103  	return nil
  7104  }
  7105  
  7106  func (l *LsTLVOspfRouteType) Serialize() ([]byte, error) {
  7107  	var buf [1]byte
  7108  	buf[0] = byte(l.RouteType)
  7109  
  7110  	return l.LsTLV.Serialize(buf[:])
  7111  }
  7112  
  7113  func (l *LsTLVOspfRouteType) String() string {
  7114  	return fmt.Sprintf("{OSPF Route Type: %v}", l.RouteType)
  7115  }
  7116  
  7117  func (l *LsTLVOspfRouteType) MarshalJSON() ([]byte, error) {
  7118  	return json.Marshal(struct {
  7119  		Type      LsTLVType `json:"type"`
  7120  		RouteType string    `json:"ospf_route_type"`
  7121  	}{
  7122  		Type:      l.Type,
  7123  		RouteType: l.RouteType.String(),
  7124  	})
  7125  }
  7126  
  7127  type LsTLVIPReachability struct {
  7128  	LsTLV
  7129  	PrefixLength uint8
  7130  	Prefix       []byte
  7131  }
  7132  
  7133  func (l *LsTLVIPReachability) ToIPNet(ipv6 bool) net.IPNet {
  7134  	b := make([]byte, 16)
  7135  	for i := 0; i < int(((l.PrefixLength-1)/8)+1); i++ {
  7136  		b[i] = l.Prefix[i]
  7137  	}
  7138  
  7139  	ip := net.IPv4(b[0], b[1], b[2], b[3]).To4()
  7140  	if ipv6 {
  7141  		ip = net.IP(b).To16()
  7142  	}
  7143  
  7144  	_, n, err := net.ParseCIDR(fmt.Sprintf("%v/%v", ip, l.PrefixLength))
  7145  	if err != nil {
  7146  		return net.IPNet{}
  7147  	}
  7148  
  7149  	return *n
  7150  }
  7151  
  7152  func (l *LsTLVIPReachability) DecodeFromBytes(data []byte) error {
  7153  	value, err := l.LsTLV.DecodeFromBytes(data)
  7154  	if err != nil {
  7155  		return err
  7156  	}
  7157  
  7158  	if l.Type != LS_TLV_IP_REACH_INFO {
  7159  		return malformedAttrListErr("Unexpected TLV type")
  7160  	}
  7161  
  7162  	if len(value) < 2 {
  7163  		return malformedAttrListErr("Incorrect IP reachability Info length")
  7164  	}
  7165  
  7166  	// https://tools.ietf.org/html/rfc7752#section-3.2.3.2
  7167  	if value[0] > 128 || value[0] == 0 {
  7168  		return malformedAttrListErr("Incorrect IP prefix length")
  7169  	}
  7170  
  7171  	ll := int(((value[0] - 1) / 8) + 1)
  7172  	if len(value[1:]) != ll {
  7173  		return malformedAttrListErr("Malformed IP reachability TLV")
  7174  	}
  7175  
  7176  	l.PrefixLength = value[0]
  7177  	l.Prefix = value[1 : 1+ll]
  7178  
  7179  	return nil
  7180  }
  7181  
  7182  func (l *LsTLVIPReachability) Serialize() ([]byte, error) {
  7183  	b := []byte{l.PrefixLength}
  7184  
  7185  	return l.LsTLV.Serialize(append(b, l.Prefix...))
  7186  }
  7187  
  7188  func (l *LsTLVIPReachability) String() string {
  7189  	return fmt.Sprintf("{IP Reachability: %v/%v}", l.Prefix, l.PrefixLength)
  7190  }
  7191  
  7192  func (l *LsTLVIPReachability) MarshalJSON() ([]byte, error) {
  7193  	return json.Marshal(struct {
  7194  		Type         LsTLVType `json:"type"`
  7195  		PrefixLength uint8     `json:"prefix_length"`
  7196  		Prefix       string    `json:"prefix"`
  7197  	}{
  7198  		Type:         l.Type,
  7199  		PrefixLength: l.PrefixLength,
  7200  		Prefix:       fmt.Sprintf("%v", l.Prefix),
  7201  	})
  7202  }
  7203  
  7204  type LsTLVAdminGroup struct {
  7205  	LsTLV
  7206  	AdminGroup uint32
  7207  }
  7208  
  7209  func NewLsTLVAdminGroup(l *uint32) *LsTLVAdminGroup {
  7210  	return &LsTLVAdminGroup{
  7211  		LsTLV: LsTLV{
  7212  			Type:   BGP_ASPATH_ATTR_TYPE_SET,
  7213  			Length: 4,
  7214  		},
  7215  		AdminGroup: *l,
  7216  	}
  7217  }
  7218  
  7219  func (l *LsTLVAdminGroup) DecodeFromBytes(data []byte) error {
  7220  	value, err := l.LsTLV.DecodeFromBytes(data)
  7221  	if err != nil {
  7222  		return err
  7223  	}
  7224  
  7225  	if l.Type != LS_TLV_ADMIN_GROUP {
  7226  		return malformedAttrListErr("Unexpected TLV type")
  7227  	}
  7228  
  7229  	// https://tools.ietf.org/html/rfc5305#section-3.1
  7230  	if len(value) != 4 {
  7231  		return malformedAttrListErr("Incorrect Admin Group length")
  7232  	}
  7233  
  7234  	l.AdminGroup = binary.BigEndian.Uint32(value)
  7235  
  7236  	return nil
  7237  }
  7238  
  7239  func (l *LsTLVAdminGroup) Serialize() ([]byte, error) {
  7240  	var buf [4]byte
  7241  	binary.BigEndian.PutUint32(buf[:4], l.AdminGroup)
  7242  
  7243  	return l.LsTLV.Serialize(buf[:])
  7244  }
  7245  
  7246  func (l *LsTLVAdminGroup) String() string {
  7247  	return fmt.Sprintf("{Admin Group: %08x}", l.AdminGroup)
  7248  }
  7249  
  7250  func (l *LsTLVAdminGroup) MarshalJSON() ([]byte, error) {
  7251  	return json.Marshal(struct {
  7252  		Type       LsTLVType `json:"type"`
  7253  		AdminGroup string    `json:"admin_group"`
  7254  	}{
  7255  		Type:       l.Type,
  7256  		AdminGroup: fmt.Sprintf("%08x", l.AdminGroup),
  7257  	})
  7258  }
  7259  
  7260  type LsTLVMaxLinkBw struct {
  7261  	LsTLV
  7262  	Bandwidth float32
  7263  }
  7264  
  7265  func NewLsTLVMaxLinkBw(l *float32) *LsTLVMaxLinkBw {
  7266  	return &LsTLVMaxLinkBw{
  7267  		LsTLV: LsTLV{
  7268  			Type:   BGP_ASPATH_ATTR_TYPE_SET,
  7269  			Length: 4,
  7270  		},
  7271  		Bandwidth: *l,
  7272  	}
  7273  }
  7274  
  7275  func (l *LsTLVMaxLinkBw) DecodeFromBytes(data []byte) error {
  7276  	value, err := l.LsTLV.DecodeFromBytes(data)
  7277  	if err != nil {
  7278  		return err
  7279  	}
  7280  
  7281  	if l.Type != LS_TLV_MAX_LINK_BANDWIDTH {
  7282  		return malformedAttrListErr("Unexpected TLV type")
  7283  	}
  7284  
  7285  	// https://tools.ietf.org/html/rfc5305#section-3.4
  7286  	if len(value) != 4 {
  7287  		return malformedAttrListErr("Incorrect maximum link bandwidth length")
  7288  	}
  7289  
  7290  	l.Bandwidth = math.Float32frombits(binary.BigEndian.Uint32(value))
  7291  
  7292  	if l.Bandwidth < 0 || math.IsNaN(float64(l.Bandwidth)) || math.IsInf(float64(l.Bandwidth), 0) {
  7293  		return malformedAttrListErr("Incorrect maximum link bandwidth value")
  7294  	}
  7295  
  7296  	return nil
  7297  }
  7298  
  7299  func (l *LsTLVMaxLinkBw) Serialize() ([]byte, error) {
  7300  	var buf [4]byte
  7301  	binary.BigEndian.PutUint32(buf[:4], math.Float32bits(l.Bandwidth))
  7302  
  7303  	return l.LsTLV.Serialize(buf[:])
  7304  }
  7305  
  7306  func (l *LsTLVMaxLinkBw) String() string {
  7307  	return fmt.Sprintf("{Max Link BW: %v}", l.Bandwidth)
  7308  }
  7309  
  7310  func (l *LsTLVMaxLinkBw) MarshalJSON() ([]byte, error) {
  7311  	return json.Marshal(struct {
  7312  		Type      LsTLVType `json:"type"`
  7313  		Bandwidth float32   `json:"max_link_bw"`
  7314  	}{
  7315  		Type:      l.Type,
  7316  		Bandwidth: l.Bandwidth,
  7317  	})
  7318  }
  7319  
  7320  type LsTLVMaxReservableLinkBw struct {
  7321  	LsTLV
  7322  	Bandwidth float32
  7323  }
  7324  
  7325  func NewLsTLVMaxReservableLinkBw(l *float32) *LsTLVMaxReservableLinkBw {
  7326  	return &LsTLVMaxReservableLinkBw{
  7327  		LsTLV: LsTLV{
  7328  			Type:   BGP_ASPATH_ATTR_TYPE_SET,
  7329  			Length: 4,
  7330  		},
  7331  		Bandwidth: *l,
  7332  	}
  7333  }
  7334  
  7335  func (l *LsTLVMaxReservableLinkBw) DecodeFromBytes(data []byte) error {
  7336  	value, err := l.LsTLV.DecodeFromBytes(data)
  7337  	if err != nil {
  7338  		return err
  7339  	}
  7340  
  7341  	if l.Type != LS_TLV_MAX_RESERVABLE_BANDWIDTH {
  7342  		return malformedAttrListErr("Unexpected TLV type")
  7343  	}
  7344  
  7345  	// https://tools.ietf.org/html/rfc5305#section-3.5
  7346  	if len(value) != 4 {
  7347  		return malformedAttrListErr("Incorrect maximum reservable link bandwidth length")
  7348  	}
  7349  
  7350  	l.Bandwidth = math.Float32frombits(binary.BigEndian.Uint32(value))
  7351  
  7352  	if l.Bandwidth < 0 || math.IsNaN(float64(l.Bandwidth)) || math.IsInf(float64(l.Bandwidth), 0) {
  7353  		return malformedAttrListErr("Incorrect maximum reservable link bandwidth value")
  7354  	}
  7355  
  7356  	return nil
  7357  }
  7358  
  7359  func (l *LsTLVMaxReservableLinkBw) Serialize() ([]byte, error) {
  7360  	var buf [4]byte
  7361  	binary.BigEndian.PutUint32(buf[:4], math.Float32bits(l.Bandwidth))
  7362  
  7363  	return l.LsTLV.Serialize(buf[:])
  7364  }
  7365  
  7366  func (l *LsTLVMaxReservableLinkBw) String() string {
  7367  	return fmt.Sprintf("{Max Reservable Link BW: %v}", l.Bandwidth)
  7368  }
  7369  
  7370  func (l *LsTLVMaxReservableLinkBw) MarshalJSON() ([]byte, error) {
  7371  	return json.Marshal(struct {
  7372  		Type      LsTLVType `json:"type"`
  7373  		Bandwidth float32   `json:"max_reservable_link_bw"`
  7374  	}{
  7375  		Type:      l.Type,
  7376  		Bandwidth: l.Bandwidth,
  7377  	})
  7378  }
  7379  
  7380  type LsTLVUnreservedBw struct {
  7381  	LsTLV
  7382  	Bandwidth [8]float32
  7383  }
  7384  
  7385  func NewLsTLVUnreservedBw(l *[8]float32) *LsTLVUnreservedBw {
  7386  	return &LsTLVUnreservedBw{
  7387  		LsTLV: LsTLV{
  7388  			Type:   BGP_ASPATH_ATTR_TYPE_SET,
  7389  			Length: 32,
  7390  		},
  7391  		Bandwidth: *l,
  7392  	}
  7393  }
  7394  
  7395  func (l *LsTLVUnreservedBw) DecodeFromBytes(data []byte) error {
  7396  	value, err := l.LsTLV.DecodeFromBytes(data)
  7397  	if err != nil {
  7398  		return err
  7399  	}
  7400  
  7401  	if l.Type != LS_TLV_UNRESERVED_BANDWIDTH {
  7402  		return malformedAttrListErr("Unexpected TLV type")
  7403  	}
  7404  
  7405  	// https://tools.ietf.org/html/rfc5305#section-3.6
  7406  	if len(value) != 32 {
  7407  		return malformedAttrListErr("Incorrect unreserved bandwidth length")
  7408  	}
  7409  
  7410  	for i := 0; i < len(l.Bandwidth); i++ {
  7411  		l.Bandwidth[i] = math.Float32frombits(binary.BigEndian.Uint32(value[:4]))
  7412  		value = value[4:]
  7413  
  7414  		if l.Bandwidth[i] < 0 || math.IsNaN(float64(l.Bandwidth[i])) || math.IsInf(float64(l.Bandwidth[i]), 0) {
  7415  			return malformedAttrListErr("Incorrect unreserved bandwidth value")
  7416  		}
  7417  	}
  7418  
  7419  	return nil
  7420  }
  7421  
  7422  func (l *LsTLVUnreservedBw) Serialize() ([]byte, error) {
  7423  	buf := make([]byte, 0, 4*len(l.Bandwidth))
  7424  
  7425  	var b [4]byte
  7426  	for i := 0; i < len(l.Bandwidth); i++ {
  7427  		binary.BigEndian.PutUint32(b[:4], math.Float32bits(l.Bandwidth[i]))
  7428  		buf = append(buf, b[:]...)
  7429  	}
  7430  
  7431  	return l.LsTLV.Serialize(buf)
  7432  }
  7433  
  7434  func (l *LsTLVUnreservedBw) String() string {
  7435  	return fmt.Sprintf("{Unreserved BW: %v}", l.Bandwidth)
  7436  }
  7437  
  7438  func (l *LsTLVUnreservedBw) MarshalJSON() ([]byte, error) {
  7439  	return json.Marshal(struct {
  7440  		Type      LsTLVType  `json:"type"`
  7441  		Bandwidth [8]float32 `json:"unreserved_bw"`
  7442  	}{
  7443  		Type:      l.Type,
  7444  		Bandwidth: l.Bandwidth,
  7445  	})
  7446  }
  7447  
  7448  type LsTLVTEDefaultMetric struct {
  7449  	LsTLV
  7450  	Metric uint32
  7451  }
  7452  
  7453  func NewLsTLVTEDefaultMetric(l *uint32) *LsTLVTEDefaultMetric {
  7454  	return &LsTLVTEDefaultMetric{
  7455  		LsTLV: LsTLV{
  7456  			Type:   BGP_ASPATH_ATTR_TYPE_SET,
  7457  			Length: 4,
  7458  		},
  7459  		Metric: *l,
  7460  	}
  7461  }
  7462  
  7463  func (l *LsTLVTEDefaultMetric) DecodeFromBytes(data []byte) error {
  7464  	value, err := l.LsTLV.DecodeFromBytes(data)
  7465  	if err != nil {
  7466  		return err
  7467  	}
  7468  
  7469  	if l.Type != LS_TLV_TE_DEFAULT_METRIC {
  7470  		return malformedAttrListErr("Unexpected TLV type")
  7471  	}
  7472  
  7473  	// https://tools.ietf.org/html/rfc7752#section-3.3.2.3
  7474  	if len(value) != 4 {
  7475  		return malformedAttrListErr("Incorrect metric length length")
  7476  	}
  7477  
  7478  	l.Metric = binary.BigEndian.Uint32(value)
  7479  
  7480  	return nil
  7481  }
  7482  
  7483  func (l *LsTLVTEDefaultMetric) Serialize() ([]byte, error) {
  7484  	var buf [4]byte
  7485  	binary.BigEndian.PutUint32(buf[:4], l.Metric)
  7486  
  7487  	return l.LsTLV.Serialize(buf[:])
  7488  }
  7489  
  7490  func (l *LsTLVTEDefaultMetric) String() string {
  7491  	return fmt.Sprintf("{TE Default metric: %d}", l.Metric)
  7492  }
  7493  
  7494  func (l *LsTLVTEDefaultMetric) MarshalJSON() ([]byte, error) {
  7495  	return json.Marshal(struct {
  7496  		Type          LsTLVType `json:"type"`
  7497  		DefaultMetric uint32    `json:"te_default_metric"`
  7498  	}{
  7499  		Type:          l.Type,
  7500  		DefaultMetric: l.Metric,
  7501  	})
  7502  }
  7503  
  7504  type LsTLVIGPMetric struct {
  7505  	LsTLV
  7506  	Metric uint32
  7507  }
  7508  
  7509  func NewLsTLVIGPMetric(l *uint32) *LsTLVIGPMetric {
  7510  	return &LsTLVIGPMetric{
  7511  		LsTLV: LsTLV{
  7512  			Type:   BGP_ASPATH_ATTR_TYPE_SET,
  7513  			Length: 3, // TODO: implementation for IS-IS small metrics and OSPF link metrics.
  7514  		},
  7515  		Metric: *l,
  7516  	}
  7517  }
  7518  
  7519  func (l *LsTLVIGPMetric) DecodeFromBytes(data []byte) error {
  7520  	value, err := l.LsTLV.DecodeFromBytes(data)
  7521  	if err != nil {
  7522  		return err
  7523  	}
  7524  
  7525  	if l.Type != LS_TLV_IGP_METRIC {
  7526  		return malformedAttrListErr("Unexpected TLV type")
  7527  	}
  7528  
  7529  	// https://tools.ietf.org/html/rfc7752#section-3.3.2.4
  7530  	switch len(value) {
  7531  	case 1:
  7532  		l.Metric = uint32(value[0] & 0x3F)
  7533  
  7534  	case 2:
  7535  		l.Metric = uint32(binary.BigEndian.Uint16(value))
  7536  
  7537  	case 3:
  7538  		l.Metric = binary.BigEndian.Uint32([]byte{0, value[0], value[1], value[2]})
  7539  
  7540  	default:
  7541  		return malformedAttrListErr("Incorrect metric length")
  7542  	}
  7543  
  7544  	return nil
  7545  }
  7546  
  7547  func (l *LsTLVIGPMetric) Serialize() ([]byte, error) {
  7548  	switch l.Length {
  7549  	case 1:
  7550  		return l.LsTLV.Serialize([]byte{uint8(l.Metric) & 0x3F})
  7551  
  7552  	case 2:
  7553  		var buf [2]byte
  7554  		binary.BigEndian.PutUint16(buf[:2], uint16(l.Metric))
  7555  		return l.LsTLV.Serialize(buf[:])
  7556  
  7557  	case 3:
  7558  		var buf [4]byte
  7559  		binary.BigEndian.PutUint32(buf[:4], l.Metric)
  7560  		return l.LsTLV.Serialize(buf[1:])
  7561  
  7562  	default:
  7563  		return nil, malformedAttrListErr("Incorrect metric length")
  7564  	}
  7565  }
  7566  
  7567  func (l *LsTLVIGPMetric) String() string {
  7568  	return fmt.Sprintf("{IGP metric: %d}", l.Metric)
  7569  }
  7570  
  7571  func (l *LsTLVIGPMetric) MarshalJSON() ([]byte, error) {
  7572  	return json.Marshal(struct {
  7573  		Type   LsTLVType `json:"type"`
  7574  		Metric uint32    `json:"igp_metric"`
  7575  	}{
  7576  		Type:   l.Type,
  7577  		Metric: l.Metric,
  7578  	})
  7579  }
  7580  
  7581  type LsTLVLinkName struct {
  7582  	LsTLV
  7583  	Name string
  7584  }
  7585  
  7586  func NewLsTLVLinkName(l *string) *LsTLVLinkName {
  7587  	return &LsTLVLinkName{
  7588  		LsTLV: LsTLV{
  7589  			Type:   BGP_ASPATH_ATTR_TYPE_SET,
  7590  			Length: uint16(len(*l)),
  7591  		},
  7592  		Name: *l,
  7593  	}
  7594  }
  7595  
  7596  func (l *LsTLVLinkName) DecodeFromBytes(data []byte) error {
  7597  	value, err := l.LsTLV.DecodeFromBytes(data)
  7598  	if err != nil {
  7599  		return err
  7600  	}
  7601  
  7602  	if l.Type != LS_TLV_LINK_NAME {
  7603  		return malformedAttrListErr("Unexpected TLV type")
  7604  	}
  7605  
  7606  	// https://tools.ietf.org/html/rfc7752#section-3.3.2.7
  7607  	if len(value) < 1 || len(value) > 255 {
  7608  		return malformedAttrListErr("Incorrect Link Name")
  7609  	}
  7610  
  7611  	l.Name = string(value)
  7612  
  7613  	return nil
  7614  }
  7615  
  7616  func (l *LsTLVLinkName) Serialize() ([]byte, error) {
  7617  	return l.LsTLV.Serialize([]byte(l.Name))
  7618  }
  7619  
  7620  func (l *LsTLVLinkName) String() string {
  7621  	return fmt.Sprintf("{Link Name: %s}", l.Name)
  7622  }
  7623  
  7624  func (l *LsTLVLinkName) MarshalJSON() ([]byte, error) {
  7625  	return json.Marshal(struct {
  7626  		Type LsTLVType `json:"type"`
  7627  		Name string    `json:"link_name"`
  7628  	}{
  7629  		Type: l.Type,
  7630  		Name: l.Name,
  7631  	})
  7632  }
  7633  
  7634  type LsTLVSrAlgorithm struct {
  7635  	LsTLV
  7636  	Algorithm []byte
  7637  }
  7638  
  7639  func NewLsTLVSrAlgorithm(l *[]byte) *LsTLVSrAlgorithm {
  7640  	return &LsTLVSrAlgorithm{
  7641  		LsTLV: LsTLV{
  7642  			Type:   BGP_ASPATH_ATTR_TYPE_SET,
  7643  			Length: uint16(len(*l)),
  7644  		},
  7645  		Algorithm: *l,
  7646  	}
  7647  }
  7648  
  7649  func (l *LsTLVSrAlgorithm) DecodeFromBytes(data []byte) error {
  7650  	value, err := l.LsTLV.DecodeFromBytes(data)
  7651  	if err != nil {
  7652  		return err
  7653  	}
  7654  
  7655  	if l.Type != LS_TLV_SR_ALGORITHM {
  7656  		return malformedAttrListErr("Unexpected TLV type")
  7657  	}
  7658  
  7659  	if len(value) < 1 {
  7660  		return malformedAttrListErr("Incorrect SR algorithm length")
  7661  	}
  7662  
  7663  	l.Algorithm = value
  7664  
  7665  	return nil
  7666  }
  7667  
  7668  func (l *LsTLVSrAlgorithm) Serialize() ([]byte, error) {
  7669  	return l.LsTLV.Serialize(l.Algorithm)
  7670  }
  7671  
  7672  func (l *LsTLVSrAlgorithm) String() string {
  7673  	return fmt.Sprintf("{SR Algorithms: %v}", l.Algorithm)
  7674  }
  7675  
  7676  func (l *LsTLVSrAlgorithm) MarshalJSON() ([]byte, error) {
  7677  	return json.Marshal(struct {
  7678  		Type       LsTLVType `json:"type"`
  7679  		Algorithms string    `json:"sr_algorithm"`
  7680  	}{
  7681  		Type:       l.Type,
  7682  		Algorithms: fmt.Sprintf("%v", l.Algorithm),
  7683  	})
  7684  }
  7685  
  7686  type LsSrLabelRange struct {
  7687  	Range      uint32
  7688  	FirstLabel LsTLVSIDLabel
  7689  }
  7690  
  7691  type LsTLVSrCapabilities struct {
  7692  	LsTLV
  7693  	Flags  uint8
  7694  	Ranges []LsSrLabelRange
  7695  }
  7696  
  7697  func NewLsTLVSrCapabilities(l *LsSrCapabilities) *LsTLVSrCapabilities {
  7698  	var flags uint8
  7699  	if l.IPv4Supported {
  7700  		flags = flags & (1 >> 0)
  7701  	}
  7702  	if l.IPv6Supported {
  7703  		flags = flags & (1 >> 1)
  7704  	}
  7705  	ranges := []LsSrLabelRange{}
  7706  	var length uint16
  7707  	for _, r := range l.Ranges {
  7708  		ranges = append(ranges, LsSrLabelRange{
  7709  			Range: uint32(r.End - r.Begin),
  7710  			FirstLabel: LsTLVSIDLabel{
  7711  				LsTLV: LsTLV{
  7712  					Type:   BGP_ASPATH_ATTR_TYPE_SET,
  7713  					Length: 4,
  7714  				},
  7715  				SID: r.Begin,
  7716  			},
  7717  		})
  7718  		length += 4
  7719  	}
  7720  	return &LsTLVSrCapabilities{
  7721  		LsTLV: LsTLV{
  7722  			Type:   BGP_ASPATH_ATTR_TYPE_SET,
  7723  			Length: length,
  7724  		},
  7725  		Flags:  flags,
  7726  		Ranges: ranges,
  7727  	}
  7728  }
  7729  
  7730  type LsSrRange struct {
  7731  	Begin uint32 `json:"begin"`
  7732  	End   uint32 `json:"end"`
  7733  }
  7734  
  7735  type LsSrCapabilities struct {
  7736  	IPv4Supported bool        `json:"ipv4_supported"`
  7737  	IPv6Supported bool        `json:"ipv6_supported"`
  7738  	Ranges        []LsSrRange `json:"ranges"`
  7739  }
  7740  
  7741  func (l *LsTLVSrCapabilities) Extract() *LsSrCapabilities {
  7742  	lsc := &LsSrCapabilities{
  7743  		IPv4Supported: (l.Flags & (1 << 0)) > 0,
  7744  		IPv6Supported: (l.Flags & (1 << 1)) > 0,
  7745  	}
  7746  
  7747  	for _, r := range l.Ranges {
  7748  		lsc.Ranges = append(lsc.Ranges, LsSrRange{
  7749  			Begin: r.FirstLabel.SID,
  7750  			End:   r.FirstLabel.SID + r.Range,
  7751  		})
  7752  	}
  7753  
  7754  	return lsc
  7755  }
  7756  
  7757  func (l *LsTLVSrCapabilities) DecodeFromBytes(data []byte) error {
  7758  	value, err := l.LsTLV.DecodeFromBytes(data)
  7759  	if err != nil {
  7760  		return err
  7761  	}
  7762  
  7763  	if l.Type != LS_TLV_SR_CAPABILITIES {
  7764  		return malformedAttrListErr("Unexpected TLV type")
  7765  	}
  7766  
  7767  	if len(value) < 2 {
  7768  		return malformedAttrListErr("Incorrect SR Capabilities length")
  7769  	}
  7770  	l.Flags = value[0]
  7771  
  7772  	// Skip two bytes: flags and reserved.
  7773  	value = value[2:]
  7774  
  7775  	// The value field should be at least eight bytes long. Three bytes
  7776  	// for the range size and five or six bytes for the SID/Label TLV.
  7777  	for len(value) > 8 {
  7778  		// First, parse range size (3 bytes)
  7779  		buf := []byte{0, 0, 0, 0}
  7780  		for i := 1; i < len(buf); i++ {
  7781  			buf[i] = value[i-1]
  7782  		}
  7783  		r := binary.BigEndian.Uint32(buf)
  7784  		value = value[3:]
  7785  
  7786  		// Second, parse SID/Label sub-TLV.
  7787  		label := LsTLVSIDLabel{}
  7788  		if err := label.DecodeFromBytes(value); err != nil {
  7789  			return err
  7790  		}
  7791  
  7792  		l.Ranges = append(l.Ranges, LsSrLabelRange{
  7793  			Range:      r,
  7794  			FirstLabel: label,
  7795  		})
  7796  
  7797  		value = value[label.Len():]
  7798  	}
  7799  
  7800  	if len(value) > 0 {
  7801  		return malformedAttrListErr("Malformed SR Capabilities TLV")
  7802  	}
  7803  
  7804  	return nil
  7805  }
  7806  
  7807  func (l *LsTLVSrCapabilities) Serialize() ([]byte, error) {
  7808  	buf := make([]byte, 0)
  7809  	buf = append(buf, l.Flags)
  7810  	buf = append(buf, 0)
  7811  	var b [4]byte
  7812  
  7813  	for _, r := range l.Ranges {
  7814  		binary.BigEndian.PutUint32(b[:4], r.Range)
  7815  		buf = append(buf, b[1:]...)
  7816  		ser, err := r.FirstLabel.Serialize()
  7817  		if err != nil {
  7818  			return nil, err
  7819  		}
  7820  		buf = append(buf, ser...)
  7821  	}
  7822  
  7823  	return l.LsTLV.Serialize(buf)
  7824  }
  7825  
  7826  func (l *LsTLVSrCapabilities) String() string {
  7827  	var buf bytes.Buffer
  7828  
  7829  	for _, r := range l.Ranges {
  7830  		buf.WriteString(fmt.Sprintf("%v:%v ", r.FirstLabel.SID, r.FirstLabel.SID+r.Range))
  7831  	}
  7832  
  7833  	return fmt.Sprintf("{SR Capabilities: Flags:%v SRGB Ranges: %v}", l.Flags, buf.String())
  7834  }
  7835  
  7836  func (l *LsTLVSrCapabilities) MarshalJSON() ([]byte, error) {
  7837  	return json.Marshal(struct {
  7838  		Type   LsTLVType        `json:"type"`
  7839  		Flags  uint8            `json:"flags"`
  7840  		Ranges []LsSrLabelRange `json:"ranges"`
  7841  	}{
  7842  		Type:   l.Type,
  7843  		Flags:  l.Flags,
  7844  		Ranges: l.Ranges,
  7845  	})
  7846  }
  7847  
  7848  type LsTLVSrLocalBlock struct {
  7849  	LsTLV
  7850  	Flags  uint8
  7851  	Ranges []LsSrLabelRange
  7852  }
  7853  
  7854  type LsSrLocalBlock struct {
  7855  	Ranges []LsSrRange `json:"ranges"`
  7856  }
  7857  
  7858  func NewLsTLVSrLocalBlock(l *LsSrLocalBlock) *LsTLVSrLocalBlock {
  7859  	var flags uint8 //
  7860  	ranges := []LsSrLabelRange{}
  7861  	var length uint16
  7862  	for _, r := range l.Ranges {
  7863  		ranges = append(ranges, LsSrLabelRange{
  7864  			Range: uint32(r.End - r.Begin),
  7865  			FirstLabel: LsTLVSIDLabel{
  7866  				LsTLV: LsTLV{
  7867  					Type:   BGP_ASPATH_ATTR_TYPE_SET,
  7868  					Length: 4,
  7869  				},
  7870  				SID: r.Begin,
  7871  			},
  7872  		})
  7873  		length += 4
  7874  	}
  7875  	return &LsTLVSrLocalBlock{
  7876  		LsTLV: LsTLV{
  7877  			Type:   BGP_ASPATH_ATTR_TYPE_SET,
  7878  			Length: length,
  7879  		},
  7880  		Flags:  flags, // MUST be set 0. (RFC9085 2.1.4)
  7881  		Ranges: ranges,
  7882  	}
  7883  }
  7884  
  7885  func (l *LsTLVSrLocalBlock) Extract() *LsSrLocalBlock {
  7886  	lb := &LsSrLocalBlock{}
  7887  
  7888  	for _, r := range l.Ranges {
  7889  		lb.Ranges = append(lb.Ranges, LsSrRange{
  7890  			Begin: r.FirstLabel.SID,
  7891  			End:   r.FirstLabel.SID + r.Range,
  7892  		})
  7893  	}
  7894  
  7895  	return lb
  7896  }
  7897  
  7898  func (l *LsTLVSrLocalBlock) DecodeFromBytes(data []byte) error {
  7899  	value, err := l.LsTLV.DecodeFromBytes(data)
  7900  	if err != nil {
  7901  		return err
  7902  	}
  7903  
  7904  	if l.Type != LS_TLV_SR_LOCAL_BLOCK {
  7905  		return malformedAttrListErr("Unexpected TLV type")
  7906  	}
  7907  
  7908  	if len(value) < 2 {
  7909  		return malformedAttrListErr("Incorrect SR Local Block length")
  7910  	}
  7911  	l.Flags = value[0]
  7912  
  7913  	// Skip two bytes: flags and reserved.
  7914  	value = value[2:]
  7915  
  7916  	// The value field should be at least eight bytes long. Three bytes
  7917  	// for the range size and five or six bytes for the SID/Label TLV.
  7918  	for len(value) > 8 {
  7919  		// First, parse range size (3 bytes)
  7920  		buf := []byte{0, 0, 0, 0}
  7921  		for i := 1; i < len(buf); i++ {
  7922  			buf[i] = value[i-1]
  7923  		}
  7924  		r := binary.BigEndian.Uint32(buf)
  7925  		value = value[3:]
  7926  
  7927  		// Second, parse SID/Label sub-TLV.
  7928  		label := LsTLVSIDLabel{}
  7929  		if err := label.DecodeFromBytes(value); err != nil {
  7930  			return err
  7931  		}
  7932  
  7933  		l.Ranges = append(l.Ranges, LsSrLabelRange{
  7934  			Range:      r,
  7935  			FirstLabel: label,
  7936  		})
  7937  
  7938  		value = value[label.Len():]
  7939  	}
  7940  
  7941  	if len(value) > 0 {
  7942  		return malformedAttrListErr("Malformed SR Local Block TLV")
  7943  	}
  7944  
  7945  	return nil
  7946  }
  7947  
  7948  func (l *LsTLVSrLocalBlock) Serialize() ([]byte, error) {
  7949  	buf := make([]byte, 0)
  7950  	buf = append(buf, l.Flags)
  7951  	buf = append(buf, 0)
  7952  	var b [4]byte
  7953  
  7954  	for _, r := range l.Ranges {
  7955  		binary.BigEndian.PutUint32(b[:4], r.Range)
  7956  		buf = append(buf, b[1:]...)
  7957  		ser, err := r.FirstLabel.Serialize()
  7958  		if err != nil {
  7959  			return nil, err
  7960  		}
  7961  		buf = append(buf, ser...)
  7962  	}
  7963  
  7964  	return l.LsTLV.Serialize(buf)
  7965  }
  7966  
  7967  func (l *LsTLVSrLocalBlock) String() string {
  7968  	var buf bytes.Buffer
  7969  
  7970  	for _, r := range l.Ranges {
  7971  		buf.WriteString(fmt.Sprintf("%v:%v ", r.FirstLabel.SID, r.FirstLabel.SID+r.Range))
  7972  	}
  7973  
  7974  	return fmt.Sprintf("{SR LocalBlock: Flags:%v SRGB Ranges: %v}", l.Flags, buf.String())
  7975  }
  7976  
  7977  func (l *LsTLVSrLocalBlock) MarshalJSON() ([]byte, error) {
  7978  	return json.Marshal(struct {
  7979  		Type   LsTLVType        `json:"type"`
  7980  		Flags  uint8            `json:"flags"`
  7981  		Ranges []LsSrLabelRange `json:"ranges"`
  7982  	}{
  7983  		Type:   l.Type,
  7984  		Flags:  l.Flags,
  7985  		Ranges: l.Ranges,
  7986  	})
  7987  }
  7988  
  7989  type LsTLVAdjacencySID struct {
  7990  	LsTLV
  7991  	Flags  uint8
  7992  	Weight uint8
  7993  	SID    uint32
  7994  }
  7995  
  7996  func NewLsTLVAdjacencySID(l *uint32) *LsTLVAdjacencySID {
  7997  	var flags uint8
  7998  	return &LsTLVAdjacencySID{
  7999  		LsTLV: LsTLV{
  8000  			Type:   LS_TLV_ADJACENCY_SID,
  8001  			Length: 7, // TODO: Implementation to judge 7 octets or 8 octets
  8002  		},
  8003  		Flags:  flags,
  8004  		Weight: 0,  // TODO: Implementation for IGP
  8005  		SID:    *l, // TODO: Implementation for IGP
  8006  	}
  8007  }
  8008  
  8009  func (l *LsTLVAdjacencySID) DecodeFromBytes(data []byte) error {
  8010  	value, err := l.LsTLV.DecodeFromBytes(data)
  8011  	if err != nil {
  8012  		return err
  8013  	}
  8014  
  8015  	if l.Type != LS_TLV_ADJACENCY_SID {
  8016  		return malformedAttrListErr("Unexpected TLV type")
  8017  	}
  8018  
  8019  	// https://tools.ietf.org/html/draft-ietf-idr-bgp-ls-segment-routing-ext-08#section-2.2.1
  8020  	if len(value) != 7 && len(value) != 8 {
  8021  		return malformedAttrListErr("Incorrect Adjacency SID length")
  8022  	}
  8023  
  8024  	l.Flags = value[0]
  8025  	l.Weight = value[1]
  8026  
  8027  	v := value[4:]
  8028  	if len(v) == 4 {
  8029  		l.SID = binary.BigEndian.Uint32(v)
  8030  	} else {
  8031  		buf := []byte{0, 0, 0, 0}
  8032  		for i := 1; i < len(buf); i++ {
  8033  			buf[i] = v[i-1]
  8034  		}
  8035  		// Label is represented by 20 rightmost bits.
  8036  		l.SID = binary.BigEndian.Uint32(buf) & 0xfffff
  8037  	}
  8038  
  8039  	return nil
  8040  }
  8041  
  8042  func (l *LsTLVAdjacencySID) Serialize() ([]byte, error) {
  8043  	buf := make([]byte, 0)
  8044  	buf = append(buf, l.Flags)
  8045  	buf = append(buf, l.Weight)
  8046  	// Reserved
  8047  	buf = append(buf, []byte{0, 0}...)
  8048  
  8049  	var b [4]byte
  8050  	binary.BigEndian.PutUint32(b[:4], l.SID)
  8051  
  8052  	if l.Length == 7 {
  8053  		return l.LsTLV.Serialize(append(buf, b[1:]...))
  8054  	}
  8055  
  8056  	return l.LsTLV.Serialize(append(buf, b[:]...))
  8057  }
  8058  
  8059  func (l *LsTLVAdjacencySID) String() string {
  8060  	return fmt.Sprintf("{Adjacency SID: %v}", l.SID)
  8061  }
  8062  
  8063  func (l *LsTLVAdjacencySID) MarshalJSON() ([]byte, error) {
  8064  	return json.Marshal(struct {
  8065  		Type LsTLVType `json:"type"`
  8066  		SID  uint32    `json:"adjacency_sid"`
  8067  	}{
  8068  		Type: l.Type,
  8069  		SID:  l.SID,
  8070  	})
  8071  }
  8072  
  8073  // https://tools.ietf.org/html/rfc9086#section-5
  8074  type LsAttributeBgpPeerSegmentSIDFlags struct {
  8075  	Value      bool `json:"value"`
  8076  	Local      bool `json:"local"`
  8077  	Backup     bool `json:"backup"`
  8078  	Persistent bool `json:"persistent"`
  8079  }
  8080  
  8081  func (l *LsAttributeBgpPeerSegmentSIDFlags) FlagBits() uint8 {
  8082  	var flags uint8
  8083  	if l.Value {
  8084  		flags = flags | (1 << 7)
  8085  	}
  8086  	if l.Local {
  8087  		flags = flags | (1 << 6)
  8088  	}
  8089  	if l.Backup {
  8090  		flags = flags | (1 << 5)
  8091  	}
  8092  	if l.Persistent {
  8093  		flags = flags | (1 << 4)
  8094  	}
  8095  	return flags
  8096  }
  8097  
  8098  func (l *LsAttributeBgpPeerSegmentSIDFlags) SidLen() uint16 {
  8099  	// https://tools.ietf.org/html/rfc9086#section-5
  8100  	if l.Value {
  8101  		return 7
  8102  	} else {
  8103  		return 8
  8104  	}
  8105  }
  8106  
  8107  func NewLsBgpPeerSegmentSIDFlag(v uint8) LsAttributeBgpPeerSegmentSIDFlags {
  8108  	return LsAttributeBgpPeerSegmentSIDFlags{
  8109  		Value:      (v & (1 << 7)) > 0,
  8110  		Local:      (v & (1 << 6)) > 0,
  8111  		Backup:     (v & (1 << 5)) > 0,
  8112  		Persistent: (v & (1 << 4)) > 0,
  8113  	}
  8114  }
  8115  
  8116  type LsBgpPeerSegmentSID struct {
  8117  	Flags  LsAttributeBgpPeerSegmentSIDFlags `json:"flags"`
  8118  	Weight uint8                             `json:"weight"`
  8119  	SID    uint32                            `json:"sid"`
  8120  }
  8121  
  8122  type LsTLVPeerNodeSID struct {
  8123  	LsTLV
  8124  	Flags  uint8
  8125  	Weight uint8
  8126  	SID    uint32
  8127  }
  8128  
  8129  func NewLsTLVPeerNodeSID(l *LsBgpPeerSegmentSID) *LsTLVPeerNodeSID {
  8130  	return &LsTLVPeerNodeSID{
  8131  		LsTLV: LsTLV{
  8132  			Type:   LS_TLV_PEER_NODE_SID,
  8133  			Length: l.Flags.SidLen(),
  8134  		},
  8135  		Flags:  l.Flags.FlagBits(),
  8136  		Weight: l.Weight,
  8137  		SID:    l.SID,
  8138  	}
  8139  }
  8140  
  8141  func (l *LsTLVPeerNodeSID) DecodeFromBytes(data []byte) error {
  8142  	value, err := l.LsTLV.DecodeFromBytes(data)
  8143  	if err != nil {
  8144  		return err
  8145  	}
  8146  
  8147  	if l.Type != LS_TLV_PEER_NODE_SID {
  8148  		return malformedAttrListErr("Unexpected TLV type")
  8149  	}
  8150  
  8151  	// https://tools.ietf.org/html/rfc9086#section-5
  8152  	if len(value) != 7 && len(value) != 8 {
  8153  		return malformedAttrListErr("Incorrect Peer Node SID length")
  8154  	}
  8155  
  8156  	l.Flags = value[0]
  8157  	l.Weight = value[1]
  8158  
  8159  	v := value[4:]
  8160  	if len(v) == 4 {
  8161  		l.SID = binary.BigEndian.Uint32(v)
  8162  	} else {
  8163  		buf := []byte{0, 0, 0, 0}
  8164  		for i := 1; i < len(buf); i++ {
  8165  			buf[i] = v[i-1]
  8166  		}
  8167  		// Label is represented by 20 rightmost bits.
  8168  		l.SID = binary.BigEndian.Uint32(buf) & 0xfffff
  8169  	}
  8170  
  8171  	return nil
  8172  }
  8173  
  8174  func (l *LsTLVPeerNodeSID) Extract() *LsBgpPeerSegmentSID {
  8175  	return &LsBgpPeerSegmentSID{
  8176  		Flags:  NewLsBgpPeerSegmentSIDFlag(l.Flags),
  8177  		Weight: l.Weight,
  8178  		SID:    l.SID,
  8179  	}
  8180  }
  8181  
  8182  func (l *LsTLVPeerNodeSID) Serialize() ([]byte, error) {
  8183  	buf := make([]byte, 0)
  8184  	buf = append(buf, l.Flags)
  8185  	buf = append(buf, l.Weight)
  8186  	// Reserved
  8187  	buf = append(buf, []byte{0, 0}...)
  8188  
  8189  	var b [4]byte
  8190  	binary.BigEndian.PutUint32(b[:4], l.SID)
  8191  
  8192  	if l.Length == 7 {
  8193  		return l.LsTLV.Serialize(append(buf, b[1:]...))
  8194  	}
  8195  
  8196  	return l.LsTLV.Serialize(append(buf, b[:]...))
  8197  }
  8198  
  8199  func (l *LsTLVPeerNodeSID) String() string {
  8200  	return fmt.Sprintf("{Peer Node SID: %v}", l.SID)
  8201  }
  8202  
  8203  func (l *LsTLVPeerNodeSID) MarshalJSON() ([]byte, error) {
  8204  	return json.Marshal(struct {
  8205  		Type LsTLVType `json:"type"`
  8206  		SID  uint32    `json:"peer_node_sid"`
  8207  	}{
  8208  		Type: l.Type,
  8209  		SID:  l.SID,
  8210  	})
  8211  }
  8212  
  8213  type LsTLVPeerAdjacencySID struct {
  8214  	LsTLV
  8215  	Flags  uint8
  8216  	Weight uint8
  8217  	SID    uint32
  8218  }
  8219  
  8220  func NewLsTLVPeerAdjacencySID(l *LsBgpPeerSegmentSID) *LsTLVPeerAdjacencySID {
  8221  	return &LsTLVPeerAdjacencySID{
  8222  		LsTLV: LsTLV{
  8223  			Type:   LS_TLV_ADJACENCY_SID,
  8224  			Length: l.Flags.SidLen(),
  8225  		},
  8226  		Flags:  l.Flags.FlagBits(),
  8227  		Weight: l.Weight,
  8228  		SID:    l.SID,
  8229  	}
  8230  }
  8231  
  8232  func (l *LsTLVPeerAdjacencySID) DecodeFromBytes(data []byte) error {
  8233  	value, err := l.LsTLV.DecodeFromBytes(data)
  8234  	if err != nil {
  8235  		return err
  8236  	}
  8237  
  8238  	if l.Type != LS_TLV_PEER_ADJACENCY_SID {
  8239  		return malformedAttrListErr("Unexpected TLV type")
  8240  	}
  8241  
  8242  	// https://tools.ietf.org/html/rfc9086#section-5
  8243  	if len(value) != 7 && len(value) != 8 {
  8244  		return malformedAttrListErr("Incorrect Peer Adjacency SID length")
  8245  	}
  8246  
  8247  	l.Flags = value[0]
  8248  	l.Weight = value[1]
  8249  
  8250  	v := value[4:]
  8251  	if len(v) == 4 {
  8252  		l.SID = binary.BigEndian.Uint32(v)
  8253  	} else {
  8254  		buf := []byte{0, 0, 0, 0}
  8255  		for i := 1; i < len(buf); i++ {
  8256  			buf[i] = v[i-1]
  8257  		}
  8258  		// Label is represented by 20 rightmost bits.
  8259  		l.SID = binary.BigEndian.Uint32(buf) & 0xfffff
  8260  	}
  8261  
  8262  	return nil
  8263  }
  8264  
  8265  func (l *LsTLVPeerAdjacencySID) Extract() *LsBgpPeerSegmentSID {
  8266  	return &LsBgpPeerSegmentSID{
  8267  		Flags:  NewLsBgpPeerSegmentSIDFlag(l.Flags),
  8268  		Weight: l.Weight,
  8269  		SID:    l.SID,
  8270  	}
  8271  }
  8272  
  8273  func (l *LsTLVPeerAdjacencySID) Serialize() ([]byte, error) {
  8274  	buf := make([]byte, 0)
  8275  	buf = append(buf, l.Flags)
  8276  	buf = append(buf, l.Weight)
  8277  	// Reserved
  8278  	buf = append(buf, []byte{0, 0}...)
  8279  
  8280  	var b [4]byte
  8281  	binary.BigEndian.PutUint32(b[:4], l.SID)
  8282  
  8283  	if l.Length == 7 {
  8284  		return l.LsTLV.Serialize(append(buf, b[1:]...))
  8285  	}
  8286  
  8287  	return l.LsTLV.Serialize(append(buf, b[:]...))
  8288  }
  8289  
  8290  func (l *LsTLVPeerAdjacencySID) String() string {
  8291  	return fmt.Sprintf("{Peer Adjacency SID: %v}", l.SID)
  8292  }
  8293  
  8294  func (l *LsTLVPeerAdjacencySID) MarshalJSON() ([]byte, error) {
  8295  	return json.Marshal(struct {
  8296  		Type LsTLVType `json:"type"`
  8297  		SID  uint32    `json:"peer_adjacency_sid"`
  8298  	}{
  8299  		Type: l.Type,
  8300  		SID:  l.SID,
  8301  	})
  8302  }
  8303  
  8304  type LsTLVPeerSetSID struct {
  8305  	LsTLV
  8306  	Flags  uint8
  8307  	Weight uint8
  8308  	SID    uint32
  8309  }
  8310  
  8311  func NewLsTLVPeerSetSID(l *LsBgpPeerSegmentSID) *LsTLVPeerSetSID {
  8312  	return &LsTLVPeerSetSID{
  8313  		LsTLV: LsTLV{
  8314  			Type:   LS_TLV_PEER_SET_SID,
  8315  			Length: l.Flags.SidLen(),
  8316  		},
  8317  		Flags:  l.Flags.FlagBits(),
  8318  		Weight: l.Weight,
  8319  		SID:    l.SID,
  8320  	}
  8321  }
  8322  
  8323  func (l *LsTLVPeerSetSID) DecodeFromBytes(data []byte) error {
  8324  	value, err := l.LsTLV.DecodeFromBytes(data)
  8325  	if err != nil {
  8326  		return err
  8327  	}
  8328  
  8329  	if l.Type != LS_TLV_PEER_SET_SID {
  8330  		return malformedAttrListErr("Unexpected TLV type")
  8331  	}
  8332  
  8333  	// https://tools.ietf.org/html/rfc9086#section-5
  8334  	if len(value) != 7 && len(value) != 8 {
  8335  		return malformedAttrListErr("Incorrect Peer Set SID length")
  8336  	}
  8337  
  8338  	l.Flags = value[0]
  8339  	l.Weight = value[1]
  8340  
  8341  	v := value[4:]
  8342  	if len(v) == 4 {
  8343  		l.SID = binary.BigEndian.Uint32(v)
  8344  	} else {
  8345  		buf := []byte{0, 0, 0, 0}
  8346  		for i := 1; i < len(buf); i++ {
  8347  			buf[i] = v[i-1]
  8348  		}
  8349  		// Label is represented by 20 rightmost bits.
  8350  		l.SID = binary.BigEndian.Uint32(buf) & 0xfffff
  8351  	}
  8352  
  8353  	return nil
  8354  }
  8355  
  8356  func (l *LsTLVPeerSetSID) Extract() *LsBgpPeerSegmentSID {
  8357  	return &LsBgpPeerSegmentSID{
  8358  		Flags:  NewLsBgpPeerSegmentSIDFlag(l.Flags),
  8359  		Weight: l.Weight,
  8360  		SID:    l.SID,
  8361  	}
  8362  }
  8363  
  8364  func (l *LsTLVPeerSetSID) Serialize() ([]byte, error) {
  8365  	buf := make([]byte, 0)
  8366  	buf = append(buf, l.Flags)
  8367  	buf = append(buf, l.Weight)
  8368  	// Reserved
  8369  	buf = append(buf, []byte{0, 0}...)
  8370  
  8371  	var b [4]byte
  8372  	binary.BigEndian.PutUint32(b[:4], l.SID)
  8373  
  8374  	if l.Length == 7 {
  8375  		return l.LsTLV.Serialize(append(buf, b[1:]...))
  8376  	}
  8377  
  8378  	return l.LsTLV.Serialize(append(buf, b[:]...))
  8379  }
  8380  
  8381  func (l *LsTLVPeerSetSID) String() string {
  8382  	return fmt.Sprintf("{Peer Set SID: %v}", l.SID)
  8383  }
  8384  
  8385  func (l *LsTLVPeerSetSID) MarshalJSON() ([]byte, error) {
  8386  	return json.Marshal(struct {
  8387  		Type LsTLVType `json:"type"`
  8388  		SID  uint32    `json:"peer_set_sid"`
  8389  	}{
  8390  		Type: l.Type,
  8391  		SID:  l.SID,
  8392  	})
  8393  }
  8394  
  8395  type LsTLVSIDLabel struct {
  8396  	LsTLV
  8397  	SID uint32
  8398  }
  8399  
  8400  func (l *LsTLVSIDLabel) DecodeFromBytes(data []byte) error {
  8401  	value, err := l.LsTLV.DecodeFromBytes(data)
  8402  	if err != nil {
  8403  		return err
  8404  	}
  8405  
  8406  	if l.Type != LS_TLV_SID_LABEL_TLV {
  8407  		return malformedAttrListErr("Unexpected TLV type")
  8408  	}
  8409  
  8410  	// https://tools.ietf.org/html/draft-ietf-idr-bgp-ls-segment-routing-ext-08#section-2.1.1
  8411  	if len(value) != 4 && len(value) != 3 {
  8412  		return malformedAttrListErr("Incorrect SID length")
  8413  	}
  8414  
  8415  	if len(value) == 4 {
  8416  		l.SID = binary.BigEndian.Uint32(value)
  8417  	} else {
  8418  		buf := []byte{0, 0, 0, 0}
  8419  		for i := 1; i < len(buf); i++ {
  8420  			buf[i] = value[i-1]
  8421  		}
  8422  		// Label is represented by 20 rightmost bits.
  8423  		l.SID = binary.BigEndian.Uint32(buf) & 0xfffff
  8424  	}
  8425  
  8426  	return nil
  8427  }
  8428  
  8429  func (l *LsTLVSIDLabel) Serialize() ([]byte, error) {
  8430  	var buf [4]byte
  8431  	binary.BigEndian.PutUint32(buf[:4], l.SID)
  8432  
  8433  	if l.Length == 3 {
  8434  		return l.LsTLV.Serialize(buf[1:])
  8435  	}
  8436  
  8437  	return l.LsTLV.Serialize(buf[:])
  8438  }
  8439  
  8440  func (l *LsTLVSIDLabel) String() string {
  8441  	return fmt.Sprintf("{SID/Label: %v}", l.SID)
  8442  }
  8443  
  8444  func (l *LsTLVSIDLabel) MarshalJSON() ([]byte, error) {
  8445  	return json.Marshal(struct {
  8446  		Type LsTLVType `json:"type"`
  8447  		SID  uint32    `json:"sid_label"`
  8448  	}{
  8449  		Type: l.Type,
  8450  		SID:  l.SID,
  8451  	})
  8452  }
  8453  
  8454  type LsTLVPrefixSID struct {
  8455  	LsTLV
  8456  	Flags     uint8
  8457  	Algorithm uint8
  8458  	SID       uint32
  8459  }
  8460  
  8461  func NewLsTLVPrefixSID(l *uint32) *LsTLVPrefixSID {
  8462  	var flags uint8
  8463  	return &LsTLVPrefixSID{
  8464  		LsTLV: LsTLV{
  8465  			Type:   BGP_ASPATH_ATTR_TYPE_SET,
  8466  			Length: 0,
  8467  		},
  8468  		Flags:     flags, // TODO: Implementation for IGP
  8469  		Algorithm: 0,     // TODO: Implementation for IGP
  8470  		SID:       *l,
  8471  	}
  8472  }
  8473  
  8474  func (l *LsTLVPrefixSID) DecodeFromBytes(data []byte) error {
  8475  	value, err := l.LsTLV.DecodeFromBytes(data)
  8476  	if err != nil {
  8477  		return err
  8478  	}
  8479  
  8480  	if l.Type != LS_TLV_PREFIX_SID {
  8481  		return malformedAttrListErr("Unexpected TLV type")
  8482  	}
  8483  
  8484  	// https://tools.ietf.org/html/draft-ietf-idr-bgp-ls-segment-routing-ext-08#section-2.3.1
  8485  	if len(value) != 7 && len(value) != 8 {
  8486  		return malformedAttrListErr("Incorrect Prefix SID length")
  8487  	}
  8488  
  8489  	l.Flags = value[0]
  8490  	l.Algorithm = value[1]
  8491  
  8492  	// Flags (1) + Algorithm (1) + Reserved (2)
  8493  	v := value[4:]
  8494  	if len(v) == 4 {
  8495  		l.SID = binary.BigEndian.Uint32(v)
  8496  	} else {
  8497  		buf := []byte{0, 0, 0, 0}
  8498  		for i := 1; i < len(buf); i++ {
  8499  			buf[i] = v[i-1]
  8500  		}
  8501  		// Label is represented by 20 rightmost bits.
  8502  		l.SID = binary.BigEndian.Uint32(buf) & 0xfffff
  8503  	}
  8504  
  8505  	return nil
  8506  }
  8507  
  8508  func (l *LsTLVPrefixSID) Serialize() ([]byte, error) {
  8509  	buf := make([]byte, 0)
  8510  	buf = append(buf, l.Flags)
  8511  	buf = append(buf, l.Algorithm)
  8512  	// Reserved
  8513  	buf = append(buf, []byte{0, 0}...)
  8514  
  8515  	var b [4]byte
  8516  	binary.BigEndian.PutUint32(b[:4], l.SID)
  8517  
  8518  	if l.Length == 7 {
  8519  		return l.LsTLV.Serialize(append(buf, b[1:]...))
  8520  	}
  8521  
  8522  	return l.LsTLV.Serialize(append(buf, b[:]...))
  8523  }
  8524  
  8525  func (l *LsTLVPrefixSID) String() string {
  8526  	return fmt.Sprintf("{Prefix SID: %v}", l.SID)
  8527  }
  8528  
  8529  func (l *LsTLVPrefixSID) MarshalJSON() ([]byte, error) {
  8530  	return json.Marshal(struct {
  8531  		Type LsTLVType `json:"type"`
  8532  		SID  uint32    `json:"prefix_sid"`
  8533  	}{
  8534  		Type: l.Type,
  8535  		SID:  l.SID,
  8536  	})
  8537  }
  8538  
  8539  type LsTLVSourceRouterID struct {
  8540  	LsTLV
  8541  	RouterID []byte
  8542  }
  8543  
  8544  func (l *LsTLVSourceRouterID) DecodeFromBytes(data []byte) error {
  8545  	value, err := l.LsTLV.DecodeFromBytes(data)
  8546  	if err != nil {
  8547  		return err
  8548  	}
  8549  
  8550  	if l.Type != LS_TLV_SOURCE_ROUTER_ID {
  8551  		return malformedAttrListErr("Unexpected TLV type")
  8552  	}
  8553  
  8554  	// https://tools.ietf.org/html/draft-ietf-idr-bgp-ls-segment-routing-ext-08#section-2.3.3
  8555  	if len(value) != 4 && len(value) != 16 {
  8556  		return malformedAttrListErr("Incorrect Source Router ID length")
  8557  	}
  8558  
  8559  	l.RouterID = value
  8560  
  8561  	return nil
  8562  }
  8563  
  8564  func (l *LsTLVSourceRouterID) Serialize() ([]byte, error) {
  8565  	return l.LsTLV.Serialize(l.RouterID)
  8566  }
  8567  
  8568  func (l *LsTLVSourceRouterID) String() string {
  8569  	return fmt.Sprintf("{Source Router ID: %v}", net.IP(l.RouterID))
  8570  }
  8571  
  8572  func (l *LsTLVSourceRouterID) MarshalJSON() ([]byte, error) {
  8573  	return json.Marshal(struct {
  8574  		Type     LsTLVType `json:"type"`
  8575  		RouterID string    `json:"source_router_id"`
  8576  	}{
  8577  		Type:     l.Type,
  8578  		RouterID: fmt.Sprintf("%v", net.IP(l.RouterID)),
  8579  	})
  8580  }
  8581  
  8582  type LsTLVOpaqueLinkAttr struct {
  8583  	LsTLV
  8584  	Attr []byte
  8585  }
  8586  
  8587  func NewLsTLVOpaqueLinkAttr(l *[]byte) *LsTLVOpaqueLinkAttr {
  8588  	return &LsTLVOpaqueLinkAttr{
  8589  		LsTLV: LsTLV{
  8590  			Type:   BGP_ASPATH_ATTR_TYPE_SET,
  8591  			Length: uint16(len(*l)),
  8592  		},
  8593  		Attr: *l,
  8594  	}
  8595  }
  8596  
  8597  func (l *LsTLVOpaqueLinkAttr) DecodeFromBytes(data []byte) error {
  8598  	value, err := l.LsTLV.DecodeFromBytes(data)
  8599  	if err != nil {
  8600  		return err
  8601  	}
  8602  
  8603  	if l.Type != LS_TLV_OPAQUE_LINK_ATTR {
  8604  		return malformedAttrListErr("Unexpected TLV type")
  8605  	}
  8606  
  8607  	l.Attr = value
  8608  
  8609  	return nil
  8610  }
  8611  
  8612  func (l *LsTLVOpaqueLinkAttr) Serialize() ([]byte, error) {
  8613  	return l.LsTLV.Serialize(l.Attr)
  8614  }
  8615  
  8616  func (l *LsTLVOpaqueLinkAttr) String() string {
  8617  	return fmt.Sprintf("{Opaque link attribute: %v}", l.Attr)
  8618  }
  8619  
  8620  func (l *LsTLVOpaqueLinkAttr) MarshalJSON() ([]byte, error) {
  8621  	return json.Marshal(struct {
  8622  		Type  LsTLVType `json:"type"`
  8623  		Value string    `json:"link_opaque_attribute"`
  8624  	}{
  8625  		Type:  l.Type,
  8626  		Value: fmt.Sprintf("%v", l.Attr),
  8627  	})
  8628  }
  8629  
  8630  type LsTLVSrlg struct {
  8631  	LsTLV
  8632  	Srlgs []uint32
  8633  }
  8634  
  8635  func NewLsTLVSrlg(l *[]uint32) *LsTLVSrlg {
  8636  	return &LsTLVSrlg{
  8637  		LsTLV: LsTLV{
  8638  			Type:   BGP_ASPATH_ATTR_TYPE_SET,
  8639  			Length: uint16(4 * len(*l)),
  8640  		},
  8641  		Srlgs: *l,
  8642  	}
  8643  }
  8644  
  8645  func (l *LsTLVSrlg) DecodeFromBytes(data []byte) error {
  8646  	value, err := l.LsTLV.DecodeFromBytes(data)
  8647  	if err != nil {
  8648  		return err
  8649  	}
  8650  
  8651  	if l.Type != LS_TLV_SRLG {
  8652  		return malformedAttrListErr("Unexpected TLV type")
  8653  	}
  8654  
  8655  	if len(value)%4 != 0 {
  8656  		return malformedAttrListErr("Incorrect SRLG length")
  8657  	}
  8658  
  8659  	for len(value) > 0 {
  8660  		l.Srlgs = append(l.Srlgs, binary.BigEndian.Uint32(value[:4]))
  8661  		value = value[4:]
  8662  	}
  8663  
  8664  	return nil
  8665  }
  8666  
  8667  func (l *LsTLVSrlg) Serialize() ([]byte, error) {
  8668  	buf := make([]byte, 0, 4*len(l.Srlgs))
  8669  
  8670  	var b [4]byte
  8671  	for i := 0; i < len(l.Srlgs); i++ {
  8672  		binary.BigEndian.PutUint32(b[:4], l.Srlgs[i])
  8673  		buf = append(buf, b[:]...)
  8674  	}
  8675  
  8676  	return l.LsTLV.Serialize(buf)
  8677  }
  8678  
  8679  func (l *LsTLVSrlg) String() string {
  8680  	return fmt.Sprintf("{SRLG link attribute: %d}", l.Srlgs)
  8681  }
  8682  
  8683  func (l *LsTLVSrlg) MarshalJSON() ([]byte, error) {
  8684  	return json.Marshal(struct {
  8685  		Type  LsTLVType `json:"type"`
  8686  		Value []uint32  `json:"link_srlg_attribute"`
  8687  	}{
  8688  		Type:  l.Type,
  8689  		Value: l.Srlgs,
  8690  	})
  8691  }
  8692  
  8693  type LsTLVIGPFlags struct {
  8694  	LsTLV
  8695  	Flags uint8
  8696  }
  8697  
  8698  func NewLsTLVIGPFlags(l *LsIGPFlags) *LsTLVIGPFlags {
  8699  	var flags uint8
  8700  	if l.Down {
  8701  		flags = flags & (1 >> 0)
  8702  	}
  8703  	if l.NoUnicast {
  8704  		flags = flags & (1 >> 1)
  8705  	}
  8706  	if l.LocalAddress {
  8707  		flags = flags & (1 >> 2)
  8708  	}
  8709  	if l.PropagateNSSA {
  8710  		flags = flags & (1 >> 3)
  8711  	}
  8712  	return &LsTLVIGPFlags{
  8713  		LsTLV: LsTLV{
  8714  			Type:   BGP_ASPATH_ATTR_TYPE_SET,
  8715  			Length: 1,
  8716  		},
  8717  		Flags: flags,
  8718  	}
  8719  }
  8720  
  8721  // https://tools.ietf.org/html/rfc7752#section-3.3.3.1
  8722  type LsIGPFlags struct {
  8723  	Down          bool `json:"down"`
  8724  	NoUnicast     bool `json:"no_unicast"`
  8725  	LocalAddress  bool `json:"local_address"`
  8726  	PropagateNSSA bool `json:"propagate_nssa"`
  8727  }
  8728  
  8729  func (l *LsTLVIGPFlags) Extract() *LsIGPFlags {
  8730  	return &LsIGPFlags{
  8731  		Down:          (l.Flags & (1 << 0)) > 0,
  8732  		NoUnicast:     (l.Flags & (1 << 1)) > 0,
  8733  		LocalAddress:  (l.Flags & (1 << 2)) > 0,
  8734  		PropagateNSSA: (l.Flags & (1 << 3)) > 0,
  8735  	}
  8736  }
  8737  
  8738  func (l *LsTLVIGPFlags) DecodeFromBytes(data []byte) error {
  8739  	value, err := l.LsTLV.DecodeFromBytes(data)
  8740  	if err != nil {
  8741  		return err
  8742  	}
  8743  
  8744  	if l.Type != LS_TLV_IGP_FLAGS {
  8745  		return malformedAttrListErr("Unexpected TLV type")
  8746  	}
  8747  
  8748  	if l.Length != 1 {
  8749  		return malformedAttrListErr("Node Flag Bits TLV malformed")
  8750  	}
  8751  
  8752  	l.Flags = value[0]
  8753  
  8754  	return nil
  8755  }
  8756  
  8757  func (l *LsTLVIGPFlags) Serialize() ([]byte, error) {
  8758  	return l.LsTLV.Serialize([]byte{l.Flags})
  8759  }
  8760  
  8761  func (l *LsTLVIGPFlags) String() string {
  8762  	flags := "XXXXPLND"
  8763  
  8764  	var buf bytes.Buffer
  8765  
  8766  	for i := 0; i < len(flags); i++ {
  8767  		if l.Flags&(1<<uint(i)) > 0 {
  8768  			buf.WriteString(flags[i : i+1])
  8769  		} else {
  8770  			buf.WriteString("*")
  8771  		}
  8772  	}
  8773  
  8774  	return fmt.Sprintf("{IGP Flags: %s}", buf.String())
  8775  }
  8776  
  8777  func (l *LsTLVIGPFlags) MarshalJSON() ([]byte, error) {
  8778  	return json.Marshal(struct {
  8779  		Type  LsTLVType `json:"type"`
  8780  		Flags string    `json:"igp_flags"`
  8781  	}{
  8782  		Type:  l.Type,
  8783  		Flags: l.String(),
  8784  	})
  8785  }
  8786  
  8787  type LsTLVOpaquePrefixAttr struct {
  8788  	LsTLV
  8789  	Attr []byte
  8790  }
  8791  
  8792  func NewLsTLVOpaquePrefixAttr(l *[]byte) *LsTLVOpaquePrefixAttr {
  8793  	return &LsTLVOpaquePrefixAttr{
  8794  		LsTLV: LsTLV{
  8795  			Type:   BGP_ASPATH_ATTR_TYPE_SET,
  8796  			Length: 0,
  8797  		},
  8798  		Attr: *l,
  8799  	}
  8800  }
  8801  
  8802  func (l *LsTLVOpaquePrefixAttr) DecodeFromBytes(data []byte) error {
  8803  	value, err := l.LsTLV.DecodeFromBytes(data)
  8804  	if err != nil {
  8805  		return err
  8806  	}
  8807  
  8808  	if l.Type != LS_TLV_OPAQUE_PREFIX_ATTR {
  8809  		return malformedAttrListErr("Unexpected TLV type")
  8810  	}
  8811  
  8812  	l.Attr = value
  8813  
  8814  	return nil
  8815  }
  8816  
  8817  func (l *LsTLVOpaquePrefixAttr) Serialize() ([]byte, error) {
  8818  	return l.LsTLV.Serialize(l.Attr)
  8819  }
  8820  
  8821  func (l *LsTLVOpaquePrefixAttr) String() string {
  8822  	return fmt.Sprintf("{Prefix opaque attribute: %v}", l.Attr)
  8823  }
  8824  
  8825  func (l *LsTLVOpaquePrefixAttr) MarshalJSON() ([]byte, error) {
  8826  	return json.Marshal(struct {
  8827  		Type  LsTLVType `json:"type"`
  8828  		Value string    `json:"prefix_opaque_attribute"`
  8829  	}{
  8830  		Type:  l.Type,
  8831  		Value: fmt.Sprintf("%v", l.Attr),
  8832  	})
  8833  }
  8834  
  8835  type LsTLVNodeDescriptor struct {
  8836  	LsTLV
  8837  	SubTLVs []LsTLVInterface
  8838  }
  8839  
  8840  func (l *LsTLVNodeDescriptor) DecodeFromBytes(data []byte) error {
  8841  	tlv, err := l.LsTLV.DecodeFromBytes(data)
  8842  	if err != nil {
  8843  		return err
  8844  	}
  8845  
  8846  	if l.Type != LS_TLV_LOCAL_NODE_DESC && l.Type != LS_TLV_REMOTE_NODE_DESC {
  8847  		return malformedAttrListErr("Unexpected TLV type")
  8848  	}
  8849  
  8850  	// RFC7752, 3.2.1.4
  8851  	// There can be at most one instance of each sub-TLV type present in
  8852  	// any Node Descriptor.  The sub-TLVs within a Node Descriptor MUST
  8853  	// be arranged in ascending order by sub-TLV type.
  8854  	prevType := uint16(0)
  8855  	m := make(map[LsTLVType]bool)
  8856  
  8857  	for len(tlv) >= tlvHdrLen {
  8858  		sub := &LsTLV{}
  8859  		_, err := sub.DecodeFromBytes(tlv)
  8860  		if err != nil {
  8861  			return err
  8862  		}
  8863  
  8864  		if uint16(sub.Type) < prevType {
  8865  			return malformedAttrListErr("Incorrect TLV order")
  8866  		}
  8867  		if _, ok := m[sub.Type]; ok {
  8868  			return malformedAttrListErr("Duplicate TLV")
  8869  		}
  8870  		prevType = uint16(sub.Type)
  8871  		m[sub.Type] = true
  8872  
  8873  		var subTLV LsTLVInterface
  8874  		switch sub.Type {
  8875  		case LS_TLV_AS:
  8876  			subTLV = &LsTLVAutonomousSystem{}
  8877  		case LS_TLV_BGP_LS_ID:
  8878  			subTLV = &LsTLVBgpLsID{}
  8879  		case LS_TLV_OSPF_AREA:
  8880  			subTLV = &LsTLVOspfAreaID{}
  8881  		case LS_TLV_IGP_ROUTER_ID:
  8882  			subTLV = &LsTLVIgpRouterID{}
  8883  		case LS_TLV_BGP_ROUTER_ID:
  8884  			subTLV = &LsTLVBgpRouterID{}
  8885  		case LS_TLV_BGP_CONFEDERATION_MEMBER:
  8886  			subTLV = &LsTLVBgpConfederationMember{}
  8887  
  8888  		default:
  8889  			tlv = tlv[sub.Len():]
  8890  			l.Length -= uint16(sub.Len())
  8891  			continue
  8892  		}
  8893  
  8894  		if err := subTLV.DecodeFromBytes(tlv); err != nil {
  8895  			return err
  8896  		}
  8897  		l.SubTLVs = append(l.SubTLVs, subTLV)
  8898  		tlv = tlv[subTLV.Len():]
  8899  	}
  8900  
  8901  	_, lsTLVIgpRouterIDExists := m[LS_TLV_IGP_ROUTER_ID]
  8902  	_, lsTLVBgpRouterIDExists := m[LS_TLV_BGP_ROUTER_ID]
  8903  	_, lsTLVAutonomousSystemExists := m[LS_TLV_AS]
  8904  
  8905  	if !(lsTLVIgpRouterIDExists || (lsTLVBgpRouterIDExists && lsTLVAutonomousSystemExists)) {
  8906  		return malformedAttrListErr("Required TLV missing")
  8907  	}
  8908  
  8909  	return nil
  8910  }
  8911  
  8912  func (l *LsTLVNodeDescriptor) Extract() *LsNodeDescriptor {
  8913  	nd := &LsNodeDescriptor{}
  8914  
  8915  	for _, tlv := range l.SubTLVs {
  8916  		switch v := tlv.(type) {
  8917  		case *LsTLVAutonomousSystem:
  8918  			nd.Asn = v.ASN
  8919  		case *LsTLVBgpLsID:
  8920  			nd.BGPLsID = v.BGPLsID
  8921  		case *LsTLVOspfAreaID:
  8922  			nd.OspfAreaID = v.AreaID
  8923  		case *LsTLVIgpRouterID:
  8924  			nd.IGPRouterID, nd.PseudoNode = parseIGPRouterID(v.RouterID)
  8925  		case *LsTLVBgpRouterID:
  8926  			nd.BGPRouterID = v.RouterID
  8927  		case *LsTLVBgpConfederationMember:
  8928  			nd.BGPConfederationMember = v.BgpConfederationMember
  8929  		}
  8930  	}
  8931  
  8932  	return nd
  8933  }
  8934  
  8935  func (l *LsTLVNodeDescriptor) Serialize() ([]byte, error) {
  8936  	buf := []byte{}
  8937  	for _, tlv := range l.SubTLVs {
  8938  		ser, err := tlv.Serialize()
  8939  		if err != nil {
  8940  			return nil, err
  8941  		}
  8942  
  8943  		buf = append(buf, ser...)
  8944  	}
  8945  
  8946  	return l.LsTLV.Serialize(buf)
  8947  }
  8948  
  8949  func (l *LsTLVNodeDescriptor) MarshalJSON() ([]byte, error) {
  8950  	return json.Marshal(struct {
  8951  		Type LsTLVType `json:"type"`
  8952  		LsNodeDescriptor
  8953  	}{
  8954  		l.Type,
  8955  		*l.Extract(),
  8956  	})
  8957  }
  8958  
  8959  func (l *LsTLVNodeDescriptor) String() string {
  8960  	nd := l.Extract()
  8961  
  8962  	return nd.String()
  8963  }
  8964  
  8965  type LsNodeDescriptor struct {
  8966  	Asn                    uint32 `json:"asn"`
  8967  	BGPLsID                uint32 `json:"bgp_ls_id"`
  8968  	OspfAreaID             uint32 `json:"ospf_area_id"`
  8969  	PseudoNode             bool   `json:"pseudo_node"`
  8970  	IGPRouterID            string `json:"igp_router_id"`
  8971  	BGPRouterID            net.IP `json:"bgp_router_id"`
  8972  	BGPConfederationMember uint32 `json:"bgp_confederation_member"`
  8973  }
  8974  
  8975  func (l *LsNodeDescriptor) String() string {
  8976  
  8977  	if l.BGPRouterID == nil {
  8978  		return fmt.Sprintf("{ASN: %v, BGP LS ID: %v, OSPF AREA: %v, IGP ROUTER ID: %v}", l.Asn, l.BGPLsID, l.OspfAreaID, l.IGPRouterID)
  8979  	}
  8980  
  8981  	return fmt.Sprintf("{ASN: %v, BGP LS ID: %v, BGP ROUTER ID: %v}", l.Asn, l.BGPLsID, l.BGPRouterID)
  8982  }
  8983  
  8984  func parseIGPRouterID(id []byte) (string, bool) {
  8985  	switch len(id) {
  8986  	// OSPF or OSPFv3 non-pseudonode
  8987  	case 4:
  8988  		return net.IP(id).String(), false
  8989  
  8990  	// ISIS non-pseudonode
  8991  	case 6:
  8992  		return fmt.Sprintf("%0.2x%0.2x.%0.2x%0.2x.%0.2x%0.2x", id[0], id[1], id[2], id[3], id[4], id[5]), false
  8993  
  8994  	// ISIS pseudonode
  8995  	case 7:
  8996  		return fmt.Sprintf("%0.2x%0.2x.%0.2x%0.2x.%0.2x%0.2x-%0.2x", id[0], id[1], id[2], id[3], id[4], id[5], id[6]), true
  8997  
  8998  	// OSPF or OSPFv3 pseudonode
  8999  	case 8:
  9000  		return fmt.Sprintf("%v:%v", net.IP(id[:4]).String(), net.IP(id[4:]).String()), true
  9001  
  9002  	default:
  9003  		return fmt.Sprintf("%v", id), false
  9004  	}
  9005  }
  9006  
  9007  // Generate LsTLVNodeDescriptor from LsNodeDescriptor
  9008  func NewLsTLVNodeDescriptor(nd *LsNodeDescriptor, tlvType LsTLVType) LsTLVNodeDescriptor {
  9009  	subTLVs := []LsTLVInterface{}
  9010  	// ASN 0 is invalid.
  9011  	if nd.Asn != 0 {
  9012  		subTLVs = append(subTLVs,
  9013  			&LsTLVAutonomousSystem{
  9014  				LsTLV: LsTLV{
  9015  					Type:   LS_TLV_AS,
  9016  					Length: 4, // 4 is the only valid value.
  9017  				},
  9018  				ASN: nd.Asn,
  9019  			})
  9020  	}
  9021  
  9022  	// For BGP
  9023  	if nd.BGPRouterID != nil {
  9024  		subTLVs = append(subTLVs,
  9025  			&LsTLVBgpRouterID{
  9026  				LsTLV: LsTLV{
  9027  					Type:   LS_TLV_BGP_ROUTER_ID,
  9028  					Length: 4, // 4 is the only valid value.
  9029  				},
  9030  				RouterID: nd.BGPRouterID,
  9031  			})
  9032  		if nd.BGPConfederationMember != 0 {
  9033  			subTLVs = append(subTLVs,
  9034  				&LsTLVBgpConfederationMember{
  9035  					LsTLV: LsTLV{
  9036  						Type:   LS_TLV_BGP_CONFEDERATION_MEMBER,
  9037  						Length: 4, // 4 is the only valid value.
  9038  					},
  9039  					BgpConfederationMember: nd.BGPConfederationMember,
  9040  				})
  9041  		}
  9042  	}
  9043  	// For IGP
  9044  	if nd.IGPRouterID != "" {
  9045  		routerIdBytes := []byte(nd.IGPRouterID)
  9046  		routerIdLength := len([]byte(nd.IGPRouterID))
  9047  		subTLVs = append(subTLVs,
  9048  			&LsTLVIgpRouterID{
  9049  				LsTLV: LsTLV{
  9050  					Type:   LS_TLV_IGP_ROUTER_ID,
  9051  					Length: uint16(routerIdLength),
  9052  				},
  9053  				RouterID: routerIdBytes,
  9054  			})
  9055  		isOspf := false
  9056  		// OSPF/OSPFv3 non-pseudonode or pseudonode
  9057  		if routerIdLength == 4 || routerIdLength == 8 {
  9058  			isOspf = true
  9059  		}
  9060  		if isOspf {
  9061  			subTLVs = append(subTLVs,
  9062  				&LsTLVOspfAreaID{
  9063  					LsTLV: LsTLV{
  9064  						Type:   LS_TLV_OSPF_AREA,
  9065  						Length: 4, // 4 is the only valid value.
  9066  					},
  9067  					AreaID: nd.OspfAreaID,
  9068  				})
  9069  		}
  9070  
  9071  	}
  9072  
  9073  	subTLVs = append(subTLVs,
  9074  		&LsTLVBgpLsID{
  9075  			LsTLV: LsTLV{
  9076  				Type:   LS_TLV_BGP_LS_ID,
  9077  				Length: 4, // 4 is the only valid value.
  9078  			},
  9079  			BGPLsID: nd.BGPLsID,
  9080  		})
  9081  
  9082  	ndLength := 0
  9083  	for _, val := range subTLVs {
  9084  		ndLength += val.Len()
  9085  	}
  9086  
  9087  	return LsTLVNodeDescriptor{
  9088  		LsTLV: LsTLV{
  9089  			Type:   tlvType, // LocalNodeDesc
  9090  			Length: uint16(ndLength),
  9091  		},
  9092  		SubTLVs: subTLVs,
  9093  	}
  9094  
  9095  }
  9096  
  9097  type LsAddrPrefix struct {
  9098  	PrefixDefault
  9099  	Type   LsNLRIType
  9100  	Length uint16
  9101  	NLRI   LsNLRIInterface
  9102  }
  9103  
  9104  func (l *LsAddrPrefix) AFI() uint16 {
  9105  	return AFI_LS
  9106  }
  9107  
  9108  func (l *LsAddrPrefix) SAFI() uint8 {
  9109  	return SAFI_LS
  9110  }
  9111  
  9112  func (l *LsAddrPrefix) Len(...*MarshallingOption) int {
  9113  	return int(4 + l.Length)
  9114  }
  9115  
  9116  func (l *LsAddrPrefix) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
  9117  	if len(data) < 4 {
  9118  		return malformedAttrListErr("Malformed BGP-LS Address Prefix")
  9119  	}
  9120  
  9121  	l.Type = LsNLRIType(binary.BigEndian.Uint16(data[:2]))
  9122  	l.Length = binary.BigEndian.Uint16(data[2:4])
  9123  
  9124  	switch l.Type {
  9125  	case LS_NLRI_TYPE_NODE:
  9126  		node := &LsNodeNLRI{}
  9127  		node.Length = l.Length
  9128  		node.NLRIType = LS_NLRI_TYPE_NODE
  9129  		l.NLRI = node
  9130  
  9131  	case LS_NLRI_TYPE_LINK:
  9132  		link := &LsLinkNLRI{}
  9133  		link.Length = l.Length
  9134  		link.NLRIType = LS_NLRI_TYPE_LINK
  9135  		l.NLRI = link
  9136  
  9137  	case LS_NLRI_TYPE_PREFIX_IPV4:
  9138  		prefixv4 := &LsPrefixV4NLRI{}
  9139  		prefixv4.Length = l.Length
  9140  		prefixv4.NLRIType = LS_NLRI_TYPE_PREFIX_IPV4
  9141  		l.NLRI = prefixv4
  9142  
  9143  	case LS_NLRI_TYPE_PREFIX_IPV6:
  9144  		prefixv6 := &LsPrefixV6NLRI{}
  9145  		prefixv6.Length = l.Length
  9146  		prefixv6.NLRIType = LS_NLRI_TYPE_PREFIX_IPV4
  9147  		l.NLRI = prefixv6
  9148  
  9149  	default:
  9150  		return malformedAttrListErr("Unsupported BGP-LS NLRI")
  9151  	}
  9152  
  9153  	if l.NLRI != nil {
  9154  		return l.NLRI.DecodeFromBytes(data[4:])
  9155  	}
  9156  
  9157  	return nil
  9158  }
  9159  
  9160  func (l *LsAddrPrefix) Serialize(options ...*MarshallingOption) ([]byte, error) {
  9161  	if l.NLRI == nil {
  9162  		return nil, errors.New("empty NLRI")
  9163  	}
  9164  
  9165  	ser, err := l.NLRI.Serialize()
  9166  	if err != nil {
  9167  		return nil, err
  9168  	}
  9169  
  9170  	buf := make([]byte, 4+len(ser))
  9171  	binary.BigEndian.PutUint16(buf[:2], uint16(l.Type))
  9172  	binary.BigEndian.PutUint16(buf[2:], l.Length)
  9173  	copy(buf[4:], ser)
  9174  
  9175  	return buf, nil
  9176  }
  9177  
  9178  func (l *LsAddrPrefix) MarshalJSON() ([]byte, error) {
  9179  	return json.Marshal(struct {
  9180  		Type   LsNLRIType `json:"type"`
  9181  		Length uint16     `json:"length"`
  9182  		NLRI   string     `json:"nlri"`
  9183  	}{
  9184  		l.Type,
  9185  		l.Length,
  9186  		l.String(),
  9187  	})
  9188  }
  9189  
  9190  func (l *LsAddrPrefix) String() string {
  9191  	if l.NLRI == nil {
  9192  		return "NLRI: (nil)"
  9193  	}
  9194  
  9195  	return "NLRI { " + l.NLRI.String() + " }"
  9196  }
  9197  
  9198  func (l *LsAddrPrefix) Flat() map[string]string {
  9199  	return map[string]string{}
  9200  }
  9201  
  9202  type LsAttributeNode struct {
  9203  	Flags           *LsNodeFlags `json:"flags,omitempty"`
  9204  	Opaque          *[]byte      `json:"opaque,omitempty"`
  9205  	Name            *string      `json:"name,omitempty"`
  9206  	IsisArea        *[]byte      `json:"isis_area,omitempty"`
  9207  	LocalRouterID   *net.IP      `json:"local_router_id_ipv4,omitempty"`
  9208  	LocalRouterIDv6 *net.IP      `json:"local_router_id_ipv6,omitempty"`
  9209  
  9210  	// Segment Routing
  9211  	SrCapabilties *LsSrCapabilities `json:"sr_capabilities,omitempty"`
  9212  	SrAlgorithms  *[]byte           `json:"sr_algorithms,omitempty"`
  9213  	SrLocalBlock  *LsSrLocalBlock   `json:"sr_local_block,omitempty"`
  9214  }
  9215  
  9216  type LsAttributeLink struct {
  9217  	Name             *string `json:"name,omitempty"`
  9218  	LocalRouterID    *net.IP `json:"local_router_id_ipv4,omitempty"`
  9219  	LocalRouterIDv6  *net.IP `json:"local_router_id_ipv6,omitempty"`
  9220  	RemoteRouterID   *net.IP `json:"remote_router_id_ipv4,omitempty"`
  9221  	RemoteRouterIDv6 *net.IP `json:"remote_router_id_ipv6,omitempty"`
  9222  	AdminGroup       *uint32 `json:"admin_group,omitempty"`
  9223  	DefaultTEMetric  *uint32 `json:"default_te_metric,omitempty"`
  9224  	IGPMetric        *uint32 `json:"igp_metric,omitempty"`
  9225  	Opaque           *[]byte `json:"opaque,omitempty"`
  9226  
  9227  	// Bandwidth is expressed in bytes (not bits) per second.
  9228  	Bandwidth           *float32    `json:"bandwidth,omitempty"`
  9229  	ReservableBandwidth *float32    `json:"reservable_bandwidth,omitempty"`
  9230  	UnreservedBandwidth *[8]float32 `json:"unreserved_bandwidth,omitempty"`
  9231  	Srlgs               *[]uint32   `json:"srlgs,omitempty"`
  9232  
  9233  	// TODO flag
  9234  	SrAdjacencySID *uint32 `json:"adjacency_sid,omitempty"`
  9235  }
  9236  
  9237  type LsAttributePrefix struct {
  9238  	IGPFlags *LsIGPFlags `json:"igp_flags,omitempty"`
  9239  	Opaque   *[]byte     `json:"opaque,omitempty"`
  9240  
  9241  	SrPrefixSID *uint32 `json:"sr_prefix_sid,omitempty"`
  9242  }
  9243  
  9244  type LsAttributeBgpPeerSegment struct {
  9245  	BgpPeerNodeSid      *LsBgpPeerSegmentSID `json:"bgp_peer_node_sid,omitempty"`
  9246  	BgpPeerAdjacencySid *LsBgpPeerSegmentSID `json:"bgp_peer_adjacency_sid,omitempty"`
  9247  	BgpPeerSetSid       *LsBgpPeerSegmentSID `json:"bgp_peer_set_sid,omitempty"`
  9248  }
  9249  
  9250  type LsAttribute struct {
  9251  	Node           LsAttributeNode           `json:"node"`
  9252  	Link           LsAttributeLink           `json:"link"`
  9253  	Prefix         LsAttributePrefix         `json:"prefix"`
  9254  	BgpPeerSegment LsAttributeBgpPeerSegment `json:"bgp_peer_segment"`
  9255  }
  9256  
  9257  type PathAttributeLs struct {
  9258  	PathAttribute
  9259  	TLVs []LsTLVInterface
  9260  }
  9261  
  9262  func (p *PathAttributeLs) Extract() *LsAttribute {
  9263  	l := &LsAttribute{}
  9264  
  9265  	for _, tlv := range p.TLVs {
  9266  		switch v := tlv.(type) {
  9267  		case *LsTLVNodeFlagBits:
  9268  			l.Node.Flags = v.Extract()
  9269  
  9270  		case *LsTLVOpaqueNodeAttr:
  9271  			l.Node.Opaque = &v.Attr
  9272  
  9273  		case *LsTLVNodeName:
  9274  			l.Node.Name = &v.Name
  9275  
  9276  		case *LsTLVIsisArea:
  9277  			l.Node.IsisArea = &v.Area
  9278  
  9279  		case *LsTLVLocalIPv4RouterID:
  9280  			l.Node.LocalRouterID = &v.IP
  9281  			l.Link.LocalRouterID = &v.IP
  9282  
  9283  		case *LsTLVLocalIPv6RouterID:
  9284  			l.Node.LocalRouterIDv6 = &v.IP
  9285  			l.Link.LocalRouterIDv6 = &v.IP
  9286  
  9287  		case *LsTLVSrCapabilities:
  9288  			l.Node.SrCapabilties = v.Extract()
  9289  
  9290  		case *LsTLVSrAlgorithm:
  9291  			l.Node.SrAlgorithms = &v.Algorithm
  9292  
  9293  		case *LsTLVSrLocalBlock:
  9294  			l.Node.SrLocalBlock = v.Extract()
  9295  
  9296  		case *LsTLVRemoteIPv4RouterID:
  9297  			l.Link.RemoteRouterID = &v.IP
  9298  
  9299  		case *LsTLVRemoteIPv6RouterID:
  9300  			l.Link.RemoteRouterIDv6 = &v.IP
  9301  
  9302  		case *LsTLVAdminGroup:
  9303  			l.Link.AdminGroup = &v.AdminGroup
  9304  
  9305  		case *LsTLVMaxLinkBw:
  9306  			l.Link.Bandwidth = &v.Bandwidth
  9307  
  9308  		case *LsTLVMaxReservableLinkBw:
  9309  			l.Link.ReservableBandwidth = &v.Bandwidth
  9310  
  9311  		case *LsTLVUnreservedBw:
  9312  			l.Link.UnreservedBandwidth = &v.Bandwidth
  9313  
  9314  		case *LsTLVSrlg:
  9315  			l.Link.Srlgs = &v.Srlgs
  9316  
  9317  		case *LsTLVTEDefaultMetric:
  9318  			l.Link.DefaultTEMetric = &v.Metric
  9319  
  9320  		case *LsTLVIGPMetric:
  9321  			l.Link.IGPMetric = &v.Metric
  9322  
  9323  		case *LsTLVOpaqueLinkAttr:
  9324  			l.Link.Opaque = &v.Attr
  9325  
  9326  		case *LsTLVLinkName:
  9327  			l.Link.Name = &v.Name
  9328  
  9329  		case *LsTLVAdjacencySID:
  9330  			l.Link.SrAdjacencySID = &v.SID
  9331  
  9332  		case *LsTLVIGPFlags:
  9333  			l.Prefix.IGPFlags = v.Extract()
  9334  
  9335  		case *LsTLVOpaquePrefixAttr:
  9336  			l.Prefix.Opaque = &v.Attr
  9337  
  9338  		case *LsTLVPrefixSID:
  9339  			l.Prefix.SrPrefixSID = &v.SID
  9340  
  9341  		case *LsTLVPeerNodeSID:
  9342  			l.BgpPeerSegment.BgpPeerNodeSid = v.Extract()
  9343  
  9344  		case *LsTLVPeerAdjacencySID:
  9345  			l.BgpPeerSegment.BgpPeerAdjacencySid = v.Extract()
  9346  
  9347  		case *LsTLVPeerSetSID:
  9348  			l.BgpPeerSegment.BgpPeerSetSid = v.Extract()
  9349  		}
  9350  	}
  9351  
  9352  	return l
  9353  }
  9354  
  9355  func (p *PathAttributeLs) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
  9356  	tlvs, err := p.PathAttribute.DecodeFromBytes(data)
  9357  	if err != nil {
  9358  		return err
  9359  	}
  9360  
  9361  	for len(tlvs) >= tlvHdrLen {
  9362  		t := &LsTLV{}
  9363  		_, err := t.DecodeFromBytes(tlvs)
  9364  		if err != nil {
  9365  			return err
  9366  		}
  9367  
  9368  		var tlv LsTLVInterface
  9369  		switch t.Type {
  9370  		// Node NLRI-related TLVs (https://tools.ietf.org/html/rfc7752#section-3.3.1)
  9371  		case LS_TLV_NODE_FLAG_BITS:
  9372  			tlv = &LsTLVNodeFlagBits{}
  9373  
  9374  		case LS_TLV_OPAQUE_NODE_ATTR:
  9375  			tlv = &LsTLVOpaqueNodeAttr{}
  9376  
  9377  		case LS_TLV_NODE_NAME:
  9378  			tlv = &LsTLVNodeName{}
  9379  
  9380  		case LS_TLV_ISIS_AREA:
  9381  			tlv = &LsTLVIsisArea{}
  9382  
  9383  		// Used by Link NLRI as well.
  9384  		case LS_TLV_IPV4_LOCAL_ROUTER_ID:
  9385  			tlv = &LsTLVLocalIPv4RouterID{}
  9386  
  9387  		// Used by Link NLRI as well.
  9388  		case LS_TLV_IPV6_LOCAL_ROUTER_ID:
  9389  			tlv = &LsTLVLocalIPv6RouterID{}
  9390  
  9391  		// SR-related TLVs (draft-ietf-idr-bgp-ls-segment-routing-ext-08) for Node NLRI
  9392  		case LS_TLV_SR_CAPABILITIES:
  9393  			tlv = &LsTLVSrCapabilities{}
  9394  
  9395  		case LS_TLV_SR_ALGORITHM:
  9396  			tlv = &LsTLVSrAlgorithm{}
  9397  
  9398  		case LS_TLV_SR_LOCAL_BLOCK:
  9399  			tlv = &LsTLVSrLocalBlock{}
  9400  
  9401  		// Link NLRI-related TLVs (https://tools.ietf.org/html/rfc7752#section-3.3.2)
  9402  		case LS_TLV_IPV4_REMOTE_ROUTER_ID:
  9403  			tlv = &LsTLVRemoteIPv4RouterID{}
  9404  
  9405  		case LS_TLV_IPV6_REMOTE_ROUTER_ID:
  9406  			tlv = &LsTLVRemoteIPv6RouterID{}
  9407  
  9408  		case LS_TLV_ADMIN_GROUP:
  9409  			tlv = &LsTLVAdminGroup{}
  9410  
  9411  		case LS_TLV_MAX_LINK_BANDWIDTH:
  9412  			tlv = &LsTLVMaxLinkBw{}
  9413  
  9414  		case LS_TLV_MAX_RESERVABLE_BANDWIDTH:
  9415  			tlv = &LsTLVMaxReservableLinkBw{}
  9416  
  9417  		case LS_TLV_UNRESERVED_BANDWIDTH:
  9418  			tlv = &LsTLVUnreservedBw{}
  9419  
  9420  		case LS_TLV_SRLG:
  9421  			tlv = &LsTLVSrlg{}
  9422  
  9423  		case LS_TLV_TE_DEFAULT_METRIC:
  9424  			tlv = &LsTLVTEDefaultMetric{}
  9425  
  9426  		case LS_TLV_IGP_METRIC:
  9427  			tlv = &LsTLVIGPMetric{}
  9428  
  9429  		case LS_TLV_OPAQUE_LINK_ATTR:
  9430  			tlv = &LsTLVOpaqueLinkAttr{}
  9431  
  9432  		case LS_TLV_LINK_NAME:
  9433  			tlv = &LsTLVLinkName{}
  9434  
  9435  		// SR-related TLVs (draft-ietf-idr-bgp-ls-segment-routing-ext-08) for Link NLRI
  9436  		case LS_TLV_ADJACENCY_SID:
  9437  			tlv = &LsTLVAdjacencySID{}
  9438  
  9439  		// Prefix NLRI-related TLVs (https://tools.ietf.org/html/rfc7752#section-3.3.3)
  9440  		case LS_TLV_IGP_FLAGS:
  9441  			tlv = &LsTLVIGPFlags{}
  9442  
  9443  		case LS_TLV_OPAQUE_PREFIX_ATTR:
  9444  			tlv = &LsTLVOpaquePrefixAttr{}
  9445  
  9446  		// SR-related TLVs (draft-ietf-idr-bgp-ls-segment-routing-ext-08) for Prefix NLRI
  9447  		case LS_TLV_PREFIX_SID:
  9448  			tlv = &LsTLVPrefixSID{}
  9449  
  9450  		// BGP-EPE related TLVs (https://tools.ietf.org/html/rfc9086)
  9451  		case LS_TLV_PEER_NODE_SID:
  9452  			tlv = &LsTLVPeerNodeSID{}
  9453  
  9454  		case LS_TLV_PEER_ADJACENCY_SID:
  9455  			tlv = &LsTLVPeerAdjacencySID{}
  9456  
  9457  		case LS_TLV_PEER_SET_SID:
  9458  			tlv = &LsTLVPeerSetSID{}
  9459  
  9460  		default:
  9461  			tlvs = tlvs[t.Len():]
  9462  			continue
  9463  		}
  9464  
  9465  		if err := tlv.DecodeFromBytes(tlvs); err != nil {
  9466  			return err
  9467  		}
  9468  		tlvs = tlvs[t.Len():]
  9469  
  9470  		p.TLVs = append(p.TLVs, tlv)
  9471  	}
  9472  
  9473  	return nil
  9474  }
  9475  
  9476  func (p *PathAttributeLs) Serialize(options ...*MarshallingOption) ([]byte, error) {
  9477  	buf := []byte{}
  9478  
  9479  	for _, tlv := range p.TLVs {
  9480  		s, err := tlv.Serialize()
  9481  		if err != nil {
  9482  			return nil, err
  9483  		}
  9484  		buf = append(buf, s...)
  9485  	}
  9486  
  9487  	return p.PathAttribute.Serialize(buf, options...)
  9488  }
  9489  
  9490  func (p *PathAttributeLs) String() string {
  9491  	var buf bytes.Buffer
  9492  
  9493  	for _, tlv := range p.TLVs {
  9494  		buf.WriteString(tlv.String() + " ")
  9495  	}
  9496  	if buf.String() != "" {
  9497  		return "{LsAttributes: " + buf.String() + "}"
  9498  	}
  9499  	return ""
  9500  }
  9501  
  9502  func (p *PathAttributeLs) MarshalJSON() ([]byte, error) {
  9503  	return json.Marshal(struct {
  9504  		Type  BGPAttrType `json:"type"`
  9505  		Flags BGPAttrFlag `json:"flags"`
  9506  		LsAttribute
  9507  	}{
  9508  		p.GetType(),
  9509  		p.GetFlags(),
  9510  		*p.Extract(),
  9511  	})
  9512  }
  9513  
  9514  func AfiSafiToRouteFamily(afi uint16, safi uint8) RouteFamily {
  9515  	return RouteFamily(int(afi)<<16 | int(safi))
  9516  }
  9517  
  9518  func RouteFamilyToAfiSafi(rf RouteFamily) (uint16, uint8) {
  9519  	return uint16(int(rf) >> 16), uint8(int(rf) & 0xff)
  9520  }
  9521  
  9522  type RouteFamily int
  9523  
  9524  func (f RouteFamily) String() string {
  9525  	if n, y := AddressFamilyNameMap[f]; y {
  9526  		return n
  9527  	}
  9528  	return fmt.Sprintf("UnknownFamily(%d)", f)
  9529  }
  9530  
  9531  const (
  9532  	RF_IPv4_UC        RouteFamily = AFI_IP<<16 | SAFI_UNICAST
  9533  	RF_IPv6_UC        RouteFamily = AFI_IP6<<16 | SAFI_UNICAST
  9534  	RF_IPv4_MC        RouteFamily = AFI_IP<<16 | SAFI_MULTICAST
  9535  	RF_IPv6_MC        RouteFamily = AFI_IP6<<16 | SAFI_MULTICAST
  9536  	RF_IPv4_VPN       RouteFamily = AFI_IP<<16 | SAFI_MPLS_VPN
  9537  	RF_IPv6_VPN       RouteFamily = AFI_IP6<<16 | SAFI_MPLS_VPN
  9538  	RF_IPv4_VPN_MC    RouteFamily = AFI_IP<<16 | SAFI_MPLS_VPN_MULTICAST
  9539  	RF_IPv6_VPN_MC    RouteFamily = AFI_IP6<<16 | SAFI_MPLS_VPN_MULTICAST
  9540  	RF_IPv4_MPLS      RouteFamily = AFI_IP<<16 | SAFI_MPLS_LABEL
  9541  	RF_IPv6_MPLS      RouteFamily = AFI_IP6<<16 | SAFI_MPLS_LABEL
  9542  	RF_VPLS           RouteFamily = AFI_L2VPN<<16 | SAFI_VPLS
  9543  	RF_EVPN           RouteFamily = AFI_L2VPN<<16 | SAFI_EVPN
  9544  	RF_RTC_UC         RouteFamily = AFI_IP<<16 | SAFI_ROUTE_TARGET_CONSTRAINTS
  9545  	RF_IPv4_ENCAP     RouteFamily = AFI_IP<<16 | SAFI_ENCAPSULATION
  9546  	RF_IPv6_ENCAP     RouteFamily = AFI_IP6<<16 | SAFI_ENCAPSULATION
  9547  	RF_FS_IPv4_UC     RouteFamily = AFI_IP<<16 | SAFI_FLOW_SPEC_UNICAST
  9548  	RF_FS_IPv4_VPN    RouteFamily = AFI_IP<<16 | SAFI_FLOW_SPEC_VPN
  9549  	RF_FS_IPv6_UC     RouteFamily = AFI_IP6<<16 | SAFI_FLOW_SPEC_UNICAST
  9550  	RF_FS_IPv6_VPN    RouteFamily = AFI_IP6<<16 | SAFI_FLOW_SPEC_VPN
  9551  	RF_FS_L2_VPN      RouteFamily = AFI_L2VPN<<16 | SAFI_FLOW_SPEC_VPN
  9552  	RF_OPAQUE         RouteFamily = AFI_OPAQUE<<16 | SAFI_KEY_VALUE
  9553  	RF_LS             RouteFamily = AFI_LS<<16 | SAFI_LS
  9554  	RF_SR_POLICY_IPv4 RouteFamily = AFI_IP<<16 | SAFI_SRPOLICY
  9555  	RF_SR_POLICY_IPv6 RouteFamily = AFI_IP6<<16 | SAFI_SRPOLICY
  9556  	RF_MUP_IPv4       RouteFamily = AFI_IP<<16 | SAFI_MUP
  9557  	RF_MUP_IPv6       RouteFamily = AFI_IP6<<16 | SAFI_MUP
  9558  )
  9559  
  9560  var AddressFamilyNameMap = map[RouteFamily]string{
  9561  	RF_IPv4_UC:        "ipv4-unicast",
  9562  	RF_IPv6_UC:        "ipv6-unicast",
  9563  	RF_IPv4_MC:        "ipv4-multicast",
  9564  	RF_IPv6_MC:        "ipv6-multicast",
  9565  	RF_IPv4_MPLS:      "ipv4-labelled-unicast",
  9566  	RF_IPv6_MPLS:      "ipv6-labelled-unicast",
  9567  	RF_IPv4_VPN:       "l3vpn-ipv4-unicast",
  9568  	RF_IPv6_VPN:       "l3vpn-ipv6-unicast",
  9569  	RF_IPv4_VPN_MC:    "l3vpn-ipv4-multicast",
  9570  	RF_IPv6_VPN_MC:    "l3vpn-ipv6-multicast",
  9571  	RF_VPLS:           "l2vpn-vpls",
  9572  	RF_EVPN:           "l2vpn-evpn",
  9573  	RF_RTC_UC:         "rtc",
  9574  	RF_IPv4_ENCAP:     "ipv4-encap",
  9575  	RF_IPv6_ENCAP:     "ipv6-encap",
  9576  	RF_FS_IPv4_UC:     "ipv4-flowspec",
  9577  	RF_FS_IPv4_VPN:    "l3vpn-ipv4-flowspec",
  9578  	RF_FS_IPv6_UC:     "ipv6-flowspec",
  9579  	RF_FS_IPv6_VPN:    "l3vpn-ipv6-flowspec",
  9580  	RF_FS_L2_VPN:      "l2vpn-flowspec",
  9581  	RF_OPAQUE:         "opaque",
  9582  	RF_LS:             "ls",
  9583  	RF_SR_POLICY_IPv4: "ipv4-srpolicy",
  9584  	RF_SR_POLICY_IPv6: "ipv6-srpolicy",
  9585  	RF_MUP_IPv4:       "ipv4-mup",
  9586  	RF_MUP_IPv6:       "ipv6-mup",
  9587  }
  9588  
  9589  var AddressFamilyValueMap = map[string]RouteFamily{
  9590  	AddressFamilyNameMap[RF_IPv4_UC]:        RF_IPv4_UC,
  9591  	AddressFamilyNameMap[RF_IPv6_UC]:        RF_IPv6_UC,
  9592  	AddressFamilyNameMap[RF_IPv4_MC]:        RF_IPv4_MC,
  9593  	AddressFamilyNameMap[RF_IPv6_MC]:        RF_IPv6_MC,
  9594  	AddressFamilyNameMap[RF_IPv4_MPLS]:      RF_IPv4_MPLS,
  9595  	AddressFamilyNameMap[RF_IPv6_MPLS]:      RF_IPv6_MPLS,
  9596  	AddressFamilyNameMap[RF_IPv4_VPN]:       RF_IPv4_VPN,
  9597  	AddressFamilyNameMap[RF_IPv6_VPN]:       RF_IPv6_VPN,
  9598  	AddressFamilyNameMap[RF_IPv4_VPN_MC]:    RF_IPv4_VPN_MC,
  9599  	AddressFamilyNameMap[RF_IPv6_VPN_MC]:    RF_IPv6_VPN_MC,
  9600  	AddressFamilyNameMap[RF_VPLS]:           RF_VPLS,
  9601  	AddressFamilyNameMap[RF_EVPN]:           RF_EVPN,
  9602  	AddressFamilyNameMap[RF_RTC_UC]:         RF_RTC_UC,
  9603  	AddressFamilyNameMap[RF_IPv4_ENCAP]:     RF_IPv4_ENCAP,
  9604  	AddressFamilyNameMap[RF_IPv6_ENCAP]:     RF_IPv6_ENCAP,
  9605  	AddressFamilyNameMap[RF_FS_IPv4_UC]:     RF_FS_IPv4_UC,
  9606  	AddressFamilyNameMap[RF_FS_IPv4_VPN]:    RF_FS_IPv4_VPN,
  9607  	AddressFamilyNameMap[RF_FS_IPv6_UC]:     RF_FS_IPv6_UC,
  9608  	AddressFamilyNameMap[RF_FS_IPv6_VPN]:    RF_FS_IPv6_VPN,
  9609  	AddressFamilyNameMap[RF_FS_L2_VPN]:      RF_FS_L2_VPN,
  9610  	AddressFamilyNameMap[RF_OPAQUE]:         RF_OPAQUE,
  9611  	AddressFamilyNameMap[RF_LS]:             RF_LS,
  9612  	AddressFamilyNameMap[RF_SR_POLICY_IPv4]: RF_SR_POLICY_IPv4,
  9613  	AddressFamilyNameMap[RF_SR_POLICY_IPv6]: RF_SR_POLICY_IPv6,
  9614  	AddressFamilyNameMap[RF_MUP_IPv4]:       RF_MUP_IPv4,
  9615  	AddressFamilyNameMap[RF_MUP_IPv6]:       RF_MUP_IPv6,
  9616  }
  9617  
  9618  func GetRouteFamily(name string) (RouteFamily, error) {
  9619  	if v, ok := AddressFamilyValueMap[name]; ok {
  9620  		return v, nil
  9621  	}
  9622  	return RouteFamily(0), fmt.Errorf("%s isn't a valid route family name", name)
  9623  }
  9624  
  9625  func NewPrefixFromRouteFamily(afi uint16, safi uint8, prefixStr ...string) (prefix AddrPrefixInterface, err error) {
  9626  	family := AfiSafiToRouteFamily(afi, safi)
  9627  
  9628  	f := func(s string) (AddrPrefixInterface, error) {
  9629  		addr, net, err := net.ParseCIDR(s)
  9630  		if err != nil {
  9631  			return nil, err
  9632  		}
  9633  		len, _ := net.Mask.Size()
  9634  		switch family {
  9635  		case RF_IPv4_UC, RF_IPv4_MC:
  9636  			return NewIPAddrPrefix(uint8(len), addr.String()), nil
  9637  		}
  9638  		return NewIPv6AddrPrefix(uint8(len), addr.String()), nil
  9639  	}
  9640  
  9641  	rdEOR := &RouteDistinguisherUnknown{DefaultRouteDistinguisher{Type: BGP_RD_EOR}, []byte("EOR")}
  9642  
  9643  	switch family {
  9644  	case RF_IPv4_UC, RF_IPv4_MC:
  9645  		if len(prefixStr) > 0 {
  9646  			prefix, err = f(prefixStr[0])
  9647  		} else {
  9648  			prefix = NewIPAddrPrefix(0, "")
  9649  		}
  9650  	case RF_IPv6_UC, RF_IPv6_MC:
  9651  		if len(prefixStr) > 0 {
  9652  			prefix, err = f(prefixStr[0])
  9653  		} else {
  9654  			prefix = NewIPv6AddrPrefix(0, "")
  9655  		}
  9656  	case RF_IPv4_VPN:
  9657  		if len(prefixStr) == 0 {
  9658  			prefix = NewLabeledVPNIPAddrPrefix(0, "", *NewMPLSLabelStack(), rdEOR)
  9659  			break
  9660  		}
  9661  
  9662  		rd, addr, network, err := ParseVPNPrefix(prefixStr[0])
  9663  		if err != nil {
  9664  			return nil, err
  9665  		}
  9666  
  9667  		length, _ := network.Mask.Size()
  9668  
  9669  		prefix = NewLabeledVPNIPAddrPrefix(
  9670  			uint8(length),
  9671  			addr.String(),
  9672  			*NewMPLSLabelStack(),
  9673  			rd,
  9674  		)
  9675  	case RF_IPv6_VPN:
  9676  		if len(prefixStr) == 0 {
  9677  			prefix = NewLabeledVPNIPv6AddrPrefix(0, "", *NewMPLSLabelStack(), rdEOR)
  9678  			break
  9679  		}
  9680  
  9681  		rd, addr, network, err := ParseVPNPrefix(prefixStr[0])
  9682  		if err != nil {
  9683  			return nil, err
  9684  		}
  9685  
  9686  		length, _ := network.Mask.Size()
  9687  
  9688  		prefix = NewLabeledVPNIPv6AddrPrefix(
  9689  			uint8(length),
  9690  			addr.String(),
  9691  			*NewMPLSLabelStack(),
  9692  			rd,
  9693  		)
  9694  	case RF_IPv4_MPLS:
  9695  		prefix = NewLabeledIPAddrPrefix(0, "", *NewMPLSLabelStack())
  9696  	case RF_IPv6_MPLS:
  9697  		prefix = NewLabeledIPv6AddrPrefix(0, "", *NewMPLSLabelStack())
  9698  	case RF_EVPN:
  9699  		prefix = NewEVPNNLRI(0, nil)
  9700  	case RF_VPLS:
  9701  		prefix = &VPLSNLRI{}
  9702  
  9703  	// TODO (sbezverk) Add processing SR Policy NLRI
  9704  	case RF_SR_POLICY_IPv4:
  9705  		prefix = &SRPolicyIPv4{
  9706  			SRPolicyNLRI: SRPolicyNLRI{
  9707  				rf: RF_SR_POLICY_IPv4,
  9708  			},
  9709  		}
  9710  	case RF_SR_POLICY_IPv6:
  9711  		prefix = &SRPolicyIPv6{
  9712  			SRPolicyNLRI: SRPolicyNLRI{
  9713  				rf: RF_SR_POLICY_IPv6,
  9714  			},
  9715  		}
  9716  	case RF_RTC_UC:
  9717  		prefix = &RouteTargetMembershipNLRI{}
  9718  	case RF_IPv4_ENCAP:
  9719  		prefix = NewEncapNLRI("")
  9720  	case RF_IPv6_ENCAP:
  9721  		prefix = NewEncapv6NLRI("")
  9722  	case RF_FS_IPv4_UC:
  9723  		prefix = &FlowSpecIPv4Unicast{FlowSpecNLRI{rf: RF_FS_IPv4_UC}}
  9724  	case RF_FS_IPv4_VPN:
  9725  		prefix = &FlowSpecIPv4VPN{FlowSpecNLRI{rf: RF_FS_IPv4_VPN}}
  9726  	case RF_FS_IPv6_UC:
  9727  		prefix = &FlowSpecIPv6Unicast{FlowSpecNLRI{rf: RF_FS_IPv6_UC}}
  9728  	case RF_FS_IPv6_VPN:
  9729  		prefix = &FlowSpecIPv6VPN{FlowSpecNLRI{rf: RF_FS_IPv6_VPN}}
  9730  	case RF_FS_L2_VPN:
  9731  		prefix = &FlowSpecL2VPN{FlowSpecNLRI{rf: RF_FS_L2_VPN}}
  9732  	case RF_OPAQUE:
  9733  		prefix = &OpaqueNLRI{}
  9734  	case RF_LS:
  9735  		prefix = &LsAddrPrefix{}
  9736  	case RF_MUP_IPv4:
  9737  		prefix = NewMUPNLRI(AFI_IP, 0, 0, nil)
  9738  	case RF_MUP_IPv6:
  9739  		prefix = NewMUPNLRI(AFI_IP6, 0, 0, nil)
  9740  	default:
  9741  		err = fmt.Errorf("unknown route family. AFI: %d, SAFI: %d", afi, safi)
  9742  	}
  9743  	return prefix, err
  9744  }
  9745  
  9746  type BGPAttrFlag uint8
  9747  
  9748  const (
  9749  	BGP_ATTR_FLAG_EXTENDED_LENGTH BGPAttrFlag = 1 << 4
  9750  	BGP_ATTR_FLAG_PARTIAL         BGPAttrFlag = 1 << 5
  9751  	BGP_ATTR_FLAG_TRANSITIVE      BGPAttrFlag = 1 << 6
  9752  	BGP_ATTR_FLAG_OPTIONAL        BGPAttrFlag = 1 << 7
  9753  )
  9754  
  9755  func (f BGPAttrFlag) String() string {
  9756  	strs := make([]string, 0, 4)
  9757  	if f&BGP_ATTR_FLAG_EXTENDED_LENGTH > 0 {
  9758  		strs = append(strs, "EXTENDED_LENGTH")
  9759  	}
  9760  	if f&BGP_ATTR_FLAG_PARTIAL > 0 {
  9761  		strs = append(strs, "PARTIAL")
  9762  	}
  9763  	if f&BGP_ATTR_FLAG_TRANSITIVE > 0 {
  9764  		strs = append(strs, "TRANSITIVE")
  9765  	}
  9766  	if f&BGP_ATTR_FLAG_OPTIONAL > 0 {
  9767  		strs = append(strs, "OPTIONAL")
  9768  	}
  9769  	return strings.Join(strs, "|")
  9770  }
  9771  
  9772  //go:generate stringer -type=BGPAttrType
  9773  type BGPAttrType uint8
  9774  
  9775  const (
  9776  	_ BGPAttrType = iota
  9777  	BGP_ATTR_TYPE_ORIGIN
  9778  	BGP_ATTR_TYPE_AS_PATH
  9779  	BGP_ATTR_TYPE_NEXT_HOP
  9780  	BGP_ATTR_TYPE_MULTI_EXIT_DISC
  9781  	BGP_ATTR_TYPE_LOCAL_PREF
  9782  	BGP_ATTR_TYPE_ATOMIC_AGGREGATE
  9783  	BGP_ATTR_TYPE_AGGREGATOR
  9784  	BGP_ATTR_TYPE_COMMUNITIES
  9785  	BGP_ATTR_TYPE_ORIGINATOR_ID
  9786  	BGP_ATTR_TYPE_CLUSTER_LIST
  9787  	_
  9788  	_
  9789  	_
  9790  	BGP_ATTR_TYPE_MP_REACH_NLRI // = 14
  9791  	BGP_ATTR_TYPE_MP_UNREACH_NLRI
  9792  	BGP_ATTR_TYPE_EXTENDED_COMMUNITIES
  9793  	BGP_ATTR_TYPE_AS4_PATH
  9794  	BGP_ATTR_TYPE_AS4_AGGREGATOR
  9795  	_
  9796  	_
  9797  	_
  9798  	BGP_ATTR_TYPE_PMSI_TUNNEL // = 22
  9799  	BGP_ATTR_TYPE_TUNNEL_ENCAP
  9800  	_
  9801  	BGP_ATTR_TYPE_IP6_EXTENDED_COMMUNITIES // = 25
  9802  	BGP_ATTR_TYPE_AIGP                     // = 26
  9803  	_
  9804  	_
  9805  	BGP_ATTR_TYPE_LS                          // = 29
  9806  	BGP_ATTR_TYPE_LARGE_COMMUNITY BGPAttrType = 32
  9807  	BGP_ATTR_TYPE_PREFIX_SID      BGPAttrType = 40
  9808  )
  9809  
  9810  // NOTIFICATION Error Code  RFC 4271 4.5.
  9811  const (
  9812  	_ = iota
  9813  	BGP_ERROR_MESSAGE_HEADER_ERROR
  9814  	BGP_ERROR_OPEN_MESSAGE_ERROR
  9815  	BGP_ERROR_UPDATE_MESSAGE_ERROR
  9816  	BGP_ERROR_HOLD_TIMER_EXPIRED
  9817  	BGP_ERROR_FSM_ERROR
  9818  	BGP_ERROR_CEASE
  9819  	BGP_ERROR_ROUTE_REFRESH_MESSAGE_ERROR
  9820  )
  9821  
  9822  // NOTIFICATION Error Subcode for BGP_ERROR_MESSAGE_HEADER_ERROR
  9823  const (
  9824  	_ = iota
  9825  	BGP_ERROR_SUB_CONNECTION_NOT_SYNCHRONIZED
  9826  	BGP_ERROR_SUB_BAD_MESSAGE_LENGTH
  9827  	BGP_ERROR_SUB_BAD_MESSAGE_TYPE
  9828  )
  9829  
  9830  // NOTIFICATION Error Subcode for BGP_ERROR_OPEN_MESSAGE_ERROR
  9831  const (
  9832  	_ = iota
  9833  	BGP_ERROR_SUB_UNSUPPORTED_VERSION_NUMBER
  9834  	BGP_ERROR_SUB_BAD_PEER_AS
  9835  	BGP_ERROR_SUB_BAD_BGP_IDENTIFIER
  9836  	BGP_ERROR_SUB_UNSUPPORTED_OPTIONAL_PARAMETER
  9837  	BGP_ERROR_SUB_DEPRECATED_AUTHENTICATION_FAILURE
  9838  	BGP_ERROR_SUB_UNACCEPTABLE_HOLD_TIME
  9839  	BGP_ERROR_SUB_UNSUPPORTED_CAPABILITY
  9840  )
  9841  
  9842  // NOTIFICATION Error Subcode for BGP_ERROR_UPDATE_MESSAGE_ERROR
  9843  const (
  9844  	_ = iota
  9845  	BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST
  9846  	BGP_ERROR_SUB_UNRECOGNIZED_WELL_KNOWN_ATTRIBUTE
  9847  	BGP_ERROR_SUB_MISSING_WELL_KNOWN_ATTRIBUTE
  9848  	BGP_ERROR_SUB_ATTRIBUTE_FLAGS_ERROR
  9849  	BGP_ERROR_SUB_ATTRIBUTE_LENGTH_ERROR
  9850  	BGP_ERROR_SUB_INVALID_ORIGIN_ATTRIBUTE
  9851  	BGP_ERROR_SUB_DEPRECATED_ROUTING_LOOP
  9852  	BGP_ERROR_SUB_INVALID_NEXT_HOP_ATTRIBUTE
  9853  	BGP_ERROR_SUB_OPTIONAL_ATTRIBUTE_ERROR
  9854  	BGP_ERROR_SUB_INVALID_NETWORK_FIELD
  9855  	BGP_ERROR_SUB_MALFORMED_AS_PATH
  9856  )
  9857  
  9858  // NOTIFICATION Error Subcode for BGP_ERROR_HOLD_TIMER_EXPIRED
  9859  const (
  9860  	_ = iota
  9861  	BGP_ERROR_SUB_HOLD_TIMER_EXPIRED
  9862  )
  9863  
  9864  // NOTIFICATION Error Subcode for BGP_ERROR_FSM_ERROR
  9865  const (
  9866  	_ = iota
  9867  	BGP_ERROR_SUB_RECEIVE_UNEXPECTED_MESSAGE_IN_OPENSENT_STATE
  9868  	BGP_ERROR_SUB_RECEIVE_UNEXPECTED_MESSAGE_IN_OPENCONFIRM_STATE
  9869  	BGP_ERROR_SUB_RECEIVE_UNEXPECTED_MESSAGE_IN_ESTABLISHED_STATE
  9870  )
  9871  
  9872  // NOTIFICATION Error Subcode for BGP_ERROR_CEASE  (RFC 4486)
  9873  const (
  9874  	_ = iota
  9875  	BGP_ERROR_SUB_MAXIMUM_NUMBER_OF_PREFIXES_REACHED
  9876  	BGP_ERROR_SUB_ADMINISTRATIVE_SHUTDOWN
  9877  	BGP_ERROR_SUB_PEER_DECONFIGURED
  9878  	BGP_ERROR_SUB_ADMINISTRATIVE_RESET
  9879  	BGP_ERROR_SUB_CONNECTION_REJECTED
  9880  	BGP_ERROR_SUB_OTHER_CONFIGURATION_CHANGE
  9881  	BGP_ERROR_SUB_CONNECTION_COLLISION_RESOLUTION
  9882  	BGP_ERROR_SUB_OUT_OF_RESOURCES
  9883  	BGP_ERROR_SUB_HARD_RESET // RFC8538
  9884  )
  9885  
  9886  // Constants for BGP_ERROR_SUB_ADMINISTRATIVE_SHUTDOWN and BGP_ERROR_SUB_ADMINISTRATIVE_RESET
  9887  const (
  9888  	BGP_ERROR_ADMINISTRATIVE_COMMUNICATION_MAX = 128
  9889  )
  9890  
  9891  // NOTIFICATION Error Subcode for BGP_ERROR_ROUTE_REFRESH
  9892  const (
  9893  	_ = iota
  9894  	BGP_ERROR_SUB_INVALID_MESSAGE_LENGTH
  9895  )
  9896  
  9897  type NotificationErrorCode uint16
  9898  
  9899  func (c NotificationErrorCode) String() string {
  9900  	code := uint8(uint16(c) >> 8)
  9901  	subcode := uint8(uint16(c) & 0xff)
  9902  	UNDEFINED := "undefined"
  9903  	codeStr := UNDEFINED
  9904  	subcodeList := []string{}
  9905  	switch code {
  9906  	case BGP_ERROR_MESSAGE_HEADER_ERROR:
  9907  		codeStr = "header"
  9908  		subcodeList = []string{
  9909  			UNDEFINED,
  9910  			"connection not synchronized",
  9911  			"bad message length",
  9912  			"bad message type"}
  9913  	case BGP_ERROR_OPEN_MESSAGE_ERROR:
  9914  		codeStr = "open"
  9915  		subcodeList = []string{
  9916  			UNDEFINED,
  9917  			"unsupported version number",
  9918  			"bad peer as",
  9919  			"bad bgp identifier",
  9920  			"unsupported optional parameter",
  9921  			"deprecated authentication failure",
  9922  			"unacceptable hold time",
  9923  			"unsupported capability"}
  9924  	case BGP_ERROR_UPDATE_MESSAGE_ERROR:
  9925  		codeStr = "update"
  9926  		subcodeList = []string{
  9927  			UNDEFINED,
  9928  			"malformed attribute list",
  9929  			"unrecognized well known attribute",
  9930  			"missing well known attribute",
  9931  			"attribute flags error",
  9932  			"attribute length error",
  9933  			"invalid origin attribute",
  9934  			"deprecated routing loop",
  9935  			"invalid next hop attribute",
  9936  			"optional attribute error",
  9937  			"invalid network field",
  9938  			"sub malformed as path"}
  9939  	case BGP_ERROR_HOLD_TIMER_EXPIRED:
  9940  		codeStr = "hold timer expired"
  9941  		subcodeList = []string{
  9942  			UNDEFINED,
  9943  			"hold timer expired"}
  9944  	case BGP_ERROR_FSM_ERROR:
  9945  		codeStr = "fsm"
  9946  		subcodeList = []string{
  9947  			UNDEFINED,
  9948  			"receive unexpected message in opensent state",
  9949  			"receive unexpected message in openconfirm state",
  9950  			"receive unexpected message in established state"}
  9951  	case BGP_ERROR_CEASE:
  9952  		codeStr = "cease"
  9953  		subcodeList = []string{
  9954  			UNDEFINED,
  9955  			"maximum number of prefixes reached",
  9956  			"administrative shutdown",
  9957  			"peer deconfigured",
  9958  			"administrative reset",
  9959  			"connection rejected",
  9960  			"other configuration change",
  9961  			"connection collision resolution",
  9962  			"out of resources"}
  9963  	case BGP_ERROR_ROUTE_REFRESH_MESSAGE_ERROR:
  9964  		codeStr = "route refresh"
  9965  		subcodeList = []string{"invalid message length"}
  9966  	}
  9967  	subcodeStr := func(idx uint8, l []string) string {
  9968  		if len(l) == 0 || int(idx) > len(l)-1 {
  9969  			return UNDEFINED
  9970  		}
  9971  		return l[idx]
  9972  	}(subcode, subcodeList)
  9973  	return fmt.Sprintf("code %v(%v) subcode %v(%v)", code, codeStr, subcode, subcodeStr)
  9974  }
  9975  
  9976  func NewNotificationErrorCode(code, subcode uint8) NotificationErrorCode {
  9977  	return NotificationErrorCode(uint16(code)<<8 | uint16(subcode))
  9978  }
  9979  
  9980  var PathAttrFlags map[BGPAttrType]BGPAttrFlag = map[BGPAttrType]BGPAttrFlag{
  9981  	BGP_ATTR_TYPE_ORIGIN:                   BGP_ATTR_FLAG_TRANSITIVE,
  9982  	BGP_ATTR_TYPE_AS_PATH:                  BGP_ATTR_FLAG_TRANSITIVE,
  9983  	BGP_ATTR_TYPE_NEXT_HOP:                 BGP_ATTR_FLAG_TRANSITIVE,
  9984  	BGP_ATTR_TYPE_MULTI_EXIT_DISC:          BGP_ATTR_FLAG_OPTIONAL,
  9985  	BGP_ATTR_TYPE_LOCAL_PREF:               BGP_ATTR_FLAG_TRANSITIVE,
  9986  	BGP_ATTR_TYPE_ATOMIC_AGGREGATE:         BGP_ATTR_FLAG_TRANSITIVE,
  9987  	BGP_ATTR_TYPE_AGGREGATOR:               BGP_ATTR_FLAG_TRANSITIVE | BGP_ATTR_FLAG_OPTIONAL,
  9988  	BGP_ATTR_TYPE_COMMUNITIES:              BGP_ATTR_FLAG_TRANSITIVE | BGP_ATTR_FLAG_OPTIONAL,
  9989  	BGP_ATTR_TYPE_ORIGINATOR_ID:            BGP_ATTR_FLAG_OPTIONAL,
  9990  	BGP_ATTR_TYPE_CLUSTER_LIST:             BGP_ATTR_FLAG_OPTIONAL,
  9991  	BGP_ATTR_TYPE_MP_REACH_NLRI:            BGP_ATTR_FLAG_OPTIONAL,
  9992  	BGP_ATTR_TYPE_MP_UNREACH_NLRI:          BGP_ATTR_FLAG_OPTIONAL,
  9993  	BGP_ATTR_TYPE_EXTENDED_COMMUNITIES:     BGP_ATTR_FLAG_TRANSITIVE | BGP_ATTR_FLAG_OPTIONAL,
  9994  	BGP_ATTR_TYPE_AS4_PATH:                 BGP_ATTR_FLAG_TRANSITIVE | BGP_ATTR_FLAG_OPTIONAL,
  9995  	BGP_ATTR_TYPE_AS4_AGGREGATOR:           BGP_ATTR_FLAG_TRANSITIVE | BGP_ATTR_FLAG_OPTIONAL,
  9996  	BGP_ATTR_TYPE_PMSI_TUNNEL:              BGP_ATTR_FLAG_TRANSITIVE | BGP_ATTR_FLAG_OPTIONAL,
  9997  	BGP_ATTR_TYPE_TUNNEL_ENCAP:             BGP_ATTR_FLAG_TRANSITIVE | BGP_ATTR_FLAG_OPTIONAL,
  9998  	BGP_ATTR_TYPE_IP6_EXTENDED_COMMUNITIES: BGP_ATTR_FLAG_TRANSITIVE | BGP_ATTR_FLAG_OPTIONAL,
  9999  	BGP_ATTR_TYPE_AIGP:                     BGP_ATTR_FLAG_OPTIONAL,
 10000  	BGP_ATTR_TYPE_LARGE_COMMUNITY:          BGP_ATTR_FLAG_TRANSITIVE | BGP_ATTR_FLAG_OPTIONAL,
 10001  	BGP_ATTR_TYPE_LS:                       BGP_ATTR_FLAG_OPTIONAL,
 10002  	BGP_ATTR_TYPE_PREFIX_SID:               BGP_ATTR_FLAG_TRANSITIVE | BGP_ATTR_FLAG_OPTIONAL,
 10003  }
 10004  
 10005  // getPathAttrFlags returns BGP Path Attribute flags value from its type and
 10006  // length (byte length of value field).
 10007  func getPathAttrFlags(typ BGPAttrType, length int) BGPAttrFlag {
 10008  	flags := PathAttrFlags[typ]
 10009  	if length > 255 {
 10010  		flags |= BGP_ATTR_FLAG_EXTENDED_LENGTH
 10011  	}
 10012  	return flags
 10013  }
 10014  
 10015  type PathAttributeInterface interface {
 10016  	DecodeFromBytes([]byte, ...*MarshallingOption) error
 10017  	Serialize(...*MarshallingOption) ([]byte, error)
 10018  	Len(...*MarshallingOption) int
 10019  	GetFlags() BGPAttrFlag
 10020  	GetType() BGPAttrType
 10021  	String() string
 10022  	MarshalJSON() ([]byte, error)
 10023  	Flat() map[string]string
 10024  }
 10025  
 10026  type PathAttribute struct {
 10027  	Flags  BGPAttrFlag
 10028  	Type   BGPAttrType
 10029  	Length uint16 // length of Value
 10030  }
 10031  
 10032  func (p *PathAttribute) Len(options ...*MarshallingOption) int {
 10033  	if p.Flags&BGP_ATTR_FLAG_EXTENDED_LENGTH != 0 {
 10034  		return 4 + int(p.Length)
 10035  	}
 10036  	return 3 + int(p.Length)
 10037  }
 10038  
 10039  func (p *PathAttribute) GetFlags() BGPAttrFlag {
 10040  	return p.Flags
 10041  }
 10042  
 10043  func (p *PathAttribute) GetType() BGPAttrType {
 10044  	return p.Type
 10045  }
 10046  
 10047  func (p *PathAttribute) DecodeFromBytes(data []byte, options ...*MarshallingOption) (value []byte, err error) {
 10048  	eCode := uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR)
 10049  	eSubCode := uint8(BGP_ERROR_SUB_ATTRIBUTE_LENGTH_ERROR)
 10050  	if len(data) < 2 {
 10051  		return nil, NewMessageError(eCode, eSubCode, data, "attribute header length is short")
 10052  	}
 10053  	p.Flags = BGPAttrFlag(data[0])
 10054  	p.Type = BGPAttrType(data[1])
 10055  
 10056  	if p.Flags&BGP_ATTR_FLAG_EXTENDED_LENGTH != 0 {
 10057  		if len(data) < 4 {
 10058  			return nil, NewMessageError(eCode, eSubCode, data, "attribute header length is short")
 10059  		}
 10060  		p.Length = binary.BigEndian.Uint16(data[2:4])
 10061  		data = data[4:]
 10062  	} else {
 10063  		if len(data) < 3 {
 10064  			return nil, NewMessageError(eCode, eSubCode, data, "attribute header length is short")
 10065  		}
 10066  		p.Length = uint16(data[2])
 10067  		data = data[3:]
 10068  	}
 10069  	if len(data) < int(p.Length) {
 10070  		return nil, NewMessageError(eCode, eSubCode, data, "attribute value length is short")
 10071  	}
 10072  
 10073  	if eMsg := validatePathAttributeFlags(p.Type, p.Flags); eMsg != "" {
 10074  		return nil, NewMessageError(eCode, BGP_ERROR_SUB_ATTRIBUTE_FLAGS_ERROR, data, eMsg)
 10075  	}
 10076  
 10077  	return data[:p.Length], nil
 10078  }
 10079  
 10080  func (p *PathAttribute) Serialize(value []byte, options ...*MarshallingOption) ([]byte, error) {
 10081  	// Note: Do not update "p.Flags" and "p.Length" to avoid data race.
 10082  	flags := p.Flags
 10083  	length := uint16(len(value))
 10084  	if flags&BGP_ATTR_FLAG_EXTENDED_LENGTH == 0 && length > 255 {
 10085  		flags |= BGP_ATTR_FLAG_EXTENDED_LENGTH
 10086  	}
 10087  	var buf []byte
 10088  	if flags&BGP_ATTR_FLAG_EXTENDED_LENGTH != 0 {
 10089  		buf = append(make([]byte, 4), value...)
 10090  		binary.BigEndian.PutUint16(buf[2:4], length)
 10091  	} else {
 10092  		buf = append(make([]byte, 3), value...)
 10093  		buf[2] = byte(length)
 10094  	}
 10095  	buf[0] = uint8(flags)
 10096  	buf[1] = uint8(p.Type)
 10097  	return buf, nil
 10098  }
 10099  
 10100  type PathAttributeOrigin struct {
 10101  	PathAttribute
 10102  	Value uint8
 10103  }
 10104  
 10105  func (p *PathAttributeOrigin) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
 10106  	value, err := p.PathAttribute.DecodeFromBytes(data, options...)
 10107  	if err != nil {
 10108  		return err
 10109  	}
 10110  	if p.Length != 1 {
 10111  		eCode := uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR)
 10112  		eSubCode := uint8(BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST)
 10113  		return NewMessageError(eCode, eSubCode, nil, "Origin attribute length is incorrect")
 10114  	}
 10115  	p.Value = value[0]
 10116  	return nil
 10117  }
 10118  
 10119  func (p *PathAttributeOrigin) Serialize(options ...*MarshallingOption) ([]byte, error) {
 10120  	return p.PathAttribute.Serialize([]byte{p.Value}, options...)
 10121  }
 10122  
 10123  func (p *PathAttributeOrigin) String() string {
 10124  	typ := "-"
 10125  	switch p.Value {
 10126  	case BGP_ORIGIN_ATTR_TYPE_IGP:
 10127  		typ = "i"
 10128  	case BGP_ORIGIN_ATTR_TYPE_EGP:
 10129  		typ = "e"
 10130  	case BGP_ORIGIN_ATTR_TYPE_INCOMPLETE:
 10131  		typ = "?"
 10132  	}
 10133  	return "{Origin: " + typ + "}"
 10134  }
 10135  
 10136  func (p *PathAttributeOrigin) MarshalJSON() ([]byte, error) {
 10137  	return json.Marshal(struct {
 10138  		Type  BGPAttrType `json:"type"`
 10139  		Value uint8       `json:"value"`
 10140  	}{
 10141  		Type:  p.GetType(),
 10142  		Value: p.Value,
 10143  	})
 10144  }
 10145  
 10146  func NewPathAttributeOrigin(value uint8) *PathAttributeOrigin {
 10147  	t := BGP_ATTR_TYPE_ORIGIN
 10148  	return &PathAttributeOrigin{
 10149  		PathAttribute: PathAttribute{
 10150  			Flags:  PathAttrFlags[t],
 10151  			Type:   t,
 10152  			Length: 1,
 10153  		},
 10154  		Value: value,
 10155  	}
 10156  }
 10157  
 10158  type AsPathParamFormat struct {
 10159  	start     string
 10160  	end       string
 10161  	separator string
 10162  }
 10163  
 10164  var asPathParamFormatMap = map[uint8]*AsPathParamFormat{
 10165  	BGP_ASPATH_ATTR_TYPE_SET:        {"{", "}", ","},
 10166  	BGP_ASPATH_ATTR_TYPE_SEQ:        {"", "", " "},
 10167  	BGP_ASPATH_ATTR_TYPE_CONFED_SET: {"(", ")", " "},
 10168  	BGP_ASPATH_ATTR_TYPE_CONFED_SEQ: {"[", "]", ","},
 10169  }
 10170  
 10171  type AsPathParamInterface interface {
 10172  	GetType() uint8
 10173  	GetAS() []uint32
 10174  	Serialize() ([]byte, error)
 10175  	DecodeFromBytes([]byte) error
 10176  	Len() int
 10177  	ASLen() int
 10178  	MarshalJSON() ([]byte, error)
 10179  	String() string
 10180  }
 10181  
 10182  func AsPathString(aspath *PathAttributeAsPath) string {
 10183  	s := bytes.NewBuffer(make([]byte, 0, 64))
 10184  	for i, param := range aspath.Value {
 10185  		segType := param.GetType()
 10186  		asList := param.GetAS()
 10187  		if i != 0 {
 10188  			s.WriteString(" ")
 10189  		}
 10190  
 10191  		sep := " "
 10192  		switch segType {
 10193  		case BGP_ASPATH_ATTR_TYPE_CONFED_SEQ:
 10194  			s.WriteString("(")
 10195  		case BGP_ASPATH_ATTR_TYPE_CONFED_SET:
 10196  			s.WriteString("[")
 10197  			sep = ","
 10198  		case BGP_ASPATH_ATTR_TYPE_SET:
 10199  			s.WriteString("{")
 10200  			sep = ","
 10201  		}
 10202  		for j, as := range asList {
 10203  			s.WriteString(fmt.Sprintf("%d", as))
 10204  			if j != len(asList)-1 {
 10205  				s.WriteString(sep)
 10206  			}
 10207  		}
 10208  		switch segType {
 10209  		case BGP_ASPATH_ATTR_TYPE_CONFED_SEQ:
 10210  			s.WriteString(")")
 10211  		case BGP_ASPATH_ATTR_TYPE_CONFED_SET:
 10212  			s.WriteString("]")
 10213  		case BGP_ASPATH_ATTR_TYPE_SET:
 10214  			s.WriteString("}")
 10215  		}
 10216  	}
 10217  	return s.String()
 10218  }
 10219  
 10220  type AsPathParam struct {
 10221  	Type uint8
 10222  	Num  uint8
 10223  	AS   []uint16
 10224  }
 10225  
 10226  func (a *AsPathParam) GetType() uint8 {
 10227  	return a.Type
 10228  }
 10229  
 10230  func (a *AsPathParam) GetAS() []uint32 {
 10231  	nums := make([]uint32, 0, len(a.AS))
 10232  	for _, as := range a.AS {
 10233  		nums = append(nums, uint32(as))
 10234  	}
 10235  	return nums
 10236  }
 10237  
 10238  func (a *AsPathParam) Serialize() ([]byte, error) {
 10239  	buf := make([]byte, 2+len(a.AS)*2)
 10240  	buf[0] = uint8(a.Type)
 10241  	buf[1] = a.Num
 10242  	for j, as := range a.AS {
 10243  		binary.BigEndian.PutUint16(buf[2+j*2:], as)
 10244  	}
 10245  	return buf, nil
 10246  }
 10247  
 10248  func (a *AsPathParam) DecodeFromBytes(data []byte) error {
 10249  	eCode := uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR)
 10250  	eSubCode := uint8(BGP_ERROR_SUB_MALFORMED_AS_PATH)
 10251  	if len(data) < 2 {
 10252  		return NewMessageError(eCode, eSubCode, nil, "AS param header length is short")
 10253  	}
 10254  	a.Type = data[0]
 10255  	a.Num = data[1]
 10256  	data = data[2:]
 10257  	if len(data) < int(a.Num*2) {
 10258  		return NewMessageError(eCode, eSubCode, nil, "AS param data length is short")
 10259  	}
 10260  	for i := 0; i < int(a.Num); i++ {
 10261  		a.AS = append(a.AS, binary.BigEndian.Uint16(data))
 10262  		data = data[2:]
 10263  	}
 10264  	return nil
 10265  }
 10266  
 10267  func (a *AsPathParam) Len() int {
 10268  	return 2 + len(a.AS)*2
 10269  }
 10270  
 10271  func (a *AsPathParam) ASLen() int {
 10272  	switch a.Type {
 10273  	case BGP_ASPATH_ATTR_TYPE_SEQ:
 10274  		return len(a.AS)
 10275  	case BGP_ASPATH_ATTR_TYPE_SET:
 10276  		return 1
 10277  	case BGP_ASPATH_ATTR_TYPE_CONFED_SET, BGP_ASPATH_ATTR_TYPE_CONFED_SEQ:
 10278  		return 0
 10279  	}
 10280  	return 0
 10281  }
 10282  
 10283  func (a *AsPathParam) String() string {
 10284  	format, ok := asPathParamFormatMap[a.Type]
 10285  	if !ok {
 10286  		return fmt.Sprintf("%v", a.AS)
 10287  	}
 10288  	aspath := make([]string, 0, len(a.AS))
 10289  	for _, asn := range a.AS {
 10290  		aspath = append(aspath, strconv.FormatUint(uint64(asn), 10))
 10291  	}
 10292  	s := bytes.NewBuffer(make([]byte, 0, 32))
 10293  	s.WriteString(format.start)
 10294  	s.WriteString(strings.Join(aspath, format.separator))
 10295  	s.WriteString(format.end)
 10296  	return s.String()
 10297  }
 10298  
 10299  func (a *AsPathParam) MarshalJSON() ([]byte, error) {
 10300  	return json.Marshal(struct {
 10301  		Type uint8    `json:"segment_type"`
 10302  		Num  uint8    `json:"num"`
 10303  		AS   []uint16 `json:"asns"`
 10304  	}{
 10305  		Type: a.Type,
 10306  		Num:  a.Num,
 10307  		AS:   a.AS,
 10308  	})
 10309  }
 10310  
 10311  func NewAsPathParam(segType uint8, as []uint16) *AsPathParam {
 10312  	return &AsPathParam{
 10313  		Type: segType,
 10314  		Num:  uint8(len(as)),
 10315  		AS:   as,
 10316  	}
 10317  }
 10318  
 10319  type As4PathParam struct {
 10320  	Type uint8
 10321  	Num  uint8
 10322  	AS   []uint32
 10323  }
 10324  
 10325  func (a *As4PathParam) GetType() uint8 {
 10326  	return a.Type
 10327  }
 10328  
 10329  func (a *As4PathParam) GetAS() []uint32 {
 10330  	return a.AS
 10331  }
 10332  
 10333  func (a *As4PathParam) Serialize() ([]byte, error) {
 10334  	buf := make([]byte, 2+len(a.AS)*4)
 10335  	buf[0] = a.Type
 10336  	buf[1] = a.Num
 10337  	for j, as := range a.AS {
 10338  		binary.BigEndian.PutUint32(buf[2+j*4:], as)
 10339  	}
 10340  	return buf, nil
 10341  }
 10342  
 10343  func (a *As4PathParam) DecodeFromBytes(data []byte) error {
 10344  	eCode := uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR)
 10345  	eSubCode := uint8(BGP_ERROR_SUB_MALFORMED_AS_PATH)
 10346  	if len(data) < 2 {
 10347  		return NewMessageError(eCode, eSubCode, nil, "AS4 param header length is short")
 10348  	}
 10349  	a.Type = data[0]
 10350  	a.Num = data[1]
 10351  	data = data[2:]
 10352  	if len(data) < int(a.Num)*4 {
 10353  		return NewMessageError(eCode, eSubCode, nil, "AS4 param data length is short")
 10354  	}
 10355  	for i := 0; i < int(a.Num); i++ {
 10356  		a.AS = append(a.AS, binary.BigEndian.Uint32(data))
 10357  		data = data[4:]
 10358  	}
 10359  	return nil
 10360  }
 10361  
 10362  func (a *As4PathParam) Len() int {
 10363  	return 2 + len(a.AS)*4
 10364  }
 10365  
 10366  func (a *As4PathParam) ASLen() int {
 10367  	switch a.Type {
 10368  	case BGP_ASPATH_ATTR_TYPE_SEQ:
 10369  		return len(a.AS)
 10370  	case BGP_ASPATH_ATTR_TYPE_SET:
 10371  		return 1
 10372  	case BGP_ASPATH_ATTR_TYPE_CONFED_SET, BGP_ASPATH_ATTR_TYPE_CONFED_SEQ:
 10373  		return 0
 10374  	}
 10375  	return 0
 10376  }
 10377  
 10378  func (a *As4PathParam) String() string {
 10379  	format, ok := asPathParamFormatMap[a.Type]
 10380  	if !ok {
 10381  		return fmt.Sprintf("%v", a.AS)
 10382  	}
 10383  	aspath := make([]string, 0, len(a.AS))
 10384  	for _, asn := range a.AS {
 10385  		aspath = append(aspath, strconv.FormatUint(uint64(asn), 10))
 10386  	}
 10387  	s := bytes.NewBuffer(make([]byte, 0, 32))
 10388  	s.WriteString(format.start)
 10389  	s.WriteString(strings.Join(aspath, format.separator))
 10390  	s.WriteString(format.end)
 10391  	return s.String()
 10392  }
 10393  
 10394  func (a *As4PathParam) MarshalJSON() ([]byte, error) {
 10395  	return json.Marshal(struct {
 10396  		Type uint8    `json:"segment_type"`
 10397  		Num  uint8    `json:"num"`
 10398  		AS   []uint32 `json:"asns"`
 10399  	}{
 10400  		Type: a.Type,
 10401  		Num:  a.Num,
 10402  		AS:   a.AS,
 10403  	})
 10404  }
 10405  
 10406  func NewAs4PathParam(segType uint8, as []uint32) *As4PathParam {
 10407  	return &As4PathParam{
 10408  		Type: segType,
 10409  		Num:  uint8(len(as)),
 10410  		AS:   as,
 10411  	}
 10412  }
 10413  
 10414  type PathAttributeAsPath struct {
 10415  	PathAttribute
 10416  	Value []AsPathParamInterface
 10417  }
 10418  
 10419  func (p *PathAttributeAsPath) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
 10420  	value, err := p.PathAttribute.DecodeFromBytes(data, options...)
 10421  	if err != nil {
 10422  		return err
 10423  	}
 10424  	if p.Length == 0 {
 10425  		// ibgp or something
 10426  		return nil
 10427  	}
 10428  	isAs4, err := validateAsPathValueBytes(value)
 10429  	if err != nil {
 10430  		err.(*MessageError).Data, _ = p.PathAttribute.Serialize(value, options...)
 10431  		return err
 10432  	}
 10433  	for len(value) > 0 {
 10434  		var tuple AsPathParamInterface
 10435  		if isAs4 {
 10436  			tuple = &As4PathParam{}
 10437  		} else {
 10438  			tuple = &AsPathParam{}
 10439  		}
 10440  		err := tuple.DecodeFromBytes(value)
 10441  		if err != nil {
 10442  			return err
 10443  		}
 10444  		p.Value = append(p.Value, tuple)
 10445  		value = value[tuple.Len():]
 10446  	}
 10447  	return nil
 10448  }
 10449  
 10450  func (p *PathAttributeAsPath) Serialize(options ...*MarshallingOption) ([]byte, error) {
 10451  	buf := make([]byte, 0)
 10452  	for _, v := range p.Value {
 10453  		vbuf, err := v.Serialize()
 10454  		if err != nil {
 10455  			return nil, err
 10456  		}
 10457  		buf = append(buf, vbuf...)
 10458  	}
 10459  	return p.PathAttribute.Serialize(buf, options...)
 10460  }
 10461  
 10462  func (p *PathAttributeAsPath) String() string {
 10463  	params := make([]string, 0, len(p.Value))
 10464  	for _, param := range p.Value {
 10465  		params = append(params, param.String())
 10466  	}
 10467  	return "{AsPath: " + strings.Join(params, " ") + "}"
 10468  }
 10469  
 10470  func (p *PathAttributeAsPath) MarshalJSON() ([]byte, error) {
 10471  	return json.Marshal(struct {
 10472  		Type  BGPAttrType            `json:"type"`
 10473  		Value []AsPathParamInterface `json:"as_paths"`
 10474  	}{
 10475  		Type:  p.GetType(),
 10476  		Value: p.Value,
 10477  	})
 10478  }
 10479  
 10480  func NewPathAttributeAsPath(value []AsPathParamInterface) *PathAttributeAsPath {
 10481  	var l int
 10482  	for _, v := range value {
 10483  		l += v.Len()
 10484  	}
 10485  	t := BGP_ATTR_TYPE_AS_PATH
 10486  	return &PathAttributeAsPath{
 10487  		PathAttribute: PathAttribute{
 10488  			Flags:  getPathAttrFlags(t, l),
 10489  			Type:   t,
 10490  			Length: uint16(l),
 10491  		},
 10492  		Value: value,
 10493  	}
 10494  }
 10495  
 10496  type PathAttributeNextHop struct {
 10497  	PathAttribute
 10498  	Value net.IP
 10499  }
 10500  
 10501  func (p *PathAttributeNextHop) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
 10502  	value, err := p.PathAttribute.DecodeFromBytes(data, options...)
 10503  	if err != nil {
 10504  		return err
 10505  	}
 10506  	if p.Length != 4 && p.Length != 16 {
 10507  		eCode := uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR)
 10508  		eSubCode := uint8(BGP_ERROR_SUB_ATTRIBUTE_LENGTH_ERROR)
 10509  		return NewMessageError(eCode, eSubCode, nil, "nexthop length isn't correct")
 10510  	}
 10511  	p.Value = value
 10512  	return nil
 10513  }
 10514  
 10515  func (p *PathAttributeNextHop) Serialize(options ...*MarshallingOption) ([]byte, error) {
 10516  	return p.PathAttribute.Serialize(p.Value, options...)
 10517  }
 10518  
 10519  func (p *PathAttributeNextHop) String() string {
 10520  	return "{Nexthop: " + p.Value.String() + "}"
 10521  }
 10522  
 10523  func (p *PathAttributeNextHop) MarshalJSON() ([]byte, error) {
 10524  	value := "0.0.0.0"
 10525  	if p.Value != nil {
 10526  		value = p.Value.String()
 10527  	}
 10528  	return json.Marshal(struct {
 10529  		Type  BGPAttrType `json:"type"`
 10530  		Value string      `json:"nexthop"`
 10531  	}{
 10532  		Type:  p.GetType(),
 10533  		Value: value,
 10534  	})
 10535  }
 10536  
 10537  func NewPathAttributeNextHop(addr string) *PathAttributeNextHop {
 10538  	t := BGP_ATTR_TYPE_NEXT_HOP
 10539  	ip := net.ParseIP(addr)
 10540  	l := net.IPv4len
 10541  	if ip.To4() == nil {
 10542  		l = net.IPv6len
 10543  	} else {
 10544  		ip = ip.To4()
 10545  	}
 10546  	return &PathAttributeNextHop{
 10547  		PathAttribute: PathAttribute{
 10548  			Flags:  PathAttrFlags[t],
 10549  			Type:   t,
 10550  			Length: uint16(l),
 10551  		},
 10552  		Value: ip,
 10553  	}
 10554  }
 10555  
 10556  type PathAttributeMultiExitDisc struct {
 10557  	PathAttribute
 10558  	Value uint32
 10559  }
 10560  
 10561  func (p *PathAttributeMultiExitDisc) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
 10562  	value, err := p.PathAttribute.DecodeFromBytes(data, options...)
 10563  	if err != nil {
 10564  		return err
 10565  	}
 10566  	if p.Length != 4 {
 10567  		eCode := uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR)
 10568  		eSubCode := uint8(BGP_ERROR_SUB_ATTRIBUTE_LENGTH_ERROR)
 10569  		return NewMessageError(eCode, eSubCode, nil, "med length isn't correct")
 10570  	}
 10571  	p.Value = binary.BigEndian.Uint32(value)
 10572  	return nil
 10573  }
 10574  
 10575  func (p *PathAttributeMultiExitDisc) Serialize(options ...*MarshallingOption) ([]byte, error) {
 10576  	var buf [4]byte
 10577  	binary.BigEndian.PutUint32(buf[:], p.Value)
 10578  	return p.PathAttribute.Serialize(buf[:], options...)
 10579  }
 10580  
 10581  func (p *PathAttributeMultiExitDisc) String() string {
 10582  	return "{Med: " + strconv.FormatUint(uint64(p.Value), 10) + "}"
 10583  }
 10584  
 10585  func (p *PathAttributeMultiExitDisc) MarshalJSON() ([]byte, error) {
 10586  	return json.Marshal(struct {
 10587  		Type  BGPAttrType `json:"type"`
 10588  		Value uint32      `json:"metric"`
 10589  	}{
 10590  		Type:  p.GetType(),
 10591  		Value: p.Value,
 10592  	})
 10593  }
 10594  
 10595  func NewPathAttributeMultiExitDisc(value uint32) *PathAttributeMultiExitDisc {
 10596  	t := BGP_ATTR_TYPE_MULTI_EXIT_DISC
 10597  	return &PathAttributeMultiExitDisc{
 10598  		PathAttribute: PathAttribute{
 10599  			Flags:  PathAttrFlags[t],
 10600  			Type:   t,
 10601  			Length: 4,
 10602  		},
 10603  		Value: value,
 10604  	}
 10605  }
 10606  
 10607  type PathAttributeLocalPref struct {
 10608  	PathAttribute
 10609  	Value uint32
 10610  }
 10611  
 10612  func (p *PathAttributeLocalPref) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
 10613  	value, err := p.PathAttribute.DecodeFromBytes(data, options...)
 10614  	if err != nil {
 10615  		return err
 10616  	}
 10617  	if p.Length != 4 {
 10618  		eCode := uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR)
 10619  		eSubCode := uint8(BGP_ERROR_SUB_ATTRIBUTE_LENGTH_ERROR)
 10620  		return NewMessageError(eCode, eSubCode, nil, "local pref length isn't correct")
 10621  	}
 10622  	p.Value = binary.BigEndian.Uint32(value)
 10623  	return nil
 10624  }
 10625  
 10626  func (p *PathAttributeLocalPref) Serialize(options ...*MarshallingOption) ([]byte, error) {
 10627  	var buf [4]byte
 10628  	binary.BigEndian.PutUint32(buf[:], p.Value)
 10629  	return p.PathAttribute.Serialize(buf[:], options...)
 10630  }
 10631  
 10632  func (p *PathAttributeLocalPref) String() string {
 10633  	return "{LocalPref: " + strconv.FormatUint(uint64(p.Value), 10) + "}"
 10634  }
 10635  
 10636  func (p *PathAttributeLocalPref) MarshalJSON() ([]byte, error) {
 10637  	return json.Marshal(struct {
 10638  		Type  BGPAttrType `json:"type"`
 10639  		Value uint32      `json:"value"`
 10640  	}{
 10641  		Type:  p.GetType(),
 10642  		Value: p.Value,
 10643  	})
 10644  }
 10645  
 10646  func NewPathAttributeLocalPref(value uint32) *PathAttributeLocalPref {
 10647  	t := BGP_ATTR_TYPE_LOCAL_PREF
 10648  	return &PathAttributeLocalPref{
 10649  		PathAttribute: PathAttribute{
 10650  			Flags:  PathAttrFlags[t],
 10651  			Type:   t,
 10652  			Length: 4,
 10653  		},
 10654  		Value: value,
 10655  	}
 10656  }
 10657  
 10658  type PathAttributeAtomicAggregate struct {
 10659  	PathAttribute
 10660  }
 10661  
 10662  func (p *PathAttributeAtomicAggregate) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
 10663  	_, err := p.PathAttribute.DecodeFromBytes(data, options...)
 10664  	if err != nil {
 10665  		return err
 10666  	}
 10667  	if p.Length != 0 {
 10668  		eCode := uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR)
 10669  		eSubCode := uint8(BGP_ERROR_SUB_ATTRIBUTE_LENGTH_ERROR)
 10670  		return NewMessageError(eCode, eSubCode, nil, "atomic aggregate should have no value")
 10671  	}
 10672  	return nil
 10673  }
 10674  
 10675  func (p *PathAttributeAtomicAggregate) Serialize(options ...*MarshallingOption) ([]byte, error) {
 10676  	return p.PathAttribute.Serialize(nil, options...)
 10677  }
 10678  
 10679  func (p *PathAttributeAtomicAggregate) String() string {
 10680  	return "{AtomicAggregate}"
 10681  }
 10682  
 10683  func (p *PathAttributeAtomicAggregate) MarshalJSON() ([]byte, error) {
 10684  	return json.Marshal(struct {
 10685  		Type BGPAttrType `json:"type"`
 10686  	}{
 10687  		Type: p.GetType(),
 10688  	})
 10689  }
 10690  
 10691  func NewPathAttributeAtomicAggregate() *PathAttributeAtomicAggregate {
 10692  	t := BGP_ATTR_TYPE_ATOMIC_AGGREGATE
 10693  	return &PathAttributeAtomicAggregate{
 10694  		PathAttribute: PathAttribute{
 10695  			Flags:  PathAttrFlags[t],
 10696  			Type:   t,
 10697  			Length: 0,
 10698  		},
 10699  	}
 10700  }
 10701  
 10702  type PathAttributeAggregatorParam struct {
 10703  	AS      uint32
 10704  	Askind  reflect.Kind
 10705  	Address net.IP
 10706  }
 10707  
 10708  type PathAttributeAggregator struct {
 10709  	PathAttribute
 10710  	Value PathAttributeAggregatorParam
 10711  }
 10712  
 10713  func (p *PathAttributeAggregator) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
 10714  	value, err := p.PathAttribute.DecodeFromBytes(data, options...)
 10715  	if err != nil {
 10716  		return err
 10717  	}
 10718  	switch p.Length {
 10719  	case 6:
 10720  		p.Value.Askind = reflect.Uint16
 10721  		p.Value.AS = uint32(binary.BigEndian.Uint16(value[0:2]))
 10722  		p.Value.Address = value[2:]
 10723  	case 8:
 10724  		p.Value.Askind = reflect.Uint32
 10725  		p.Value.AS = binary.BigEndian.Uint32(value[0:4])
 10726  		p.Value.Address = value[4:]
 10727  	default:
 10728  		eCode := uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR)
 10729  		eSubCode := uint8(BGP_ERROR_SUB_ATTRIBUTE_LENGTH_ERROR)
 10730  		return NewMessageError(eCode, eSubCode, nil, "aggregator length isn't correct")
 10731  	}
 10732  	return nil
 10733  }
 10734  
 10735  func (p *PathAttributeAggregator) Serialize(options ...*MarshallingOption) ([]byte, error) {
 10736  	var buf []byte
 10737  	switch p.Value.Askind {
 10738  	case reflect.Uint16:
 10739  		buf = make([]byte, 6)
 10740  		binary.BigEndian.PutUint16(buf, uint16(p.Value.AS))
 10741  		copy(buf[2:], p.Value.Address)
 10742  	case reflect.Uint32:
 10743  		buf = make([]byte, 8)
 10744  		binary.BigEndian.PutUint32(buf, p.Value.AS)
 10745  		copy(buf[4:], p.Value.Address)
 10746  	}
 10747  	return p.PathAttribute.Serialize(buf, options...)
 10748  }
 10749  
 10750  func (p *PathAttributeAggregator) String() string {
 10751  	return "{Aggregate: {AS: " + strconv.FormatUint(uint64(p.Value.AS), 10) +
 10752  		", Address: " + p.Value.Address.String() + "}}"
 10753  }
 10754  
 10755  func (p *PathAttributeAggregator) MarshalJSON() ([]byte, error) {
 10756  	return json.Marshal(struct {
 10757  		Type    BGPAttrType `json:"type"`
 10758  		AS      uint32      `json:"as"`
 10759  		Address string      `json:"address"`
 10760  	}{
 10761  		Type:    p.GetType(),
 10762  		AS:      p.Value.AS,
 10763  		Address: p.Value.Address.String(),
 10764  	})
 10765  }
 10766  
 10767  func NewPathAttributeAggregator(as interface{}, address string) *PathAttributeAggregator {
 10768  	v := reflect.ValueOf(as)
 10769  	asKind := v.Kind()
 10770  	var l uint16
 10771  	switch asKind {
 10772  	case reflect.Uint16:
 10773  		l = 6
 10774  	case reflect.Uint32:
 10775  		l = 8
 10776  	default:
 10777  		// Invalid type
 10778  		return nil
 10779  	}
 10780  	t := BGP_ATTR_TYPE_AGGREGATOR
 10781  	return &PathAttributeAggregator{
 10782  		PathAttribute: PathAttribute{
 10783  			Flags:  PathAttrFlags[t],
 10784  			Type:   t,
 10785  			Length: l,
 10786  		},
 10787  		Value: PathAttributeAggregatorParam{
 10788  			AS:      uint32(v.Uint()),
 10789  			Askind:  asKind,
 10790  			Address: net.ParseIP(address).To4(),
 10791  		},
 10792  	}
 10793  }
 10794  
 10795  type PathAttributeCommunities struct {
 10796  	PathAttribute
 10797  	Value []uint32
 10798  }
 10799  
 10800  func (p *PathAttributeCommunities) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
 10801  	value, err := p.PathAttribute.DecodeFromBytes(data, options...)
 10802  	if err != nil {
 10803  		return err
 10804  	}
 10805  	if p.Length%4 != 0 {
 10806  		eCode := uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR)
 10807  		eSubCode := uint8(BGP_ERROR_SUB_ATTRIBUTE_LENGTH_ERROR)
 10808  		return NewMessageError(eCode, eSubCode, nil, "communities length isn't correct")
 10809  	}
 10810  	for len(value) >= 4 {
 10811  		p.Value = append(p.Value, binary.BigEndian.Uint32(value))
 10812  		value = value[4:]
 10813  	}
 10814  	return nil
 10815  }
 10816  
 10817  func (p *PathAttributeCommunities) Serialize(options ...*MarshallingOption) ([]byte, error) {
 10818  	buf := make([]byte, len(p.Value)*4)
 10819  	for i, v := range p.Value {
 10820  		binary.BigEndian.PutUint32(buf[i*4:], v)
 10821  	}
 10822  	return p.PathAttribute.Serialize(buf, options...)
 10823  }
 10824  
 10825  type WellKnownCommunity uint32
 10826  
 10827  const (
 10828  	COMMUNITY_INTERNET                   WellKnownCommunity = 0x00000000
 10829  	COMMUNITY_PLANNED_SHUT               WellKnownCommunity = 0xffff0000
 10830  	COMMUNITY_ACCEPT_OWN                 WellKnownCommunity = 0xffff0001
 10831  	COMMUNITY_ROUTE_FILTER_TRANSLATED_v4 WellKnownCommunity = 0xffff0002
 10832  	COMMUNITY_ROUTE_FILTER_v4            WellKnownCommunity = 0xffff0003
 10833  	COMMUNITY_ROUTE_FILTER_TRANSLATED_v6 WellKnownCommunity = 0xffff0004
 10834  	COMMUNITY_ROUTE_FILTER_v6            WellKnownCommunity = 0xffff0005
 10835  	COMMUNITY_LLGR_STALE                 WellKnownCommunity = 0xffff0006
 10836  	COMMUNITY_NO_LLGR                    WellKnownCommunity = 0xffff0007
 10837  	COMMUNITY_BLACKHOLE                  WellKnownCommunity = 0xffff029a
 10838  	COMMUNITY_NO_EXPORT                  WellKnownCommunity = 0xffffff01
 10839  	COMMUNITY_NO_ADVERTISE               WellKnownCommunity = 0xffffff02
 10840  	COMMUNITY_NO_EXPORT_SUBCONFED        WellKnownCommunity = 0xffffff03
 10841  	COMMUNITY_NO_PEER                    WellKnownCommunity = 0xffffff04
 10842  )
 10843  
 10844  var WellKnownCommunityNameMap = map[WellKnownCommunity]string{
 10845  	COMMUNITY_INTERNET:                   "internet",
 10846  	COMMUNITY_PLANNED_SHUT:               "planned-shut",
 10847  	COMMUNITY_ACCEPT_OWN:                 "accept-own",
 10848  	COMMUNITY_ROUTE_FILTER_TRANSLATED_v4: "route-filter-translated-v4",
 10849  	COMMUNITY_ROUTE_FILTER_v4:            "route-filter-v4",
 10850  	COMMUNITY_ROUTE_FILTER_TRANSLATED_v6: "route-filter-translated-v6",
 10851  	COMMUNITY_ROUTE_FILTER_v6:            "route-filter-v6",
 10852  	COMMUNITY_LLGR_STALE:                 "llgr-stale",
 10853  	COMMUNITY_NO_LLGR:                    "no-llgr",
 10854  	COMMUNITY_BLACKHOLE:                  "blackhole",
 10855  	COMMUNITY_NO_EXPORT:                  "no-export",
 10856  	COMMUNITY_NO_ADVERTISE:               "no-advertise",
 10857  	COMMUNITY_NO_EXPORT_SUBCONFED:        "no-export-subconfed",
 10858  	COMMUNITY_NO_PEER:                    "no-peer",
 10859  }
 10860  
 10861  var WellKnownCommunityValueMap = map[string]WellKnownCommunity{
 10862  	WellKnownCommunityNameMap[COMMUNITY_INTERNET]:                   COMMUNITY_INTERNET,
 10863  	WellKnownCommunityNameMap[COMMUNITY_PLANNED_SHUT]:               COMMUNITY_PLANNED_SHUT,
 10864  	WellKnownCommunityNameMap[COMMUNITY_ACCEPT_OWN]:                 COMMUNITY_ACCEPT_OWN,
 10865  	WellKnownCommunityNameMap[COMMUNITY_ROUTE_FILTER_TRANSLATED_v4]: COMMUNITY_ROUTE_FILTER_TRANSLATED_v4,
 10866  	WellKnownCommunityNameMap[COMMUNITY_ROUTE_FILTER_v4]:            COMMUNITY_ROUTE_FILTER_v4,
 10867  	WellKnownCommunityNameMap[COMMUNITY_ROUTE_FILTER_TRANSLATED_v6]: COMMUNITY_ROUTE_FILTER_TRANSLATED_v6,
 10868  	WellKnownCommunityNameMap[COMMUNITY_ROUTE_FILTER_v6]:            COMMUNITY_ROUTE_FILTER_v6,
 10869  	WellKnownCommunityNameMap[COMMUNITY_LLGR_STALE]:                 COMMUNITY_LLGR_STALE,
 10870  	WellKnownCommunityNameMap[COMMUNITY_NO_LLGR]:                    COMMUNITY_NO_LLGR,
 10871  	WellKnownCommunityNameMap[COMMUNITY_NO_EXPORT]:                  COMMUNITY_NO_EXPORT,
 10872  	WellKnownCommunityNameMap[COMMUNITY_BLACKHOLE]:                  COMMUNITY_BLACKHOLE,
 10873  	WellKnownCommunityNameMap[COMMUNITY_NO_ADVERTISE]:               COMMUNITY_NO_ADVERTISE,
 10874  	WellKnownCommunityNameMap[COMMUNITY_NO_EXPORT_SUBCONFED]:        COMMUNITY_NO_EXPORT_SUBCONFED,
 10875  	WellKnownCommunityNameMap[COMMUNITY_NO_PEER]:                    COMMUNITY_NO_PEER,
 10876  }
 10877  
 10878  func (p *PathAttributeCommunities) String() string {
 10879  	l := make([]string, 0, len(p.Value))
 10880  	for _, v := range p.Value {
 10881  		n, ok := WellKnownCommunityNameMap[WellKnownCommunity(v)]
 10882  		if ok {
 10883  			l = append(l, n)
 10884  		} else {
 10885  			comm := strconv.FormatUint(uint64((0xffff0000&v)>>16), 10) + ":" + strconv.FormatUint(uint64(0xffff&v), 10)
 10886  			l = append(l, comm)
 10887  		}
 10888  	}
 10889  	return "{Communities: " + strings.Join(l, ", ") + "}"
 10890  }
 10891  
 10892  func (p *PathAttributeCommunities) MarshalJSON() ([]byte, error) {
 10893  	return json.Marshal(struct {
 10894  		Type  BGPAttrType `json:"type"`
 10895  		Value []uint32    `json:"communities"`
 10896  	}{
 10897  		Type:  p.GetType(),
 10898  		Value: p.Value,
 10899  	})
 10900  }
 10901  
 10902  func NewPathAttributeCommunities(value []uint32) *PathAttributeCommunities {
 10903  	l := len(value) * 4
 10904  	t := BGP_ATTR_TYPE_COMMUNITIES
 10905  	return &PathAttributeCommunities{
 10906  		PathAttribute: PathAttribute{
 10907  			Flags:  getPathAttrFlags(t, l),
 10908  			Type:   t,
 10909  			Length: uint16(l),
 10910  		},
 10911  		Value: value,
 10912  	}
 10913  }
 10914  
 10915  type PathAttributeOriginatorId struct {
 10916  	PathAttribute
 10917  	Value net.IP
 10918  }
 10919  
 10920  func (p *PathAttributeOriginatorId) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
 10921  	value, err := p.PathAttribute.DecodeFromBytes(data, options...)
 10922  	if err != nil {
 10923  		return err
 10924  	}
 10925  	if p.Length != 4 {
 10926  		eCode := uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR)
 10927  		eSubCode := uint8(BGP_ERROR_SUB_ATTRIBUTE_LENGTH_ERROR)
 10928  		return NewMessageError(eCode, eSubCode, nil, "originator id length isn't correct")
 10929  	}
 10930  	p.Value = value
 10931  	return nil
 10932  }
 10933  
 10934  func (p *PathAttributeOriginatorId) String() string {
 10935  	return "{Originator: " + p.Value.String() + "}"
 10936  }
 10937  
 10938  func (p *PathAttributeOriginatorId) MarshalJSON() ([]byte, error) {
 10939  	return json.Marshal(struct {
 10940  		Type  BGPAttrType `json:"type"`
 10941  		Value string      `json:"value"`
 10942  	}{
 10943  		Type:  p.GetType(),
 10944  		Value: p.Value.String(),
 10945  	})
 10946  }
 10947  
 10948  func (p *PathAttributeOriginatorId) Serialize(options ...*MarshallingOption) ([]byte, error) {
 10949  	var buf [4]byte
 10950  	copy(buf[:], p.Value)
 10951  	return p.PathAttribute.Serialize(buf[:], options...)
 10952  }
 10953  
 10954  func NewPathAttributeOriginatorId(value string) *PathAttributeOriginatorId {
 10955  	t := BGP_ATTR_TYPE_ORIGINATOR_ID
 10956  	return &PathAttributeOriginatorId{
 10957  		PathAttribute: PathAttribute{
 10958  			Flags:  PathAttrFlags[t],
 10959  			Type:   t,
 10960  			Length: 4,
 10961  		},
 10962  		Value: net.ParseIP(value).To4(),
 10963  	}
 10964  }
 10965  
 10966  type PathAttributeClusterList struct {
 10967  	PathAttribute
 10968  	Value []net.IP
 10969  }
 10970  
 10971  func (p *PathAttributeClusterList) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
 10972  	value, err := p.PathAttribute.DecodeFromBytes(data, options...)
 10973  	if err != nil {
 10974  		return err
 10975  	}
 10976  	if p.Length%4 != 0 {
 10977  		eCode := uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR)
 10978  		eSubCode := uint8(BGP_ERROR_SUB_ATTRIBUTE_LENGTH_ERROR)
 10979  		return NewMessageError(eCode, eSubCode, nil, "clusterlist length isn't correct")
 10980  	}
 10981  	for len(value) >= 4 {
 10982  		p.Value = append(p.Value, value[:4])
 10983  		value = value[4:]
 10984  	}
 10985  	return nil
 10986  }
 10987  
 10988  func (p *PathAttributeClusterList) Serialize(options ...*MarshallingOption) ([]byte, error) {
 10989  	buf := make([]byte, len(p.Value)*4)
 10990  	for i, v := range p.Value {
 10991  		copy(buf[i*4:], v)
 10992  	}
 10993  	return p.PathAttribute.Serialize(buf, options...)
 10994  }
 10995  
 10996  func (p *PathAttributeClusterList) String() string {
 10997  	return fmt.Sprintf("{ClusterList: %v}", p.Value)
 10998  }
 10999  
 11000  func (p *PathAttributeClusterList) MarshalJSON() ([]byte, error) {
 11001  	value := make([]string, 0, len(p.Value))
 11002  	for _, v := range p.Value {
 11003  		value = append(value, v.String())
 11004  	}
 11005  	return json.Marshal(struct {
 11006  		Type  BGPAttrType `json:"type"`
 11007  		Value []string    `json:"value"`
 11008  	}{
 11009  		Type:  p.GetType(),
 11010  		Value: value,
 11011  	})
 11012  }
 11013  
 11014  func NewPathAttributeClusterList(value []string) *PathAttributeClusterList {
 11015  	l := len(value) * 4
 11016  	list := make([]net.IP, len(value))
 11017  	for i, v := range value {
 11018  		list[i] = net.ParseIP(v).To4()
 11019  	}
 11020  	t := BGP_ATTR_TYPE_CLUSTER_LIST
 11021  	return &PathAttributeClusterList{
 11022  		PathAttribute: PathAttribute{
 11023  			Flags:  getPathAttrFlags(t, l),
 11024  			Type:   t,
 11025  			Length: uint16(l),
 11026  		},
 11027  		Value: list,
 11028  	}
 11029  }
 11030  
 11031  type PathAttributeMpReachNLRI struct {
 11032  	PathAttribute
 11033  	Nexthop          net.IP
 11034  	LinkLocalNexthop net.IP
 11035  	AFI              uint16
 11036  	SAFI             uint8
 11037  	Value            []AddrPrefixInterface
 11038  }
 11039  
 11040  func (p *PathAttributeMpReachNLRI) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
 11041  
 11042  	value, err := p.PathAttribute.DecodeFromBytes(data, options...)
 11043  	if err != nil {
 11044  		return err
 11045  	}
 11046  	eCode := uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR)
 11047  	eSubCode := uint8(BGP_ERROR_SUB_ATTRIBUTE_LENGTH_ERROR)
 11048  	eData, _ := p.PathAttribute.Serialize(value, options...)
 11049  	if p.Length < 3 {
 11050  		return NewMessageError(eCode, eSubCode, value, "mpreach header length is short")
 11051  	}
 11052  
 11053  	var afi uint16
 11054  	var safi uint8
 11055  
 11056  	// In MRT dumps, AFI+SAFI+NLRI is implicit based on RIB Entry Header, see RFC 6396 4.3.4
 11057  	implicitPrefix := GetImplicitPrefix(options)
 11058  	if implicitPrefix == nil {
 11059  		afi = binary.BigEndian.Uint16(value[0:2])
 11060  		safi = value[2]
 11061  
 11062  		value = value[3:]
 11063  	} else {
 11064  		afi = implicitPrefix.AFI()
 11065  		safi = implicitPrefix.SAFI()
 11066  
 11067  		p.Value = []AddrPrefixInterface{implicitPrefix}
 11068  	}
 11069  
 11070  	p.AFI = afi
 11071  	p.SAFI = safi
 11072  	_, err = NewPrefixFromRouteFamily(afi, safi)
 11073  	if err != nil {
 11074  		return NewMessageError(eCode, BGP_ERROR_SUB_INVALID_NETWORK_FIELD, eData, err.Error())
 11075  	}
 11076  	nexthoplen := int(value[0])
 11077  	if len(value) < 1+nexthoplen {
 11078  		return NewMessageError(eCode, eSubCode, value, "mpreach nexthop length is short")
 11079  	}
 11080  	nexthopbin := value[1 : 1+nexthoplen]
 11081  	if nexthoplen > 0 {
 11082  		v4addrlen := 4
 11083  		v6addrlen := 16
 11084  		offset := 0
 11085  		if safi == SAFI_MPLS_VPN {
 11086  			offset = 8
 11087  		}
 11088  		switch nexthoplen {
 11089  		case 2 * (offset + v6addrlen):
 11090  			p.LinkLocalNexthop = nexthopbin[offset+v6addrlen+offset : 2*(offset+v6addrlen)]
 11091  			fallthrough
 11092  		case offset + v6addrlen:
 11093  			p.Nexthop = nexthopbin[offset : offset+v6addrlen]
 11094  		case offset + v4addrlen:
 11095  			p.Nexthop = nexthopbin[offset : offset+v4addrlen]
 11096  		default:
 11097  			return NewMessageError(eCode, eSubCode, value, "mpreach nexthop length is incorrect")
 11098  		}
 11099  	}
 11100  
 11101  	// NLRI implicit for MRT dumps
 11102  	if implicitPrefix != nil {
 11103  		return nil
 11104  	}
 11105  
 11106  	value = value[1+nexthoplen:]
 11107  	// skip reserved
 11108  	if len(value) == 0 {
 11109  		return NewMessageError(eCode, eSubCode, value, "no skip byte")
 11110  	}
 11111  	value = value[1:]
 11112  	addpathLen := 0
 11113  	if IsAddPathEnabled(true, AfiSafiToRouteFamily(afi, safi), options) {
 11114  		addpathLen = 4
 11115  	}
 11116  	for len(value) > 0 {
 11117  		prefix, err := NewPrefixFromRouteFamily(afi, safi)
 11118  		if err != nil {
 11119  			return NewMessageError(eCode, BGP_ERROR_SUB_INVALID_NETWORK_FIELD, eData, err.Error())
 11120  		}
 11121  		err = prefix.DecodeFromBytes(value, options...)
 11122  		if err != nil {
 11123  			return err
 11124  		}
 11125  		if prefix.Len(options...)+addpathLen > len(value) {
 11126  			return NewMessageError(eCode, eSubCode, value, "prefix length is incorrect")
 11127  		}
 11128  		value = value[prefix.Len(options...)+addpathLen:]
 11129  		p.Value = append(p.Value, prefix)
 11130  	}
 11131  	return nil
 11132  }
 11133  
 11134  func (p *PathAttributeMpReachNLRI) Serialize(options ...*MarshallingOption) ([]byte, error) {
 11135  	afi := p.AFI
 11136  	safi := p.SAFI
 11137  	nexthoplen := 4
 11138  	if afi == AFI_IP6 || p.Nexthop.To4() == nil {
 11139  		nexthoplen = BGP_ATTR_NHLEN_IPV6_GLOBAL
 11140  	}
 11141  	offset := 0
 11142  	switch safi {
 11143  	case SAFI_MPLS_VPN:
 11144  		offset = 8
 11145  		nexthoplen += offset
 11146  	case SAFI_FLOW_SPEC_VPN, SAFI_FLOW_SPEC_UNICAST:
 11147  		nexthoplen = 0
 11148  	}
 11149  	if p.LinkLocalNexthop != nil && p.LinkLocalNexthop.IsLinkLocalUnicast() {
 11150  		nexthoplen = BGP_ATTR_NHLEN_IPV6_GLOBAL_AND_LL
 11151  	}
 11152  	var buf []byte
 11153  	includeNLRI := GetImplicitPrefix(options) == nil
 11154  	if includeNLRI {
 11155  		family := make([]byte, 3)
 11156  		binary.BigEndian.PutUint16(family[0:], afi)
 11157  		family[2] = safi
 11158  
 11159  		buf = append(buf, family...)
 11160  	}
 11161  	buf = append(buf, uint8(nexthoplen))
 11162  	if nexthoplen != 0 {
 11163  		nexthop := make([]byte, nexthoplen)
 11164  
 11165  		if p.Nexthop.To4() == nil {
 11166  			copy(nexthop[offset:], p.Nexthop.To16())
 11167  
 11168  			if nexthoplen == BGP_ATTR_NHLEN_IPV6_GLOBAL_AND_LL {
 11169  				copy(nexthop[offset+16:], p.LinkLocalNexthop.To16())
 11170  			}
 11171  		} else {
 11172  			copy(nexthop[offset:], p.Nexthop)
 11173  		}
 11174  
 11175  		buf = append(buf, nexthop...)
 11176  	}
 11177  	if includeNLRI {
 11178  		buf = append(buf, 0)
 11179  		for _, prefix := range p.Value {
 11180  			pbuf, err := prefix.Serialize(options...)
 11181  			if err != nil {
 11182  				return nil, err
 11183  			}
 11184  			buf = append(buf, pbuf...)
 11185  		}
 11186  	}
 11187  	return p.PathAttribute.Serialize(buf, options...)
 11188  }
 11189  
 11190  func (p *PathAttributeMpReachNLRI) MarshalJSON() ([]byte, error) {
 11191  	nexthop := p.Nexthop.String()
 11192  	if p.Nexthop == nil {
 11193  		switch p.AFI {
 11194  		case AFI_IP:
 11195  			nexthop = "0.0.0.0"
 11196  		case AFI_IP6:
 11197  			nexthop = "::"
 11198  		default:
 11199  			nexthop = "fictitious"
 11200  		}
 11201  	}
 11202  	return json.Marshal(struct {
 11203  		Type    BGPAttrType           `json:"type"`
 11204  		Nexthop string                `json:"nexthop"`
 11205  		AFI     uint16                `json:"afi"`
 11206  		SAFI    uint8                 `json:"safi"`
 11207  		Value   []AddrPrefixInterface `json:"value"`
 11208  	}{
 11209  		Type:    p.GetType(),
 11210  		Nexthop: nexthop,
 11211  		AFI:     p.AFI,
 11212  		SAFI:    p.SAFI,
 11213  		Value:   p.Value,
 11214  	})
 11215  }
 11216  
 11217  func (p *PathAttributeMpReachNLRI) String() string {
 11218  	return fmt.Sprintf("{MpReach(%s): {Nexthop: %s, NLRIs: %s}}", AfiSafiToRouteFamily(p.AFI, p.SAFI), p.Nexthop, p.Value)
 11219  }
 11220  
 11221  func NewPathAttributeMpReachNLRI(nexthop string, nlri []AddrPrefixInterface) *PathAttributeMpReachNLRI {
 11222  	// AFI(2) + SAFI(1) + NexthopLength(1) + Nexthop(variable)
 11223  	// + Reserved(1) + NLRI(variable)
 11224  	l := 5
 11225  	var afi uint16
 11226  	var safi uint8
 11227  	if len(nlri) > 0 {
 11228  		afi = nlri[0].AFI()
 11229  		safi = nlri[0].SAFI()
 11230  	}
 11231  	nh := net.ParseIP(nexthop)
 11232  	if nh.To4() != nil && afi != AFI_IP6 {
 11233  		nh = nh.To4()
 11234  		switch safi {
 11235  		case SAFI_MPLS_VPN:
 11236  			l += 12
 11237  		case SAFI_FLOW_SPEC_VPN, SAFI_FLOW_SPEC_UNICAST:
 11238  			// Should not have Nexthop
 11239  		default:
 11240  			l += 4
 11241  		}
 11242  	} else {
 11243  		switch safi {
 11244  		case SAFI_MPLS_VPN:
 11245  			l += 24
 11246  		case SAFI_FLOW_SPEC_VPN, SAFI_FLOW_SPEC_UNICAST:
 11247  			// Should not have Nexthop
 11248  		default:
 11249  			l += 16
 11250  		}
 11251  	}
 11252  	var nlriLen int
 11253  	for _, n := range nlri {
 11254  		l += n.Len()
 11255  		nBuf, _ := n.Serialize()
 11256  		nlriLen += len(nBuf)
 11257  	}
 11258  	t := BGP_ATTR_TYPE_MP_REACH_NLRI
 11259  	return &PathAttributeMpReachNLRI{
 11260  		PathAttribute: PathAttribute{
 11261  			Flags:  getPathAttrFlags(t, l),
 11262  			Type:   t,
 11263  			Length: uint16(l),
 11264  		},
 11265  		Nexthop: nh,
 11266  		AFI:     afi,
 11267  		SAFI:    safi,
 11268  		Value:   nlri,
 11269  	}
 11270  }
 11271  
 11272  type PathAttributeMpUnreachNLRI struct {
 11273  	PathAttribute
 11274  	AFI   uint16
 11275  	SAFI  uint8
 11276  	Value []AddrPrefixInterface
 11277  }
 11278  
 11279  func (p *PathAttributeMpUnreachNLRI) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
 11280  	value, err := p.PathAttribute.DecodeFromBytes(data, options...)
 11281  	if err != nil {
 11282  		return err
 11283  	}
 11284  	eCode := uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR)
 11285  	eSubCode := uint8(BGP_ERROR_SUB_ATTRIBUTE_LENGTH_ERROR)
 11286  	eData, _ := p.PathAttribute.Serialize(value, options...)
 11287  	if p.Length < 3 {
 11288  		return NewMessageError(eCode, eSubCode, value, "unreach header length is incorrect")
 11289  	}
 11290  	afi := binary.BigEndian.Uint16(value[0:2])
 11291  	safi := value[2]
 11292  	_, err = NewPrefixFromRouteFamily(afi, safi)
 11293  	if err != nil {
 11294  		return NewMessageError(eCode, BGP_ERROR_SUB_INVALID_NETWORK_FIELD, eData, err.Error())
 11295  	}
 11296  	value = value[3:]
 11297  	p.AFI = afi
 11298  	p.SAFI = safi
 11299  	addpathLen := 0
 11300  	if IsAddPathEnabled(true, AfiSafiToRouteFamily(afi, safi), options) {
 11301  		addpathLen = 4
 11302  	}
 11303  	for len(value) > 0 {
 11304  		prefix, err := NewPrefixFromRouteFamily(afi, safi)
 11305  		if err != nil {
 11306  			return NewMessageError(eCode, BGP_ERROR_SUB_INVALID_NETWORK_FIELD, eData, err.Error())
 11307  		}
 11308  		err = prefix.DecodeFromBytes(value, options...)
 11309  		if err != nil {
 11310  			return err
 11311  		}
 11312  		if prefix.Len(options...)+addpathLen > len(value) {
 11313  			return NewMessageError(eCode, eSubCode, eData, "prefix length is incorrect")
 11314  		}
 11315  		value = value[prefix.Len(options...)+addpathLen:]
 11316  		p.Value = append(p.Value, prefix)
 11317  	}
 11318  	return nil
 11319  }
 11320  
 11321  func (p *PathAttributeMpUnreachNLRI) Serialize(options ...*MarshallingOption) ([]byte, error) {
 11322  	buf := make([]byte, 3)
 11323  	binary.BigEndian.PutUint16(buf, p.AFI)
 11324  	buf[2] = p.SAFI
 11325  	for _, prefix := range p.Value {
 11326  		pbuf, err := prefix.Serialize(options...)
 11327  		if err != nil {
 11328  			return nil, err
 11329  		}
 11330  		buf = append(buf, pbuf...)
 11331  	}
 11332  	return p.PathAttribute.Serialize(buf, options...)
 11333  }
 11334  
 11335  func (p *PathAttributeMpUnreachNLRI) MarshalJSON() ([]byte, error) {
 11336  	return json.Marshal(struct {
 11337  		Type  BGPAttrType           `json:"type"`
 11338  		AFI   uint16                `json:"afi"`
 11339  		SAFI  uint8                 `json:"safi"`
 11340  		Value []AddrPrefixInterface `json:"value"`
 11341  	}{
 11342  		Type:  p.GetType(),
 11343  		AFI:   p.AFI,
 11344  		SAFI:  p.SAFI,
 11345  		Value: p.Value,
 11346  	})
 11347  }
 11348  
 11349  func (p *PathAttributeMpUnreachNLRI) String() string {
 11350  	if len(p.Value) > 0 {
 11351  		return fmt.Sprintf("{MpUnreach(%s): {NLRIs: %s}}", AfiSafiToRouteFamily(p.AFI, p.SAFI), p.Value)
 11352  	}
 11353  	return fmt.Sprintf("{MpUnreach(%s): End-of-Rib}", AfiSafiToRouteFamily(p.AFI, p.SAFI))
 11354  }
 11355  
 11356  func NewPathAttributeMpUnreachNLRI(nlri []AddrPrefixInterface) *PathAttributeMpUnreachNLRI {
 11357  	// AFI(2) + SAFI(1) + NLRI(variable)
 11358  	l := 3
 11359  	var afi uint16
 11360  	var safi uint8
 11361  	if len(nlri) > 0 {
 11362  		afi = nlri[0].AFI()
 11363  		safi = nlri[0].SAFI()
 11364  	}
 11365  	for _, n := range nlri {
 11366  		l += n.Len()
 11367  	}
 11368  	t := BGP_ATTR_TYPE_MP_UNREACH_NLRI
 11369  	return &PathAttributeMpUnreachNLRI{
 11370  		PathAttribute: PathAttribute{
 11371  			Flags:  getPathAttrFlags(t, l),
 11372  			Type:   t,
 11373  			Length: uint16(l),
 11374  		},
 11375  		AFI:   afi,
 11376  		SAFI:  safi,
 11377  		Value: nlri,
 11378  	}
 11379  }
 11380  
 11381  type ExtendedCommunityInterface interface {
 11382  	Serialize() ([]byte, error)
 11383  	String() string
 11384  	GetTypes() (ExtendedCommunityAttrType, ExtendedCommunityAttrSubType)
 11385  	MarshalJSON() ([]byte, error)
 11386  	Flat() map[string]string
 11387  }
 11388  
 11389  type TwoOctetAsSpecificExtended struct {
 11390  	SubType      ExtendedCommunityAttrSubType
 11391  	AS           uint16
 11392  	LocalAdmin   uint32
 11393  	IsTransitive bool
 11394  }
 11395  
 11396  func (e *TwoOctetAsSpecificExtended) Serialize() ([]byte, error) {
 11397  	buf := make([]byte, 8)
 11398  	if e.IsTransitive {
 11399  		buf[0] = byte(EC_TYPE_TRANSITIVE_TWO_OCTET_AS_SPECIFIC)
 11400  	} else {
 11401  		buf[0] = byte(EC_TYPE_NON_TRANSITIVE_TWO_OCTET_AS_SPECIFIC)
 11402  	}
 11403  	buf[1] = byte(e.SubType)
 11404  	binary.BigEndian.PutUint16(buf[2:], e.AS)
 11405  	binary.BigEndian.PutUint32(buf[4:], e.LocalAdmin)
 11406  	return buf, nil
 11407  }
 11408  
 11409  func (e *TwoOctetAsSpecificExtended) String() string {
 11410  	return strconv.FormatUint(uint64(e.AS), 10) + ":" + strconv.FormatUint(uint64(e.LocalAdmin), 10)
 11411  }
 11412  
 11413  func (e *TwoOctetAsSpecificExtended) MarshalJSON() ([]byte, error) {
 11414  	t, s := e.GetTypes()
 11415  	return json.Marshal(struct {
 11416  		Type    ExtendedCommunityAttrType    `json:"type"`
 11417  		Subtype ExtendedCommunityAttrSubType `json:"subtype"`
 11418  		Value   string                       `json:"value"`
 11419  	}{
 11420  		Type:    t,
 11421  		Subtype: s,
 11422  		Value:   e.String(),
 11423  	})
 11424  }
 11425  
 11426  func (e *TwoOctetAsSpecificExtended) GetTypes() (ExtendedCommunityAttrType, ExtendedCommunityAttrSubType) {
 11427  	t := EC_TYPE_TRANSITIVE_TWO_OCTET_AS_SPECIFIC
 11428  	if !e.IsTransitive {
 11429  		t = EC_TYPE_NON_TRANSITIVE_TWO_OCTET_AS_SPECIFIC
 11430  	}
 11431  	return t, e.SubType
 11432  }
 11433  
 11434  func NewTwoOctetAsSpecificExtended(subtype ExtendedCommunityAttrSubType, as uint16, localAdmin uint32, isTransitive bool) *TwoOctetAsSpecificExtended {
 11435  	return &TwoOctetAsSpecificExtended{
 11436  		SubType:      subtype,
 11437  		AS:           as,
 11438  		LocalAdmin:   localAdmin,
 11439  		IsTransitive: isTransitive,
 11440  	}
 11441  }
 11442  
 11443  type IPv4AddressSpecificExtended struct {
 11444  	SubType      ExtendedCommunityAttrSubType
 11445  	IPv4         net.IP
 11446  	LocalAdmin   uint16
 11447  	IsTransitive bool
 11448  }
 11449  
 11450  func (e *IPv4AddressSpecificExtended) Serialize() ([]byte, error) {
 11451  	buf := make([]byte, 8)
 11452  	if e.IsTransitive {
 11453  		buf[0] = byte(EC_TYPE_TRANSITIVE_IP4_SPECIFIC)
 11454  	} else {
 11455  		buf[0] = byte(EC_TYPE_NON_TRANSITIVE_IP4_SPECIFIC)
 11456  	}
 11457  	buf[1] = byte(e.SubType)
 11458  	copy(buf[2:6], e.IPv4)
 11459  	binary.BigEndian.PutUint16(buf[6:], e.LocalAdmin)
 11460  	return buf, nil
 11461  }
 11462  
 11463  func (e *IPv4AddressSpecificExtended) String() string {
 11464  	return e.IPv4.String() + ":" + strconv.FormatUint(uint64(e.LocalAdmin), 10)
 11465  }
 11466  
 11467  func (e *IPv4AddressSpecificExtended) MarshalJSON() ([]byte, error) {
 11468  	t, s := e.GetTypes()
 11469  	return json.Marshal(struct {
 11470  		Type    ExtendedCommunityAttrType    `json:"type"`
 11471  		Subtype ExtendedCommunityAttrSubType `json:"subtype"`
 11472  		Value   string                       `json:"value"`
 11473  	}{
 11474  		Type:    t,
 11475  		Subtype: s,
 11476  		Value:   e.String(),
 11477  	})
 11478  }
 11479  
 11480  func (e *IPv4AddressSpecificExtended) GetTypes() (ExtendedCommunityAttrType, ExtendedCommunityAttrSubType) {
 11481  	t := EC_TYPE_TRANSITIVE_IP4_SPECIFIC
 11482  	if !e.IsTransitive {
 11483  		t = EC_TYPE_NON_TRANSITIVE_IP4_SPECIFIC
 11484  	}
 11485  	return t, e.SubType
 11486  }
 11487  
 11488  func NewIPv4AddressSpecificExtended(subtype ExtendedCommunityAttrSubType, ip string, localAdmin uint16, isTransitive bool) *IPv4AddressSpecificExtended {
 11489  	ipv4 := net.ParseIP(ip)
 11490  	if ipv4.To4() == nil {
 11491  		return nil
 11492  	}
 11493  	return &IPv4AddressSpecificExtended{
 11494  		SubType:      subtype,
 11495  		IPv4:         ipv4.To4(),
 11496  		LocalAdmin:   localAdmin,
 11497  		IsTransitive: isTransitive,
 11498  	}
 11499  }
 11500  
 11501  type IPv6AddressSpecificExtended struct {
 11502  	SubType      ExtendedCommunityAttrSubType
 11503  	IPv6         net.IP
 11504  	LocalAdmin   uint16
 11505  	IsTransitive bool
 11506  }
 11507  
 11508  func (e *IPv6AddressSpecificExtended) Serialize() ([]byte, error) {
 11509  	buf := make([]byte, 20)
 11510  	if e.IsTransitive {
 11511  		buf[0] = byte(EC_TYPE_TRANSITIVE_IP6_SPECIFIC)
 11512  	} else {
 11513  		buf[0] = byte(EC_TYPE_NON_TRANSITIVE_IP6_SPECIFIC)
 11514  	}
 11515  	buf[1] = byte(e.SubType)
 11516  	copy(buf[2:18], e.IPv6)
 11517  	binary.BigEndian.PutUint16(buf[18:], e.LocalAdmin)
 11518  	return buf, nil
 11519  }
 11520  
 11521  func (e *IPv6AddressSpecificExtended) String() string {
 11522  	return e.IPv6.String() + ":" + strconv.FormatUint(uint64(e.LocalAdmin), 10)
 11523  }
 11524  
 11525  func (e *IPv6AddressSpecificExtended) MarshalJSON() ([]byte, error) {
 11526  	t, s := e.GetTypes()
 11527  	return json.Marshal(struct {
 11528  		Type    ExtendedCommunityAttrType    `json:"type"`
 11529  		Subtype ExtendedCommunityAttrSubType `json:"subtype"`
 11530  		Value   string                       `json:"value"`
 11531  	}{
 11532  		Type:    t,
 11533  		Subtype: s,
 11534  		Value:   e.String(),
 11535  	})
 11536  }
 11537  
 11538  func (e *IPv6AddressSpecificExtended) GetTypes() (ExtendedCommunityAttrType, ExtendedCommunityAttrSubType) {
 11539  	t := EC_TYPE_TRANSITIVE_IP6_SPECIFIC
 11540  	if !e.IsTransitive {
 11541  		t = EC_TYPE_NON_TRANSITIVE_IP6_SPECIFIC
 11542  	}
 11543  	return t, e.SubType
 11544  }
 11545  
 11546  func NewIPv6AddressSpecificExtended(subtype ExtendedCommunityAttrSubType, ip string, localAdmin uint16, isTransitive bool) *IPv6AddressSpecificExtended {
 11547  	ipv6 := net.ParseIP(ip)
 11548  	if ipv6.To16() == nil {
 11549  		return nil
 11550  	}
 11551  	return &IPv6AddressSpecificExtended{
 11552  		SubType:      subtype,
 11553  		IPv6:         ipv6.To16(),
 11554  		LocalAdmin:   localAdmin,
 11555  		IsTransitive: isTransitive,
 11556  	}
 11557  }
 11558  
 11559  type FourOctetAsSpecificExtended struct {
 11560  	SubType      ExtendedCommunityAttrSubType
 11561  	AS           uint32
 11562  	LocalAdmin   uint16
 11563  	IsTransitive bool
 11564  }
 11565  
 11566  func (e *FourOctetAsSpecificExtended) Serialize() ([]byte, error) {
 11567  	buf := make([]byte, 8)
 11568  	if e.IsTransitive {
 11569  		buf[0] = byte(EC_TYPE_TRANSITIVE_FOUR_OCTET_AS_SPECIFIC)
 11570  	} else {
 11571  		buf[0] = byte(EC_TYPE_NON_TRANSITIVE_FOUR_OCTET_AS_SPECIFIC)
 11572  	}
 11573  	buf[1] = byte(e.SubType)
 11574  	binary.BigEndian.PutUint32(buf[2:], e.AS)
 11575  	binary.BigEndian.PutUint16(buf[6:], e.LocalAdmin)
 11576  	return buf, nil
 11577  }
 11578  
 11579  func (e *FourOctetAsSpecificExtended) String() string {
 11580  	var buf [4]byte
 11581  	binary.BigEndian.PutUint32(buf[:4], e.AS)
 11582  	asUpper := binary.BigEndian.Uint16(buf[0:2])
 11583  	asLower := binary.BigEndian.Uint16(buf[2:4])
 11584  	return strconv.FormatUint(uint64(asUpper), 10) + "." + strconv.FormatUint(uint64(asLower), 10) +
 11585  		":" + strconv.FormatUint(uint64(e.LocalAdmin), 10)
 11586  }
 11587  
 11588  func (e *FourOctetAsSpecificExtended) MarshalJSON() ([]byte, error) {
 11589  	t, s := e.GetTypes()
 11590  	return json.Marshal(struct {
 11591  		Type    ExtendedCommunityAttrType    `json:"type"`
 11592  		Subtype ExtendedCommunityAttrSubType `json:"subtype"`
 11593  		Value   string                       `json:"value"`
 11594  	}{
 11595  		Type:    t,
 11596  		Subtype: s,
 11597  		Value:   e.String(),
 11598  	})
 11599  }
 11600  
 11601  func (e *FourOctetAsSpecificExtended) GetTypes() (ExtendedCommunityAttrType, ExtendedCommunityAttrSubType) {
 11602  	t := EC_TYPE_TRANSITIVE_FOUR_OCTET_AS_SPECIFIC
 11603  	if !e.IsTransitive {
 11604  		t = EC_TYPE_NON_TRANSITIVE_FOUR_OCTET_AS_SPECIFIC
 11605  	}
 11606  	return t, e.SubType
 11607  }
 11608  
 11609  func NewFourOctetAsSpecificExtended(subtype ExtendedCommunityAttrSubType, as uint32, localAdmin uint16, isTransitive bool) *FourOctetAsSpecificExtended {
 11610  	return &FourOctetAsSpecificExtended{
 11611  		SubType:      subtype,
 11612  		AS:           as,
 11613  		LocalAdmin:   localAdmin,
 11614  		IsTransitive: isTransitive,
 11615  	}
 11616  }
 11617  
 11618  func ParseExtendedCommunity(subtype ExtendedCommunityAttrSubType, com string) (ExtendedCommunityInterface, error) {
 11619  	if subtype == EC_SUBTYPE_ENCAPSULATION {
 11620  		var t TunnelType
 11621  		switch com {
 11622  		case TUNNEL_TYPE_L2TP3.String():
 11623  			t = TUNNEL_TYPE_L2TP3
 11624  		case TUNNEL_TYPE_GRE.String():
 11625  			t = TUNNEL_TYPE_GRE
 11626  		case TUNNEL_TYPE_IP_IN_IP.String():
 11627  			t = TUNNEL_TYPE_IP_IN_IP
 11628  		case TUNNEL_TYPE_VXLAN.String():
 11629  			t = TUNNEL_TYPE_VXLAN
 11630  		case TUNNEL_TYPE_NVGRE.String():
 11631  			t = TUNNEL_TYPE_NVGRE
 11632  		case TUNNEL_TYPE_MPLS.String():
 11633  			t = TUNNEL_TYPE_MPLS
 11634  		case TUNNEL_TYPE_MPLS_IN_GRE.String():
 11635  			t = TUNNEL_TYPE_MPLS_IN_GRE
 11636  		case TUNNEL_TYPE_VXLAN_GRE.String():
 11637  			t = TUNNEL_TYPE_VXLAN_GRE
 11638  		case TUNNEL_TYPE_MPLS_IN_UDP.String():
 11639  			t = TUNNEL_TYPE_MPLS_IN_UDP
 11640  		case TUNNEL_TYPE_GENEVE.String():
 11641  			t = TUNNEL_TYPE_GENEVE
 11642  		case "L2TPv3 over IP":
 11643  			t = TUNNEL_TYPE_L2TP3
 11644  		case "GRE":
 11645  			t = TUNNEL_TYPE_GRE
 11646  		case "IP in IP":
 11647  			t = TUNNEL_TYPE_IP_IN_IP
 11648  		case "VXLAN":
 11649  			t = TUNNEL_TYPE_VXLAN
 11650  		case "NVGRE":
 11651  			t = TUNNEL_TYPE_NVGRE
 11652  		case "MPLS":
 11653  			t = TUNNEL_TYPE_MPLS
 11654  		case "MPLS in GRE":
 11655  			t = TUNNEL_TYPE_MPLS_IN_GRE
 11656  		case "VXLAN GRE":
 11657  			t = TUNNEL_TYPE_VXLAN_GRE
 11658  		case "MPLS in UDP":
 11659  			t = TUNNEL_TYPE_MPLS_IN_UDP
 11660  		case "GENEVE":
 11661  			t = TUNNEL_TYPE_GENEVE
 11662  		default:
 11663  			return nil, fmt.Errorf("invalid encap type %s", com)
 11664  		}
 11665  		return NewEncapExtended(t), nil
 11666  	}
 11667  
 11668  	if subtype == EC_SUBTYPE_ORIGIN_VALIDATION {
 11669  		var state ValidationState
 11670  		switch com {
 11671  		case VALIDATION_STATE_VALID.String():
 11672  			state = VALIDATION_STATE_VALID
 11673  		case VALIDATION_STATE_NOT_FOUND.String():
 11674  			state = VALIDATION_STATE_NOT_FOUND
 11675  		case VALIDATION_STATE_INVALID.String():
 11676  			state = VALIDATION_STATE_INVALID
 11677  		default:
 11678  			return nil, errors.New("invalid validation state")
 11679  		}
 11680  		return &ValidationExtended{
 11681  			State: state,
 11682  		}, nil
 11683  	}
 11684  	elems, err := parseRdAndRt(com)
 11685  	if err != nil {
 11686  		return nil, err
 11687  	}
 11688  	localAdmin, _ := strconv.ParseUint(elems[10], 10, 32)
 11689  	if subtype == EC_SUBTYPE_SOURCE_AS {
 11690  		localAdmin = 0
 11691  	}
 11692  	ip := net.ParseIP(elems[1])
 11693  	isTransitive := true
 11694  	switch {
 11695  	case subtype == EC_SUBTYPE_LINK_BANDWIDTH:
 11696  		asn, _ := strconv.ParseUint(elems[8], 10, 16)
 11697  		return NewLinkBandwidthExtended(uint16(asn), float32(localAdmin)), nil
 11698  	case ip.To4() != nil:
 11699  		return NewIPv4AddressSpecificExtended(subtype, elems[1], uint16(localAdmin), isTransitive), nil
 11700  	case ip.To16() != nil:
 11701  		return NewIPv6AddressSpecificExtended(subtype, elems[1], uint16(localAdmin), isTransitive), nil
 11702  	case elems[6] == "" && elems[7] == "":
 11703  		asn, _ := strconv.ParseUint(elems[8], 10, 16)
 11704  		return NewTwoOctetAsSpecificExtended(subtype, uint16(asn), uint32(localAdmin), isTransitive), nil
 11705  	default:
 11706  		fst, _ := strconv.ParseUint(elems[7], 10, 16)
 11707  		snd, _ := strconv.ParseUint(elems[8], 10, 16)
 11708  		asn := fst<<16 | snd
 11709  		return NewFourOctetAsSpecificExtended(subtype, uint32(asn), uint16(localAdmin), isTransitive), nil
 11710  	}
 11711  }
 11712  
 11713  func ParseRouteTarget(rt string) (ExtendedCommunityInterface, error) {
 11714  	return ParseExtendedCommunity(EC_SUBTYPE_ROUTE_TARGET, rt)
 11715  }
 11716  
 11717  func SerializeExtendedCommunities(comms []ExtendedCommunityInterface) ([][]byte, error) {
 11718  	bufs := make([][]byte, len(comms))
 11719  	var err error
 11720  	for i, c := range comms {
 11721  		bufs[i], err = c.Serialize()
 11722  		if err != nil {
 11723  			return nil, err
 11724  		}
 11725  	}
 11726  	return bufs, err
 11727  }
 11728  
 11729  type ValidationState uint8
 11730  
 11731  const (
 11732  	VALIDATION_STATE_VALID     ValidationState = 0
 11733  	VALIDATION_STATE_NOT_FOUND ValidationState = 1
 11734  	VALIDATION_STATE_INVALID   ValidationState = 2
 11735  )
 11736  
 11737  func (s ValidationState) String() string {
 11738  	switch s {
 11739  	case VALIDATION_STATE_VALID:
 11740  		return "valid"
 11741  	case VALIDATION_STATE_NOT_FOUND:
 11742  		return "not-found"
 11743  	case VALIDATION_STATE_INVALID:
 11744  		return "invalid"
 11745  	}
 11746  	return fmt.Sprintf("unknown validation state(%d)", s)
 11747  }
 11748  
 11749  type ValidationExtended struct {
 11750  	State ValidationState
 11751  }
 11752  
 11753  func (e *ValidationExtended) Serialize() ([]byte, error) {
 11754  	buf := make([]byte, 8)
 11755  	typ, subType := e.GetTypes()
 11756  	buf[0] = byte(typ)
 11757  	buf[1] = byte(subType)
 11758  	buf[7] = byte(e.State)
 11759  	return buf, nil
 11760  }
 11761  
 11762  func (e *ValidationExtended) String() string {
 11763  	return e.State.String()
 11764  }
 11765  
 11766  func (e *ValidationExtended) GetTypes() (ExtendedCommunityAttrType, ExtendedCommunityAttrSubType) {
 11767  	return EC_TYPE_NON_TRANSITIVE_OPAQUE, EC_SUBTYPE_ORIGIN_VALIDATION
 11768  }
 11769  
 11770  func (e *ValidationExtended) MarshalJSON() ([]byte, error) {
 11771  	t, s := e.GetTypes()
 11772  	return json.Marshal(struct {
 11773  		Type    ExtendedCommunityAttrType    `json:"type"`
 11774  		SubType ExtendedCommunityAttrSubType `json:"subtype"`
 11775  		State   ValidationState              `json:"value"`
 11776  	}{
 11777  		Type:    t,
 11778  		SubType: s,
 11779  		State:   e.State,
 11780  	})
 11781  }
 11782  
 11783  func NewValidationExtended(state ValidationState) *ValidationExtended {
 11784  	return &ValidationExtended{
 11785  		State: state,
 11786  	}
 11787  }
 11788  
 11789  type LinkBandwidthExtended struct {
 11790  	AS        uint16
 11791  	Bandwidth float32
 11792  }
 11793  
 11794  func (e *LinkBandwidthExtended) GetTypes() (ExtendedCommunityAttrType, ExtendedCommunityAttrSubType) {
 11795  	return EC_TYPE_NON_TRANSITIVE_LINK_BANDWIDTH, EC_SUBTYPE_LINK_BANDWIDTH
 11796  }
 11797  
 11798  func (e *LinkBandwidthExtended) Serialize() ([]byte, error) {
 11799  	buf := make([]byte, 8)
 11800  	typ, subType := e.GetTypes()
 11801  	buf[0] = byte(typ)
 11802  	buf[1] = byte(subType)
 11803  	binary.BigEndian.PutUint16(buf[2:4], e.AS)
 11804  	binary.BigEndian.PutUint32(buf[4:8], math.Float32bits(e.Bandwidth))
 11805  	return buf, nil
 11806  }
 11807  
 11808  func (e *LinkBandwidthExtended) String() string {
 11809  	return strconv.FormatUint(uint64(e.AS), 10) + ":" + strconv.FormatUint(uint64(e.Bandwidth), 10)
 11810  }
 11811  
 11812  func (e *LinkBandwidthExtended) MarshalJSON() ([]byte, error) {
 11813  	t, s := e.GetTypes()
 11814  	return json.Marshal(struct {
 11815  		Type      ExtendedCommunityAttrType    `json:"type"`
 11816  		SubType   ExtendedCommunityAttrSubType `json:"subtype"`
 11817  		AS        uint16                       `json:"asn"`
 11818  		Bandwidth float32                      `json:"bandwidth"`
 11819  	}{
 11820  		Type:      t,
 11821  		SubType:   s,
 11822  		AS:        e.AS,
 11823  		Bandwidth: e.Bandwidth,
 11824  	})
 11825  }
 11826  
 11827  func NewLinkBandwidthExtended(as uint16, bw float32) *LinkBandwidthExtended {
 11828  	return &LinkBandwidthExtended{
 11829  		AS:        as,
 11830  		Bandwidth: bw,
 11831  	}
 11832  }
 11833  
 11834  type ColorExtended struct {
 11835  	Color uint32
 11836  }
 11837  
 11838  func (e *ColorExtended) Serialize() ([]byte, error) {
 11839  	buf := make([]byte, 8)
 11840  	typ, subType := e.GetTypes()
 11841  	buf[0] = byte(typ)
 11842  	buf[1] = byte(subType)
 11843  	binary.BigEndian.PutUint32(buf[4:8], uint32(e.Color))
 11844  	return buf, nil
 11845  }
 11846  
 11847  func (e *ColorExtended) String() string {
 11848  	return strconv.FormatUint(uint64(e.Color), 10)
 11849  }
 11850  
 11851  func (e *ColorExtended) GetTypes() (ExtendedCommunityAttrType, ExtendedCommunityAttrSubType) {
 11852  	return EC_TYPE_TRANSITIVE_OPAQUE, EC_SUBTYPE_COLOR
 11853  }
 11854  
 11855  func (e *ColorExtended) MarshalJSON() ([]byte, error) {
 11856  	t, s := e.GetTypes()
 11857  	return json.Marshal(struct {
 11858  		Type    ExtendedCommunityAttrType    `json:"type"`
 11859  		SubType ExtendedCommunityAttrSubType `json:"subtype"`
 11860  		Color   uint32                       `json:"color"`
 11861  	}{
 11862  		Type:    t,
 11863  		SubType: s,
 11864  		Color:   e.Color,
 11865  	})
 11866  }
 11867  
 11868  func NewColorExtended(color uint32) *ColorExtended {
 11869  	return &ColorExtended{
 11870  		Color: color,
 11871  	}
 11872  }
 11873  
 11874  type EncapExtended struct {
 11875  	TunnelType TunnelType
 11876  }
 11877  
 11878  func (e *EncapExtended) Serialize() ([]byte, error) {
 11879  	buf := make([]byte, 8)
 11880  	typ, subType := e.GetTypes()
 11881  	buf[0] = byte(typ)
 11882  	buf[1] = byte(subType)
 11883  	binary.BigEndian.PutUint16(buf[6:8], uint16(e.TunnelType))
 11884  	return buf, nil
 11885  }
 11886  
 11887  func (e *EncapExtended) String() string {
 11888  	switch e.TunnelType {
 11889  	case TUNNEL_TYPE_L2TP3:
 11890  		return "L2TPv3 over IP"
 11891  	case TUNNEL_TYPE_GRE:
 11892  		return "GRE"
 11893  	case TUNNEL_TYPE_IP_IN_IP:
 11894  		return "IP in IP"
 11895  	case TUNNEL_TYPE_VXLAN:
 11896  		return "VXLAN"
 11897  	case TUNNEL_TYPE_NVGRE:
 11898  		return "NVGRE"
 11899  	case TUNNEL_TYPE_MPLS:
 11900  		return "MPLS"
 11901  	case TUNNEL_TYPE_MPLS_IN_GRE:
 11902  		return "MPLS in GRE"
 11903  	case TUNNEL_TYPE_VXLAN_GRE:
 11904  		return "VXLAN GRE"
 11905  	case TUNNEL_TYPE_MPLS_IN_UDP:
 11906  		return "MPLS in UDP"
 11907  	case TUNNEL_TYPE_SR_POLICY:
 11908  		return "SR Policy"
 11909  	case TUNNEL_TYPE_GENEVE:
 11910  		return "GENEVE"
 11911  	default:
 11912  		return "tunnel: " + strconv.FormatUint(uint64(e.TunnelType), 10)
 11913  	}
 11914  }
 11915  
 11916  func (e *EncapExtended) GetTypes() (ExtendedCommunityAttrType, ExtendedCommunityAttrSubType) {
 11917  	return EC_TYPE_TRANSITIVE_OPAQUE, EC_SUBTYPE_ENCAPSULATION
 11918  }
 11919  
 11920  func (e *EncapExtended) MarshalJSON() ([]byte, error) {
 11921  	t, s := e.GetTypes()
 11922  	return json.Marshal(struct {
 11923  		Type       ExtendedCommunityAttrType    `json:"type"`
 11924  		SubType    ExtendedCommunityAttrSubType `json:"subtype"`
 11925  		TunnelType TunnelType                   `json:"tunnel_type"`
 11926  	}{
 11927  		Type:       t,
 11928  		SubType:    s,
 11929  		TunnelType: e.TunnelType,
 11930  	})
 11931  }
 11932  
 11933  func NewEncapExtended(tunnelType TunnelType) *EncapExtended {
 11934  	return &EncapExtended{
 11935  		TunnelType: tunnelType,
 11936  	}
 11937  }
 11938  
 11939  type DefaultGatewayExtended struct {
 11940  }
 11941  
 11942  func (e *DefaultGatewayExtended) Serialize() ([]byte, error) {
 11943  	buf := make([]byte, 8)
 11944  	typ, subType := e.GetTypes()
 11945  	buf[0] = byte(typ)
 11946  	buf[1] = byte(subType)
 11947  	return buf, nil
 11948  }
 11949  
 11950  func (e *DefaultGatewayExtended) String() string {
 11951  	return "default-gateway"
 11952  }
 11953  
 11954  func (e *DefaultGatewayExtended) GetTypes() (ExtendedCommunityAttrType, ExtendedCommunityAttrSubType) {
 11955  	return EC_TYPE_TRANSITIVE_OPAQUE, EC_SUBTYPE_DEFAULT_GATEWAY
 11956  }
 11957  
 11958  func (e *DefaultGatewayExtended) MarshalJSON() ([]byte, error) {
 11959  	t, s := e.GetTypes()
 11960  	return json.Marshal(struct {
 11961  		Type    ExtendedCommunityAttrType    `json:"type"`
 11962  		SubType ExtendedCommunityAttrSubType `json:"subtype"`
 11963  	}{
 11964  		Type:    t,
 11965  		SubType: s,
 11966  	})
 11967  }
 11968  
 11969  func NewDefaultGatewayExtended() *DefaultGatewayExtended {
 11970  	return &DefaultGatewayExtended{}
 11971  }
 11972  
 11973  type OpaqueExtended struct {
 11974  	IsTransitive bool
 11975  	Value        []byte
 11976  }
 11977  
 11978  func (e *OpaqueExtended) Serialize() ([]byte, error) {
 11979  	if len(e.Value) != 7 {
 11980  		return nil, fmt.Errorf("invalid value length for opaque extended community: %d", len(e.Value))
 11981  	}
 11982  	buf := make([]byte, 8)
 11983  	if e.IsTransitive {
 11984  		buf[0] = byte(EC_TYPE_TRANSITIVE_OPAQUE)
 11985  	} else {
 11986  		buf[0] = byte(EC_TYPE_NON_TRANSITIVE_OPAQUE)
 11987  	}
 11988  	copy(buf[1:], e.Value)
 11989  	return buf, nil
 11990  }
 11991  
 11992  func (e *OpaqueExtended) String() string {
 11993  	var buf [8]byte
 11994  	copy(buf[1:], e.Value)
 11995  	return strconv.FormatUint(binary.BigEndian.Uint64(buf[:]), 10)
 11996  }
 11997  
 11998  func (e *OpaqueExtended) GetTypes() (ExtendedCommunityAttrType, ExtendedCommunityAttrSubType) {
 11999  	var subType ExtendedCommunityAttrSubType
 12000  	if len(e.Value) > 0 {
 12001  		// Use the first byte of value as the sub type
 12002  		subType = ExtendedCommunityAttrSubType(e.Value[0])
 12003  	}
 12004  	if e.IsTransitive {
 12005  		return EC_TYPE_TRANSITIVE_OPAQUE, subType
 12006  	}
 12007  	return EC_TYPE_NON_TRANSITIVE_OPAQUE, subType
 12008  }
 12009  
 12010  func (e *OpaqueExtended) MarshalJSON() ([]byte, error) {
 12011  	t, s := e.GetTypes()
 12012  	return json.Marshal(struct {
 12013  		Type    ExtendedCommunityAttrType    `json:"type"`
 12014  		Subtype ExtendedCommunityAttrSubType `json:"subtype"`
 12015  		Value   []byte                       `json:"value"`
 12016  	}{
 12017  		Type:    t,
 12018  		Subtype: s,
 12019  		Value:   e.Value,
 12020  	})
 12021  }
 12022  
 12023  func NewOpaqueExtended(isTransitive bool, value []byte) *OpaqueExtended {
 12024  	v := make([]byte, 7)
 12025  	copy(v, value)
 12026  	return &OpaqueExtended{
 12027  		IsTransitive: isTransitive,
 12028  		Value:        v,
 12029  	}
 12030  }
 12031  
 12032  func parseOpaqueExtended(data []byte) (ExtendedCommunityInterface, error) {
 12033  	typ := ExtendedCommunityAttrType(data[0])
 12034  	isTransitive := false
 12035  	switch typ {
 12036  	case EC_TYPE_TRANSITIVE_OPAQUE:
 12037  		isTransitive = true
 12038  	case EC_TYPE_NON_TRANSITIVE_OPAQUE:
 12039  		// isTransitive = false
 12040  	default:
 12041  		return nil, NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("invalid opaque extended community type: %d", data[0]))
 12042  	}
 12043  	subType := ExtendedCommunityAttrSubType(data[1])
 12044  
 12045  	if isTransitive {
 12046  		switch subType {
 12047  		case EC_SUBTYPE_COLOR:
 12048  			return &ColorExtended{
 12049  				Color: binary.BigEndian.Uint32(data[4:8]),
 12050  			}, nil
 12051  		case EC_SUBTYPE_ENCAPSULATION:
 12052  			return &EncapExtended{
 12053  				TunnelType: TunnelType(binary.BigEndian.Uint16(data[6:8])),
 12054  			}, nil
 12055  		case EC_SUBTYPE_DEFAULT_GATEWAY:
 12056  			return &DefaultGatewayExtended{}, nil
 12057  		}
 12058  	} else {
 12059  		switch subType {
 12060  		case EC_SUBTYPE_ORIGIN_VALIDATION:
 12061  			return &ValidationExtended{
 12062  				State: ValidationState(data[7]),
 12063  			}, nil
 12064  		}
 12065  	}
 12066  	return NewOpaqueExtended(isTransitive, data[1:8]), nil
 12067  }
 12068  
 12069  type ESILabelExtended struct {
 12070  	Label          uint32
 12071  	IsSingleActive bool
 12072  }
 12073  
 12074  func (e *ESILabelExtended) Serialize() ([]byte, error) {
 12075  	buf := make([]byte, 8)
 12076  	buf[0] = byte(EC_TYPE_EVPN)
 12077  	buf[1] = byte(EC_SUBTYPE_ESI_LABEL)
 12078  	if e.IsSingleActive {
 12079  		buf[2] = byte(1)
 12080  	}
 12081  	buf[3] = 0
 12082  	buf[4] = 0
 12083  	buf[5] = byte((e.Label >> 16) & 0xff)
 12084  	buf[6] = byte((e.Label >> 8) & 0xff)
 12085  	buf[7] = byte(e.Label & 0xff)
 12086  	return buf, nil
 12087  }
 12088  
 12089  func (e *ESILabelExtended) String() string {
 12090  	buf := bytes.NewBuffer(make([]byte, 0, 32))
 12091  	buf.WriteString("esi-label: " + strconv.FormatUint(uint64(e.Label), 10))
 12092  	if e.IsSingleActive {
 12093  		buf.WriteString(", single-active")
 12094  	}
 12095  	return buf.String()
 12096  }
 12097  
 12098  func (e *ESILabelExtended) MarshalJSON() ([]byte, error) {
 12099  	t, s := e.GetTypes()
 12100  	return json.Marshal(struct {
 12101  		Type           ExtendedCommunityAttrType    `json:"type"`
 12102  		Subtype        ExtendedCommunityAttrSubType `json:"subtype"`
 12103  		Label          uint32                       `json:"label"`
 12104  		IsSingleActive bool                         `json:"is_single_active"`
 12105  	}{
 12106  		Type:           t,
 12107  		Subtype:        s,
 12108  		Label:          e.Label,
 12109  		IsSingleActive: e.IsSingleActive,
 12110  	})
 12111  }
 12112  
 12113  func (e *ESILabelExtended) GetTypes() (ExtendedCommunityAttrType, ExtendedCommunityAttrSubType) {
 12114  	return EC_TYPE_EVPN, EC_SUBTYPE_ESI_LABEL
 12115  }
 12116  
 12117  func NewESILabelExtended(label uint32, isSingleActive bool) *ESILabelExtended {
 12118  	return &ESILabelExtended{
 12119  		Label:          label,
 12120  		IsSingleActive: isSingleActive,
 12121  	}
 12122  }
 12123  
 12124  type ESImportRouteTarget struct {
 12125  	ESImport net.HardwareAddr
 12126  }
 12127  
 12128  func (e *ESImportRouteTarget) Serialize() ([]byte, error) {
 12129  	buf := make([]byte, 8)
 12130  	buf[0] = byte(EC_TYPE_EVPN)
 12131  	buf[1] = byte(EC_SUBTYPE_ES_IMPORT)
 12132  	copy(buf[2:], e.ESImport)
 12133  	return buf, nil
 12134  }
 12135  
 12136  func (e *ESImportRouteTarget) String() string {
 12137  	return "es-import rt: " + e.ESImport.String()
 12138  }
 12139  
 12140  func (e *ESImportRouteTarget) MarshalJSON() ([]byte, error) {
 12141  	t, s := e.GetTypes()
 12142  	return json.Marshal(struct {
 12143  		Type    ExtendedCommunityAttrType    `json:"type"`
 12144  		Subtype ExtendedCommunityAttrSubType `json:"subtype"`
 12145  		Value   string                       `json:"value"`
 12146  	}{
 12147  		Type:    t,
 12148  		Subtype: s,
 12149  		Value:   e.ESImport.String(),
 12150  	})
 12151  }
 12152  
 12153  func (e *ESImportRouteTarget) GetTypes() (ExtendedCommunityAttrType, ExtendedCommunityAttrSubType) {
 12154  	return EC_TYPE_EVPN, EC_SUBTYPE_ES_IMPORT
 12155  }
 12156  
 12157  func NewESImportRouteTarget(mac string) *ESImportRouteTarget {
 12158  	esImport, err := net.ParseMAC(mac)
 12159  	if err != nil {
 12160  		return nil
 12161  	}
 12162  	return &ESImportRouteTarget{
 12163  		ESImport: esImport,
 12164  	}
 12165  }
 12166  
 12167  type MacMobilityExtended struct {
 12168  	Sequence uint32
 12169  	IsSticky bool
 12170  }
 12171  
 12172  func (e *MacMobilityExtended) Serialize() ([]byte, error) {
 12173  	buf := make([]byte, 8)
 12174  	buf[0] = byte(EC_TYPE_EVPN)
 12175  	buf[1] = byte(EC_SUBTYPE_MAC_MOBILITY)
 12176  	if e.IsSticky {
 12177  		buf[2] = byte(1)
 12178  	}
 12179  	binary.BigEndian.PutUint32(buf[4:], e.Sequence)
 12180  	return buf, nil
 12181  }
 12182  
 12183  func (e *MacMobilityExtended) String() string {
 12184  	buf := bytes.NewBuffer(make([]byte, 0, 32))
 12185  	buf.WriteString("mac-mobility: " + strconv.FormatUint(uint64(e.Sequence), 10))
 12186  	if e.IsSticky {
 12187  		buf.WriteString(", sticky")
 12188  	}
 12189  	return buf.String()
 12190  }
 12191  
 12192  func (e *MacMobilityExtended) MarshalJSON() ([]byte, error) {
 12193  	t, s := e.GetTypes()
 12194  	return json.Marshal(struct {
 12195  		Type     ExtendedCommunityAttrType    `json:"type"`
 12196  		Subtype  ExtendedCommunityAttrSubType `json:"subtype"`
 12197  		Sequence uint32                       `json:"sequence"`
 12198  		IsSticky bool                         `json:"is_sticky"`
 12199  	}{
 12200  		Type:     t,
 12201  		Subtype:  s,
 12202  		Sequence: e.Sequence,
 12203  		IsSticky: e.IsSticky,
 12204  	})
 12205  }
 12206  
 12207  func (e *MacMobilityExtended) GetTypes() (ExtendedCommunityAttrType, ExtendedCommunityAttrSubType) {
 12208  	return EC_TYPE_EVPN, EC_SUBTYPE_MAC_MOBILITY
 12209  }
 12210  
 12211  func NewMacMobilityExtended(seq uint32, isSticky bool) *MacMobilityExtended {
 12212  	return &MacMobilityExtended{
 12213  		Sequence: seq,
 12214  		IsSticky: isSticky,
 12215  	}
 12216  }
 12217  
 12218  type RouterMacExtended struct {
 12219  	Mac net.HardwareAddr
 12220  }
 12221  
 12222  func (e *RouterMacExtended) Serialize() ([]byte, error) {
 12223  	buf := make([]byte, 2, 8)
 12224  	buf[0] = byte(EC_TYPE_EVPN)
 12225  	buf[1] = byte(EC_SUBTYPE_ROUTER_MAC)
 12226  	buf = append(buf, e.Mac...)
 12227  	return buf, nil
 12228  }
 12229  
 12230  func (e *RouterMacExtended) String() string {
 12231  	return "router's mac: " + e.Mac.String()
 12232  }
 12233  
 12234  func (e *RouterMacExtended) MarshalJSON() ([]byte, error) {
 12235  	t, s := e.GetTypes()
 12236  	return json.Marshal(struct {
 12237  		Type    ExtendedCommunityAttrType    `json:"type"`
 12238  		Subtype ExtendedCommunityAttrSubType `json:"subtype"`
 12239  		Mac     string                       `json:"mac"`
 12240  	}{
 12241  		Type:    t,
 12242  		Subtype: s,
 12243  		Mac:     e.Mac.String(),
 12244  	})
 12245  }
 12246  
 12247  func (e *RouterMacExtended) GetTypes() (ExtendedCommunityAttrType, ExtendedCommunityAttrSubType) {
 12248  	return EC_TYPE_EVPN, EC_SUBTYPE_ROUTER_MAC
 12249  }
 12250  
 12251  func NewRoutersMacExtended(mac string) *RouterMacExtended {
 12252  	hw, err := net.ParseMAC(mac)
 12253  	if err != nil {
 12254  		return nil
 12255  	}
 12256  	return &RouterMacExtended{
 12257  		Mac: hw,
 12258  	}
 12259  }
 12260  
 12261  type Layer2AttributesExtended struct {
 12262  	HasCILabel     bool
 12263  	HasFlowLabel   bool
 12264  	HasControlWord bool
 12265  	IsPrimaryPe    bool
 12266  	IsBackupPe     bool
 12267  	Mtu            uint16
 12268  }
 12269  
 12270  type EvpnControlFlag uint8
 12271  
 12272  const (
 12273  	BACKUP_PE    EvpnControlFlag = 1 << 0
 12274  	PRIMARY_PE   EvpnControlFlag = 1 << 1
 12275  	CONTROL_WORD EvpnControlFlag = 1 << 2
 12276  	FLOW_LABEL   EvpnControlFlag = 1 << 3
 12277  	CI_LABEL     EvpnControlFlag = 1 << 4
 12278  )
 12279  
 12280  func (e *Layer2AttributesExtended) Serialize() ([]byte, error) {
 12281  	buf := make([]byte, 8)
 12282  	buf[0] = byte(EC_TYPE_EVPN)
 12283  	buf[1] = byte(EC_SUBTYPE_L2_ATTRIBUTES)
 12284  
 12285  	if e.IsBackupPe {
 12286  		buf[3] |= uint8(BACKUP_PE)
 12287  	} else if e.IsPrimaryPe {
 12288  		buf[3] |= uint8(PRIMARY_PE)
 12289  	}
 12290  	if e.HasControlWord {
 12291  		buf[3] |= uint8(CONTROL_WORD)
 12292  	}
 12293  	if e.HasFlowLabel {
 12294  		buf[3] |= uint8(FLOW_LABEL)
 12295  	}
 12296  	if e.HasCILabel {
 12297  		buf[3] |= uint8(CI_LABEL)
 12298  	}
 12299  	binary.BigEndian.PutUint16(buf[4:6], e.Mtu)
 12300  	return buf, nil
 12301  }
 12302  
 12303  func (e *Layer2AttributesExtended) String() string {
 12304  	buf := bytes.NewBuffer(make([]byte, 0, 32))
 12305  	buf.WriteString("evpn-l2-info: ")
 12306  	if e.IsPrimaryPe {
 12307  		buf.WriteString("is-primary-pe, ")
 12308  	}
 12309  	if e.IsBackupPe {
 12310  		buf.WriteString("is-backup-pe, ")
 12311  	}
 12312  	if e.HasControlWord {
 12313  		buf.WriteString("control-word, ")
 12314  	}
 12315  	if e.HasFlowLabel {
 12316  		buf.WriteString("flow-label, ")
 12317  	}
 12318  	if e.HasCILabel {
 12319  		buf.WriteString("ci-label, ")
 12320  	}
 12321  
 12322  	buf.WriteString("mtu " + strconv.FormatUint(uint64(e.Mtu), 10))
 12323  	return buf.String()
 12324  }
 12325  
 12326  func (e *Layer2AttributesExtended) MarshalJSON() ([]byte, error) {
 12327  	t, s := e.GetTypes()
 12328  	return json.Marshal(struct {
 12329  		Type        ExtendedCommunityAttrType    `json:"type"`
 12330  		Subtype     ExtendedCommunityAttrSubType `json:"subtype"`
 12331  		CILabel     bool                         `json:"ci_label,omitempty"`
 12332  		FlowLabel   bool                         `json:"flow_label,omitempty"`
 12333  		ControlWord bool                         `json:"control_word,omitempty"`
 12334  		PrimaryPe   bool                         `json:"is_primary_pe,omitempty"`
 12335  		BackupPe    bool                         `json:"is_backup_pe,omitempty"`
 12336  		Mtu         uint16                       `json:"mtu"`
 12337  	}{
 12338  		Type:        t,
 12339  		Subtype:     s,
 12340  		CILabel:     e.HasCILabel,
 12341  		FlowLabel:   e.HasFlowLabel,
 12342  		ControlWord: e.HasControlWord,
 12343  		PrimaryPe:   e.IsPrimaryPe,
 12344  		BackupPe:    e.IsBackupPe,
 12345  		Mtu:         e.Mtu,
 12346  	})
 12347  }
 12348  
 12349  func (e *Layer2AttributesExtended) GetTypes() (ExtendedCommunityAttrType, ExtendedCommunityAttrSubType) {
 12350  	return EC_TYPE_EVPN, EC_SUBTYPE_L2_ATTRIBUTES
 12351  }
 12352  
 12353  func parseEvpnExtended(data []byte) (ExtendedCommunityInterface, error) {
 12354  	if ExtendedCommunityAttrType(data[0]) != EC_TYPE_EVPN {
 12355  		return nil, NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("ext comm type is not EC_TYPE_EVPN: %d", data[0]))
 12356  	}
 12357  	subType := ExtendedCommunityAttrSubType(data[1])
 12358  	switch subType {
 12359  	case EC_SUBTYPE_ESI_LABEL:
 12360  		var isSingleActive bool
 12361  		if data[2] > 0 {
 12362  			isSingleActive = true
 12363  		}
 12364  		label := uint32(data[5])<<16 | uint32(data[6])<<8 | uint32(data[7])
 12365  		return &ESILabelExtended{
 12366  			IsSingleActive: isSingleActive,
 12367  			Label:          label,
 12368  		}, nil
 12369  	case EC_SUBTYPE_ES_IMPORT:
 12370  		return &ESImportRouteTarget{
 12371  			ESImport: net.HardwareAddr(data[2:8]),
 12372  		}, nil
 12373  	case EC_SUBTYPE_MAC_MOBILITY:
 12374  		var isSticky bool
 12375  		if data[2] > 0 {
 12376  			isSticky = true
 12377  		}
 12378  		seq := binary.BigEndian.Uint32(data[4:8])
 12379  		return &MacMobilityExtended{
 12380  			Sequence: seq,
 12381  			IsSticky: isSticky,
 12382  		}, nil
 12383  	case EC_SUBTYPE_ROUTER_MAC:
 12384  		return &RouterMacExtended{
 12385  			Mac: net.HardwareAddr(data[2:8]),
 12386  		}, nil
 12387  	case EC_SUBTYPE_L2_ATTRIBUTES:
 12388  		if flags := data[3]; flags == 0 {
 12389  			return &Layer2AttributesExtended{
 12390  				Mtu: binary.BigEndian.Uint16(data[4:6]),
 12391  			}, nil
 12392  		} else {
 12393  			return &Layer2AttributesExtended{
 12394  				HasCILabel:     flags&uint8(CI_LABEL) > 0,
 12395  				HasFlowLabel:   flags&uint8(FLOW_LABEL) > 0,
 12396  				HasControlWord: flags&uint8(CONTROL_WORD) > 0,
 12397  				IsPrimaryPe:    flags&uint8(PRIMARY_PE) > 0,
 12398  				IsBackupPe:     flags&uint8(BACKUP_PE) > 0,
 12399  				Mtu:            binary.BigEndian.Uint16(data[4:6]),
 12400  			}, nil
 12401  		}
 12402  	}
 12403  	return nil, NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("unknown evpn subtype: %d", subType))
 12404  }
 12405  
 12406  type TrafficRateExtended struct {
 12407  	AS   uint16
 12408  	Rate float32
 12409  }
 12410  
 12411  func (e *TrafficRateExtended) Serialize() ([]byte, error) {
 12412  	buf := make([]byte, 8)
 12413  	buf[0] = byte(EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL)
 12414  	buf[1] = byte(EC_SUBTYPE_FLOWSPEC_TRAFFIC_RATE)
 12415  	binary.BigEndian.PutUint16(buf[2:4], e.AS)
 12416  	binary.BigEndian.PutUint32(buf[4:8], math.Float32bits(e.Rate))
 12417  	return buf, nil
 12418  }
 12419  
 12420  func (e *TrafficRateExtended) String() string {
 12421  	buf := bytes.NewBuffer(make([]byte, 0, 32))
 12422  	if e.Rate == 0 {
 12423  		buf.WriteString("discard")
 12424  	} else {
 12425  		buf.WriteString("rate: " + strconv.FormatFloat(float64(e.Rate), 'f', 6, 32))
 12426  	}
 12427  	if e.AS != 0 {
 12428  		buf.WriteString("(as: " + strconv.FormatUint(uint64(e.AS), 10) + ")")
 12429  	}
 12430  	return buf.String()
 12431  }
 12432  
 12433  func (e *TrafficRateExtended) MarshalJSON() ([]byte, error) {
 12434  	t, s := e.GetTypes()
 12435  	return json.Marshal(struct {
 12436  		Type    ExtendedCommunityAttrType    `json:"type"`
 12437  		Subtype ExtendedCommunityAttrSubType `json:"subtype"`
 12438  		As      uint16                       `json:"as"`
 12439  		Rate    float32                      `json:"rate"`
 12440  	}{t, s, e.AS, e.Rate})
 12441  }
 12442  
 12443  func (e *TrafficRateExtended) GetTypes() (ExtendedCommunityAttrType, ExtendedCommunityAttrSubType) {
 12444  	return EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL, EC_SUBTYPE_FLOWSPEC_TRAFFIC_RATE
 12445  }
 12446  
 12447  func NewTrafficRateExtended(as uint16, rate float32) *TrafficRateExtended {
 12448  	return &TrafficRateExtended{
 12449  		AS:   as,
 12450  		Rate: rate,
 12451  	}
 12452  }
 12453  
 12454  type TrafficActionExtended struct {
 12455  	Terminal bool
 12456  	Sample   bool
 12457  }
 12458  
 12459  func (e *TrafficActionExtended) Serialize() ([]byte, error) {
 12460  	buf := make([]byte, 8)
 12461  	buf[0] = byte(EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL)
 12462  	buf[1] = byte(EC_SUBTYPE_FLOWSPEC_TRAFFIC_ACTION)
 12463  	if e.Terminal {
 12464  		buf[7] = 0x01
 12465  	}
 12466  	if e.Sample {
 12467  		buf[7] = buf[7] | 0x2
 12468  	}
 12469  	return buf, nil
 12470  }
 12471  
 12472  func (e *TrafficActionExtended) String() string {
 12473  	ss := make([]string, 0, 2)
 12474  	if e.Terminal {
 12475  		ss = append(ss, "terminal")
 12476  	}
 12477  	if e.Sample {
 12478  		ss = append(ss, "sample")
 12479  	}
 12480  	return "action: " + strings.Join(ss, "-")
 12481  }
 12482  
 12483  func (e *TrafficActionExtended) MarshalJSON() ([]byte, error) {
 12484  	t, s := e.GetTypes()
 12485  	return json.Marshal(struct {
 12486  		Type     ExtendedCommunityAttrType    `json:"type"`
 12487  		Subtype  ExtendedCommunityAttrSubType `json:"subtype"`
 12488  		Terminal bool                         `json:"terminal"`
 12489  		Sample   bool                         `json:"sample"`
 12490  	}{t, s, e.Terminal, e.Sample})
 12491  }
 12492  
 12493  func (e *TrafficActionExtended) GetTypes() (ExtendedCommunityAttrType, ExtendedCommunityAttrSubType) {
 12494  	return EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL, EC_SUBTYPE_FLOWSPEC_TRAFFIC_ACTION
 12495  }
 12496  
 12497  func NewTrafficActionExtended(terminal bool, sample bool) *TrafficActionExtended {
 12498  	return &TrafficActionExtended{
 12499  		Terminal: terminal,
 12500  		Sample:   sample,
 12501  	}
 12502  }
 12503  
 12504  type RedirectTwoOctetAsSpecificExtended struct {
 12505  	TwoOctetAsSpecificExtended
 12506  }
 12507  
 12508  func (e *RedirectTwoOctetAsSpecificExtended) Serialize() ([]byte, error) {
 12509  	buf, err := e.TwoOctetAsSpecificExtended.Serialize()
 12510  	buf[0] = byte(EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL)
 12511  	buf[1] = byte(EC_SUBTYPE_FLOWSPEC_REDIRECT)
 12512  	return buf, err
 12513  }
 12514  
 12515  func (e *RedirectTwoOctetAsSpecificExtended) String() string {
 12516  	return "redirect: " + e.TwoOctetAsSpecificExtended.String()
 12517  }
 12518  
 12519  func (e *RedirectTwoOctetAsSpecificExtended) MarshalJSON() ([]byte, error) {
 12520  	t, s := e.GetTypes()
 12521  	return json.Marshal(struct {
 12522  		Type    ExtendedCommunityAttrType    `json:"type"`
 12523  		Subtype ExtendedCommunityAttrSubType `json:"subtype"`
 12524  		Value   string                       `json:"value"`
 12525  	}{t, s, e.TwoOctetAsSpecificExtended.String()})
 12526  }
 12527  
 12528  func (e *RedirectTwoOctetAsSpecificExtended) GetTypes() (ExtendedCommunityAttrType, ExtendedCommunityAttrSubType) {
 12529  	return EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL, EC_SUBTYPE_FLOWSPEC_REDIRECT
 12530  }
 12531  
 12532  func NewRedirectTwoOctetAsSpecificExtended(as uint16, localAdmin uint32) *RedirectTwoOctetAsSpecificExtended {
 12533  	return &RedirectTwoOctetAsSpecificExtended{*NewTwoOctetAsSpecificExtended(EC_SUBTYPE_ROUTE_TARGET, as, localAdmin, false)}
 12534  }
 12535  
 12536  type RedirectIPv4AddressSpecificExtended struct {
 12537  	IPv4AddressSpecificExtended
 12538  }
 12539  
 12540  func (e *RedirectIPv4AddressSpecificExtended) Serialize() ([]byte, error) {
 12541  	buf, err := e.IPv4AddressSpecificExtended.Serialize()
 12542  	buf[0] = byte(EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL2)
 12543  	buf[1] = byte(EC_SUBTYPE_FLOWSPEC_REDIRECT)
 12544  	return buf, err
 12545  }
 12546  
 12547  func (e *RedirectIPv4AddressSpecificExtended) String() string {
 12548  	return "redirect: " + e.IPv4AddressSpecificExtended.String()
 12549  }
 12550  
 12551  func (e *RedirectIPv4AddressSpecificExtended) MarshalJSON() ([]byte, error) {
 12552  	t, s := e.GetTypes()
 12553  	return json.Marshal(struct {
 12554  		Type    ExtendedCommunityAttrType    `json:"type"`
 12555  		Subtype ExtendedCommunityAttrSubType `json:"subtype"`
 12556  		Value   string                       `json:"value"`
 12557  	}{t, s, e.IPv4AddressSpecificExtended.String()})
 12558  }
 12559  
 12560  func (e *RedirectIPv4AddressSpecificExtended) GetTypes() (ExtendedCommunityAttrType, ExtendedCommunityAttrSubType) {
 12561  	return EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL2, EC_SUBTYPE_FLOWSPEC_REDIRECT
 12562  }
 12563  
 12564  func NewRedirectIPv4AddressSpecificExtended(ipv4 string, localAdmin uint16) *RedirectIPv4AddressSpecificExtended {
 12565  	e := NewIPv4AddressSpecificExtended(EC_SUBTYPE_ROUTE_TARGET, ipv4, localAdmin, false)
 12566  	if e == nil {
 12567  		return nil
 12568  	}
 12569  	return &RedirectIPv4AddressSpecificExtended{*e}
 12570  }
 12571  
 12572  type RedirectIPv6AddressSpecificExtended struct {
 12573  	IPv6AddressSpecificExtended
 12574  }
 12575  
 12576  func (e *RedirectIPv6AddressSpecificExtended) Serialize() ([]byte, error) {
 12577  	buf, err := e.IPv6AddressSpecificExtended.Serialize()
 12578  	buf[0] = byte(EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL)
 12579  	buf[1] = byte(EC_SUBTYPE_FLOWSPEC_REDIRECT_IP6)
 12580  	return buf, err
 12581  }
 12582  
 12583  func (e *RedirectIPv6AddressSpecificExtended) String() string {
 12584  	return "redirect: " + e.IPv6AddressSpecificExtended.String()
 12585  }
 12586  
 12587  func (e *RedirectIPv6AddressSpecificExtended) MarshalJSON() ([]byte, error) {
 12588  	t, s := e.GetTypes()
 12589  	return json.Marshal(struct {
 12590  		Type    ExtendedCommunityAttrType    `json:"type"`
 12591  		Subtype ExtendedCommunityAttrSubType `json:"subtype"`
 12592  		Value   string                       `json:"value"`
 12593  	}{t, s, e.IPv6AddressSpecificExtended.String()})
 12594  }
 12595  
 12596  func (e *RedirectIPv6AddressSpecificExtended) GetTypes() (ExtendedCommunityAttrType, ExtendedCommunityAttrSubType) {
 12597  	return EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL, EC_SUBTYPE_FLOWSPEC_REDIRECT_IP6
 12598  }
 12599  
 12600  func NewRedirectIPv6AddressSpecificExtended(ipv6 string, localAdmin uint16) *RedirectIPv6AddressSpecificExtended {
 12601  	e := NewIPv6AddressSpecificExtended(EC_SUBTYPE_ROUTE_TARGET, ipv6, localAdmin, false)
 12602  	if e == nil {
 12603  		return nil
 12604  	}
 12605  	return &RedirectIPv6AddressSpecificExtended{*e}
 12606  }
 12607  
 12608  type RedirectFourOctetAsSpecificExtended struct {
 12609  	FourOctetAsSpecificExtended
 12610  }
 12611  
 12612  func (e *RedirectFourOctetAsSpecificExtended) Serialize() ([]byte, error) {
 12613  	buf, err := e.FourOctetAsSpecificExtended.Serialize()
 12614  	buf[0] = byte(EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL3)
 12615  	buf[1] = byte(EC_SUBTYPE_FLOWSPEC_REDIRECT)
 12616  	return buf, err
 12617  }
 12618  
 12619  func (e *RedirectFourOctetAsSpecificExtended) String() string {
 12620  	return "redirect: " + e.FourOctetAsSpecificExtended.String()
 12621  }
 12622  
 12623  func (e *RedirectFourOctetAsSpecificExtended) MarshalJSON() ([]byte, error) {
 12624  	t, s := e.GetTypes()
 12625  	return json.Marshal(struct {
 12626  		Type    ExtendedCommunityAttrType    `json:"type"`
 12627  		Subtype ExtendedCommunityAttrSubType `json:"subtype"`
 12628  		Value   string                       `json:"value"`
 12629  	}{t, s, e.FourOctetAsSpecificExtended.String()})
 12630  }
 12631  
 12632  func (e *RedirectFourOctetAsSpecificExtended) GetTypes() (ExtendedCommunityAttrType, ExtendedCommunityAttrSubType) {
 12633  	return EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL3, EC_SUBTYPE_FLOWSPEC_REDIRECT
 12634  }
 12635  
 12636  func NewRedirectFourOctetAsSpecificExtended(as uint32, localAdmin uint16) *RedirectFourOctetAsSpecificExtended {
 12637  	return &RedirectFourOctetAsSpecificExtended{*NewFourOctetAsSpecificExtended(EC_SUBTYPE_ROUTE_TARGET, as, localAdmin, false)}
 12638  }
 12639  
 12640  type TrafficRemarkExtended struct {
 12641  	DSCP uint8
 12642  }
 12643  
 12644  func (e *TrafficRemarkExtended) Serialize() ([]byte, error) {
 12645  	buf := make([]byte, 8)
 12646  	buf[0] = byte(EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL)
 12647  	buf[1] = byte(EC_SUBTYPE_FLOWSPEC_TRAFFIC_REMARK)
 12648  	buf[7] = byte(e.DSCP)
 12649  	return buf, nil
 12650  }
 12651  
 12652  func (e *TrafficRemarkExtended) String() string {
 12653  	return "remark: " + strconv.FormatUint(uint64(e.DSCP), 10)
 12654  }
 12655  
 12656  func (e *TrafficRemarkExtended) MarshalJSON() ([]byte, error) {
 12657  	t, s := e.GetTypes()
 12658  	return json.Marshal(struct {
 12659  		Type    ExtendedCommunityAttrType    `json:"type"`
 12660  		Subtype ExtendedCommunityAttrSubType `json:"subtype"`
 12661  		Value   uint8                        `json:"value"`
 12662  	}{t, s, e.DSCP})
 12663  }
 12664  
 12665  func (e *TrafficRemarkExtended) GetTypes() (ExtendedCommunityAttrType, ExtendedCommunityAttrSubType) {
 12666  	return EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL, EC_SUBTYPE_FLOWSPEC_TRAFFIC_REMARK
 12667  }
 12668  
 12669  func NewTrafficRemarkExtended(dscp uint8) *TrafficRemarkExtended {
 12670  	return &TrafficRemarkExtended{
 12671  		DSCP: dscp,
 12672  	}
 12673  }
 12674  
 12675  func parseGenericTransitiveExperimentalExtended(data []byte) (ExtendedCommunityInterface, error) {
 12676  	typ := ExtendedCommunityAttrType(data[0])
 12677  	if typ != EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL && typ != EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL2 && typ != EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL3 {
 12678  		return nil, NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("ext comm type is not EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL: %d", data[0]))
 12679  	}
 12680  	subType := ExtendedCommunityAttrSubType(data[1])
 12681  	switch subType {
 12682  	case EC_SUBTYPE_FLOWSPEC_TRAFFIC_RATE:
 12683  		asn := binary.BigEndian.Uint16(data[2:4])
 12684  		bits := binary.BigEndian.Uint32(data[4:8])
 12685  		rate := math.Float32frombits(bits)
 12686  		return NewTrafficRateExtended(asn, rate), nil
 12687  	case EC_SUBTYPE_FLOWSPEC_TRAFFIC_ACTION:
 12688  		terminal := data[7]&0x1 == 1
 12689  		sample := (data[7]>>1)&0x1 == 1
 12690  		return NewTrafficActionExtended(terminal, sample), nil
 12691  	case EC_SUBTYPE_FLOWSPEC_REDIRECT:
 12692  		// RFC7674
 12693  		switch typ {
 12694  		case EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL:
 12695  			as := binary.BigEndian.Uint16(data[2:4])
 12696  			localAdmin := binary.BigEndian.Uint32(data[4:8])
 12697  			return NewRedirectTwoOctetAsSpecificExtended(as, localAdmin), nil
 12698  		case EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL2:
 12699  			ipv4 := net.IP(data[2:6]).String()
 12700  			localAdmin := binary.BigEndian.Uint16(data[6:8])
 12701  			return NewRedirectIPv4AddressSpecificExtended(ipv4, localAdmin), nil
 12702  		case EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL3:
 12703  			as := binary.BigEndian.Uint32(data[2:6])
 12704  			localAdmin := binary.BigEndian.Uint16(data[6:8])
 12705  			return NewRedirectFourOctetAsSpecificExtended(as, localAdmin), nil
 12706  		}
 12707  	case EC_SUBTYPE_FLOWSPEC_TRAFFIC_REMARK:
 12708  		dscp := data[7]
 12709  		return NewTrafficRemarkExtended(dscp), nil
 12710  	case EC_SUBTYPE_FLOWSPEC_REDIRECT_IP6:
 12711  		ipv6 := net.IP(data[2:18]).String()
 12712  		localAdmin := binary.BigEndian.Uint16(data[18:20])
 12713  		return NewRedirectIPv6AddressSpecificExtended(ipv6, localAdmin), nil
 12714  	case EC_SUBTYPE_L2_INFO:
 12715  		switch data[2] {
 12716  		case byte(LAYER2ENCAPSULATION_TYPE_VPLS):
 12717  			controlFlags := uint8(data[3])
 12718  			mtu := binary.BigEndian.Uint16(data[4:6])
 12719  			return NewVPLSExtended(controlFlags, mtu), nil
 12720  		}
 12721  	}
 12722  	return &UnknownExtended{
 12723  		Type:  ExtendedCommunityAttrType(data[0]),
 12724  		Value: data[1:8],
 12725  	}, nil
 12726  }
 12727  
 12728  func parseIP6FlowSpecExtended(data []byte) (ExtendedCommunityInterface, error) {
 12729  	typ := ExtendedCommunityAttrType(data[0])
 12730  	if typ != EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL && typ != EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL2 && typ != EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL3 {
 12731  		return nil, NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, fmt.Sprintf("ext comm type is not EC_TYPE_FLOWSPEC: %d", data[0]))
 12732  	}
 12733  	subType := ExtendedCommunityAttrSubType(data[1])
 12734  	switch subType {
 12735  	case EC_SUBTYPE_FLOWSPEC_REDIRECT_IP6:
 12736  		// RFC7674
 12737  		switch typ {
 12738  		case EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL:
 12739  			ipv6 := net.IP(data[2:18]).String()
 12740  			localAdmin := binary.BigEndian.Uint16(data[18:20])
 12741  			return NewRedirectIPv6AddressSpecificExtended(ipv6, localAdmin), nil
 12742  		}
 12743  	}
 12744  	return &UnknownExtended{
 12745  		Type:  ExtendedCommunityAttrType(data[0]),
 12746  		Value: data[1:20],
 12747  	}, nil
 12748  }
 12749  
 12750  type UnknownExtended struct {
 12751  	Type  ExtendedCommunityAttrType
 12752  	Value []byte
 12753  }
 12754  
 12755  func (e *UnknownExtended) Serialize() ([]byte, error) {
 12756  	if len(e.Value) != 7 {
 12757  		return nil, fmt.Errorf("invalid value length for unknown extended community: %d", len(e.Value))
 12758  	}
 12759  	buf := make([]byte, 8)
 12760  	buf[0] = uint8(e.Type)
 12761  	copy(buf[1:], e.Value)
 12762  	return buf, nil
 12763  }
 12764  
 12765  func (e *UnknownExtended) String() string {
 12766  	var buf [8]byte
 12767  	copy(buf[1:], e.Value)
 12768  	return strconv.FormatUint(binary.BigEndian.Uint64(buf[:]), 10)
 12769  }
 12770  
 12771  func (e *UnknownExtended) MarshalJSON() ([]byte, error) {
 12772  	t, s := e.GetTypes()
 12773  	return json.Marshal(struct {
 12774  		Type    ExtendedCommunityAttrType    `json:"type"`
 12775  		Subtype ExtendedCommunityAttrSubType `json:"subtype"`
 12776  		Value   []byte                       `json:"value"`
 12777  	}{
 12778  		Type:    t,
 12779  		Subtype: s,
 12780  		Value:   e.Value,
 12781  	})
 12782  }
 12783  
 12784  func (e *UnknownExtended) GetTypes() (ExtendedCommunityAttrType, ExtendedCommunityAttrSubType) {
 12785  	var subType ExtendedCommunityAttrSubType
 12786  	if len(e.Value) > 0 {
 12787  		// Use the first byte of value as the sub type
 12788  		subType = ExtendedCommunityAttrSubType(e.Value[0])
 12789  	}
 12790  	return e.Type, subType
 12791  }
 12792  
 12793  func NewUnknownExtended(typ ExtendedCommunityAttrType, value []byte) *UnknownExtended {
 12794  	v := make([]byte, 7)
 12795  	copy(v, value)
 12796  	return &UnknownExtended{
 12797  		Type:  typ,
 12798  		Value: v,
 12799  	}
 12800  }
 12801  
 12802  type PathAttributeExtendedCommunities struct {
 12803  	PathAttribute
 12804  	Value []ExtendedCommunityInterface
 12805  }
 12806  
 12807  func ParseExtended(data []byte) (ExtendedCommunityInterface, error) {
 12808  	if len(data) < 8 {
 12809  		return nil, NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "not all extended community bytes are available")
 12810  	}
 12811  	attrType := ExtendedCommunityAttrType(data[0])
 12812  	subtype := ExtendedCommunityAttrSubType(data[1])
 12813  	transitive := false
 12814  	switch attrType {
 12815  	case EC_TYPE_TRANSITIVE_TWO_OCTET_AS_SPECIFIC:
 12816  		transitive = true
 12817  		fallthrough
 12818  	case EC_TYPE_NON_TRANSITIVE_TWO_OCTET_AS_SPECIFIC:
 12819  		as := binary.BigEndian.Uint16(data[2:4])
 12820  		localAdmin := binary.BigEndian.Uint32(data[4:8])
 12821  
 12822  		if subtype == EC_SUBTYPE_LINK_BANDWIDTH {
 12823  			return NewLinkBandwidthExtended(as, math.Float32frombits(localAdmin)), nil
 12824  		} else {
 12825  			return NewTwoOctetAsSpecificExtended(subtype, as, localAdmin, transitive), nil
 12826  		}
 12827  	case EC_TYPE_TRANSITIVE_IP4_SPECIFIC:
 12828  		transitive = true
 12829  		fallthrough
 12830  	case EC_TYPE_NON_TRANSITIVE_IP4_SPECIFIC:
 12831  		ipv4 := net.IP(data[2:6]).String()
 12832  		localAdmin := binary.BigEndian.Uint16(data[6:8])
 12833  		return NewIPv4AddressSpecificExtended(subtype, ipv4, localAdmin, transitive), nil
 12834  	case EC_TYPE_TRANSITIVE_FOUR_OCTET_AS_SPECIFIC:
 12835  		transitive = true
 12836  		fallthrough
 12837  	case EC_TYPE_NON_TRANSITIVE_FOUR_OCTET_AS_SPECIFIC:
 12838  		as := binary.BigEndian.Uint32(data[2:6])
 12839  		localAdmin := binary.BigEndian.Uint16(data[6:8])
 12840  		return NewFourOctetAsSpecificExtended(subtype, as, localAdmin, transitive), nil
 12841  	case EC_TYPE_TRANSITIVE_OPAQUE:
 12842  		transitive = true
 12843  		fallthrough
 12844  	case EC_TYPE_NON_TRANSITIVE_OPAQUE:
 12845  		return parseOpaqueExtended(data)
 12846  	case EC_TYPE_EVPN:
 12847  		return parseEvpnExtended(data)
 12848  	case EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL, EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL2, EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL3:
 12849  		return parseGenericTransitiveExperimentalExtended(data)
 12850  	case EC_TYPE_MUP:
 12851  		return parseMUPExtended(data)
 12852  	default:
 12853  		return &UnknownExtended{
 12854  			Type:  ExtendedCommunityAttrType(data[0]),
 12855  			Value: data[1:8],
 12856  		}, nil
 12857  	}
 12858  }
 12859  
 12860  func (p *PathAttributeExtendedCommunities) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
 12861  	value, err := p.PathAttribute.DecodeFromBytes(data, options...)
 12862  	if err != nil {
 12863  		return err
 12864  	}
 12865  	if p.Length%8 != 0 {
 12866  		eCode := uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR)
 12867  		eSubCode := uint8(BGP_ERROR_SUB_ATTRIBUTE_LENGTH_ERROR)
 12868  		return NewMessageError(eCode, eSubCode, nil, "extendedcommunities length isn't correct")
 12869  	}
 12870  	for len(value) >= 8 {
 12871  		e, err := ParseExtended(value)
 12872  		if err != nil {
 12873  			return err
 12874  		}
 12875  		p.Value = append(p.Value, e)
 12876  		value = value[8:]
 12877  	}
 12878  	return nil
 12879  }
 12880  
 12881  func (p *PathAttributeExtendedCommunities) Serialize(options ...*MarshallingOption) ([]byte, error) {
 12882  	buf := make([]byte, 0)
 12883  	for _, p := range p.Value {
 12884  		ebuf, err := p.Serialize()
 12885  		if err != nil {
 12886  			return nil, err
 12887  		}
 12888  		buf = append(buf, ebuf...)
 12889  	}
 12890  	return p.PathAttribute.Serialize(buf, options...)
 12891  }
 12892  
 12893  func (p *PathAttributeExtendedCommunities) String() string {
 12894  	buf := bytes.NewBuffer(make([]byte, 0, 32))
 12895  	for idx, v := range p.Value {
 12896  		buf.WriteString("[")
 12897  		buf.WriteString(v.String())
 12898  		buf.WriteString("]")
 12899  		if idx < len(p.Value)-1 {
 12900  			buf.WriteString(", ")
 12901  		}
 12902  	}
 12903  	return "{Extcomms: " + buf.String() + "}"
 12904  }
 12905  
 12906  func (p *PathAttributeExtendedCommunities) MarshalJSON() ([]byte, error) {
 12907  	return json.Marshal(struct {
 12908  		Type  BGPAttrType                  `json:"type"`
 12909  		Value []ExtendedCommunityInterface `json:"value"`
 12910  	}{
 12911  		Type:  p.GetType(),
 12912  		Value: p.Value,
 12913  	})
 12914  }
 12915  
 12916  func NewPathAttributeExtendedCommunities(value []ExtendedCommunityInterface) *PathAttributeExtendedCommunities {
 12917  	l := len(value) * 8
 12918  	t := BGP_ATTR_TYPE_EXTENDED_COMMUNITIES
 12919  	return &PathAttributeExtendedCommunities{
 12920  		PathAttribute: PathAttribute{
 12921  			Flags:  getPathAttrFlags(t, l),
 12922  			Type:   t,
 12923  			Length: uint16(l),
 12924  		},
 12925  		Value: value,
 12926  	}
 12927  }
 12928  
 12929  type PathAttributeAs4Path struct {
 12930  	PathAttribute
 12931  	Value []*As4PathParam
 12932  }
 12933  
 12934  func (p *PathAttributeAs4Path) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
 12935  	value, err := p.PathAttribute.DecodeFromBytes(data, options...)
 12936  	if err != nil {
 12937  		return err
 12938  	}
 12939  	if p.Length == 0 {
 12940  		// ibgp or something
 12941  		return nil
 12942  	}
 12943  	eCode := uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR)
 12944  	eSubCode := uint8(BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST)
 12945  	isAs4, err := validateAsPathValueBytes(value)
 12946  	if err != nil {
 12947  		return err
 12948  	}
 12949  
 12950  	if !isAs4 {
 12951  		return NewMessageError(eCode, eSubCode, nil, "AS4 PATH param is malformed")
 12952  	}
 12953  
 12954  	for len(value) > 0 {
 12955  		tuple := &As4PathParam{}
 12956  		tuple.DecodeFromBytes(value)
 12957  		p.Value = append(p.Value, tuple)
 12958  		if len(value) < tuple.Len() {
 12959  			return NewMessageError(eCode, eSubCode, nil, "AS4 PATH param is malformed")
 12960  		}
 12961  		value = value[tuple.Len():]
 12962  	}
 12963  	return nil
 12964  }
 12965  
 12966  func (p *PathAttributeAs4Path) Serialize(options ...*MarshallingOption) ([]byte, error) {
 12967  	buf := make([]byte, 0)
 12968  	for _, v := range p.Value {
 12969  		vbuf, err := v.Serialize()
 12970  		if err != nil {
 12971  			return nil, err
 12972  		}
 12973  		buf = append(buf, vbuf...)
 12974  	}
 12975  	return p.PathAttribute.Serialize(buf, options...)
 12976  }
 12977  
 12978  func (p *PathAttributeAs4Path) String() string {
 12979  	params := make([]string, 0, len(p.Value))
 12980  	for _, param := range p.Value {
 12981  		params = append(params, param.String())
 12982  	}
 12983  	return strings.Join(params, " ")
 12984  }
 12985  
 12986  func (p *PathAttributeAs4Path) MarshalJSON() ([]byte, error) {
 12987  	return json.Marshal(struct {
 12988  		Type  BGPAttrType     `json:"type"`
 12989  		Value []*As4PathParam `json:"as_paths"`
 12990  	}{
 12991  		Type:  p.GetType(),
 12992  		Value: p.Value,
 12993  	})
 12994  }
 12995  
 12996  func NewPathAttributeAs4Path(value []*As4PathParam) *PathAttributeAs4Path {
 12997  	var l int
 12998  	for _, v := range value {
 12999  		l += v.Len()
 13000  	}
 13001  	t := BGP_ATTR_TYPE_AS4_PATH
 13002  	return &PathAttributeAs4Path{
 13003  		PathAttribute: PathAttribute{
 13004  			Flags:  getPathAttrFlags(t, l),
 13005  			Type:   t,
 13006  			Length: uint16(l),
 13007  		},
 13008  		Value: value,
 13009  	}
 13010  }
 13011  
 13012  type PathAttributeAs4Aggregator struct {
 13013  	PathAttribute
 13014  	Value PathAttributeAggregatorParam
 13015  }
 13016  
 13017  func (p *PathAttributeAs4Aggregator) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
 13018  	value, err := p.PathAttribute.DecodeFromBytes(data, options...)
 13019  	if err != nil {
 13020  		return err
 13021  	}
 13022  	if p.Length != 8 {
 13023  		eCode := uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR)
 13024  		eSubCode := uint8(BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST)
 13025  		return NewMessageError(eCode, eSubCode, nil, "AS4 Aggregator length is incorrect")
 13026  	}
 13027  	p.Value.AS = binary.BigEndian.Uint32(value[0:4])
 13028  	p.Value.Address = value[4:]
 13029  	return nil
 13030  }
 13031  
 13032  func (p *PathAttributeAs4Aggregator) Serialize(options ...*MarshallingOption) ([]byte, error) {
 13033  	buf := make([]byte, 8)
 13034  	binary.BigEndian.PutUint32(buf[0:], p.Value.AS)
 13035  	copy(buf[4:], p.Value.Address.To4())
 13036  	return p.PathAttribute.Serialize(buf, options...)
 13037  }
 13038  
 13039  func (p *PathAttributeAs4Aggregator) String() string {
 13040  	return "{As4Aggregator: {AS: " +
 13041  		strconv.FormatUint(uint64(p.Value.AS), 10) + ", Address: " + p.Value.Address.String() + "}}"
 13042  }
 13043  
 13044  func (p *PathAttributeAs4Aggregator) MarshalJSON() ([]byte, error) {
 13045  	return json.Marshal(struct {
 13046  		Type    BGPAttrType `json:"type"`
 13047  		AS      uint32      `json:"as"`
 13048  		Address string      `json:"address"`
 13049  	}{
 13050  		Type:    p.GetType(),
 13051  		AS:      p.Value.AS,
 13052  		Address: p.Value.Address.String(),
 13053  	})
 13054  }
 13055  
 13056  func NewPathAttributeAs4Aggregator(as uint32, address string) *PathAttributeAs4Aggregator {
 13057  	t := BGP_ATTR_TYPE_AS4_AGGREGATOR
 13058  	return &PathAttributeAs4Aggregator{
 13059  		PathAttribute: PathAttribute{
 13060  			Flags:  PathAttrFlags[t],
 13061  			Type:   t,
 13062  			Length: 8,
 13063  		},
 13064  		Value: PathAttributeAggregatorParam{
 13065  			AS:      as,
 13066  			Address: net.ParseIP(address).To4(),
 13067  		},
 13068  	}
 13069  }
 13070  
 13071  type TunnelEncapSubTLVInterface interface {
 13072  	Len() int
 13073  	DecodeFromBytes([]byte) error
 13074  	Serialize() ([]byte, error)
 13075  	String() string
 13076  	MarshalJSON() ([]byte, error)
 13077  }
 13078  
 13079  type TunnelEncapSubTLV struct {
 13080  	Type   EncapSubTLVType
 13081  	Length uint16
 13082  }
 13083  
 13084  func (t *TunnelEncapSubTLV) Len() int {
 13085  	if t.Type >= 0x80 {
 13086  		return 3 + int(t.Length)
 13087  	}
 13088  	return 2 + int(t.Length)
 13089  }
 13090  
 13091  func (t *TunnelEncapSubTLV) DecodeFromBytes(data []byte) (value []byte, err error) {
 13092  	t.Type = EncapSubTLVType(data[0])
 13093  	if t.Type >= 0x80 {
 13094  		t.Length = binary.BigEndian.Uint16(data[1:3])
 13095  		data = data[3:]
 13096  	} else {
 13097  		t.Length = uint16(data[1])
 13098  		data = data[2:]
 13099  	}
 13100  	if len(data) < int(t.Length) {
 13101  		return nil, NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "Not all TunnelEncapSubTLV bytes available")
 13102  	}
 13103  	return data[:t.Length], nil
 13104  }
 13105  
 13106  func (t *TunnelEncapSubTLV) Serialize(value []byte) (buf []byte, err error) {
 13107  	t.Length = uint16(len(value))
 13108  	if t.Type >= 0x80 {
 13109  		buf = append(make([]byte, 3), value...)
 13110  		binary.BigEndian.PutUint16(buf[1:3], t.Length)
 13111  	} else {
 13112  		buf = append(make([]byte, 2), value...)
 13113  		buf[1] = uint8(t.Length)
 13114  	}
 13115  	buf[0] = uint8(t.Type)
 13116  	return buf, nil
 13117  }
 13118  
 13119  type TunnelEncapSubTLVUnknown struct {
 13120  	TunnelEncapSubTLV
 13121  	Value []byte
 13122  }
 13123  
 13124  func (t *TunnelEncapSubTLVUnknown) DecodeFromBytes(data []byte) error {
 13125  	value, err := t.TunnelEncapSubTLV.DecodeFromBytes(data)
 13126  	if err != nil {
 13127  		return err
 13128  	}
 13129  	t.Value = value
 13130  	return nil
 13131  }
 13132  
 13133  func (t *TunnelEncapSubTLVUnknown) Serialize() ([]byte, error) {
 13134  	return t.TunnelEncapSubTLV.Serialize(t.Value)
 13135  }
 13136  
 13137  func (t *TunnelEncapSubTLVUnknown) String() string {
 13138  	return fmt.Sprintf("{Type: %d, Value: %x}", t.Type, t.Value)
 13139  }
 13140  
 13141  func (t *TunnelEncapSubTLVUnknown) MarshalJSON() ([]byte, error) {
 13142  	return json.Marshal(struct {
 13143  		Type  EncapSubTLVType `json:"type"`
 13144  		Value []byte          `json:"value"`
 13145  	}{
 13146  		Type:  t.Type,
 13147  		Value: t.Value,
 13148  	})
 13149  }
 13150  
 13151  func NewTunnelEncapSubTLVUnknown(typ EncapSubTLVType, value []byte) *TunnelEncapSubTLVUnknown {
 13152  	return &TunnelEncapSubTLVUnknown{
 13153  		TunnelEncapSubTLV: TunnelEncapSubTLV{
 13154  			Type: typ,
 13155  		},
 13156  		Value: value,
 13157  	}
 13158  }
 13159  
 13160  type TunnelEncapSubTLVEncapsulation struct {
 13161  	TunnelEncapSubTLV
 13162  	Key    uint32 // this represent both SessionID for L2TPv3 case and GRE-key for GRE case (RFC5512 4.)
 13163  	Cookie []byte
 13164  }
 13165  
 13166  func (t *TunnelEncapSubTLVEncapsulation) DecodeFromBytes(data []byte) error {
 13167  	value, err := t.TunnelEncapSubTLV.DecodeFromBytes(data)
 13168  	if err != nil {
 13169  		return err
 13170  	}
 13171  	if t.Length < 4 {
 13172  		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "Not all TunnelEncapSubTLVEncapsulation bytes available")
 13173  	}
 13174  	t.Key = binary.BigEndian.Uint32(value[0:4])
 13175  	t.Cookie = value[4:]
 13176  	return nil
 13177  }
 13178  
 13179  func (t *TunnelEncapSubTLVEncapsulation) Serialize() ([]byte, error) {
 13180  	buf := make([]byte, 4, 4+len(t.Cookie))
 13181  	binary.BigEndian.PutUint32(buf, t.Key)
 13182  	buf = append(buf, t.Cookie...)
 13183  	return t.TunnelEncapSubTLV.Serialize(buf)
 13184  }
 13185  
 13186  func (t *TunnelEncapSubTLVEncapsulation) String() string {
 13187  	return fmt.Sprintf("{Key: %d, Cookie: %x}", t.Key, t.Cookie)
 13188  }
 13189  
 13190  func (t *TunnelEncapSubTLVEncapsulation) MarshalJSON() ([]byte, error) {
 13191  	return json.Marshal(struct {
 13192  		Type   EncapSubTLVType `json:"type"`
 13193  		Key    uint32          `json:"key"`
 13194  		Cookie []byte          `json:"cookie"`
 13195  	}{
 13196  		Type:   t.Type,
 13197  		Key:    t.Key,
 13198  		Cookie: t.Cookie,
 13199  	})
 13200  }
 13201  
 13202  func NewTunnelEncapSubTLVEncapsulation(key uint32, cookie []byte) *TunnelEncapSubTLVEncapsulation {
 13203  	return &TunnelEncapSubTLVEncapsulation{
 13204  		TunnelEncapSubTLV: TunnelEncapSubTLV{
 13205  			Type: ENCAP_SUBTLV_TYPE_ENCAPSULATION,
 13206  		},
 13207  		Key:    key,
 13208  		Cookie: cookie,
 13209  	}
 13210  }
 13211  
 13212  type TunnelEncapSubTLVProtocol struct {
 13213  	TunnelEncapSubTLV
 13214  	Protocol uint16
 13215  }
 13216  
 13217  func (t *TunnelEncapSubTLVProtocol) DecodeFromBytes(data []byte) error {
 13218  	value, err := t.TunnelEncapSubTLV.DecodeFromBytes(data)
 13219  	if err != nil {
 13220  		return err
 13221  	}
 13222  	if t.Length < 2 {
 13223  		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "Not all TunnelEncapSubTLVProtocol bytes available")
 13224  	}
 13225  	t.Protocol = binary.BigEndian.Uint16(value[0:2])
 13226  	return nil
 13227  }
 13228  
 13229  func (t *TunnelEncapSubTLVProtocol) Serialize() ([]byte, error) {
 13230  	var buf [2]byte
 13231  	binary.BigEndian.PutUint16(buf[:2], t.Protocol)
 13232  	return t.TunnelEncapSubTLV.Serialize(buf[:])
 13233  }
 13234  
 13235  func (t *TunnelEncapSubTLVProtocol) String() string {
 13236  	return fmt.Sprintf("{Protocol: %d}", t.Protocol)
 13237  }
 13238  
 13239  func (t *TunnelEncapSubTLVProtocol) MarshalJSON() ([]byte, error) {
 13240  	return json.Marshal(struct {
 13241  		Type     EncapSubTLVType `json:"type"`
 13242  		Protocol uint16          `json:"protocol"`
 13243  	}{
 13244  		Type:     t.Type,
 13245  		Protocol: t.Protocol,
 13246  	})
 13247  }
 13248  
 13249  func NewTunnelEncapSubTLVProtocol(protocol uint16) *TunnelEncapSubTLVProtocol {
 13250  	return &TunnelEncapSubTLVProtocol{
 13251  		TunnelEncapSubTLV: TunnelEncapSubTLV{
 13252  			Type: ENCAP_SUBTLV_TYPE_PROTOCOL,
 13253  		},
 13254  		Protocol: protocol,
 13255  	}
 13256  }
 13257  
 13258  type TunnelEncapSubTLVColor struct {
 13259  	TunnelEncapSubTLV
 13260  	Color uint32
 13261  }
 13262  
 13263  func (t *TunnelEncapSubTLVColor) DecodeFromBytes(data []byte) error {
 13264  	value, err := t.TunnelEncapSubTLV.DecodeFromBytes(data)
 13265  	if err != nil {
 13266  		return err
 13267  	}
 13268  	if t.Length != 8 {
 13269  		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "Invalid TunnelEncapSubTLVColor length")
 13270  	}
 13271  	t.Color = binary.BigEndian.Uint32(value[4:8])
 13272  	return nil
 13273  }
 13274  
 13275  func (t *TunnelEncapSubTLVColor) Serialize() ([]byte, error) {
 13276  	var buf [8]byte
 13277  	buf[0] = byte(EC_TYPE_TRANSITIVE_OPAQUE)
 13278  	buf[1] = byte(EC_SUBTYPE_COLOR)
 13279  	binary.BigEndian.PutUint32(buf[4:8], t.Color)
 13280  	return t.TunnelEncapSubTLV.Serialize(buf[:])
 13281  }
 13282  
 13283  func (t *TunnelEncapSubTLVColor) String() string {
 13284  	return fmt.Sprintf("{Color: %d}", t.Color)
 13285  }
 13286  
 13287  func (t *TunnelEncapSubTLVColor) MarshalJSON() ([]byte, error) {
 13288  	return json.Marshal(struct {
 13289  		Type  EncapSubTLVType `json:"type"`
 13290  		Color uint32          `json:"color"`
 13291  	}{
 13292  		Type:  t.Type,
 13293  		Color: t.Color,
 13294  	})
 13295  }
 13296  
 13297  func NewTunnelEncapSubTLVColor(color uint32) *TunnelEncapSubTLVColor {
 13298  	return &TunnelEncapSubTLVColor{
 13299  		TunnelEncapSubTLV: TunnelEncapSubTLV{
 13300  			Type: ENCAP_SUBTLV_TYPE_COLOR,
 13301  		},
 13302  		Color: color,
 13303  	}
 13304  }
 13305  
 13306  type TunnelEncapSubTLVEgressEndpoint struct {
 13307  	TunnelEncapSubTLV
 13308  	Address net.IP
 13309  }
 13310  
 13311  // Tunnel Egress Endpoint Sub-TLV subfield positions
 13312  const (
 13313  	EGRESS_ENDPOINT_RESERVED_POS = 0
 13314  	EGRESS_ENDPOINT_FAMILY_POS   = 4
 13315  	EGRESS_ENDPOINT_ADDRESS_POS  = 6
 13316  )
 13317  
 13318  func (t *TunnelEncapSubTLVEgressEndpoint) DecodeFromBytes(data []byte) error {
 13319  	value, err := t.TunnelEncapSubTLV.DecodeFromBytes(data)
 13320  	if err != nil {
 13321  		return err
 13322  	}
 13323  	if t.Length < EGRESS_ENDPOINT_ADDRESS_POS {
 13324  		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "Not all TunnelEncapSubTLVEgressEndpoint bytes available")
 13325  	}
 13326  	addressFamily := binary.BigEndian.Uint16(value[EGRESS_ENDPOINT_FAMILY_POS : EGRESS_ENDPOINT_FAMILY_POS+2])
 13327  
 13328  	var addressLen uint16
 13329  	switch addressFamily {
 13330  	case 0:
 13331  		addressLen = 0
 13332  	case AFI_IP:
 13333  		addressLen = net.IPv4len
 13334  	case AFI_IP6:
 13335  		addressLen = net.IPv6len
 13336  	default:
 13337  		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "Unsupported address family in TunnelEncapSubTLVEgressEndpoint")
 13338  	}
 13339  	if t.Length != EGRESS_ENDPOINT_ADDRESS_POS+addressLen {
 13340  		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "Not all TunnelEncapSubTLVEgressEndpoint address bytes available")
 13341  	}
 13342  	t.Address = nil
 13343  	if addressFamily != 0 {
 13344  		t.Address = net.IP(value[EGRESS_ENDPOINT_ADDRESS_POS : EGRESS_ENDPOINT_ADDRESS_POS+addressLen])
 13345  	}
 13346  
 13347  	return nil
 13348  }
 13349  
 13350  func (t *TunnelEncapSubTLVEgressEndpoint) Serialize() ([]byte, error) {
 13351  	var length uint32 = EGRESS_ENDPOINT_ADDRESS_POS
 13352  	var family uint16
 13353  	var ip net.IP
 13354  	if t.Address == nil {
 13355  		family = 0
 13356  	} else if t.Address.To4() != nil {
 13357  		length += net.IPv4len
 13358  		family = AFI_IP
 13359  		ip = t.Address.To4()
 13360  	} else {
 13361  		length += net.IPv6len
 13362  		family = AFI_IP6
 13363  		ip = t.Address.To16()
 13364  	}
 13365  	buf := make([]byte, length)
 13366  	binary.BigEndian.PutUint32(buf, 0)
 13367  	binary.BigEndian.PutUint16(buf[EGRESS_ENDPOINT_FAMILY_POS:], family)
 13368  	if family != 0 {
 13369  		copy(buf[EGRESS_ENDPOINT_ADDRESS_POS:], ip)
 13370  	}
 13371  	return t.TunnelEncapSubTLV.Serialize(buf)
 13372  }
 13373  
 13374  func (t *TunnelEncapSubTLVEgressEndpoint) String() string {
 13375  	address := ""
 13376  	if t.Address != nil {
 13377  		address = t.Address.String()
 13378  	}
 13379  	return fmt.Sprintf("{EgressEndpoint: %s}", address)
 13380  }
 13381  
 13382  func (t *TunnelEncapSubTLVEgressEndpoint) MarshalJSON() ([]byte, error) {
 13383  	address := ""
 13384  	if t.Address != nil {
 13385  		address = t.Address.String()
 13386  	}
 13387  
 13388  	return json.Marshal(struct {
 13389  		Type    EncapSubTLVType `json:"type"`
 13390  		Address string          `json:"address"`
 13391  	}{
 13392  		Type:    t.Type,
 13393  		Address: address,
 13394  	})
 13395  }
 13396  
 13397  func NewTunnelEncapSubTLVEgressEndpoint(address string) *TunnelEncapSubTLVEgressEndpoint {
 13398  	var ip net.IP = nil
 13399  	if address != "" {
 13400  		ip = net.ParseIP(address)
 13401  	}
 13402  	return &TunnelEncapSubTLVEgressEndpoint{
 13403  		TunnelEncapSubTLV: TunnelEncapSubTLV{
 13404  			Type: ENCAP_SUBTLV_TYPE_EGRESS_ENDPOINT,
 13405  		},
 13406  		Address: ip,
 13407  	}
 13408  }
 13409  
 13410  type TunnelEncapSubTLVUDPDestPort struct {
 13411  	TunnelEncapSubTLV
 13412  	UDPDestPort uint16
 13413  }
 13414  
 13415  func (t *TunnelEncapSubTLVUDPDestPort) DecodeFromBytes(data []byte) error {
 13416  	value, err := t.TunnelEncapSubTLV.DecodeFromBytes(data)
 13417  	if err != nil {
 13418  		return err
 13419  	}
 13420  	if t.Length < 2 {
 13421  		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "Not all TunnelEncapSubTLVUDPDestPort bytes available")
 13422  	}
 13423  	t.UDPDestPort = binary.BigEndian.Uint16(value[0:2])
 13424  	return nil
 13425  }
 13426  
 13427  func (t *TunnelEncapSubTLVUDPDestPort) Serialize() ([]byte, error) {
 13428  	buf := make([]byte, 2)
 13429  	binary.BigEndian.PutUint16(buf, t.UDPDestPort)
 13430  	return t.TunnelEncapSubTLV.Serialize(buf)
 13431  }
 13432  
 13433  func (t *TunnelEncapSubTLVUDPDestPort) String() string {
 13434  	return fmt.Sprintf("{UDPDestPort: %d}", t.UDPDestPort)
 13435  }
 13436  
 13437  func (t *TunnelEncapSubTLVUDPDestPort) MarshalJSON() ([]byte, error) {
 13438  	return json.Marshal(struct {
 13439  		Type        EncapSubTLVType `json:"type"`
 13440  		UDPDestPort uint16          `json:"port"`
 13441  	}{
 13442  		Type:        t.Type,
 13443  		UDPDestPort: t.UDPDestPort,
 13444  	})
 13445  }
 13446  
 13447  func NewTunnelEncapSubTLVUDPDestPort(port uint16) *TunnelEncapSubTLVUDPDestPort {
 13448  	return &TunnelEncapSubTLVUDPDestPort{
 13449  		TunnelEncapSubTLV: TunnelEncapSubTLV{
 13450  			Type: ENCAP_SUBTLV_TYPE_UDP_DEST_PORT,
 13451  		},
 13452  		UDPDestPort: port,
 13453  	}
 13454  }
 13455  
 13456  type TunnelEncapTLV struct {
 13457  	Type   TunnelType
 13458  	Length uint16
 13459  	Value  []TunnelEncapSubTLVInterface
 13460  }
 13461  
 13462  func (t *TunnelEncapTLV) Len() int {
 13463  	var l int
 13464  	for _, v := range t.Value {
 13465  		l += v.Len()
 13466  	}
 13467  	return 4 + l // Type(2) + Length(2) + Value(variable)
 13468  }
 13469  
 13470  func (t *TunnelEncapTLV) DecodeFromBytes(data []byte) error {
 13471  	t.Type = TunnelType(binary.BigEndian.Uint16(data[0:2]))
 13472  	t.Length = binary.BigEndian.Uint16(data[2:4])
 13473  	data = data[4:]
 13474  	if len(data) < int(t.Length) {
 13475  		return NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "Not all TunnelEncapTLV bytes available")
 13476  	}
 13477  	value := data[:t.Length]
 13478  	for len(value) > 2 {
 13479  		subType := EncapSubTLVType(value[0])
 13480  		var subTlv TunnelEncapSubTLVInterface
 13481  		switch subType {
 13482  		case ENCAP_SUBTLV_TYPE_ENCAPSULATION:
 13483  			subTlv = &TunnelEncapSubTLVEncapsulation{}
 13484  		case ENCAP_SUBTLV_TYPE_PROTOCOL:
 13485  			subTlv = &TunnelEncapSubTLVProtocol{}
 13486  		case ENCAP_SUBTLV_TYPE_COLOR:
 13487  			subTlv = &TunnelEncapSubTLVColor{}
 13488  		case ENCAP_SUBTLV_TYPE_UDP_DEST_PORT:
 13489  			subTlv = &TunnelEncapSubTLVUDPDestPort{}
 13490  		case ENCAP_SUBTLV_TYPE_EGRESS_ENDPOINT:
 13491  			subTlv = &TunnelEncapSubTLVEgressEndpoint{}
 13492  		case ENCAP_SUBTLV_TYPE_SRPREFERENCE:
 13493  			subTlv = &TunnelEncapSubTLVSRPreference{}
 13494  		case ENCAP_SUBTLV_TYPE_SRBINDING_SID:
 13495  			subTlv = &TunnelEncapSubTLVSRBSID{}
 13496  		case ENCAP_SUBTLV_TYPE_SRSEGMENT_LIST:
 13497  			subTlv = &TunnelEncapSubTLVSRSegmentList{}
 13498  		case ENCAP_SUBTLV_TYPE_SRENLP:
 13499  			subTlv = &TunnelEncapSubTLVSRENLP{}
 13500  		case ENCAP_SUBTLV_TYPE_SRPRIORITY:
 13501  			subTlv = &TunnelEncapSubTLVSRPriority{}
 13502  		case ENCAP_SUBTLV_TYPE_SRCANDIDATE_PATH_NAME:
 13503  			subTlv = &TunnelEncapSubTLVSRCandidatePathName{}
 13504  		default:
 13505  			subTlv = &TunnelEncapSubTLVUnknown{
 13506  				TunnelEncapSubTLV: TunnelEncapSubTLV{
 13507  					Type: subType,
 13508  				},
 13509  			}
 13510  		}
 13511  		err := subTlv.DecodeFromBytes(value)
 13512  		if err != nil {
 13513  			return err
 13514  		}
 13515  		t.Value = append(t.Value, subTlv)
 13516  		value = value[subTlv.Len():]
 13517  	}
 13518  	return nil
 13519  }
 13520  
 13521  func (p *TunnelEncapTLV) Serialize() ([]byte, error) {
 13522  	buf := make([]byte, 4)
 13523  	for _, t := range p.Value {
 13524  		tBuf, err := t.Serialize()
 13525  		if err != nil {
 13526  			return nil, err
 13527  		}
 13528  		buf = append(buf, tBuf...)
 13529  	}
 13530  	binary.BigEndian.PutUint16(buf, uint16(p.Type))
 13531  	binary.BigEndian.PutUint16(buf[2:], uint16(len(buf)-4))
 13532  	return buf, nil
 13533  }
 13534  
 13535  func (p *TunnelEncapTLV) String() string {
 13536  	tlvList := make([]string, len(p.Value))
 13537  	for i, v := range p.Value {
 13538  		tlvList[i] = v.String()
 13539  	}
 13540  	return fmt.Sprintf("{%s: %s}", p.Type, strings.Join(tlvList, ", "))
 13541  }
 13542  
 13543  func (p *TunnelEncapTLV) MarshalJSON() ([]byte, error) {
 13544  	return json.Marshal(struct {
 13545  		Type  TunnelType                   `json:"type"`
 13546  		Value []TunnelEncapSubTLVInterface `json:"value"`
 13547  	}{
 13548  		Type:  p.Type,
 13549  		Value: p.Value,
 13550  	})
 13551  }
 13552  
 13553  func NewTunnelEncapTLV(typ TunnelType, value []TunnelEncapSubTLVInterface) *TunnelEncapTLV {
 13554  	return &TunnelEncapTLV{
 13555  		Type:  typ,
 13556  		Value: value,
 13557  	}
 13558  }
 13559  
 13560  type PathAttributeTunnelEncap struct {
 13561  	PathAttribute
 13562  	Value []*TunnelEncapTLV
 13563  }
 13564  
 13565  func (p *PathAttributeTunnelEncap) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
 13566  	value, err := p.PathAttribute.DecodeFromBytes(data, options...)
 13567  	if err != nil {
 13568  		return err
 13569  	}
 13570  	for len(value) > 4 {
 13571  		tlv := &TunnelEncapTLV{}
 13572  		err = tlv.DecodeFromBytes(value)
 13573  		if err != nil {
 13574  			return err
 13575  		}
 13576  		p.Value = append(p.Value, tlv)
 13577  		value = value[4+tlv.Length:]
 13578  	}
 13579  	return nil
 13580  }
 13581  
 13582  func (p *PathAttributeTunnelEncap) Serialize(options ...*MarshallingOption) ([]byte, error) {
 13583  	buf := make([]byte, 0)
 13584  	for _, t := range p.Value {
 13585  		bbuf, err := t.Serialize()
 13586  		if err != nil {
 13587  			return nil, err
 13588  		}
 13589  		buf = append(buf, bbuf...)
 13590  	}
 13591  	return p.PathAttribute.Serialize(buf, options...)
 13592  }
 13593  
 13594  func (p *PathAttributeTunnelEncap) String() string {
 13595  	tlvList := make([]string, len(p.Value))
 13596  	for i, v := range p.Value {
 13597  		tlvList[i] = v.String()
 13598  	}
 13599  	return "{TunnelEncap: " + strings.Join(tlvList, ", ") + "}"
 13600  }
 13601  
 13602  func (p *PathAttributeTunnelEncap) MarshalJSON() ([]byte, error) {
 13603  	return json.Marshal(struct {
 13604  		Type  BGPAttrType       `json:"type"`
 13605  		Value []*TunnelEncapTLV `json:"value"`
 13606  	}{
 13607  		Type:  p.Type,
 13608  		Value: p.Value,
 13609  	})
 13610  }
 13611  
 13612  func NewPathAttributeTunnelEncap(value []*TunnelEncapTLV) *PathAttributeTunnelEncap {
 13613  	var l int
 13614  	for _, v := range value {
 13615  		l += v.Len()
 13616  	}
 13617  	t := BGP_ATTR_TYPE_TUNNEL_ENCAP
 13618  	return &PathAttributeTunnelEncap{
 13619  		PathAttribute: PathAttribute{
 13620  			Flags:  getPathAttrFlags(t, l),
 13621  			Type:   t,
 13622  			Length: uint16(l),
 13623  		},
 13624  		Value: value,
 13625  	}
 13626  }
 13627  
 13628  type PmsiTunnelIDInterface interface {
 13629  	Len() int
 13630  	Serialize() ([]byte, error)
 13631  	String() string
 13632  }
 13633  
 13634  type DefaultPmsiTunnelID struct {
 13635  	Value []byte
 13636  }
 13637  
 13638  func (i *DefaultPmsiTunnelID) Len() int {
 13639  	return len(i.Value)
 13640  }
 13641  
 13642  func (i *DefaultPmsiTunnelID) Serialize() ([]byte, error) {
 13643  	return i.Value, nil
 13644  }
 13645  
 13646  func (i *DefaultPmsiTunnelID) String() string {
 13647  	return string(i.Value)
 13648  }
 13649  
 13650  func NewDefaultPmsiTunnelID(value []byte) *DefaultPmsiTunnelID {
 13651  	return &DefaultPmsiTunnelID{
 13652  		Value: value,
 13653  	}
 13654  }
 13655  
 13656  type IngressReplTunnelID struct {
 13657  	Value net.IP
 13658  }
 13659  
 13660  func (i *IngressReplTunnelID) Len() int {
 13661  	return len(i.Value)
 13662  }
 13663  
 13664  func (i *IngressReplTunnelID) Serialize() ([]byte, error) {
 13665  	if i.Value.To4() != nil {
 13666  		return []byte(i.Value.To4()), nil
 13667  	}
 13668  	return []byte(i.Value), nil
 13669  }
 13670  
 13671  func (i *IngressReplTunnelID) String() string {
 13672  	return i.Value.String()
 13673  }
 13674  
 13675  func NewIngressReplTunnelID(value string) *IngressReplTunnelID {
 13676  	ip := net.ParseIP(value)
 13677  	if ip == nil {
 13678  		return nil
 13679  	}
 13680  	return &IngressReplTunnelID{
 13681  		Value: ip,
 13682  	}
 13683  }
 13684  
 13685  type PathAttributePmsiTunnel struct {
 13686  	PathAttribute
 13687  	IsLeafInfoRequired bool
 13688  	TunnelType         PmsiTunnelType
 13689  	Label              uint32
 13690  	TunnelID           PmsiTunnelIDInterface
 13691  }
 13692  
 13693  func (p *PathAttributePmsiTunnel) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
 13694  	value, err := p.PathAttribute.DecodeFromBytes(data, options...)
 13695  	if err != nil {
 13696  		return err
 13697  	}
 13698  	if p.Length < 5 {
 13699  		eCode := uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR)
 13700  		eSubCode := uint8(BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST)
 13701  		return NewMessageError(eCode, eSubCode, nil, "PMSI Tunnel length is incorrect")
 13702  	}
 13703  
 13704  	if (value[0] & 0x01) > 0 {
 13705  		p.IsLeafInfoRequired = true
 13706  	}
 13707  	p.TunnelType = PmsiTunnelType(value[1])
 13708  	if p.Label, err = labelDecode(value[2:5]); err != nil {
 13709  		return err
 13710  	}
 13711  
 13712  	switch p.TunnelType {
 13713  	case PMSI_TUNNEL_TYPE_INGRESS_REPL:
 13714  		p.TunnelID = &IngressReplTunnelID{net.IP(value[5:])}
 13715  	default:
 13716  		p.TunnelID = &DefaultPmsiTunnelID{value[5:]}
 13717  	}
 13718  	return nil
 13719  }
 13720  
 13721  func (p *PathAttributePmsiTunnel) Serialize(options ...*MarshallingOption) ([]byte, error) {
 13722  	buf := make([]byte, 2)
 13723  	if p.IsLeafInfoRequired {
 13724  		buf[0] = 0x01
 13725  	}
 13726  	buf[1] = byte(p.TunnelType)
 13727  	tbuf, err := labelSerialize(p.Label)
 13728  	if err != nil {
 13729  		return nil, err
 13730  	}
 13731  	buf = append(buf, tbuf...)
 13732  	tbuf, err = p.TunnelID.Serialize()
 13733  	if err != nil {
 13734  		return nil, err
 13735  	}
 13736  	buf = append(buf, tbuf...)
 13737  	return p.PathAttribute.Serialize(buf, options...)
 13738  }
 13739  
 13740  func (p *PathAttributePmsiTunnel) String() string {
 13741  	buf := bytes.NewBuffer(make([]byte, 0, 32))
 13742  	buf.WriteString(fmt.Sprintf("{Pmsi: type: %s,", p.TunnelType))
 13743  	if p.IsLeafInfoRequired {
 13744  		buf.WriteString(" leaf-info-required,")
 13745  	}
 13746  	buf.WriteString(fmt.Sprintf(" label: %d, tunnel-id: %s}", p.Label, p.TunnelID))
 13747  	return buf.String()
 13748  }
 13749  
 13750  func (p *PathAttributePmsiTunnel) MarshalJSON() ([]byte, error) {
 13751  	return json.Marshal(struct {
 13752  		Type               BGPAttrType `json:"type"`
 13753  		IsLeafInfoRequired bool        `json:"is-leaf-info-required"`
 13754  		TunnelType         uint8       `json:"tunnel-type"`
 13755  		Label              uint32      `json:"label"`
 13756  		TunnelID           string      `json:"tunnel-id"`
 13757  	}{
 13758  		Type:               p.Type,
 13759  		IsLeafInfoRequired: p.IsLeafInfoRequired,
 13760  		TunnelType:         uint8(p.TunnelType),
 13761  		Label:              p.Label,
 13762  		TunnelID:           p.TunnelID.String(),
 13763  	})
 13764  }
 13765  
 13766  func NewPathAttributePmsiTunnel(typ PmsiTunnelType, isLeafInfoRequired bool, label uint32, id PmsiTunnelIDInterface) *PathAttributePmsiTunnel {
 13767  	if id == nil {
 13768  		return nil
 13769  	}
 13770  	// Flags(1) + TunnelType(1) + Label(3) + TunnelID(variable)
 13771  	l := 5 + id.Len()
 13772  	t := BGP_ATTR_TYPE_PMSI_TUNNEL
 13773  	return &PathAttributePmsiTunnel{
 13774  		PathAttribute: PathAttribute{
 13775  			Flags:  getPathAttrFlags(t, l),
 13776  			Type:   t,
 13777  			Length: uint16(l),
 13778  		},
 13779  		IsLeafInfoRequired: isLeafInfoRequired,
 13780  		TunnelType:         typ,
 13781  		Label:              label,
 13782  		TunnelID:           id,
 13783  	}
 13784  }
 13785  
 13786  func ParsePmsiTunnel(args []string) (*PathAttributePmsiTunnel, error) {
 13787  	// Format:
 13788  	// "<type>" ["leaf-info-required"] "<label>" "<tunnel-id>"
 13789  	if len(args) < 3 {
 13790  		return nil, fmt.Errorf("invalid pmsi tunnel arguments: %s", args)
 13791  	}
 13792  
 13793  	var tunnelType PmsiTunnelType
 13794  	var isLeafInfoRequired bool
 13795  	switch args[0] {
 13796  	case "ingress-repl":
 13797  		tunnelType = PMSI_TUNNEL_TYPE_INGRESS_REPL
 13798  	default:
 13799  		typ, err := strconv.ParseUint(args[0], 10, 8)
 13800  		if err != nil {
 13801  			return nil, fmt.Errorf("invalid pmsi tunnel type: %s", args[0])
 13802  		}
 13803  		tunnelType = PmsiTunnelType(typ)
 13804  	}
 13805  
 13806  	indx := 1
 13807  	if args[indx] == "leaf-info-required" {
 13808  		isLeafInfoRequired = true
 13809  		indx++
 13810  	}
 13811  
 13812  	label, err := strconv.ParseUint(args[indx], 10, 32)
 13813  	if err != nil {
 13814  		return nil, fmt.Errorf("invalid pmsi tunnel label: %s", args[indx])
 13815  	}
 13816  	indx++
 13817  
 13818  	var id PmsiTunnelIDInterface
 13819  	switch tunnelType {
 13820  	case PMSI_TUNNEL_TYPE_INGRESS_REPL:
 13821  		ip := net.ParseIP(args[indx])
 13822  		if ip == nil {
 13823  			return nil, fmt.Errorf("invalid pmsi tunnel identifier: %s", args[indx])
 13824  		}
 13825  		id = &IngressReplTunnelID{Value: ip}
 13826  	default:
 13827  		id = &DefaultPmsiTunnelID{Value: []byte(args[indx])}
 13828  	}
 13829  
 13830  	return NewPathAttributePmsiTunnel(tunnelType, isLeafInfoRequired, uint32(label), id), nil
 13831  }
 13832  
 13833  type PathAttributeIP6ExtendedCommunities struct {
 13834  	PathAttribute
 13835  	Value []ExtendedCommunityInterface
 13836  }
 13837  
 13838  func ParseIP6Extended(data []byte) (ExtendedCommunityInterface, error) {
 13839  	if len(data) < 8 {
 13840  		return nil, NewMessageError(BGP_ERROR_UPDATE_MESSAGE_ERROR, BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST, nil, "not all extended community bytes are available")
 13841  	}
 13842  	attrType := ExtendedCommunityAttrType(data[0])
 13843  	subtype := ExtendedCommunityAttrSubType(data[1])
 13844  	transitive := false
 13845  	switch attrType {
 13846  	case EC_TYPE_TRANSITIVE_IP6_SPECIFIC:
 13847  		transitive = true
 13848  		fallthrough
 13849  	case EC_TYPE_NON_TRANSITIVE_IP6_SPECIFIC:
 13850  		ipv6 := net.IP(data[2:18]).String()
 13851  		localAdmin := binary.BigEndian.Uint16(data[18:20])
 13852  		return NewIPv6AddressSpecificExtended(subtype, ipv6, localAdmin, transitive), nil
 13853  	case EC_TYPE_GENERIC_TRANSITIVE_EXPERIMENTAL:
 13854  		return parseIP6FlowSpecExtended(data)
 13855  	default:
 13856  		return &UnknownExtended{
 13857  			Type:  ExtendedCommunityAttrType(data[0]),
 13858  			Value: data[1:8],
 13859  		}, nil
 13860  	}
 13861  }
 13862  
 13863  func (p *PathAttributeIP6ExtendedCommunities) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
 13864  	value, err := p.PathAttribute.DecodeFromBytes(data)
 13865  	if err != nil {
 13866  		return err
 13867  	}
 13868  	if p.Length%20 != 0 {
 13869  		eCode := uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR)
 13870  		eSubCode := uint8(BGP_ERROR_SUB_ATTRIBUTE_LENGTH_ERROR)
 13871  		return NewMessageError(eCode, eSubCode, nil, "extendedcommunities length isn't correct")
 13872  	}
 13873  	for len(value) >= 20 {
 13874  		e, err := ParseIP6Extended(value)
 13875  		if err != nil {
 13876  			return err
 13877  		}
 13878  		p.Value = append(p.Value, e)
 13879  		value = value[20:]
 13880  	}
 13881  	return nil
 13882  }
 13883  
 13884  func (p *PathAttributeIP6ExtendedCommunities) Serialize(options ...*MarshallingOption) ([]byte, error) {
 13885  	buf := make([]byte, 0)
 13886  	for _, p := range p.Value {
 13887  		ebuf, err := p.Serialize()
 13888  		if err != nil {
 13889  			return nil, err
 13890  		}
 13891  		buf = append(buf, ebuf...)
 13892  	}
 13893  	return p.PathAttribute.Serialize(buf, options...)
 13894  }
 13895  
 13896  func (p *PathAttributeIP6ExtendedCommunities) String() string {
 13897  	buf := make([]string, len(p.Value))
 13898  	for i, v := range p.Value {
 13899  		buf[i] = "[" + v.String() + "]"
 13900  	}
 13901  	return "{Extcomms: " + strings.Join(buf, ",") + "}"
 13902  }
 13903  
 13904  func (p *PathAttributeIP6ExtendedCommunities) MarshalJSON() ([]byte, error) {
 13905  	return json.Marshal(struct {
 13906  		Type  BGPAttrType                  `json:"type"`
 13907  		Value []ExtendedCommunityInterface `json:"value"`
 13908  	}{
 13909  		Type:  p.GetType(),
 13910  		Value: p.Value,
 13911  	})
 13912  }
 13913  
 13914  func NewPathAttributeIP6ExtendedCommunities(value []ExtendedCommunityInterface) *PathAttributeIP6ExtendedCommunities {
 13915  	l := len(value) * 20
 13916  	t := BGP_ATTR_TYPE_IP6_EXTENDED_COMMUNITIES
 13917  	return &PathAttributeIP6ExtendedCommunities{
 13918  		PathAttribute: PathAttribute{
 13919  			Flags:  getPathAttrFlags(t, l),
 13920  			Type:   t,
 13921  			Length: uint16(l),
 13922  		},
 13923  		Value: value,
 13924  	}
 13925  }
 13926  
 13927  type AigpTLVType uint8
 13928  
 13929  const (
 13930  	AIGP_TLV_UNKNOWN AigpTLVType = iota
 13931  	AIGP_TLV_IGP_METRIC
 13932  )
 13933  
 13934  type AigpTLVInterface interface {
 13935  	Serialize() ([]byte, error)
 13936  	String() string
 13937  	MarshalJSON() ([]byte, error)
 13938  	Type() AigpTLVType
 13939  	Len() int
 13940  }
 13941  
 13942  type AigpTLVDefault struct {
 13943  	typ   AigpTLVType
 13944  	Value []byte
 13945  }
 13946  
 13947  func (t *AigpTLVDefault) Serialize() ([]byte, error) {
 13948  	buf := make([]byte, 3+len(t.Value))
 13949  	buf[0] = uint8(t.Type())
 13950  	binary.BigEndian.PutUint16(buf[1:], uint16(3+len(t.Value)))
 13951  	copy(buf[3:], t.Value)
 13952  	return buf, nil
 13953  }
 13954  
 13955  func (t *AigpTLVDefault) String() string {
 13956  	return fmt.Sprintf("{Type: %d, Value: %v}", t.Type(), t.Value)
 13957  }
 13958  
 13959  func (t *AigpTLVDefault) MarshalJSON() ([]byte, error) {
 13960  	return json.Marshal(struct {
 13961  		Type  AigpTLVType `json:"type"`
 13962  		Value []byte      `json:"value"`
 13963  	}{
 13964  		Type:  t.Type(),
 13965  		Value: t.Value,
 13966  	})
 13967  }
 13968  
 13969  func (t *AigpTLVDefault) Type() AigpTLVType {
 13970  	return t.typ
 13971  }
 13972  
 13973  func (t *AigpTLVDefault) Len() int {
 13974  	return 3 + len(t.Value) // Type(1) + Length(2) + Value(variable)
 13975  }
 13976  
 13977  func NewAigpTLVDefault(typ AigpTLVType, value []byte) *AigpTLVDefault {
 13978  	return &AigpTLVDefault{
 13979  		typ:   typ,
 13980  		Value: value,
 13981  	}
 13982  }
 13983  
 13984  type AigpTLVIgpMetric struct {
 13985  	Metric uint64
 13986  }
 13987  
 13988  func (t *AigpTLVIgpMetric) Serialize() ([]byte, error) {
 13989  	buf := make([]byte, 11)
 13990  	buf[0] = uint8(AIGP_TLV_IGP_METRIC)
 13991  	binary.BigEndian.PutUint16(buf[1:], uint16(11))
 13992  	binary.BigEndian.PutUint64(buf[3:], t.Metric)
 13993  	return buf, nil
 13994  }
 13995  
 13996  func (t *AigpTLVIgpMetric) String() string {
 13997  	return fmt.Sprintf("{Metric: %d}", t.Metric)
 13998  }
 13999  
 14000  func (t *AigpTLVIgpMetric) MarshalJSON() ([]byte, error) {
 14001  	return json.Marshal(struct {
 14002  		Type   AigpTLVType `json:"type"`
 14003  		Metric uint64      `json:"metric"`
 14004  	}{
 14005  		Type:   AIGP_TLV_IGP_METRIC,
 14006  		Metric: t.Metric,
 14007  	})
 14008  }
 14009  
 14010  func NewAigpTLVIgpMetric(metric uint64) *AigpTLVIgpMetric {
 14011  	return &AigpTLVIgpMetric{
 14012  		Metric: metric,
 14013  	}
 14014  }
 14015  
 14016  func (t *AigpTLVIgpMetric) Type() AigpTLVType {
 14017  	return AIGP_TLV_IGP_METRIC
 14018  }
 14019  
 14020  func (t *AigpTLVIgpMetric) Len() int {
 14021  	return 11
 14022  }
 14023  
 14024  type PathAttributeAigp struct {
 14025  	PathAttribute
 14026  	Values []AigpTLVInterface
 14027  }
 14028  
 14029  func (p *PathAttributeAigp) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
 14030  	value, err := p.PathAttribute.DecodeFromBytes(data, options...)
 14031  	if err != nil {
 14032  		return err
 14033  	}
 14034  	for len(value) > 3 {
 14035  		typ := value[0]
 14036  		length := binary.BigEndian.Uint16(value[1:3])
 14037  		if length <= 3 {
 14038  			return NewMessageError(BGP_ERROR_MESSAGE_HEADER_ERROR, BGP_ERROR_SUB_BAD_MESSAGE_LENGTH, nil, "Malformed BGP message")
 14039  		}
 14040  		if len(value) < int(length) {
 14041  			break
 14042  		}
 14043  		v := value[3:length]
 14044  		switch AigpTLVType(typ) {
 14045  		case AIGP_TLV_IGP_METRIC:
 14046  			if len(v) < 8 {
 14047  				break
 14048  			}
 14049  			metric := binary.BigEndian.Uint64(v)
 14050  			p.Values = append(p.Values, NewAigpTLVIgpMetric(metric))
 14051  		default:
 14052  			p.Values = append(p.Values, NewAigpTLVDefault(AigpTLVType(typ), v))
 14053  		}
 14054  		value = value[length:]
 14055  	}
 14056  	if len(value) != 0 {
 14057  		eCode := uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR)
 14058  		eSubCode := uint8(BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST)
 14059  		return NewMessageError(eCode, eSubCode, nil, "Aigp length is incorrect")
 14060  	}
 14061  	return nil
 14062  }
 14063  
 14064  func (p *PathAttributeAigp) Serialize(options ...*MarshallingOption) ([]byte, error) {
 14065  	buf := make([]byte, 0)
 14066  	for _, t := range p.Values {
 14067  		bbuf, err := t.Serialize()
 14068  		if err != nil {
 14069  			return nil, err
 14070  		}
 14071  		buf = append(buf, bbuf...)
 14072  	}
 14073  	return p.PathAttribute.Serialize(buf, options...)
 14074  }
 14075  
 14076  func (p *PathAttributeAigp) String() string {
 14077  	buf := bytes.NewBuffer(make([]byte, 0, 32))
 14078  	buf.WriteString("{Aigp: [")
 14079  	for _, v := range p.Values {
 14080  		buf.WriteString(v.String())
 14081  	}
 14082  	buf.WriteString("]}")
 14083  	return buf.String()
 14084  }
 14085  
 14086  func (p *PathAttributeAigp) MarshalJSON() ([]byte, error) {
 14087  	return json.Marshal(struct {
 14088  		Type  BGPAttrType        `json:"type"`
 14089  		Value []AigpTLVInterface `json:"value"`
 14090  	}{
 14091  		Type:  p.GetType(),
 14092  		Value: p.Values,
 14093  	})
 14094  }
 14095  
 14096  func NewPathAttributeAigp(values []AigpTLVInterface) *PathAttributeAigp {
 14097  	var l int
 14098  	for _, v := range values {
 14099  		l += v.Len()
 14100  	}
 14101  	t := BGP_ATTR_TYPE_AIGP
 14102  	return &PathAttributeAigp{
 14103  		PathAttribute: PathAttribute{
 14104  			Flags:  getPathAttrFlags(t, l),
 14105  			Type:   t,
 14106  			Length: uint16(l),
 14107  		},
 14108  		Values: values,
 14109  	}
 14110  }
 14111  
 14112  type LargeCommunity struct {
 14113  	ASN        uint32
 14114  	LocalData1 uint32
 14115  	LocalData2 uint32
 14116  }
 14117  
 14118  func (c *LargeCommunity) Serialize() ([]byte, error) {
 14119  	buf := make([]byte, 12)
 14120  	binary.BigEndian.PutUint32(buf, c.ASN)
 14121  	binary.BigEndian.PutUint32(buf[4:], c.LocalData1)
 14122  	binary.BigEndian.PutUint32(buf[8:], c.LocalData2)
 14123  	return buf, nil
 14124  }
 14125  
 14126  func (c *LargeCommunity) String() string {
 14127  	return fmt.Sprintf("%d:%d:%d", c.ASN, c.LocalData1, c.LocalData2)
 14128  }
 14129  
 14130  func (c *LargeCommunity) Eq(rhs *LargeCommunity) bool {
 14131  	return c.ASN == rhs.ASN && c.LocalData1 == rhs.LocalData1 && c.LocalData2 == rhs.LocalData2
 14132  }
 14133  
 14134  func NewLargeCommunity(asn, data1, data2 uint32) *LargeCommunity {
 14135  	return &LargeCommunity{
 14136  		ASN:        asn,
 14137  		LocalData1: data1,
 14138  		LocalData2: data2,
 14139  	}
 14140  }
 14141  
 14142  func ParseLargeCommunity(value string) (*LargeCommunity, error) {
 14143  	elems := strings.Split(value, ":")
 14144  	if len(elems) != 3 {
 14145  		return nil, errors.New("invalid large community format")
 14146  	}
 14147  	v := make([]uint32, 0, 3)
 14148  	for _, elem := range elems {
 14149  		e, err := strconv.ParseUint(elem, 10, 32)
 14150  		if err != nil {
 14151  			return nil, errors.New("invalid large community format")
 14152  		}
 14153  		v = append(v, uint32(e))
 14154  	}
 14155  	return NewLargeCommunity(v[0], v[1], v[2]), nil
 14156  }
 14157  
 14158  type PathAttributeLargeCommunities struct {
 14159  	PathAttribute
 14160  	Values []*LargeCommunity
 14161  }
 14162  
 14163  func (p *PathAttributeLargeCommunities) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
 14164  	value, err := p.PathAttribute.DecodeFromBytes(data)
 14165  	if err != nil {
 14166  		return err
 14167  	}
 14168  	if p.Length%12 != 0 {
 14169  		eCode := uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR)
 14170  		eSubCode := uint8(BGP_ERROR_SUB_ATTRIBUTE_LENGTH_ERROR)
 14171  		return NewMessageError(eCode, eSubCode, nil, "large communities length isn't correct")
 14172  	}
 14173  	p.Values = make([]*LargeCommunity, 0, p.Length/12)
 14174  	for len(value) >= 12 {
 14175  		asn := binary.BigEndian.Uint32(value[:4])
 14176  		data1 := binary.BigEndian.Uint32(value[4:8])
 14177  		data2 := binary.BigEndian.Uint32(value[8:12])
 14178  		p.Values = append(p.Values, NewLargeCommunity(asn, data1, data2))
 14179  		value = value[12:]
 14180  	}
 14181  	return nil
 14182  }
 14183  
 14184  func (p *PathAttributeLargeCommunities) Serialize(options ...*MarshallingOption) ([]byte, error) {
 14185  	buf := make([]byte, 0, len(p.Values)*12)
 14186  	for _, t := range p.Values {
 14187  		bbuf, err := t.Serialize()
 14188  		if err != nil {
 14189  			return nil, err
 14190  		}
 14191  		buf = append(buf, bbuf...)
 14192  	}
 14193  	return p.PathAttribute.Serialize(buf, options...)
 14194  }
 14195  
 14196  func (p *PathAttributeLargeCommunities) String() string {
 14197  	buf := bytes.NewBuffer(make([]byte, 0, 32))
 14198  	buf.WriteString("{LargeCommunity: [ ")
 14199  	ss := []string{}
 14200  	for _, v := range p.Values {
 14201  		ss = append(ss, v.String())
 14202  	}
 14203  	buf.WriteString(strings.Join(ss, ", "))
 14204  	buf.WriteString("]}")
 14205  	return buf.String()
 14206  }
 14207  
 14208  func (p *PathAttributeLargeCommunities) MarshalJSON() ([]byte, error) {
 14209  	return json.Marshal(struct {
 14210  		Type  BGPAttrType       `json:"type"`
 14211  		Value []*LargeCommunity `json:"value"`
 14212  	}{
 14213  		Type:  p.GetType(),
 14214  		Value: p.Values,
 14215  	})
 14216  }
 14217  
 14218  func NewPathAttributeLargeCommunities(values []*LargeCommunity) *PathAttributeLargeCommunities {
 14219  	l := len(values) * 12
 14220  	t := BGP_ATTR_TYPE_LARGE_COMMUNITY
 14221  	return &PathAttributeLargeCommunities{
 14222  		PathAttribute: PathAttribute{
 14223  			Flags:  getPathAttrFlags(t, l),
 14224  			Type:   t,
 14225  			Length: uint16(l),
 14226  		},
 14227  		Values: values,
 14228  	}
 14229  }
 14230  
 14231  type PathAttributeUnknown struct {
 14232  	PathAttribute
 14233  	Value []byte
 14234  }
 14235  
 14236  func (p *PathAttributeUnknown) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
 14237  	value, err := p.PathAttribute.DecodeFromBytes(data)
 14238  	if err != nil {
 14239  		return err
 14240  	}
 14241  	p.Value = value
 14242  	return nil
 14243  }
 14244  
 14245  func (p *PathAttributeUnknown) Serialize(options ...*MarshallingOption) ([]byte, error) {
 14246  	return p.PathAttribute.Serialize(p.Value, options...)
 14247  }
 14248  
 14249  func (p *PathAttributeUnknown) String() string {
 14250  	return fmt.Sprintf("{Flags: %s, Type: %s, Value: %v}", p.Flags, p.Type, p.Value)
 14251  }
 14252  
 14253  func (p *PathAttributeUnknown) MarshalJSON() ([]byte, error) {
 14254  	return json.Marshal(struct {
 14255  		Flags BGPAttrFlag `json:"flags"`
 14256  		Type  BGPAttrType `json:"type"`
 14257  		Value []byte      `json:"value"`
 14258  	}{
 14259  		Flags: p.GetFlags(),
 14260  		Type:  p.GetType(),
 14261  		Value: p.Value,
 14262  	})
 14263  }
 14264  
 14265  func NewPathAttributeUnknown(flags BGPAttrFlag, typ BGPAttrType, value []byte) *PathAttributeUnknown {
 14266  	l := len(value)
 14267  	if l > 255 {
 14268  		flags |= BGP_ATTR_FLAG_EXTENDED_LENGTH
 14269  	}
 14270  	return &PathAttributeUnknown{
 14271  		PathAttribute: PathAttribute{
 14272  			Flags:  flags,
 14273  			Type:   typ,
 14274  			Length: uint16(l),
 14275  		},
 14276  		Value: value,
 14277  	}
 14278  }
 14279  
 14280  // BGPUpdateAttributes defines a map with a key as bgp attribute type
 14281  // and value as bool. Value set to true indicates that the attribute specified by the key
 14282  // exists in the bgp update.
 14283  type BGPUpdateAttributes struct {
 14284  	Attribute map[BGPAttrType]bool
 14285  }
 14286  
 14287  func GetBGPUpdateAttributes(data []byte) map[BGPAttrType]bool {
 14288  	m := make(map[BGPAttrType]bool)
 14289  	for p := 0; p < len(data); {
 14290  		flag := data[p]
 14291  		p++
 14292  		if p < len(data) {
 14293  			t := data[p]
 14294  			m[BGPAttrType(t)] = true
 14295  		} else {
 14296  			break
 14297  		}
 14298  		p++
 14299  		var l uint16
 14300  		// Checking for Extened
 14301  		if flag&0x10 == 0x10 {
 14302  			if p+2 <= len(data) {
 14303  				l = binary.BigEndian.Uint16(data[p : p+2])
 14304  			} else {
 14305  				break
 14306  			}
 14307  			p += 2
 14308  		} else {
 14309  			if p < len(data) {
 14310  				l = uint16(data[p])
 14311  				p++
 14312  			} else {
 14313  				break
 14314  			}
 14315  		}
 14316  		p += int(l)
 14317  	}
 14318  	return m
 14319  }
 14320  
 14321  func GetBGPUpdateAttributesFromMsg(msg *BGPUpdate) map[BGPAttrType]bool {
 14322  	m := make(map[BGPAttrType]bool)
 14323  	for _, p := range msg.PathAttributes {
 14324  		m[p.GetType()] = true
 14325  	}
 14326  
 14327  	return m
 14328  }
 14329  
 14330  func GetPathAttribute(data []byte) (PathAttributeInterface, error) {
 14331  	if len(data) < 2 {
 14332  		eCode := uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR)
 14333  		eSubCode := uint8(BGP_ERROR_SUB_ATTRIBUTE_LENGTH_ERROR)
 14334  		return nil, NewMessageError(eCode, eSubCode, data, "attribute type length is short")
 14335  	}
 14336  	switch BGPAttrType(data[1]) {
 14337  	case BGP_ATTR_TYPE_ORIGIN:
 14338  		return &PathAttributeOrigin{}, nil
 14339  	case BGP_ATTR_TYPE_AS_PATH:
 14340  		return &PathAttributeAsPath{}, nil
 14341  	case BGP_ATTR_TYPE_NEXT_HOP:
 14342  		return &PathAttributeNextHop{}, nil
 14343  	case BGP_ATTR_TYPE_MULTI_EXIT_DISC:
 14344  		return &PathAttributeMultiExitDisc{}, nil
 14345  	case BGP_ATTR_TYPE_LOCAL_PREF:
 14346  		return &PathAttributeLocalPref{}, nil
 14347  	case BGP_ATTR_TYPE_ATOMIC_AGGREGATE:
 14348  		return &PathAttributeAtomicAggregate{}, nil
 14349  	case BGP_ATTR_TYPE_AGGREGATOR:
 14350  		return &PathAttributeAggregator{}, nil
 14351  	case BGP_ATTR_TYPE_COMMUNITIES:
 14352  		return &PathAttributeCommunities{}, nil
 14353  	case BGP_ATTR_TYPE_ORIGINATOR_ID:
 14354  		return &PathAttributeOriginatorId{}, nil
 14355  	case BGP_ATTR_TYPE_CLUSTER_LIST:
 14356  		return &PathAttributeClusterList{}, nil
 14357  	case BGP_ATTR_TYPE_MP_REACH_NLRI:
 14358  		return &PathAttributeMpReachNLRI{}, nil
 14359  	case BGP_ATTR_TYPE_MP_UNREACH_NLRI:
 14360  		return &PathAttributeMpUnreachNLRI{}, nil
 14361  	case BGP_ATTR_TYPE_EXTENDED_COMMUNITIES:
 14362  		return &PathAttributeExtendedCommunities{}, nil
 14363  	case BGP_ATTR_TYPE_AS4_PATH:
 14364  		return &PathAttributeAs4Path{}, nil
 14365  	case BGP_ATTR_TYPE_AS4_AGGREGATOR:
 14366  		return &PathAttributeAs4Aggregator{}, nil
 14367  	case BGP_ATTR_TYPE_TUNNEL_ENCAP:
 14368  		return &PathAttributeTunnelEncap{}, nil
 14369  	case BGP_ATTR_TYPE_PMSI_TUNNEL:
 14370  		return &PathAttributePmsiTunnel{}, nil
 14371  	case BGP_ATTR_TYPE_IP6_EXTENDED_COMMUNITIES:
 14372  		return &PathAttributeIP6ExtendedCommunities{}, nil
 14373  	case BGP_ATTR_TYPE_AIGP:
 14374  		return &PathAttributeAigp{}, nil
 14375  	case BGP_ATTR_TYPE_LARGE_COMMUNITY:
 14376  		return &PathAttributeLargeCommunities{}, nil
 14377  	case BGP_ATTR_TYPE_LS:
 14378  		return &PathAttributeLs{}, nil
 14379  	case BGP_ATTR_TYPE_PREFIX_SID:
 14380  		return &PathAttributePrefixSID{}, nil
 14381  	}
 14382  	return &PathAttributeUnknown{}, nil
 14383  }
 14384  
 14385  type BGPUpdate struct {
 14386  	WithdrawnRoutesLen    uint16
 14387  	WithdrawnRoutes       []*IPAddrPrefix
 14388  	TotalPathAttributeLen uint16
 14389  	PathAttributes        []PathAttributeInterface
 14390  	NLRI                  []*IPAddrPrefix
 14391  }
 14392  
 14393  func (msg *BGPUpdate) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
 14394  	var strongestError error
 14395  
 14396  	// cache error codes
 14397  	eCode := uint8(BGP_ERROR_UPDATE_MESSAGE_ERROR)
 14398  	eSubCode := uint8(BGP_ERROR_SUB_MALFORMED_ATTRIBUTE_LIST)
 14399  
 14400  	// check withdrawn route length
 14401  	if len(data) < 2 {
 14402  		return NewMessageError(eCode, eSubCode, nil, "message length isn't enough for withdrawn route length")
 14403  	}
 14404  
 14405  	msg.WithdrawnRoutesLen = binary.BigEndian.Uint16(data[0:2])
 14406  	data = data[2:]
 14407  
 14408  	// check withdrawn route
 14409  	if len(data) < int(msg.WithdrawnRoutesLen) {
 14410  		return NewMessageError(eCode, eSubCode, nil, "withdrawn route length exceeds message length")
 14411  	}
 14412  
 14413  	addpathLen := 0
 14414  	if IsAddPathEnabled(true, RF_IPv4_UC, options) {
 14415  		addpathLen = 4
 14416  	}
 14417  
 14418  	msg.WithdrawnRoutes = make([]*IPAddrPrefix, 0, msg.WithdrawnRoutesLen)
 14419  	for routelen := msg.WithdrawnRoutesLen; routelen > 0; {
 14420  		w := &IPAddrPrefix{}
 14421  		err := w.DecodeFromBytes(data, options...)
 14422  		if err != nil {
 14423  			return err
 14424  		}
 14425  		routelen -= uint16(w.Len(options...) + addpathLen)
 14426  		if len(data) < w.Len(options...)+addpathLen {
 14427  			return NewMessageError(eCode, eSubCode, nil, "Withdrawn route length is short")
 14428  		}
 14429  		data = data[w.Len(options...)+addpathLen:]
 14430  		msg.WithdrawnRoutes = append(msg.WithdrawnRoutes, w)
 14431  	}
 14432  
 14433  	// check path total attribute length
 14434  	if len(data) < 2 {
 14435  		return NewMessageError(eCode, eSubCode, nil, "message length isn't enough for path total attribute length")
 14436  	}
 14437  
 14438  	msg.TotalPathAttributeLen = binary.BigEndian.Uint16(data[0:2])
 14439  	data = data[2:]
 14440  
 14441  	// check path attribute
 14442  	if len(data) < int(msg.TotalPathAttributeLen) {
 14443  		return NewMessageError(eCode, eSubCode, nil, "path total attribute length exceeds message length")
 14444  	}
 14445  	attributes := GetBGPUpdateAttributes(data)
 14446  	o := MarshallingOption{
 14447  		Attributes: attributes,
 14448  	}
 14449  	options = append(options, &o)
 14450  
 14451  	msg.PathAttributes = []PathAttributeInterface{}
 14452  	for pathlen := msg.TotalPathAttributeLen; pathlen > 0; {
 14453  		var e error
 14454  		if pathlen < 3 {
 14455  			e = NewMessageErrorWithErrorHandling(
 14456  				eCode, BGP_ERROR_SUB_ATTRIBUTE_LENGTH_ERROR, data, ERROR_HANDLING_TREAT_AS_WITHDRAW, nil, "insufficient data to decode")
 14457  			if e.(*MessageError).Stronger(strongestError) {
 14458  				strongestError = e
 14459  			}
 14460  			data = data[pathlen:]
 14461  			break
 14462  		}
 14463  		p, err := GetPathAttribute(data)
 14464  		if err != nil {
 14465  			return err
 14466  		}
 14467  		err = p.DecodeFromBytes(data, options...)
 14468  		if err != nil {
 14469  			e = err.(*MessageError)
 14470  			if e.(*MessageError).SubTypeCode == BGP_ERROR_SUB_ATTRIBUTE_FLAGS_ERROR {
 14471  				e.(*MessageError).ErrorHandling = ERROR_HANDLING_TREAT_AS_WITHDRAW
 14472  			} else {
 14473  				e.(*MessageError).ErrorHandling = getErrorHandlingFromPathAttribute(p.GetType())
 14474  				e.(*MessageError).ErrorAttribute = &p
 14475  			}
 14476  			if e.(*MessageError).Stronger(strongestError) {
 14477  				strongestError = e
 14478  			}
 14479  		}
 14480  		pathlen -= uint16(p.Len(options...))
 14481  		if len(data) < p.Len(options...) {
 14482  			e = NewMessageErrorWithErrorHandling(
 14483  				eCode, BGP_ERROR_SUB_ATTRIBUTE_LENGTH_ERROR, data, ERROR_HANDLING_TREAT_AS_WITHDRAW, nil, "attribute length is short")
 14484  			if e.(*MessageError).Stronger(strongestError) {
 14485  				strongestError = e
 14486  			}
 14487  			return strongestError
 14488  		}
 14489  		data = data[p.Len(options...):]
 14490  		if e == nil || e.(*MessageError).ErrorHandling != ERROR_HANDLING_ATTRIBUTE_DISCARD {
 14491  			msg.PathAttributes = append(msg.PathAttributes, p)
 14492  		}
 14493  	}
 14494  
 14495  	msg.NLRI = make([]*IPAddrPrefix, 0)
 14496  	for restlen := len(data); restlen > 0; {
 14497  		n := &IPAddrPrefix{}
 14498  		err := n.DecodeFromBytes(data, options...)
 14499  		if err != nil {
 14500  			return err
 14501  		}
 14502  		restlen -= n.Len(options...) + addpathLen
 14503  		if len(data) < n.Len(options...)+addpathLen {
 14504  			return NewMessageError(eCode, BGP_ERROR_SUB_INVALID_NETWORK_FIELD, nil, "NLRI length is short")
 14505  		}
 14506  		if n.Len(options...) > 32 {
 14507  			return NewMessageError(eCode, BGP_ERROR_SUB_INVALID_NETWORK_FIELD, nil, "NLRI length is too long")
 14508  		}
 14509  		data = data[n.Len(options...)+addpathLen:]
 14510  		msg.NLRI = append(msg.NLRI, n)
 14511  	}
 14512  
 14513  	return strongestError
 14514  }
 14515  
 14516  func (msg *BGPUpdate) Serialize(options ...*MarshallingOption) ([]byte, error) {
 14517  	wbuf := make([]byte, 2)
 14518  	for _, w := range msg.WithdrawnRoutes {
 14519  		onewbuf, err := w.Serialize(options...)
 14520  		if err != nil {
 14521  			return nil, err
 14522  		}
 14523  		wbuf = append(wbuf, onewbuf...)
 14524  	}
 14525  	msg.WithdrawnRoutesLen = uint16(len(wbuf) - 2)
 14526  	binary.BigEndian.PutUint16(wbuf, msg.WithdrawnRoutesLen)
 14527  
 14528  	attributes := GetBGPUpdateAttributesFromMsg(msg)
 14529  	o := MarshallingOption{
 14530  		Attributes: attributes,
 14531  	}
 14532  	options = append(options, &o)
 14533  	pbuf := make([]byte, 2)
 14534  	for _, p := range msg.PathAttributes {
 14535  		onepbuf, err := p.Serialize(options...)
 14536  		if err != nil {
 14537  			return nil, err
 14538  		}
 14539  		pbuf = append(pbuf, onepbuf...)
 14540  	}
 14541  	msg.TotalPathAttributeLen = uint16(len(pbuf) - 2)
 14542  	binary.BigEndian.PutUint16(pbuf, msg.TotalPathAttributeLen)
 14543  
 14544  	buf := append(wbuf, pbuf...)
 14545  	for _, n := range msg.NLRI {
 14546  		nbuf, err := n.Serialize(options...)
 14547  		if err != nil {
 14548  			return nil, err
 14549  		}
 14550  		buf = append(buf, nbuf...)
 14551  	}
 14552  
 14553  	return buf, nil
 14554  }
 14555  
 14556  func (msg *BGPUpdate) IsEndOfRib() (bool, RouteFamily) {
 14557  	if len(msg.WithdrawnRoutes) == 0 && len(msg.NLRI) == 0 {
 14558  		if len(msg.PathAttributes) == 0 {
 14559  			return true, RF_IPv4_UC
 14560  		} else if len(msg.PathAttributes) == 1 && msg.PathAttributes[0].GetType() == BGP_ATTR_TYPE_MP_UNREACH_NLRI {
 14561  			unreach := msg.PathAttributes[0].(*PathAttributeMpUnreachNLRI)
 14562  			if len(unreach.Value) == 0 {
 14563  				return true, AfiSafiToRouteFamily(unreach.AFI, unreach.SAFI)
 14564  			}
 14565  		}
 14566  	}
 14567  	return false, RouteFamily(0)
 14568  }
 14569  
 14570  func TreatAsWithdraw(msg *BGPUpdate) *BGPUpdate {
 14571  	withdraw := &BGPUpdate{
 14572  		WithdrawnRoutesLen:    0,
 14573  		WithdrawnRoutes:       []*IPAddrPrefix{},
 14574  		TotalPathAttributeLen: 0,
 14575  		PathAttributes:        make([]PathAttributeInterface, 0, len(msg.PathAttributes)),
 14576  		NLRI:                  []*IPAddrPrefix{},
 14577  	}
 14578  	withdraw.WithdrawnRoutes = append(msg.WithdrawnRoutes, msg.NLRI...)
 14579  	var unreach []AddrPrefixInterface
 14580  
 14581  	for _, p := range msg.PathAttributes {
 14582  		switch nlri := p.(type) {
 14583  		case *PathAttributeMpReachNLRI:
 14584  			unreach = append(unreach, nlri.Value...)
 14585  		case *PathAttributeMpUnreachNLRI:
 14586  			unreach = append(unreach, nlri.Value...)
 14587  		}
 14588  	}
 14589  	if len(unreach) != 0 {
 14590  		withdraw.PathAttributes = append(withdraw.PathAttributes, NewPathAttributeMpUnreachNLRI(unreach))
 14591  	}
 14592  	return withdraw
 14593  }
 14594  
 14595  func NewBGPUpdateMessage(withdrawnRoutes []*IPAddrPrefix, pathattrs []PathAttributeInterface, nlri []*IPAddrPrefix) *BGPMessage {
 14596  	return &BGPMessage{
 14597  		Header: BGPHeader{Type: BGP_MSG_UPDATE},
 14598  		Body:   &BGPUpdate{0, withdrawnRoutes, 0, pathattrs, nlri},
 14599  	}
 14600  }
 14601  
 14602  func NewEndOfRib(family RouteFamily) *BGPMessage {
 14603  	if family == RF_IPv4_UC {
 14604  		return NewBGPUpdateMessage(nil, nil, nil)
 14605  	} else {
 14606  		afi, safi := RouteFamilyToAfiSafi(family)
 14607  		t := BGP_ATTR_TYPE_MP_UNREACH_NLRI
 14608  		unreach := &PathAttributeMpUnreachNLRI{
 14609  			PathAttribute: PathAttribute{
 14610  				Flags: PathAttrFlags[t],
 14611  				Type:  t,
 14612  			},
 14613  			AFI:  afi,
 14614  			SAFI: safi,
 14615  		}
 14616  		return NewBGPUpdateMessage(nil, []PathAttributeInterface{unreach}, nil)
 14617  	}
 14618  }
 14619  
 14620  type BGPNotification struct {
 14621  	ErrorCode    uint8
 14622  	ErrorSubcode uint8
 14623  	Data         []byte
 14624  }
 14625  
 14626  func (msg *BGPNotification) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
 14627  	if len(data) < 2 {
 14628  		return NewMessageError(BGP_ERROR_MESSAGE_HEADER_ERROR, BGP_ERROR_SUB_BAD_MESSAGE_LENGTH, nil, "Not all Notification bytes available")
 14629  	}
 14630  	msg.ErrorCode = data[0]
 14631  	msg.ErrorSubcode = data[1]
 14632  	if len(data) > 2 {
 14633  		msg.Data = data[2:]
 14634  	}
 14635  	return nil
 14636  }
 14637  
 14638  func (msg *BGPNotification) Serialize(options ...*MarshallingOption) ([]byte, error) {
 14639  	buf := make([]byte, 2, 2+len(msg.Data))
 14640  	buf[0] = msg.ErrorCode
 14641  	buf[1] = msg.ErrorSubcode
 14642  	buf = append(buf, msg.Data...)
 14643  	return buf, nil
 14644  }
 14645  
 14646  func NewBGPNotificationMessage(errcode uint8, errsubcode uint8, data []byte) *BGPMessage {
 14647  	return &BGPMessage{
 14648  		Header: BGPHeader{Type: BGP_MSG_NOTIFICATION},
 14649  		Body:   &BGPNotification{errcode, errsubcode, data},
 14650  	}
 14651  }
 14652  
 14653  // RFC8538 makes a suggestion that which Cease notification subcodes should be
 14654  // mapped to the Hard Reset. This function takes a subcode and returns true if
 14655  // the subcode should be treated as a Hard Reset. Otherwise, it returns false.
 14656  //
 14657  // The second argument is a boolean value that indicates whether the Hard Reset
 14658  // should be performed on the Admin Reset. This reflects the RFC8538's
 14659  // suggestion that the implementation should provide a control to treat the
 14660  // Admin Reset as a Hard Reset. When the second argument is true, the function
 14661  // returns true if the subcode is BGP_ERROR_SUB_ADMINISTRATIVE_RESET.
 14662  // Otherwise, it returns false.
 14663  //
 14664  // As RFC8538 states, it is not mandatory to follow this suggestion. You can
 14665  // use this function when you want to follow the suggestion.
 14666  func ShouldHardReset(subcode uint8, hardResetOnAdminReset bool) bool {
 14667  	switch subcode {
 14668  	case BGP_ERROR_SUB_MAXIMUM_NUMBER_OF_PREFIXES_REACHED,
 14669  		BGP_ERROR_SUB_ADMINISTRATIVE_SHUTDOWN,
 14670  		BGP_ERROR_SUB_PEER_DECONFIGURED,
 14671  		BGP_ERROR_SUB_HARD_RESET:
 14672  		return true
 14673  	default:
 14674  		if hardResetOnAdminReset && subcode == BGP_ERROR_SUB_ADMINISTRATIVE_RESET {
 14675  			return true
 14676  		}
 14677  		return false
 14678  	}
 14679  }
 14680  
 14681  type BGPKeepAlive struct {
 14682  }
 14683  
 14684  func (msg *BGPKeepAlive) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
 14685  	return nil
 14686  }
 14687  
 14688  func (msg *BGPKeepAlive) Serialize(options ...*MarshallingOption) ([]byte, error) {
 14689  	return nil, nil
 14690  }
 14691  
 14692  func NewBGPKeepAliveMessage() *BGPMessage {
 14693  	return &BGPMessage{
 14694  		Header: BGPHeader{Len: BGP_HEADER_LENGTH, Type: BGP_MSG_KEEPALIVE},
 14695  		Body:   &BGPKeepAlive{},
 14696  	}
 14697  }
 14698  
 14699  type BGPRouteRefresh struct {
 14700  	AFI         uint16
 14701  	Demarcation uint8
 14702  	SAFI        uint8
 14703  }
 14704  
 14705  func (msg *BGPRouteRefresh) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
 14706  	if len(data) < 4 {
 14707  		return NewMessageError(BGP_ERROR_ROUTE_REFRESH_MESSAGE_ERROR, BGP_ERROR_SUB_INVALID_MESSAGE_LENGTH, nil, "Not all RouteRefresh bytes available")
 14708  	}
 14709  	msg.AFI = binary.BigEndian.Uint16(data[0:2])
 14710  	msg.Demarcation = data[2]
 14711  	msg.SAFI = data[3]
 14712  	return nil
 14713  }
 14714  
 14715  func (msg *BGPRouteRefresh) Serialize(options ...*MarshallingOption) ([]byte, error) {
 14716  	buf := make([]byte, 4)
 14717  	binary.BigEndian.PutUint16(buf[0:2], msg.AFI)
 14718  	buf[2] = msg.Demarcation
 14719  	buf[3] = msg.SAFI
 14720  	return buf, nil
 14721  }
 14722  
 14723  func NewBGPRouteRefreshMessage(afi uint16, demarcation uint8, safi uint8) *BGPMessage {
 14724  	return &BGPMessage{
 14725  		Header: BGPHeader{Type: BGP_MSG_ROUTE_REFRESH},
 14726  		Body:   &BGPRouteRefresh{afi, demarcation, safi},
 14727  	}
 14728  }
 14729  
 14730  type BGPBody interface {
 14731  	DecodeFromBytes([]byte, ...*MarshallingOption) error
 14732  	Serialize(...*MarshallingOption) ([]byte, error)
 14733  }
 14734  
 14735  const (
 14736  	BGP_HEADER_LENGTH      = 19
 14737  	BGP_MAX_MESSAGE_LENGTH = 4096
 14738  )
 14739  
 14740  type BGPHeader struct {
 14741  	Marker []byte
 14742  	Len    uint16
 14743  	Type   uint8
 14744  }
 14745  
 14746  func (msg *BGPHeader) DecodeFromBytes(data []byte, options ...*MarshallingOption) error {
 14747  	// minimum BGP message length
 14748  	if uint16(len(data)) < BGP_HEADER_LENGTH {
 14749  		return NewMessageError(BGP_ERROR_MESSAGE_HEADER_ERROR, BGP_ERROR_SUB_BAD_MESSAGE_LENGTH, nil, "not all BGP message header")
 14750  	}
 14751  
 14752  	msg.Len = binary.BigEndian.Uint16(data[16:18])
 14753  	if int(msg.Len) < BGP_HEADER_LENGTH {
 14754  		return NewMessageError(BGP_ERROR_MESSAGE_HEADER_ERROR, BGP_ERROR_SUB_BAD_MESSAGE_LENGTH, nil, "unknown message type")
 14755  	}
 14756  
 14757  	msg.Type = data[18]
 14758  	return nil
 14759  }
 14760  
 14761  func (msg *BGPHeader) Serialize(options ...*MarshallingOption) ([]byte, error) {
 14762  	buf := make([]byte, BGP_HEADER_LENGTH)
 14763  	for i := range buf[:16] {
 14764  		buf[i] = 0xff
 14765  	}
 14766  	binary.BigEndian.PutUint16(buf[16:18], msg.Len)
 14767  	buf[18] = msg.Type
 14768  	return buf, nil
 14769  }
 14770  
 14771  type BGPMessage struct {
 14772  	Header BGPHeader
 14773  	Body   BGPBody
 14774  }
 14775  
 14776  func parseBody(h *BGPHeader, data []byte, options ...*MarshallingOption) (*BGPMessage, error) {
 14777  	if len(data) < int(h.Len)-BGP_HEADER_LENGTH {
 14778  		return nil, NewMessageError(BGP_ERROR_MESSAGE_HEADER_ERROR, BGP_ERROR_SUB_BAD_MESSAGE_LENGTH, nil, "Not all BGP message bytes available")
 14779  	}
 14780  	msg := &BGPMessage{Header: *h}
 14781  
 14782  	switch msg.Header.Type {
 14783  	case BGP_MSG_OPEN:
 14784  		msg.Body = &BGPOpen{}
 14785  	case BGP_MSG_UPDATE:
 14786  		msg.Body = &BGPUpdate{}
 14787  	case BGP_MSG_NOTIFICATION:
 14788  		msg.Body = &BGPNotification{}
 14789  	case BGP_MSG_KEEPALIVE:
 14790  		msg.Body = &BGPKeepAlive{}
 14791  	case BGP_MSG_ROUTE_REFRESH:
 14792  		msg.Body = &BGPRouteRefresh{}
 14793  	default:
 14794  		return nil, NewMessageError(BGP_ERROR_MESSAGE_HEADER_ERROR, BGP_ERROR_SUB_BAD_MESSAGE_TYPE, nil, "unknown message type")
 14795  	}
 14796  	err := msg.Body.DecodeFromBytes(data, options...)
 14797  	return msg, err
 14798  }
 14799  
 14800  func ParseBGPMessage(data []byte, options ...*MarshallingOption) (*BGPMessage, error) {
 14801  	h := &BGPHeader{}
 14802  	err := h.DecodeFromBytes(data, options...)
 14803  	if err != nil {
 14804  		return nil, err
 14805  	}
 14806  
 14807  	if int(h.Len) > len(data) {
 14808  		return nil, NewMessageError(BGP_ERROR_MESSAGE_HEADER_ERROR, BGP_ERROR_SUB_BAD_MESSAGE_LENGTH, nil, "unknown message type")
 14809  	}
 14810  
 14811  	return parseBody(h, data[BGP_HEADER_LENGTH:h.Len], options...)
 14812  }
 14813  
 14814  func ParseBGPBody(h *BGPHeader, data []byte, options ...*MarshallingOption) (*BGPMessage, error) {
 14815  	return parseBody(h, data, options...)
 14816  }
 14817  
 14818  func (msg *BGPMessage) Serialize(options ...*MarshallingOption) ([]byte, error) {
 14819  	b, err := msg.Body.Serialize(options...)
 14820  	if err != nil {
 14821  		return nil, err
 14822  	}
 14823  	if msg.Header.Len == 0 {
 14824  		if BGP_HEADER_LENGTH+len(b) > BGP_MAX_MESSAGE_LENGTH {
 14825  			return nil, NewMessageError(0, 0, nil, fmt.Sprintf("too long message length %d", BGP_HEADER_LENGTH+len(b)))
 14826  		}
 14827  		msg.Header.Len = BGP_HEADER_LENGTH + uint16(len(b))
 14828  	}
 14829  	h, err := msg.Header.Serialize(options...)
 14830  	if err != nil {
 14831  		return nil, err
 14832  	}
 14833  	return append(h, b...), nil
 14834  }
 14835  
 14836  type ErrorHandling int
 14837  
 14838  const (
 14839  	ERROR_HANDLING_NONE ErrorHandling = iota
 14840  	ERROR_HANDLING_ATTRIBUTE_DISCARD
 14841  	ERROR_HANDLING_TREAT_AS_WITHDRAW
 14842  	ERROR_HANDLING_AFISAFI_DISABLE
 14843  	ERROR_HANDLING_SESSION_RESET
 14844  )
 14845  
 14846  func getErrorHandlingFromPathAttribute(t BGPAttrType) ErrorHandling {
 14847  	switch t {
 14848  	case BGP_ATTR_TYPE_ORIGIN:
 14849  		return ERROR_HANDLING_TREAT_AS_WITHDRAW
 14850  	case BGP_ATTR_TYPE_AS_PATH:
 14851  		return ERROR_HANDLING_TREAT_AS_WITHDRAW
 14852  	case BGP_ATTR_TYPE_AS4_PATH:
 14853  		return ERROR_HANDLING_TREAT_AS_WITHDRAW
 14854  	case BGP_ATTR_TYPE_NEXT_HOP:
 14855  		return ERROR_HANDLING_TREAT_AS_WITHDRAW
 14856  	case BGP_ATTR_TYPE_MULTI_EXIT_DISC:
 14857  		return ERROR_HANDLING_TREAT_AS_WITHDRAW
 14858  	case BGP_ATTR_TYPE_LOCAL_PREF:
 14859  		return ERROR_HANDLING_TREAT_AS_WITHDRAW
 14860  	case BGP_ATTR_TYPE_ATOMIC_AGGREGATE:
 14861  		return ERROR_HANDLING_ATTRIBUTE_DISCARD
 14862  	case BGP_ATTR_TYPE_AGGREGATOR:
 14863  		return ERROR_HANDLING_ATTRIBUTE_DISCARD
 14864  	case BGP_ATTR_TYPE_AS4_AGGREGATOR:
 14865  		return ERROR_HANDLING_TREAT_AS_WITHDRAW
 14866  	case BGP_ATTR_TYPE_COMMUNITIES:
 14867  		return ERROR_HANDLING_TREAT_AS_WITHDRAW
 14868  	case BGP_ATTR_TYPE_ORIGINATOR_ID:
 14869  		return ERROR_HANDLING_TREAT_AS_WITHDRAW
 14870  	case BGP_ATTR_TYPE_CLUSTER_LIST:
 14871  		return ERROR_HANDLING_TREAT_AS_WITHDRAW
 14872  	case BGP_ATTR_TYPE_MP_REACH_NLRI:
 14873  		return ERROR_HANDLING_AFISAFI_DISABLE
 14874  	case BGP_ATTR_TYPE_MP_UNREACH_NLRI:
 14875  		return ERROR_HANDLING_AFISAFI_DISABLE
 14876  	case BGP_ATTR_TYPE_EXTENDED_COMMUNITIES:
 14877  		return ERROR_HANDLING_TREAT_AS_WITHDRAW
 14878  	case BGP_ATTR_TYPE_IP6_EXTENDED_COMMUNITIES:
 14879  		return ERROR_HANDLING_TREAT_AS_WITHDRAW
 14880  	case BGP_ATTR_TYPE_PMSI_TUNNEL:
 14881  		return ERROR_HANDLING_TREAT_AS_WITHDRAW
 14882  	case BGP_ATTR_TYPE_LARGE_COMMUNITY:
 14883  		return ERROR_HANDLING_TREAT_AS_WITHDRAW
 14884  	case BGP_ATTR_TYPE_TUNNEL_ENCAP:
 14885  		return ERROR_HANDLING_ATTRIBUTE_DISCARD
 14886  	case BGP_ATTR_TYPE_AIGP:
 14887  		return ERROR_HANDLING_ATTRIBUTE_DISCARD
 14888  	default:
 14889  		return ERROR_HANDLING_ATTRIBUTE_DISCARD
 14890  	}
 14891  }
 14892  
 14893  type MessageError struct {
 14894  	TypeCode       uint8
 14895  	SubTypeCode    uint8
 14896  	Data           []byte
 14897  	Message        string
 14898  	ErrorHandling  ErrorHandling
 14899  	ErrorAttribute *PathAttributeInterface
 14900  }
 14901  
 14902  func NewMessageError(typeCode, subTypeCode uint8, data []byte, msg string) error {
 14903  	return &MessageError{
 14904  		TypeCode:       typeCode,
 14905  		SubTypeCode:    subTypeCode,
 14906  		Data:           data,
 14907  		ErrorHandling:  ERROR_HANDLING_SESSION_RESET,
 14908  		ErrorAttribute: nil,
 14909  		Message:        msg,
 14910  	}
 14911  }
 14912  
 14913  func NewMessageErrorWithErrorHandling(typeCode, subTypeCode uint8, data []byte, errorHandling ErrorHandling, errorAttribute *PathAttributeInterface, msg string) error {
 14914  	return &MessageError{
 14915  		TypeCode:       typeCode,
 14916  		SubTypeCode:    subTypeCode,
 14917  		Data:           data,
 14918  		ErrorHandling:  errorHandling,
 14919  		ErrorAttribute: errorAttribute,
 14920  		Message:        msg,
 14921  	}
 14922  }
 14923  
 14924  func (e *MessageError) Error() string {
 14925  	return e.Message
 14926  }
 14927  
 14928  func (e *MessageError) Stronger(err error) bool {
 14929  	if err == nil {
 14930  		return true
 14931  	}
 14932  	if msgErr, ok := err.(*MessageError); ok {
 14933  		return e.ErrorHandling > msgErr.ErrorHandling
 14934  	}
 14935  	return false
 14936  }
 14937  
 14938  func (e *TwoOctetAsSpecificExtended) Flat() map[string]string {
 14939  	if e.SubType == EC_SUBTYPE_ROUTE_TARGET {
 14940  		return map[string]string{"routeTarget": e.String()}
 14941  	}
 14942  	return map[string]string{}
 14943  }
 14944  
 14945  func (e *ColorExtended) Flat() map[string]string {
 14946  	return map[string]string{}
 14947  }
 14948  
 14949  func (e *EncapExtended) Flat() map[string]string {
 14950  	return map[string]string{"encaspulation": e.TunnelType.String()}
 14951  }
 14952  
 14953  func (e *DefaultGatewayExtended) Flat() map[string]string {
 14954  	return map[string]string{}
 14955  }
 14956  
 14957  func (e *ValidationExtended) Flat() map[string]string {
 14958  	return map[string]string{}
 14959  }
 14960  
 14961  func (e *LinkBandwidthExtended) Flat() map[string]string {
 14962  	return map[string]string{}
 14963  }
 14964  
 14965  func (e *OpaqueExtended) Flat() map[string]string {
 14966  	return map[string]string{}
 14967  }
 14968  
 14969  func (e *IPv4AddressSpecificExtended) Flat() map[string]string {
 14970  	return map[string]string{}
 14971  }
 14972  
 14973  func (e *IPv6AddressSpecificExtended) Flat() map[string]string {
 14974  	return map[string]string{}
 14975  }
 14976  
 14977  func (e *FourOctetAsSpecificExtended) Flat() map[string]string {
 14978  	return map[string]string{}
 14979  }
 14980  
 14981  func (e *ESILabelExtended) Flat() map[string]string {
 14982  	return map[string]string{}
 14983  }
 14984  
 14985  func (e *ESImportRouteTarget) Flat() map[string]string {
 14986  	return map[string]string{}
 14987  }
 14988  
 14989  func (e *MacMobilityExtended) Flat() map[string]string {
 14990  	return map[string]string{}
 14991  }
 14992  
 14993  func (e *RouterMacExtended) Flat() map[string]string {
 14994  	return map[string]string{}
 14995  }
 14996  
 14997  func (e *Layer2AttributesExtended) Flat() map[string]string {
 14998  	return map[string]string{}
 14999  }
 15000  
 15001  func (e *TrafficRateExtended) Flat() map[string]string {
 15002  	return map[string]string{}
 15003  }
 15004  
 15005  func (e *TrafficRemarkExtended) Flat() map[string]string {
 15006  	return map[string]string{}
 15007  }
 15008  
 15009  func (e *RedirectIPv4AddressSpecificExtended) Flat() map[string]string {
 15010  	return map[string]string{}
 15011  }
 15012  
 15013  func (e *RedirectIPv6AddressSpecificExtended) Flat() map[string]string {
 15014  	return map[string]string{}
 15015  }
 15016  
 15017  func (e *RedirectFourOctetAsSpecificExtended) Flat() map[string]string {
 15018  	return map[string]string{}
 15019  }
 15020  
 15021  func (e *UnknownExtended) Flat() map[string]string {
 15022  	return map[string]string{}
 15023  }
 15024  
 15025  func (e *TrafficActionExtended) Flat() map[string]string {
 15026  	return map[string]string{}
 15027  }
 15028  
 15029  func (p *PathAttributeExtendedCommunities) Flat() map[string]string {
 15030  	flat := map[string]string{}
 15031  	for _, ec := range p.Value {
 15032  		FlatUpdate(flat, ec.Flat())
 15033  	}
 15034  	return flat
 15035  }
 15036  
 15037  func (p *PathAttribute) Flat() map[string]string {
 15038  	return map[string]string{}
 15039  }
 15040  
 15041  func (l *LabeledVPNIPAddrPrefix) Flat() map[string]string {
 15042  	prefixLen := l.IPAddrPrefixDefault.Length - uint8(8*(l.Labels.Len()+l.RD.Len()))
 15043  	return map[string]string{
 15044  		"Prefix":    l.IPAddrPrefixDefault.Prefix.String(),
 15045  		"PrefixLen": fmt.Sprintf("%d", prefixLen),
 15046  		"NLRI":      l.String(),
 15047  		"Label":     l.Labels.String(),
 15048  	}
 15049  }
 15050  
 15051  func (p *IPAddrPrefixDefault) Flat() map[string]string {
 15052  	l := strings.Split(p.String(), "/")
 15053  	if len(l) == 2 {
 15054  		return map[string]string{
 15055  			"Prefix":    l[0],
 15056  			"PrefixLen": l[1],
 15057  		}
 15058  	}
 15059  	return map[string]string{}
 15060  }
 15061  
 15062  func (l *EVPNNLRI) Flat() map[string]string {
 15063  	return map[string]string{}
 15064  }
 15065  func (l *RouteTargetMembershipNLRI) Flat() map[string]string {
 15066  	return map[string]string{}
 15067  }
 15068  func (l *FlowSpecIPv4Unicast) Flat() map[string]string {
 15069  	return map[string]string{}
 15070  }
 15071  func (l *FlowSpecIPv4VPN) Flat() map[string]string {
 15072  	return map[string]string{}
 15073  }
 15074  func (l *FlowSpecIPv6Unicast) Flat() map[string]string {
 15075  	return map[string]string{}
 15076  }
 15077  func (l *FlowSpecIPv6VPN) Flat() map[string]string {
 15078  	return map[string]string{}
 15079  }
 15080  func (l *FlowSpecL2VPN) Flat() map[string]string {
 15081  	return map[string]string{}
 15082  }
 15083  func (l *OpaqueNLRI) Flat() map[string]string {
 15084  	return map[string]string{}
 15085  }
 15086  
 15087  // Update a Flat representation by adding elements of the second
 15088  // one. If two elements use same keys, values are separated with
 15089  // ';'. In this case, it returns an error but the update has been
 15090  // realized.
 15091  func FlatUpdate(f1, f2 map[string]string) error {
 15092  	conflict := false
 15093  	for k2, v2 := range f2 {
 15094  		if v1, ok := f1[k2]; ok {
 15095  			f1[k2] = v1 + ";" + v2
 15096  			conflict = true
 15097  		} else {
 15098  			f1[k2] = v2
 15099  		}
 15100  	}
 15101  	if conflict {
 15102  		return errors.New("keys conflict")
 15103  	} else {
 15104  		return nil
 15105  	}
 15106  }