Ejemplo n.º 1
0
 def encode(self):
     r_prio = struct.pack('H', self['prio'])
     r_addr = struct.pack('BBBBBB',
                          *[int(i, 16) for i in
                            self['addr'].split(':')])
     self['value'] = r_prio + r_addr
     nla.encode(self)
Ejemplo n.º 2
0
        def encode(self):
            if not isinstance(self['kind'], str):
                raise ValueError("kind' keywords must be set!")

            kind = self['kind'].lower()
            if kind in strings_meta:
                self['id'] = TCF_META_TYPE_VAR
            else:
                self['id'] = TCF_META_TYPE_INT
            self['id'] <<= 12

            for k, v in META_ID.items():
                if kind == k:
                    self['kind'] = self['id'] | v
                    break

            if isinstance(self['opnd'], str):
                for k, v in OPERANDS_DICT.items():
                    if self['opnd'].lower() in v:
                        self['opnd'] = k
                        break

            # Perform sanity checks on 'shift' value
            if isinstance(self['shift'], str):
                # If it fails, it will raise a ValueError
                # which is what we want
                self['shift'] = int(self['shift'])
            if not 0 <= self['shift'] <= 255:
                raise ValueError("'shift' value must be between"
                                 "0 and 255 included!")
            nla.encode(self)
Ejemplo n.º 3
0
 def encode(self):
     r_prio = struct.pack('H', self['prio'])
     r_addr = struct.pack('BBBBBB',
                          *[int(i, 16) for i in
                            self['addr'].split(':')])
     self['value'] = r_prio + r_addr
     nla.encode(self)
Ejemplo n.º 4
0
 def encode(self):
     family = self.get('family', AF_UNSPEC)
     if family in (AF_INET, AF_INET6):
         addr = inet_pton(family, self['addr'])
     else:
         raise TypeError('Family %s not supported for RTA_VIA' % family)
     self['value'] = struct.pack('H', family) + addr
     nla.encode(self)
Ejemplo n.º 5
0
 def encode(self):
     parms = self.parent.get_encoded('TCA_TBF_PARMS') or \
         self.parent.get_encoded('TCA_HTB_PARMS') or \
         self.parent.get_encoded('TCA_POLICE_TBF')
     if parms is not None:
         self.value = getattr(parms, self.__class__.__name__)
         self['value'] = struct.pack('I' * 256,
                                     *(int(x) for x in self.value))
     nla.encode(self)
Ejemplo n.º 6
0
 def encode(self):
     # Get action type and convert string to value
     action = self['value']
     self['value'] = (self.actions.get(
         action, self.SEG6_LOCAL_ACTION_UNSPEC))
     # Convert action type to u32
     self['value'] = self['value'] & 0xffffffff
     # Finally encode as nla
     nla.encode(self)
Ejemplo n.º 7
0
 def encode(self):
     parms = self.parent.get_encoded('TCA_TBF_PARMS') or \
         self.parent.get_encoded('TCA_HTB_PARMS') or \
         self.parent.get_encoded('TCA_POLICE_TBF')
     if parms is not None:
         self.value = getattr(parms, self.__class__.__name__)
         self['value'] = struct.pack('I' * 256,
                                     *(int(x) for x in self.value))
     nla.encode(self)
Ejemplo n.º 8
0
 def encode(self):
     family = self.get('family', AF_UNSPEC)
     if family in (AF_INET, AF_INET6):
         addr = inet_pton(family, self['addr'])
     else:
         raise TypeError('Family %s not supported for RTA_VIA'
                         % family)
     self['value'] = struct.pack('H', family) + addr
     nla.encode(self)
Ejemplo n.º 9
0
 def encode(self):
     self.rtab = None
     self.ptab = None
     if self.get('rate', False):
         self.rtab = self.calc_rtab('rate')
     if self.get('peak', False):
         self.ptab = self.calc_rtab('peak')
     if self.get('ceil', False):
         self.ctab = self.calc_rtab('ceil')
     nla.encode(self)
Ejemplo n.º 10
0
 def encode(self):
     self.rtab = None
     self.ptab = None
     if self.get('rate', False):
         self.rtab = self.calc_rtab('rate')
     if self.get('peak', False):
         self.ptab = self.calc_rtab('peak')
     if self.get('ceil', False):
         self.ctab = self.calc_rtab('ceil')
     nla.encode(self)
Ejemplo n.º 11
0
 def encode(self):
     if self['addr'].find(":") > -1:
         self['family'] = AF_INET6
         self['addr4'] = 0  # Set to NULL
         self['addr6'] = inet_pton(AF_INET6, self['addr'])
     else:
         self['family'] = AF_INET
         self['addr4'] = unpack('>I', inet_aton(self['addr']))[0]
         self['addr6'] = b'\x00\x00\x00\x00\x00\x00\x00\x00'
     self['port'] = int(self['port'])
     nla.encode(self)
Ejemplo n.º 12
0
 def encode(self):
     # Get action type and convert string to value
     action = self['value']
     self['value'] = (self
                      .actions
                      .get(action,
                           self.SEG6_LOCAL_ACTION_UNSPEC))
     # Convert action type to u32
     self['value'] = self['value'] & 0xffffffff
     # Finally encode as nla
     nla.encode(self)
Ejemplo n.º 13
0
                def encode(self):
                    #
                    # for details see:
                    url = 'https://github.com/svinota/pyroute2/issues/531'

                    v = self.value
                    for flag in GRE_VALUES:
                        v &= ~flag
                    if v != 0:
                        log.warning('possibly incorrect GRE flags, '
                                    'see %s' % url)
                    nla.encode(self)
Ejemplo n.º 14
0
                def encode(self):
                    #
                    # for details see:
                    url = 'https://github.com/svinota/pyroute2/issues/531'

                    v = self.value
                    for flag in GRE_VALUES:
                        v &= ~flag
                    if v != 0:
                        log.warning('possibly incorrect GRE flags, '
                                    'see %s' % url)
                    nla.encode(self)
Ejemplo n.º 15
0
 def encode(self):
     if self['addr'].find(":") > -1:
         self['family'] = AF_INET6
         self['addr4'] = 0  # Set to NULL
         self['addr6'] = inet_pton(AF_INET6, self['addr'])
     else:
         self['family'] = AF_INET
         self['addr4'] = unpack('>I',
                                inet_aton(self['addr']))[0]
         self['addr6'] = bytearray(4)  # Set 4 bytes to NULL
     self['port'] = int(self['port'])
     self['__padding'] = 0
     nla.encode(self)
Ejemplo n.º 16
0
 def encode(self):
     #
     # There are two ways to specify netns
     #
     # 1. provide fd to an open file
     # 2. provide a file name
     #
     # In the first case, the value is passed to the kernel
     # as is. In the second case, the object opens appropriate
     # file from `self.netns_run_dir` and closes it upon
     # `__del__(self)`
     if isinstance(self.value, int):
         self['value'] = self.value
     else:
         self.netns_fd = os.open('%s/%s' % (self.netns_run_dir,
                                            self.value), os.O_RDONLY)
         self['value'] = self.netns_fd
         self.register_clean_cb(self.close)
     nla.encode(self)
Ejemplo n.º 17
0
 def encode(self):
     #
     # There are two ways to specify netns
     #
     # 1. provide fd to an open file
     # 2. provide a file name
     #
     # In the first case, the value is passed to the kernel
     # as is. In the second case, the object opens appropriate
     # file from `self.netns_run_dir` and closes it upon
     # `__del__(self)`
     if isinstance(self.value, int):
         self['value'] = self.value
     else:
         self.netns_fd = os.open('%s/%s' % (self.netns_run_dir,
                                            self.value), os.O_RDONLY)
         self['value'] = self.netns_fd
         self.register_clean_cb(self.close)
     nla.encode(self)
Ejemplo n.º 18
0
    def encode(self):
        # Set default values
        self['layer_opnd'] = 0
        self['align_flags'] = 0

        # Build align_flags byte
        if 'trans' in self:
            self['align_flags'] = TCF_EM_CMP_TRANS << 4
        for k, v in ALIGNS_DICT.items():
            if self['align'].lower() == v:
                self['align_flags'] |= k
                break

        # Build layer_opnd byte
        if isinstance(self['opnd'], int):
            self['layer_opnd'] = self['opnd'] << 4
        else:
            for k, v in OPERANDS_DICT.items():
                if self['opnd'].lower() in v:
                    self['layer_opnd'] = k << 4
                    break

        # Layer code
        if isinstance(self['layer'], int):
            self['layer_opnd'] |= self['layer']
        else:
            for k, v in LAYERS_DICT.items():
                if self['layer'].lower() in v:
                    self['layer_opnd'] |= k
                    break

        self['off'] = self.get('offset', 0)
        self['val'] = self.get('value', 0)
        nla.encode(self)

        # Patch NLA structure
        self['header']['length'] -= 4
        self.data = self.data[4:]
Ejemplo n.º 19
0
    def encode(self):
        if 'object' not in self:
            raise ValueError('An object definition must be given!')

        if 'value' not in self:
            raise ValueError('A value must be given!')

        # The value can either be a string or an int depending
        # on the selected meta kind.
        # It is really important to distinct them otherwise
        # the kernel won't be nice with us...
        value = self['value']
        kind = self['object'].get('kind')
        if not kind:
            raise ValueError('Not meta kind specified!')
        else:
            if kind in strings_meta:
                if not isinstance(value, str):
                    raise ValueError('{} kinds have to use string value!'
                                     .format(' and '.join(strings_meta)))
                else:
                    value = value.encode('utf-8')
            else:
                if not isinstance(value, int):
                    raise ValueError('Invalid value specified, it must '
                                     'be an integer')
                else:
                    value = pack('<I', value)

        self['attrs'].append(['TCA_EM_META_HDR', self['object']])
        self['attrs'].append(['TCA_EM_META_LVALUE', self.get('mask', 0)])
        self['attrs'].append(['TCA_EM_META_RVALUE', value])
        nla.encode(self)

        # Patch NLA structure
        self['header']['length'] -= 4
        self.data = self.data[4:]
Ejemplo n.º 20
0
 def encode(self):
     self["value"] = state_by_name[self.value]
     nla.encode(self)
Ejemplo n.º 21
0
 def encode(self):
     self['value'] = struct.pack('B' * 256,
                                 *(int(x) for x in self.value))
     nla.encode(self)
Ejemplo n.º 22
0
 def encode(self):
     self['value'] = state_by_name[self.value]
     nla.encode(self)
Ejemplo n.º 23
0
 def encode(self):
     self['mac'] = ([int(x, 16) for x
                     in self['mac'].split(':')] +
                    [0] * 26)
     nla.encode(self)
Ejemplo n.º 24
0
            def encode(self):
                '''
                'keys': ['0x0006/0x00ff+8',
                         '0x0000/0xffc0+2',
                         '0x5/0xf+0',
                         '0x10/0xff+33']

                => 00060000/00ff0000 + 8
                   05000000/0f00ffc0 + 0
                   00100000/00ff0000 + 32

                '''
                def cut_field(key, separator):
                    '''
                    split a field from the end of the string
                    '''
                    field = '0'
                    pos = key.find(separator)
                    new_key = key
                    if pos > 0:
                        field = key[pos + 1:]
                        new_key = key[:pos]
                    return (new_key, field)

                # 'header' array to pack keys to
                header = [(0, 0) for i in range(256)]

                keys = []
                # iterate keys and pack them to the 'header'
                for key in self['keys']:
                    # TODO tags: filter
                    (key, nh) = cut_field(key, '@')  # FIXME: do not ignore nh
                    (key, offset) = cut_field(key, '+')
                    offset = int(offset, 0)
                    # a little trick: if you provide /00ff+8, that
                    # really means /ff+9, so we should take it into
                    # account
                    (key, mask) = cut_field(key, '/')
                    if mask[:2] == '0x':
                        mask = mask[2:]
                        while True:
                            if mask[:2] == '00':
                                offset += 1
                                mask = mask[2:]
                            else:
                                break
                        mask = '0x' + mask
                    mask = int(mask, 0)
                    value = int(key, 0)
                    bits = 24
                    if mask == 0 and value == 0:
                        key = self.u32_key(self.buf)
                        key['key_off'] = offset
                        key['key_mask'] = mask
                        key['key_val'] = value
                        keys.append(key)
                    for bmask in struct.unpack('4B', struct.pack('>I', mask)):
                        if bmask > 0:
                            bvalue = (value & (bmask << bits)) >> bits
                            header[offset] = (bvalue, bmask)
                            offset += 1
                        bits -= 8

                # recalculate keys from 'header'
                key = None
                value = 0
                mask = 0
                for offset in range(256):
                    (bvalue, bmask) = header[offset]
                    if bmask > 0 and key is None:
                        key = self.u32_key(self.buf)
                        key['key_off'] = offset
                        key['key_mask'] = 0
                        key['key_val'] = 0
                        bits = 24
                    if key is not None and bits >= 0:
                        key['key_mask'] |= bmask << bits
                        key['key_val'] |= bvalue << bits
                        bits -= 8
                        if (bits < 0 or offset == 255):
                            keys.append(key)
                            key = None

                assert keys
                self['nkeys'] = len(keys)
                # FIXME: do not hardcode flags :)
                self['flags'] = 1
                start = self.buf.tell()

                nla.encode(self)
                for key in keys:
                    key.encode()
                self.update_length(start)
Ejemplo n.º 25
0
 def encode(self):
     # Convert to network byte order
     self['value'] = inet_pton(AF_INET6, self['value'])
     # Finally encode as nla
     nla.encode(self)
Ejemplo n.º 26
0
 def encode(self):
     self['start'], self['end'] = self.value.split(':')
     nla.encode(self)
Ejemplo n.º 27
0
 def encode(self):
     self['value'] = struct.pack('B' * 256,
                                 *(int(x) for x in self.value))
     nla.encode(self)
Ejemplo n.º 28
0
 def encode(self):
     # convert flags
     if isinstance(self['value'], basestring):
         self['value'] = BRIDGE_FLAGS_NAMES['BRIDGE_FLAGS_' +
                                            self['value'].upper()]
     nla.encode(self)
Ejemplo n.º 29
0
        def encode(self):
            '''
            Key sample::

                'keys': ['0x0006/0x00ff+8',
                         '0x0000/0xffc0+2',
                         '0x5/0xf+0',
                         '0x10/0xff+33']

                => 00060000/00ff0000 + 8
                   05000000/0f00ffc0 + 0
                   00100000/00ff0000 + 32
            '''

            def cut_field(key, separator):
                '''
                split a field from the end of the string
                '''
                field = '0'
                pos = key.find(separator)
                new_key = key
                if pos > 0:
                    field = key[pos + 1:]
                    new_key = key[:pos]
                return (new_key, field)

            # 'header' array to pack keys to
            header = [(0, 0) for i in range(256)]

            keys = []
            # iterate keys and pack them to the 'header'
            for key in self['keys']:
                # TODO tags: filter
                (key, nh) = cut_field(key, '@')  # FIXME: do not ignore nh
                (key, offset) = cut_field(key, '+')
                offset = int(offset, 0)
                # a little trick: if you provide /00ff+8, that
                # really means /ff+9, so we should take it into
                # account
                (key, mask) = cut_field(key, '/')
                if mask[:2] == '0x':
                    mask = mask[2:]
                    while True:
                        if mask[:2] == '00':
                            offset += 1
                            mask = mask[2:]
                        else:
                            break
                    mask = '0x' + mask
                mask = int(mask, 0)
                value = int(key, 0)
                bits = 24
                if mask == 0 and value == 0:
                    key = self.u32_key(self.buf)
                    key['key_off'] = offset
                    key['key_mask'] = mask
                    key['key_val'] = value
                    keys.append(key)
                for bmask in struct.unpack('4B', struct.pack('>I', mask)):
                    if bmask > 0:
                        bvalue = (value & (bmask << bits)) >> bits
                        header[offset] = (bvalue, bmask)
                        offset += 1
                    bits -= 8

            # recalculate keys from 'header'
            key = None
            value = 0
            mask = 0
            for offset in range(256):
                (bvalue, bmask) = header[offset]
                if bmask > 0 and key is None:
                    key = self.u32_key(self.buf)
                    key['key_off'] = offset
                    key['key_mask'] = 0
                    key['key_val'] = 0
                    bits = 24
                if key is not None and bits >= 0:
                    key['key_mask'] |= bmask << bits
                    key['key_val'] |= bvalue << bits
                    bits -= 8
                    if (bits < 0 or offset == 255):
                        keys.append(key)
                        key = None

            assert keys
            self['nkeys'] = len(keys)
            # FIXME: do not hardcode flags :)
            self['flags'] = 1
            start = self.buf.tell()

            nla.encode(self)
            for key in keys:
                key.encode()
            self.update_length(start)
Ejemplo n.º 30
0
 def encode(self):
     self['flow_keys'] = self['value']
     nla.encode(self)
Ejemplo n.º 31
0
 def encode(self):
     # convert flags
     if isinstance(self['value'], basestring):
         self['value'] = BRIDGE_FLAGS_NAMES['BRIDGE_FLAGS_' +
                                            self['value'].upper()]
     nla.encode(self)
Ejemplo n.º 32
0
 def encode(self):
     family = self.get('family', AF_UNSPEC)
     if family in (AF_INET, AF_INET6):
         addr = inet_pton(family, self['addr'])
     self['value'] = struct.pack('H', family) + addr
     nla.encode(self)
Ejemplo n.º 33
0
 def encode(self):
     encoded_guid = self['ib_port_guid'].split(':')[::-1]
     self['ib_port_guid'] = ([0] * 4 +
                             [int(x, 16)
                              for x in encoded_guid] + [0] * 20)
     nla.encode(self)
Ejemplo n.º 34
0
 def encode(self):
     self['flow_mode'] = self['value']
     nla.encode(self)
Ejemplo n.º 35
0
 def encode(self):
     # Convert to network byte order
     self['value'] = inet_pton(AF_INET6, self['value'])
     # Finally encode as nla
     nla.encode(self)
Ejemplo n.º 36
0
 def encode(self):
     self['flow_keys'] = self['value']
     nla.encode(self)
Ejemplo n.º 37
0
 def encode(self):
     # Retrieve the family
     family = self.get_family()
     # Seg6 can be applied only to IPv6
     if family == AF_INET6:
         # Get mode
         mode = self['mode']
         # Get segs
         segs = self['segs']
         # Get hmac
         hmac = self.get('hmac', None)
         # With "inline" mode there is not
         # encap into an outer IPv6 header
         if mode == "inline":
             # Add :: to segs
             segs.insert(0, "::")
         # Add mode to value
         self['encapmode'] = (self
                              .encapmodes
                              .get(mode,
                                   self.SEG6_IPTUN_MODE_ENCAP))
         # Calculate srlen
         srhlen = 8 + 16 * len(segs)
         # If we are using hmac we have a tlv as trailer data
         if hmac:
             # Since we can use sha1 or sha256
             srhlen += 40
         # Calculate and set hdrlen
         self['hdrlen'] = (srhlen >> 3) - 1
         # Add seg6 type
         self['type'] = self.SEG6_TYPE
         # Add segments left
         self['segments_left'] = len(segs) - 1
         # Add fitst segment
         self['first_segment'] = len(segs) - 1
         # If hmac is used we have to set the flags
         if hmac:
             # Add SR6_FLAG1_HMAC
             self['flags'] |= self.SR6_FLAG1_HMAC
         # Init segs
         self['segs'] = b''
         # Iterate over segments
         for seg in segs:
             # Convert to network byte order and add to value
             self['segs'] += inet_pton(family, seg)
         # Initialize tlvs
         self['tlvs'] = b''
         # If hmac is used we have to properly init tlvs
         if hmac:
             # Put type
             self['tlvs'] += struct.pack('B', self.SR6_TLV_HMAC)
             # Put length -> 40-2
             self['tlvs'] += struct.pack('B', 38)
             # Put reserved
             self['tlvs'] += struct.pack('H', 0)
             # Put hmac key
             self['tlvs'] += struct.pack('>I', hmac)
             # Put hmac
             self['tlvs'] += struct.pack('QQQQ', 0, 0, 0, 0)
     else:
         raise TypeError('Family %s not supported for seg6 tunnel'
                         % family)
     # Finally encode as nla
     nla.encode(self)
Ejemplo n.º 38
0
 def encode(self):
     self['flow_mode'] = self['value']
     nla.encode(self)
Ejemplo n.º 39
0
 def encode(self):
     if not isinstance(self['value'], tuple):
         self['value'] = (self['value'] & 0xffffffffffffffff,
                          self['value'] >> 64)
     nla.encode(self)
Ejemplo n.º 40
0
 def encode(self):
     # Set default Auto-Rate value
     if not self.get_attr('TCA_CAKE_AUTORATE'):
         self['attrs'].append(['TCA_CAKE_AUTORATE', 0])
     nla.encode(self)
Ejemplo n.º 41
0
 def encode(self):
     self['mac'] = (
         [int(x, 16)
          for x in self['mac'].split(':')] + [0] * 26)
     nla.encode(self)
Ejemplo n.º 42
0
 def encode(self):
     self['value'] = state_by_name[self.value]
     nla.encode(self)
Ejemplo n.º 43
0
 def encode(self):
     family = self.get('family', AF_UNSPEC)
     if family in (AF_INET, AF_INET6):
         addr = inet_pton(family, self['addr'])
     self['value'] = struct.pack('H', family) + addr
     nla.encode(self)
Ejemplo n.º 44
0
 def encode(self):
     self['start'], self['end'] = self.value.split(':')
     nla.encode(self)
Ejemplo n.º 45
0
 def encode(self):
     # Retrieve the family
     family = self.get_family()
     # Seg6 can be applied only to IPv6
     if family == AF_INET6:
         # Get mode
         mode = self['mode']
         # Get segs
         segs = self['segs']
         # Get hmac
         hmac = self.get('hmac', None)
         # With "inline" mode there is not
         # encap into an outer IPv6 header
         if mode == "inline":
             # Add :: to segs
             segs.insert(0, "::")
         # Add mode to value
         self['encapmode'] = (self
                              .encapmodes
                              .get(mode,
                                   self.SEG6_IPTUN_MODE_ENCAP))
         # Calculate srlen
         srhlen = 8 + 16 * len(segs)
         # If we are using hmac we have a tlv as trailer data
         if hmac:
             # Since we can use sha1 or sha256
             srhlen += 40
         # Calculate and set hdrlen
         self['hdrlen'] = (srhlen >> 3) - 1
         # Add seg6 type
         self['type'] = self.SEG6_TYPE
         # Add segments left
         self['segments_left'] = len(segs) - 1
         # Add fitst segment
         self['first_segment'] = len(segs) - 1
         # If hmac is used we have to set the flags
         if hmac:
             # Add SR6_FLAG1_HMAC
             self['flags'] |= self.SR6_FLAG1_HMAC
         # Init segs
         self['segs'] = b''
         # Iterate over segments
         for seg in segs:
             # Convert to network byte order and add to value
             self['segs'] += inet_pton(family, seg)
         # Initialize tlvs
         self['tlvs'] = b''
         # If hmac is used we have to properly init tlvs
         if hmac:
             # Put type
             self['tlvs'] += struct.pack('B', self.SR6_TLV_HMAC)
             # Put length -> 40-2
             self['tlvs'] += struct.pack('B', 38)
             # Put reserved
             self['tlvs'] += struct.pack('H', 0)
             # Put hmac key
             self['tlvs'] += struct.pack('>I', hmac)
             # Put hmac
             self['tlvs'] += struct.pack('QQQQ', 0, 0, 0, 0)
     else:
         raise TypeError('Family %s not supported for seg6 tunnel'
                         % family)
     # Finally encode as nla
     nla.encode(self)
Ejemplo n.º 46
0
 def encode(self):
     self['key'] = b64decode(self['value'])
     nla.encode(self)