<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type='text/xsl' href='rfc2629.xslt' ?>
<!DOCTYPE rfc SYSTEM "rfc2629.dtd" [
<!ENTITY RFC2119 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.2119.xml">
<!ENTITY RFC8200 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.8200.xml">
<!ENTITY RFC4271 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.4271.xml">
<!ENTITY RFC4443 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.4443.xml">
<!ENTITY RFC4760 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.4760.xml">
<!ENTITY RFC5701 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.5701.xml">
<!ENTITY RFC7153 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.7153.xml">
<!ENTITY RFC8126 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.8126.xml">
<!ENTITY RFC8174 SYSTEM "http://xml.resource.org/public/rfc/bibxml/reference.RFC.8174.xml">
<!ENTITY I-D.ietf-idr-rfc5575bis SYSTEM "http://xml.resource.org/public/rfc/bibxml3/reference.I-D.ietf-idr-rfc5575bis.xml">
]>
<?rfc toc="yes" ?>
<?rfc symrefs="yes" ?>
<?rfc sortrefs="yes"?>
<?rfc compact="yes" ?>
<?rfc subcompact="no" ?>
<?rfc iprnotified="no" ?>
<?rfc strict="no" ?>
<rfc category="std" docName="draft-ietf-idr-flow-spec-v6-13"  ipr="trust200902">
  <front>
  <title abbrev="IPv6 Flow Specification">Dissemination of Flow Specification Rules for IPv6</title>
   <author role="editor" fullname="Christoph Loibl" initials="C.L."
           surname="Loibl">
     <organization>next layer Telekom GmbH</organization>
     <address>
       <postal>
         <street>Mariahilfer Guertel 37/7</street>
         <city>Vienna</city>
         <region></region>
         <code>1150</code>
         <country>AT</country>
       </postal>
       <phone>+43 664 1176414</phone>
       <email>cl@tix.at</email>
     </address>
   </author>
      <author fullname='Robert Raszuk' initials='R' surname='Raszuk' role="editor">
    <organization>Bloomberg LP</organization>
    <address>
        <postal>
            <street>731 Lexington Ave </street>
            <city>New York City</city>
            <region>NY</region>
            <code>10022</code>
            <country>USA</country>
        </postal>
        <email>robert@raszuk.net</email>
    </address>
    </author>
		<author role="editor" fullname="Susan Hares" initials="S" surname="Hares">
      <organization>Huawei</organization>
      <address>
        <postal>
          <street>7453 Hickory Hill</street>
          <city>Saline</city>
          <region>MI</region>
          <code>48176</code>
          <country>USA</country>
        </postal>
        <email>shares@ndzh.com</email>
      </address>
    </author>

    <date year="2020" />
    <area>Routing Area</area>
    <workgroup>IDR Working Group</workgroup>
    <keyword>RFC</keyword>
    <keyword>Request for Comments</keyword>
    <keyword>I-D</keyword>
    <keyword>Internet-Draft</keyword>
    <keyword>BGP Flow Flow Specification</keyword>
	<keyword>V6</keyword>
    <abstract>
   <t>Dissemination of Flow Specification Rules I-D.ietf-idr-rfc5575bis provides a
   protocol extension for propagation of traffic flow information for
   the purpose of rate limiting or filtering. I-D.ietf-idr-rfc5575bis specifies
   those extensions for IPv4 protocol data packets only.
   </t>
   <t>
   This specification extends I-D.ietf-idr-rfc5575bis and defines changes
   to the original document in order to make it also usable and
   applicable to IPv6 data packets.
   </t>
    </abstract>
  </front>
  <middle>
     <section anchor="intro" title="Introduction">
	 <t>The growing amount of IPv6 traffic in private and public networks
   requires the extension of tools used in the IPv4 only networks to be
   also capable of supporting IPv6 data packets.
  </t>
  <t>
   In this document authors analyze the differences of IPv6 <xref target="RFC8200"></xref>
   flows description from those of traditional IPv4 packets and propose
   subset of new encoding formats to enable Dissemination of Flow
   Specification Rules <xref target="I-D.ietf-idr-rfc5575bis" /> for IPv6.
 </t>
 <t>
   This specification should be treated as an extension of base
   <xref target="I-D.ietf-idr-rfc5575bis" /> specification and not its replacement.  It only defines the
   delta changes required to support IPv6 while all other definitions
   and operation mechanisms of Dissemination of Flow Specification Rules
   will remain in the main specification and will not be repeated here.
   </t>
	<section title="Definitions of Terms Used in This Memo">
	<t>
	<list style="hanging">
	<t hangText="AFI - ">Address Family Identifier.</t>
	<t hangText="AS - ">Autonomous System.</t>
	<t hangText="NLRI - ">Network Layer Reachability Information.</t>
    <t hangText="SAFI - ">Subsequent Address Family Identifier.</t>
	<t hangText="VRF - ">Virtual Routing and Forwarding instance.</t>
	</list>
	</t>
	<t>
    The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL
    NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "NOT RECOMMENDED",
    "MAY", and "OPTIONAL" in this document are to be interpreted as
    described in BCP 14 <xref target="RFC2119"></xref> <xref target="RFC8174"></xref>
    when, and only when, they appear in all capitals, as shown here.
	</t>
	</section>
   </section>
   <section title="IPv6 Flow Specification encoding in BGP">
   <t>
   The <xref target="I-D.ietf-idr-rfc5575bis" /> defines new SAFIs
   133 (Dissemination of Flow Specification) and 134 (L3VPN
   Dissemination of Flow Specification) applications in order to carry
   corresponding to each such application Flow Specification.
   </t>
   <t>
   Implementations wishing to exchange IPv6 Flow Specifications MUST use
   BGP's Capability Advertisement facility to exchange the Multiprotocol
   Extension Capability Code (Code 1) as defined in <xref target="RFC4760"></xref>.
   While <xref target="I-D.ietf-idr-rfc5575bis" /> specifies Flow
   Specification for IPv4 (AFI=1) only, the (AFI, SAFI) pair carried in
   the Multiprotocol Extension Capability MUST be: (AFI=2, SAFI=133) for
   IPv6 Flow Specification, and (AFI=2, SAFI=134) for VPNv6 Flow Specification.
   </t>
   <t>
   For both SAFIs the indication to which address family they are
   referring to will be recognized by AFI value (AFI=1 for IPv4 or
   VPNv4, AFI=2 for IPv6 and VPNv6 respectively).
   </t>
   <t>It needs to be observed that such choice of proposed encoding is
   compatible with filter validation against routing reachability
   information as described in Section 6 of <xref target="I-D.ietf-idr-rfc5575bis" />.
   </t>
   </section>
   <section title="IPv6 Flow Specification components">
   <t>The following components are redefined or added for the purpose
   of accommodating the IPv6 header encoding. Unless otherwise specified
   all other components defined in <xref target="I-D.ietf-idr-rfc5575bis" />
   Section 4.2.2 also apply to IPv6 Flow Specification.
   </t>
   <section anchor="type_1" title="Type 1 - Destination IPv6 Prefix" toc="include">
	   <t>Encoding: &lt;type (1 octet), length (1 octet), offset (1 octet), prefix (variable)&gt;
	  </t>
	  <t>Defines the destination prefix to match.  The offset has been
      defined to allow for flexible matching on part of the IPv6 address
      where it is required to skip (don't care) of N first bits of the address.
      This can be especially useful where part of the IPv6 address
      consists of an embedded IPv4 address and matching needs to happen
      only on the embedded IPv4 address. The encoded prefix contains
      enough octets for the bits used in matching (length minus offset
      bits).
	  </t>
   </section>
   <section anchor="type_2" title="Type 2 - Source IPv6 Prefix" toc="include">
	   <t>Encoding: &lt;type (1 octet), length (1 octet), offset
      (1 octet), prefix (variable)&gt;
      </t>
	  <t>Defines the source prefix to match. The length, offset and prefix
          are the same as in <xref target="type_1" />
	  </t>
	 </section>
   	 <section anchor="type_3" title="Type 3 - Next Header">
	   <t>Encoding: &lt;type (1 octet), [numeric_op, value]+&gt;
      </t>
	  <t>Contains a list of {numeric_op, value} pairs that
      are used to match the last Next Header (<xref target="RFC8200" />
      Section 3) value octet in IPv6 packets.
      </t>
      <t>This component uses the Numeric Operator (numeric_op) described in
      <xref target="I-D.ietf-idr-rfc5575bis" /> Section 4.2.1.1.
      Type 3 component values SHOULD be encoded as single byte
      (numeric_op len=00).
      </t>
	  <t>Note: While IPv6 allows for more then one Next Header field in the
	  packet the main goal of Type 3 flow specification component is to
      match on the subsequent IP protocol value.  Therefore the
      definition is limited to match only on last Next Header field in
      the packet.
	  </t>
	  </section>
    <section anchor="type_7" title="Type 7 - ICMPv6 type" toc="include">
    <t>Encoding: &lt;type (1 octet), [numeric_op, value]+&gt;
    </t>
    <t>Defines a list of {numeric_op, value} pairs used to match the
    type field of an ICMPv6 packet (see also <xref target="RFC4443" /> Section 2.1).
    </t>
    <t>
        This component uses the Numeric Operator (numeric_op) described
        in <xref target="I-D.ietf-idr-rfc5575bis" /> Section 4.2.1.1.
        Type 7 component values SHOULD be encoded as single byte
        (numeric_op len=00).
    </t>
    <t>
        In case of the presence of the ICMPv6 type
        component only ICMPv6 packets can match the entire Flow Specification.
        The ICMPv6 type component, if present, never matches when the packet's
        last Next Header field value is not 58 (ICMPv6), if the packet is fragmented
        and this is not the first fragment, or if the system is unable to
        locate the transport header. Different implementations may or may not be
        able to decode the transport header.
    </t>
    </section>
    <section anchor="type_8" title="Type 8 - ICMPv6 code" toc="include">
    <t>Encoding: &lt;type (1 octet), [numeric_op, value]+&gt;
    </t>
    <t>
    Defines a list of {numeric_op, value} pairs used to match the
    code field of an ICMPv6 packet (see also <xref target="RFC4443" /> Section 2.1).
    </t>
    <t>
        This component uses the Numeric Operator (numeric_op) described
        in <xref target="I-D.ietf-idr-rfc5575bis" /> Section 4.2.1.1.
        Type 8 component values SHOULD be encoded as single byte
        (numeric_op len=00).
    </t>
    <t>
        In case of the presence of the ICMPv6 code
        component only ICMPv6 packets can match the entire Flow Specification.
        The ICMPv6 code component, if present, never matches when the packet's
        last Next Header field value is not 58 (ICMPv6), if the packet is fragmented
        and this is not the first fragment, or if the system is unable to
        locate the transport header. Different implementations may or may not be
        able to decode the transport header.
    </t>
    </section>
     <section anchor="type_12 " title="Type 12 - Fragment">
	   <t>Encoding: &lt;type (1 octet), [bitmask_op, bitmask]+&gt;
      </t>
      <t> Defines a list of {bitmask_op, bitmask} pairs used to match specific IP fragments.
      </t>
      <t>This component uses the Bitmask Operator (bitmask_op) described
      in <xref target="I-D.ietf-idr-rfc5575bis" /> Section 4.2.1.2. The
      Type 12 component bitmask MUST be encoded as single byte bitmask
      (bitmask_op len=00).
      </t>
        <t>
        <figure title="Fragment Bitmask Operand" anchor="figure_fragment_bitmask_operand">
        <artwork>
                   0   1   2   3   4   5   6   7
                 +---+---+---+---+---+---+---+---+
                 | 0 | 0 | 0 | 0 |LF |FF |IsF| 0 |
                 +---+---+---+---+---+---+---+---+
        </artwork>
        </figure>
        </t>
        <t>Bitmask values:
        <list style="hanging">
        <t hangText="IsF -">Is a fragment - match if IPv6 Fragment Header (<xref target="RFC8200" /> Section 4.5)
            Fragment Offset is not 0
        </t>
        <t hangText="FF -">First fragment - match if IPv6 Fragment Header (<xref target="RFC8200" /> Section 4.5)
            Fragment Offset is 0 AND M flag is 1
        </t>
        <t hangText="LF -">Last fragment - match if IPv6 Fragment Header (<xref target="RFC8200" /> Section 4.5)
            Fragment Offset is not 0 AND M flag is 0
        </t>
        <t hangText="0 -">MUST be set to 0 on NLRI encoding, and MUST be ignored during decoding
        </t>
        </list>
        </t>
	 </section>
     <section anchor="type_13" title="Type 13 - Flow Label (new)">
	   <t>Encoding: &lt;type (1 octet), [numeric_op, value]+&gt;
      </t>
	  <t>Contains a list of {numeric_op, value} pairs that are used to match
      the 20-bit Flow Label IPv6 header field (<xref target="RFC8200"></xref>
      Section 3).
      </t>
      <t>This component uses the Numeric Operator (numeric_op) described in
      <xref target="I-D.ietf-idr-rfc5575bis" /> Section 4.2.1.1. Type 13
      component values SHOULD be encoded as 1-, 2-, or 4-byte quantities
      (numeric_op len=00, len=01 or len=10).
      </t>
	 </section>
    <section title="Encoding Example">
 <section title="Example 1" toc="exclude">
<t>
   The following example demonstrates the prefix encoding for: "all
   packets to ::1234:5678:9A00:0/64-104 from 100::/8 and port 25".
</t>
 <t>
 <figure>
 <artwork>
    +--------+-------------------------+-------------+----------+
    | length | destination             | source      | port     |
    +--------+-------------------------+-------------+----------+
    | 0x0f   | 01 68 40 12 34 56 78 9A | 02 08 00 01 | 04 81 19 |
    +--------+-------------------------+-------------+----------+
 </artwork>
 </figure>
 </t>
<t>
   Decoded:
<figure>
<artwork>
    +-------+------------+------------------------------+
    | Value |            |                              |
    +-------+------------+------------------------------+
    |  0x0f | length     | 16 octets (len&lt;240 1-octet)  |
    |  0x01 | type       | Type 1 - Dest. IPv6 Prefix   |
    |  0x68 | length     | 104 bit                      |
    |  0x40 | offset     | 64 bit                       |
    |  0x12 | prefix     |                              |
    |  0x34 | prefix     |                              |
    |  0x56 | prefix     |                              |
    |  0x78 | prefix     |                              |
    |  0x9A | prefix     |                              |
    |  0x02 | type       | Type 2 - Source IPv6 Prefix  |
    |  0x08 | length     | 8 bit                        |
    |  0x00 | offset     | 0 bit                        |
    |  0x01 | prefix     |                              |
    |  0x04 | type       | Type 4 - Port                |
    |  0x81 | numeric_op | end-of-list, value size=1, = |
    |  0x19 | value      | 25                           |
    +-------+------------+------------------------------+
</artwork>
</figure>
    This constitutes a NLRI with a NLRI length of 16 octets.
</t>
</section>
 <section title="Example 2" toc="exclude">
<t>
   The following example demonstrates the prefix encoding for: "all
   packets to ::1234:5678:9A00:0/65-104".
</t>
 <t>
 <figure>
 <artwork>
    +--------+-------------------------+
    | length | destination             |
    +--------+-------------------------+
    | 0x08   | 01 68 41 24 68 ac f1 34 |
    +--------+-------------------------+
 </artwork>
 </figure>
 </t>
<t>
   Decoded:
<figure>
<artwork>
    +-------+------------+------------------------------+
    | Value |            |                              |
    +-------+------------+------------------------------+
    |  0x08 | length     | 8 octets (len&lt;240 1-octet)   |
    |  0x01 | type       | Type 1 - Dest. IPv6 Prefix   |
    |  0x68 | length     | 104 bit                      |
    |  0x41 | offset     | 65 bit                       |
    |  0x24 | prefix     | starting with the 66ths bit  |
    |  0x68 | prefix     |                              |
    |  0xac | prefix     |                              |
    |  0xf1 | prefix     |                              |
    |  0x34 | prefix     |                              |
    +-------+------------+------------------------------+
</artwork>
</figure>
    This constitutes a NLRI with a NLRI length of 8 octets.
</t>
</section>


   </section>
   </section>
	<section title="Ordering of Flow Specifications">
	<t>
	The definition for the order of traffic filtering rules from
    <xref target="I-D.ietf-idr-rfc5575bis" /> Section 5.1 can
    be reused with new consideration for the IPv6 prefix offset.  As long
    as the offsets are equal, the comparison is the same, retaining
    longest-prefix-match semantics.  If the offsets are not equal, the
    lowest offset has precedence, as this flow matches the most
    significant bit.
	</t>
    <t>
      The code in <xref target="flow_rule_cmp_src" /> shows a Python3 implementation
      of the resulting comparison algorithm. The full code was tested with Python 3.7.2 and can be
      obtained at <eref target="https://github.com/stoffi92/draft-ietf-idr-flow-spec-v6/tree/master/flowspec-cmp">https://github.com/stoffi92/draft-ietf-idr-flow-spec-v6/tree/master/flowspec-cmp</eref>.
    </t>
	</section>
	<section title="Validation Procedure">
	<t>
    The validation procedure is the same as specified in
    <xref target="I-D.ietf-idr-rfc5575bis" /> Section 6 with the exception
    that item a) of the validation procedure should now read as follows:
    <list>
    <t>
      a) A destination prefix component with offset=0 is embedded in the
        Flow Specification
    </t>
    </list>
    </t>
	</section>
	<section title="IPv6 Traffic Filtering Action changes">
	<t>Traffic Filtering Actions from <xref target="I-D.ietf-idr-rfc5575bis" />
        Section 7 can also be applied to IPv6 Flow Specifications. To allow
        an IPv6 address specific route-target, a new Traffic Filtering
        Action IPv6 address specific extended community is specified in
        <xref target="redirect_ipv6" /> below:
    </t>
    <section anchor="redirect_ipv6" title="Redirect IPv6 (rt-redirect-ipv6) Type/Sub-Type 0x80/TBD">
       <t>The redirect IPv6 address specific extended community
       allows the traffic to be redirected to a VRF routing instance that
       lists the specified IPv6 address specific route-target in its import
       policy.  If several local instances match this criteria, the choice
       between them is a local matter (for example, the instance with the
       lowest Route Distinguisher value can be elected).
       </t>
       <t>This extended community uses the same encoding as the IPv6
       address specific Route Target extended community
       <xref target="RFC5701"></xref> Section 2 with the high-order
       octet of the Type always set to 0x80 and the Sub-Type always TBD.
       </t>
       <t>Interferes with: All BGP Flow Specification redirect Traffic Filtering
           Actions (with itself and those specified in
           <xref target="I-D.ietf-idr-rfc5575bis" /> Section 7.4).
       </t>
       </section>
	</section>
   <section title="Security Considerations">
   <t>No new security issues are introduced to the BGP protocol by this
   specification over the security considerations in
   <xref target="I-D.ietf-idr-rfc5575bis" />
   </t>
   </section>
   <section anchor="IANA" title="IANA Considerations">
   <t>This section complies with <xref target="RFC7153"></xref>
   </t>
    <t>
   IANA is requested to create and maintain a new registry entitled:
   "Flow Spec IPv6 Component Types" containing the initial entries as specified in
   <xref target="iana_flow_component_types" />.
   </t>
       <texttable anchor="iana_flow_component_types" title="Registry: Flow Spec IPv6 Component Types">
          <ttcol align="left">Value</ttcol>
          <ttcol align="left">Name</ttcol>
          <ttcol align="left">Reference</ttcol>
          <c>1</c>   <c>Destination IPv6 Prefix</c>  <c>[this document]</c>
          <c>2</c>   <c>Source IPv6 Prefix</c>       <c>[this document]</c>
          <c>3</c>   <c>Next Header</c>         <c>[this document]</c>
          <c>4</c>   <c>Port</c>                <c>[this document]</c>
          <c>5</c>   <c>Destination port</c>    <c>[this document]</c>
          <c>6</c>   <c>Source port</c>         <c>[this document]</c>
          <c>7</c>   <c>ICMPv6 type</c>         <c>[this document]</c>
          <c>8</c>   <c>ICMPv6 code</c>         <c>[this document]</c>
          <c>9</c>   <c>TCP flags</c>           <c>[this document]</c>
          <c>10</c>  <c>Packet length</c>       <c>[this document]</c>
          <c>11</c>  <c>DSCP</c>                <c>[this document]</c>
          <c>12</c>  <c>Fragment</c>            <c>[this document]</c>
          <c>13</c>  <c>Flow Label</c>            <c>[this document]</c>
    </texttable>
    <t>
      In order to manage the limited number space and accommodate several
      usages, the following policies defined by <xref target="RFC8126" />
      are used:
    </t>
    <texttable anchor="iana_flow_component_types_policies" title="Flow Spec IPv6 Component Types Registration Policy">
          <ttcol align="left">Type Values</ttcol>
          <ttcol align="left">Policy</ttcol>
          <c>0</c>           <c>Reserved</c>
          <c>[1 .. 127]</c>   <c>Specification Required</c>
          <c>[128 .. 254]</c>   <c>Expert Review</c>
          <c>255</c>   <c>Reserved</c>
    </texttable>
    <t>
    <list style="hanging" hangIndent="6">
        <t hangText="Guidance for Experts:">
        <vspace />
        128-254 requires 
        Expert Review as the registration policy. The Experts are expected 
        to check the clarity of purpose and use of the requested code points. 
        The Experts must also verify that any 
        specification produced in the IETF that requests one of these code
        points has been made available for review by the IDR working group
        and that any specification produced outside the IETF does not
        conflict with work that is active or already published within the
        IETF. It must be pointed out that introducing new component types may 
        break existing implementations of this protocol.
        </t>
    </list>
    </t>
    <t>
        IANA maintains a registry entitled "Generic Transitive
        Experimental Use Extended Community Sub-Types". For the purpose of
        this work, IANA is requested to assign a new value:
    </t>
   <texttable anchor="iana_ext_comm_subtypes" title="Registry: Generic Transitive Experimental Use Extended Community Sub-Types">
         <ttcol align="left">Sub-Type Value</ttcol>
         <ttcol align="left">Name</ttcol>
         <ttcol align="left">Reference</ttcol>
         <c>TBD</c>
         <c>
           Flow spec rt-redirect-ipv6 format
         </c>
         <c>[this document]</c>
   </texttable>
 </section>
 <section title="Acknowledgements">
 <t>Authors would like to thank Pedro Marques, Hannes Gredler and Bruno
   Rijsman, Brian Carpenter, and Thomas Mangin for their valuable input.
   </t>
 </section>
 <section title="Contributors">
     <t>
<figure>
<artwork>
Danny McPherson
Verisign, Inc.

Email: dmcpherson@verisign.com

</artwork>
</figure>
</t><t>
<figure>
<artwork>
Burjiz Pithawala
Individual

Email: burjizp@gmail.com

</artwork>
</figure>
</t><t>
<figure>
<artwork>
Andy Karch
Cisco Systems
170 West Tasman Drive
San Jose, CA  95134
USA

Email: akarch@cisco.com

</artwork>
</figure>
     </t>
 </section>
  </middle>
  <back>
    <references title="Normative References">
      &RFC2119;
	  &RFC8200;
	  &RFC4271;
      &RFC4443;
      &RFC4760;
	  &RFC5701;
	  &RFC7153;
      &RFC8126;
      &RFC8174;
      &I-D.ietf-idr-rfc5575bis;
	</references>
    <section title="Example python code: flow_rule_cmp_v6" anchor="flow_rule_cmp_src">
<t>
  <figure>
    <artwork><![CDATA[
<CODE BEGINS>
"""
Copyright (c) 2020 IETF Trust and the persons identified as authors
of draft-ietf-idr-flow-spec-v6. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, is permitted pursuant to, and subject to the license
terms contained in, the Simplified BSD License set forth in Section
4.c of the IETF Trust’s Legal Provisions Relating to IETF Documents
(http://trustee.ietf.org/license-info).
"""

import itertools
import collections
import ipaddress


EQUAL = 0
A_HAS_PRECEDENCE = 1
B_HAS_PRECEDENCE = 2
IP_DESTINATION = 1
IP_SOURCE = 2

FS_component = collections.namedtuple('FS_component', 
                                      'component_type value')


class FS_IPv6_prefix_component:
    def __init__(self, prefix, offset=0, 
                 component_type=IP_DESTINATION):
        self.offset = offset
        self.component_type = component_type
        # make sure if offset != 0 that non of the 
        # first offset bits are set in the prefix
        self.value = prefix
        if offset != 0:
            i = ipaddress.IPv6Interface(
                (self.value.network_address, offset))
            if i.network.network_address != \
                ipaddress.ip_address('0::0'):
                raise ValueError('Bits set in the offset')


class FS_nlri(object):
    """
    FS_nlri class implementation that allows sorting.

    By calling .sort() on a array of FS_nlri objects these 
    will be sorted according to the flow_rule_cmp algorithm.

    Example:
    nlri = [ FS_nlri(components=[
             FS_component(component_type=4, 
                          value=bytearray([0,1,2,3,4,5,6])),
             ]),
             FS_nlri(components=[
             FS_component(component_type=5, 
                          value=bytearray([0,1,2,3,4,5,6])),
             FS_component(component_type=6, 
                          value=bytearray([0,1,2,3,4,5,6])),
             ]),
           ]
    nlri.sort() # sorts the array accorinding to the algorithm
    """
    def __init__(self, components = None):
        """
        components: list of type FS_component
        """
        self.components = components

    def __lt__(self, other):
        # use the below algorithm for sorting
        result = flow_rule_cmp_v6(self, other)
        if result == B_HAS_PRECEDENCE:
            return True
        else:
            return False


def flow_rule_cmp_v6(a, b):
    """
    Implementation of the flowspec sorting algorithm in 
    draft-ietf-idr-flow-spec-v6.
    """
    for comp_a, comp_b in itertools.zip_longest(a.components,
                                           b.components):
        # If a component type does not exist in one rule
        # this rule has lower precedence
        if not comp_a:
            return B_HAS_PRECEDENCE
        if not comp_b:
            return A_HAS_PRECEDENCE
        # Higher precedence for lower component type
        if comp_a.component_type < comp_b.component_type:
            return A_HAS_PRECEDENCE
        if comp_a.component_type > comp_b.component_type:
            return B_HAS_PRECEDENCE
        # component types are equal -> type specific comparison
        if comp_a.component_type in (IP_DESTINATION, IP_SOURCE):
            if comp_a.offset < comp_b.offset:
                return A_HAS_PRECEDENCE
            if comp_a.offset < comp_b.offset:
                return B_HAS_PRECEDENCE
            # both components have the same offset
            # assuming comp_a.value, comp_b.value of type
            # ipaddress.IPv6Network
            # and the offset bits are reset to 0 (since they are 
            # not represented in the NLRI)
            if comp_a.value.overlaps(comp_b.value):
                # longest prefixlen has precedence
                if comp_a.value.prefixlen > \
                    comp_b.value.prefixlen:
                    return A_HAS_PRECEDENCE
                if comp_a.value.prefixlen < \
                    comp_b.value.prefixlen:
                    return B_HAS_PRECEDENCE
                # components equal -> continue with next 
                # component
            elif comp_a.value > comp_b.value:
                return B_HAS_PRECEDENCE
            elif comp_a.value < comp_b.value:
                return A_HAS_PRECEDENCE
        else:
            # assuming comp_a.value, comp_b.value of type 
            # bytearray
            if len(comp_a.value) == len(comp_b.value):
                if comp_a.value > comp_b.value:
                    return B_HAS_PRECEDENCE
                if comp_a.value < comp_b.value:
                    return A_HAS_PRECEDENCE
                # components equal -> continue with next 
                # component
            else:
                common = min(len(comp_a.value), 
                             len(comp_b.value))
                if comp_a.value[:common] > \
                    comp_b.value[:common]:
                    return B_HAS_PRECEDENCE
                elif comp_a.value[:common] < \
                      comp_b.value[:common]:
                    return A_HAS_PRECEDENCE
                # the first common bytes match
                elif len(comp_a.value) > len(comp_b.value):
                    return A_HAS_PRECEDENCE
                else:
                    return B_HAS_PRECEDENCE
    return EQUAL
<CODE ENDS>
    ]]></artwork>
  </figure>
</t>
    </section>
  </back>
</rfc>