summaryrefslogtreecommitdiffstats
path: root/src/uri
AgeCommit message (Expand)AuthorFilesLines
2017-08-29session: segment manager improvementsFlorin Coras1-1/+1
2017-08-24Fix initialization bug in sock_test_clientDave Wallace1-0/+3
2017-08-16VCL: copy complete ip addr to/from vpe-api buf.Dave Wallace1-18/+7
2017-08-11Add VPP Communications Library (VCL)Dave Wallace8-0/+4755
2017-07-25Cleanup/refactor session layer codeFlorin Coras2-8/+0
2017-07-11Horizontal (nSessions) scaling draftDave Barach1-1/+1
2017-06-22Improve svm fifo and tcp tx path performance (VPP-846)Florin Coras1-5/+5
2017-06-19Overall tcp performance improvements (VPP-846)Florin Coras3-67/+171
2017-06-01Improve fifo allocator performanceDave Barach2-21/+19
2017-05-09Fix remaining 32-bit compile issuesDamjan Marion2-15/+21
2017-05-09Add support for tcp/session buffer chainsFlorin Coras1-8/+39
2017-04-27[VPP-711] uri_tcp_test when master bind fail we met a display issue about retvalflyingeagle231-1/+3
2017-04-25Session/tcp coverity fixesFlorin Coras1-0/+2
2017-04-24Session layer improvementsFlorin Coras2-85/+144
2017-04-21[VPP-703]uri_tcp_test segment fault when mp->retval reply -30flyingeagle231-1/+1
2017-04-21[VPP-704]./uri_tcp_test slave , uri test segment faultflyingeagle231-1/+2
2017-04-17Socket API echo serverDave Barach1-0/+181
2017-04-13Session layer refactoringFlorin Coras2-225/+416
2017-03-27TCP/session improvementsFlorin Coras3-56/+244
2017-03-13VPP-659 Improve tcp/session debugging and testingFlorin Coras1-12/+31
2017-03-10VPP-659 TCP improvementsFlorin Coras1-3/+4
2017-03-04Cleanup URI code and TCP bugfixingFlorin Coras4-1824/+848
2017-03-01VPP-598: tcp stack initial commitDave Barach4-0/+2907
ght .ss { color: #e6db74 } /* Literal.String.Symbol */ .highlight .bp { color: #f8f8f2 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #a6e22e } /* Name.Function.Magic */ .highlight .vc { color: #f8f8f2 } /* Name.Variable.Class */ .highlight .vg { color: #f8f8f2 } /* Name.Variable.Global */ .highlight .vi { color: #f8f8f2 } /* Name.Variable.Instance */ .highlight .vm { color: #f8f8f2 } /* Name.Variable.Magic */ .highlight .il { color: #ae81ff } /* Literal.Number.Integer.Long */ } @media (prefers-color-scheme: light) { .highlight .hll { background-color: #ffffcc } .highlight .c { color: #888888 } /* Comment */ .highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */ .highlight .k { color: #008800; font-weight: bold } /* Keyword */ .highlight .ch { color: #888888 } /* Comment.Hashbang */ .highlight .cm { color: #888888 } /* Comment.Multiline */ .highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */ .highlight .cpf { color: #888888 } /* Comment.PreprocFile */ .highlight .c1 { color: #888888 } /* Comment.Single */ .highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */ .highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */ .highlight .ge { font-style: italic } /* Generic.Emph */ .highlight .gr { color: #aa0000 } /* Generic.Error */ .highlight .gh { color: #333333 } /* Generic.Heading */ .highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */ .highlight .go { color: #888888 } /* Generic.Output */ .highlight .gp { color: #555555 } /* Generic.Prompt */ .highlight .gs { font-weight: bold } /* Generic.Strong */ .highlight .gu { color: #666666 } /* Generic.Subheading */ .highlight .gt { color: #aa0000 } /* Generic.Traceback */ .highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */ .highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */ .highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */ .highlight .kp { color: #008800 } /* Keyword.Pseudo */ .highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */ .highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */ .highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */ .highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */ .highlight .na { color: #336699 } /* Name.Attribute */ .highlight .nb { color: #003388 } /* Name.Builtin */ .highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */ .highlight .no { color: #003366; font-weight: bold } /* Name.Constant */ .highlight .nd { color: #555555 } /* Name.Decorator */ .highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */ .highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */ .highlight .nl { color: #336699; font-style: italic } /* Name.Label */ .highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */ .highlight .py { color: #336699; font-weight: bold } /* Name.Property */ .highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */ .highlight .nv { color: #336699 } /* Name.Variable */ .highlight .ow { color: #008800 } /* Operator.Word */ .highlight .w { color: #bbbbbb } /* Text.Whitespace */ .highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */ .highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */ .highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */ .highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */ .highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */ .highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */ .highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */ .highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */ .highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */ .highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */ .highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */ .highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */ .highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */ .highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */ .highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */ .highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */ .highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */ .highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */ .highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */ .highlight .vc { color: #336699 } /* Name.Variable.Class */ .highlight .vg { color: #dd7700 } /* Name.Variable.Global */ .highlight .vi { color: #3333bb } /* Name.Variable.Instance */ .highlight .vm { color: #336699 } /* Name.Variable.Magic */ .highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */ }
#
# Copyright (c) 2018 Cisco and/or its affiliates.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import struct
import collections
from enum import IntEnum
import logging

#
# Set log-level in application by doing e.g.:
# logger = logging.getLogger('vpp_serializer')
# logger.setLevel(logging.DEBUG)
#
logger = logging.getLogger(__name__)


class BaseTypes():
    def __init__(self, type, elements=0):
        base_types = {'u8': '>B',
                      'u16': '>H',
                      'u32': '>I',
                      'i32': '>i',
                      'u64': '>Q',
                      'f64': '>d',
                      'header': '>HI'}

        if elements > 0 and type == 'u8':
            self.packer = struct.Struct('>%ss' % elements)
        else:
            self.packer = struct.Struct(base_types[type])
        self.size = self.packer.size
        logger.debug('Adding {} with format: {}'
                     .format(type, base_types[type]))

    def pack(self, data, kwargs=None):
        return self.packer.pack(data)

    def unpack(self, data, offset, result=None):
        return self.packer.unpack_from(data, offset)[0]


types = {}
types['u8'] = BaseTypes('u8')
types['u16'] = BaseTypes('u16')
types['u32'] = BaseTypes('u32')
types['i32'] = BaseTypes('i32')
types['u64'] = BaseTypes('u64')
types['f64'] = BaseTypes('f64')


class FixedList_u8():
    def __init__(self, name, field_type, num):
        self.name = name
        self.num = num
        self.packer = BaseTypes(field_type, num)
        self.size = self.packer.size

    def pack(self, list, kwargs):
        """Packs a fixed length bytestring. Left-pads with zeros
        if input data is too short."""
        if len(list) > self.num:
            raise ValueError('Fixed list length error for "{}", got: {}'
                             ' expected: {}'
                             .format(self.name, len(list), self.num))
        return self.packer.pack(list)

    def unpack(self, data, offset=0, result=None):
        if len(data[offset:]) < self.num:
            raise ValueError('Invalid array length for "{}" got {}'
                             ' expected {}'
                             .format(self.name, len(data), self.num))
        return self.packer.unpack(data, offset)


class FixedList():
    def __init__(self, name, field_type, num):
        self.num = num
        self.packer = types[field_type]
        self.size = self.packer.size * num

    def pack(self, list, kwargs):
        if len(list) != self.num:
            raise ValueError('Fixed list length error, got: {} expected: {}'
                             .format(len(list), self.num))
        b = bytes()
        for e in list:
            b += self.packer.pack(e)
        return b

    def unpack(self, data, offset=0, result=None):
        # Return a list of arguments
        result = []
        for e in range(self.num):
            x = self.packer.unpack(data, offset)
            result.append(x)
            offset += self.packer.size
        return result


class VLAList():
    def __init__(self, name, field_type, len_field_name, index):
        self.index = index
        self.packer = types[field_type]
        self.size = self.packer.size
        self.length_field = len_field_name

    def pack(self, list, kwargs=None):
        if len(list) != kwargs[self.length_field]:
            raise ValueError('Variable length error, got: {} expected: {}'
                             .format(len(list), kwargs[self.length_field]))
        b = bytes()

        # u8 array
        if self.packer.size == 1:
            return bytearray(list)

        for e in list:
            b += self.packer.pack(e)
        return b

    def unpack(self, data, offset=0, result=None):
        # Return a list of arguments

        # u8 array
        if self.packer.size == 1:
            if result[self.index] == 0:
                return b''
            p = BaseTypes('u8', result[self.index])
            r = p.unpack(data, offset)
            return r

        r = []
        for e in range(result[self.index]):
            x = self.packer.unpack(data, offset)
            r.append(x)
            offset += self.packer.size
        return r


class VLAList_legacy():
    def __init__(self, name, field_type):
        self.packer = types[field_type]
        self.size = self.packer.size

    def pack(self, list, kwargs=None):
        if self.packer.size == 1:
            return bytes(list)

        b = bytes()
        for e in list:
            b += self.packer.pack(e)
        return b

    def unpack(self, data, offset=0, result=None):
        # Return a list of arguments
        if (len(data) - offset) % self.packer.size:
            raise ValueError('Legacy Variable Length Array length mismatch.')
        elements = int((len(data) - offset) / self.packer.size)
        r = []
        for e in range(elements):
            x = self.packer.unpack(data, offset)
            r.append(x)
            offset += self.packer.size
        return r


class VPPEnumType():
    def __init__(self, name, msgdef):
        self.size = types['u32'].size
        e_hash = {}
        for f in msgdef:
            if type(f) is dict and 'enumtype' in f:
                if f['enumtype'] != 'u32':
                    raise NotImplementedError
                continue
            ename, evalue = f
            e_hash[ename] = evalue
        self.enum = IntEnum(name, e_hash)
        types[name] = self
        logger.debug('Adding enum {}'.format(name))

    def __getattr__(self, name):
        return self.enum[name]

    def pack(self, data, kwargs=None):
        return types['u32'].pack(data, kwargs)

    def unpack(self, data, offset=0, result=None):
        x = types['u32'].unpack(data, offset)
        return self.enum(x)


class VPPUnionType():
    def __init__(self, name, msgdef):
        self.name = name
        self.size = 0
        self.maxindex = 0
        fields = []
        self.packers = collections.OrderedDict()
        for i, f in enumerate(msgdef):
            if type(f) is dict and 'crc' in f:
                self.crc = f['crc']
                continue
            f_type, f_name = f
            if f_type not in types:
                logger.debug('Unknown union type {}'.format(f_type))
                raise ValueError('Unknown message type {}'.format(f_type))
            fields.append(f_name)
            size = types[f_type].size
            self.packers[f_name] = types[f_type]
            if size > self.size:
                self.size = size
                self.maxindex = i

        types[name] = self
        self.tuple = collections.namedtuple(name, fields, rename=True)
        logger.debug('Adding union {}'.format(name))

    def pack(self, data, kwargs=None):
        for k, v in data.items():
            logger.debug("Key: {} Value: {}".format(k, v))
            b = self.packers[k].pack(v, kwargs)
            offset = self.size - self.packers[k].size
            break
        r = bytearray(self.size)
        r[offset:] = b
        return r

    def unpack(self, data, offset=0, result=None):
        r = []
        for k, p in self.packers.items():
            union_offset = self.size - p.size
            r.append(p.unpack(data, offset + union_offset))
        return self.tuple._make(r)


class VPPType():
    # Set everything up to be able to pack / unpack
    def __init__(self, name, msgdef):
        self.name = name
        self.msgdef = msgdef
        self.packers = []
        self.fields = []
        self.fieldtypes = []
        self.field_by_name = {}
        size = 0
        for i, f in enumerate(msgdef):
            if type(f) is dict and 'crc' in f:
                self.crc = f['crc']
                continue
            f_type, f_name = f[:2]
            self.fields.append(f_name)
            self.field_by_name[f_name] = None
            self.fieldtypes.append(f_type)
            if f_type not in types:
                logger.debug('Unknown type {}'.format(f_type))
                raise ValueError('Unknown message type {}'.format(f_type))
            if len(f) == 3:  # list
                list_elements = f[2]
                if list_elements == 0:
                    p = VLAList_legacy(f_name, f_type)
                    self.packers.append(p)
                elif f_type == 'u8':
                    p = FixedList_u8(f_name, f_type, list_elements)
                    self.packers.append(p)
                    size += p.size
                else:
                    p = FixedList(f_name, f_type, list_elements)
                    self.packers.append(p)
                    size += p.size
            elif len(f) == 4:  # Variable length list
                    # Find index of length field
                    length_index = self.fields.index(f[3])
                    p = VLAList(f_name, f_type, f[3], length_index)
                    self.packers.append(p)
            else:
                self.packers.append(types[f_type])
                size += types[f_type].size

        self.size = size
        self.tuple = collections.namedtuple(name, self.fields, rename=True)
        types[name] = self
        logger.debug('Adding type {}'.format(name))

    def pack(self, data, kwargs=None):
        if not kwargs:
            kwargs = data
        b = bytes()
        for i, a in enumerate(self.fields):
            if a not in data:
                b += b'\x00' * self.packers[i].size
                continue

            if isinstance(self.packers[i], VPPType):
                b += self.packers[i].pack(data[a], kwargs[a])
            else:
                b += self.packers[i].pack(data[a], kwargs)
        return b

    def unpack(self, data, offset=0, result=None):
        # Return a list of arguments
        result = []
        for p in self.packers:
            x = p.unpack(data, offset, result)
            if type(x) is tuple and len(x) == 1:
                x = x[0]
            result.append(x)
            offset += p.size
        return self.tuple._make(result)


class VPPMessage(VPPType):
    pass