Instruction:
Create a Python 3 function for
overloading to restrict the acceptable x values to None.

Response:
def h2i(self, pkt, x):
        # type: (Optional[packet.Packet], int) -> int
        """ h2i is overloaded to restrict the acceptable x values (not None)

        @param packet.Packet|None pkt: the packet instance containing this field instance; probably unused.  # noqa: E501
        @param int x: the value to convert.
        @return int: the converted value.
        @raise AssertionError
        """
        ret = super(UVarIntField, self).h2i(pkt, x)
        assert(not isinstance(ret, type(None)) and ret >= 0)
        return ret


Instruction:
Can you generate a brief explanation for the following Python 3 code
def i2repr(self, pkt, x):
        # type: (Optional[packet.Packet], int) -> str
        """ i2repr is overloaded to restrict the acceptable x values (not None)

        @param packet.Packet|None pkt: the packet instance containing this field instance; probably unused.  # noqa: E501
        @param int x: the value to convert.
        @return str: the converted value.
        """
        return super(UVarIntField, self).i2repr(pkt, x)

Response: Overloaded to restrict the acceptable x values to None.


Instruction:
Make a summary of the following Python 3 code
def _compute_value(self, pkt):
        # type: (packet.Packet) -> int
        """ Computes the value of this field based on the provided packet and
        the length_of field and the adjust callback

        @param packet.Packet pkt: the packet from which is computed this field value.  # noqa: E501
        @return int: the computed value for this field.
        @raise KeyError: the packet nor its payload do not contain an attribute
          with the length_of name.
        @raise AssertionError
        @raise KeyError if _length_of is not one of pkt fields
        """
        fld, fval = pkt.getfield_and_val(self._length_of)
        val = fld.i2len(pkt, fval)
        ret = self._adjust(val)
        assert(ret >= 0)
        return ret

Response:
Compute the value of this field based on the provided packet and the length_of attribute and the adjust callback
       .


Instruction:
Can you tell what is the following Python 3 function doing
def huffman_encode(cls, s):
        # type: (str) -> Tuple[int, int]
        """ huffman_encode returns the bitstring and the bitlength of the
        bitstring representing the string provided as a parameter

        @param str s: the string to encode
        @return (int, int): the bitstring of s and its bitlength
        @raise AssertionError
        """
        i = 0
        ibl = 0
        for c in s:
            val, bl = cls._huffman_encode_char(c)
            i = (i << bl) + val
            ibl += bl

        padlen = 8 - (ibl % 8)
        if padlen != 8:
            val, bl = cls._huffman_encode_char(EOS())
            i = (i << padlen) + (val >> (bl - padlen))
            ibl += padlen

        ret = i, ibl
        assert(ret[0] >= 0)
        assert (ret[1] >= 0)
        return ret

Response:
huffman_encode returns the bitstring and the bitlength of the the
            class s parameter as a parameter


Instruction:
Can you generate the documentation for the following Python 3 function
def huffman_compute_decode_tree(cls):
        # type: () -> None
        """ huffman_compute_decode_tree initializes/builds the static_huffman_tree

        @return None
        @raise InvalidEncodingException if there is an encoding problem
        """
        cls.static_huffman_tree = HuffmanNode(None, None)
        i = 0
        for entry in cls.static_huffman_code:
            parent = cls.static_huffman_tree
            for idx in range(entry[1] - 1, -1, -1):
                b = (entry[0] >> idx) & 1
                if isinstance(parent[b], bytes):
                    raise InvalidEncodingException('Huffman unique prefix violation :/')  # noqa: E501
                if idx == 0:
                    parent[b] = chb(i) if i < 256 else EOS()
                elif parent[b] is None:
                    parent[b] = HuffmanNode(None, None)
                parent = parent[b]
            i += 1

Response: Compute the decode tree for the static_huffman_tree.


Instruction:
Here you have a function in Python 3, explain what it does
def dispatch_hook(cls, s=None, *_args, **_kwds):
        # type: (Optional[str], *Any, **Any) -> base_classes.Packet_metaclass
        """dispatch_hook returns the subclass of HPackHeaders that must be used
        to dissect the string.
        """
        if s is None:
            return config.conf.raw_layer
        fb = orb(s[0])
        if fb & 0x80 != 0:
            return HPackIndexedHdr
        if fb & 0x40 != 0:
            return HPackLitHdrFldWithIncrIndexing
        if fb & 0x20 != 0:
            return HPackDynamicSizeUpdate
        return HPackLitHdrFldWithoutIndexing

Response:
This is a private method that returns the subclass of base_classes. Packet_metaclass_base. HPackHeaderBase that must be used
        to dissect the string.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_hdrs_len(self):
        # type: () -> int
        """ get_hdrs_len computes the length of the hdrs field

        To do this computation, the length of the padlen field, the priority
        information fields and the actual padding is subtracted to the string
        that was provided to the pre_dissect fun of the pkt parameter.
        @return int: the length of the hdrs field
        @raise AssertionError
        """

        padding_len = self.getfieldval('padlen')
        fld, fval = self.getfield_and_val('padlen')
        padding_len_len = fld.i2len(self, fval)
        bit_cnt = self.get_field('exclusive').size
        bit_cnt += self.get_field('stream_dependency').size
        fld, fval = self.getfield_and_val('weight')
        weight_len = fld.i2len(self, fval)
        ret = int(self.s_len -
                  padding_len_len -
                  padding_len -
                  (bit_cnt / 8) -
                  weight_len
                  )
        assert(ret >= 0)
        return ret

Response:
This method computes the length of the hdrs field
       .


Instruction:
Here you have a function in Python 3, explain what it does
def get_hdrs_len(self):
        # type: () -> int
        """ get_hdrs_len computes the length of the hdrs field

        To do this computation, the length of the padlen field, reserved,
        stream_id and the actual padding is subtracted to the string that was
        provided to the pre_dissect fun of the pkt parameter.
        @return int: the length of the hdrs field
        @raise AssertionError
        """
        fld, padding_len = self.getfield_and_val('padlen')
        padding_len_len = fld.i2len(self, padding_len)
        bit_len = self.get_field('reserved').size
        bit_len += self.get_field('stream_id').size

        ret = int(self.s_len -
                  padding_len_len -
                  padding_len -
                  (bit_len / 8)
                  )
        assert(ret >= 0)
        return ret

Response:
This method computes the length of the hdrs field
       .


Instruction:
Can you generate a brief explanation for the following Python 3 code
def guess_payload_class(self, payload):
        # type: (str) -> base_classes.Packet_metaclass
        """ guess_payload_class returns the Class object to use for parsing a payload
        This function uses the H2Frame.type field value to decide which payload to parse. The implement cannot be  # noqa: E501
        performed using the simple bind_layers helper because sometimes the selection of which Class object to return  # noqa: E501
        also depends on the H2Frame.flags value.

        @param payload:
        @return:
        """
        if len(payload) == 0:
            return packet.NoPayload

        t = self.getfieldval('type')
        if t == H2DataFrame.type_id:
            if H2DataFrame.flags[H2DataFrame.PADDED_FLAG].short in self.getfieldval('flags'):  # noqa: E501
                return H2PaddedDataFrame
            return H2DataFrame

        if t == H2HeadersFrame.type_id:
            if H2HeadersFrame.flags[H2HeadersFrame.PADDED_FLAG].short in self.getfieldval('flags'):  # noqa: E501
                if H2HeadersFrame.flags[H2HeadersFrame.PRIORITY_FLAG].short in self.getfieldval('flags'):  # noqa: E501
                    return H2PaddedPriorityHeadersFrame
                else:
                    return H2PaddedHeadersFrame
            elif H2HeadersFrame.flags[H2HeadersFrame.PRIORITY_FLAG].short in self.getfieldval('flags'):  # noqa: E501
                return H2PriorityHeadersFrame
            return H2HeadersFrame

        if t == H2PriorityFrame.type_id:
            return H2PriorityFrame

        if t == H2ResetFrame.type_id:
            return H2ResetFrame

        if t == H2SettingsFrame.type_id:
            return H2SettingsFrame

        if t == H2PushPromiseFrame.type_id:
            if H2PushPromiseFrame.flags[H2PushPromiseFrame.PADDED_FLAG].short in self.getfieldval('flags'):  # noqa: E501
                return H2PaddedPushPromiseFrame
            return H2PushPromiseFrame

        if t == H2PingFrame.type_id:
            return H2PingFrame

        if t == H2GoAwayFrame.type_id:
            return H2GoAwayFrame

        if t == H2WindowUpdateFrame.type_id:
            return H2WindowUpdateFrame

        if t == H2ContinuationFrame.type_id:
            return H2ContinuationFrame

        return config.conf.padding_layer

Response: This function returns the Class object to use for parsing a payload.


Instruction:
Explain what the following Python 3 code does
def recap(self, nc):
        # type: (int) -> None
        """recap changes the maximum size limit of the dynamic table. It also
        proceeds to a resize(), if the new size is lower than the previous one.
        @param int nc: the new cap of the dynamic table (that is the maximum-maximum size)  # noqa: E501
        @raise AssertionError
        """
        assert(nc >= 0)
        t = self._dynamic_table_cap_size > nc
        self._dynamic_table_cap_size = nc

        if t:
            # The RFC is not clear about whether this resize should happen;
            # we do it anyway
            self.resize(nc)

Response: This method changes the maximum size limit of the dynamic table. It also updates the dynamic table cap size to match the new size of the dynamic table.


Instruction:
Explain what the following Python 3 code does
def _reduce_dynamic_table(self, new_entry_size=0):
        # type: (int) -> None
        """_reduce_dynamic_table evicts entries from the dynamic table until it
        fits in less than the current size limit. The optional parameter,
        new_entry_size, allows the resize to happen so that a new entry of this
        size fits in.
        @param int new_entry_size: if called before adding a new entry, the size of the new entry in bytes (following  # noqa: E501
        the RFC7541 definition of the size of an entry)
        @raise AssertionError
        """
        assert(new_entry_size >= 0)
        cur_sz = len(self)
        dyn_tbl_sz = len(self._dynamic_table)
        while dyn_tbl_sz > 0 and cur_sz + new_entry_size > self._dynamic_table_max_size:  # noqa: E501
            last_elmt_sz = len(self._dynamic_table[-1])
            self._dynamic_table.pop()
            dyn_tbl_sz -= 1
            cur_sz -= last_elmt_sz

Response: _reduce_dynamic_table evicts entries from the dynamic table until the current size limit is reached.


Instruction:
Can you tell what is the following Python 3 function doing
def get_idx_by_name(self, name):
        # type: (str) -> Optional[int]
        """ get_idx_by_name returns the index of a matching registered header

        This implementation will prefer returning a static entry index whenever
        possible. If multiple matching header name are found in the static
        table, there is insurance that the first entry (lowest index number)
        will be returned.
        If no matching header is found, this method returns None.
        """
        name = name.lower()
        for key, val in six.iteritems(type(self)._static_entries):
            if val.name() == name:
                return key
        for idx, val in enumerate(self._dynamic_table):
            if val.name() == name:
                return type(self)._static_entries_last_idx + idx + 1
        return None

Response: This method returns the index of a matching registered header in the static entry table that matches the given name.


Instruction:
Explain what the following Python 3 code does
def gen_txt_repr(self, hdrs, register=True):
        # type: (Union[H2Frame, List[HPackHeaders]], Optional[bool]) -> str
        """ gen_txt_repr returns a "textual" representation of the provided
        headers.

        The output of this function is compatible with the input of
        parse_txt_hdrs.
        @param H2Frame|list of HPackHeaders hdrs: the list of headers to convert to textual representation  # noqa: E501
        @param bool: whether incremental headers should be added to the dynamic table as we generate the text  # noqa: E501
            representation
        @return str: the textual representation of the provided headers
        @raise AssertionError
        """
        lst = []
        if isinstance(hdrs, H2Frame):
            hdrs = hdrs.payload.hdrs

        for hdr in hdrs:
            try:
                if isinstance(hdr, HPackIndexedHdr):
                    lst.append('{}'.format(self[hdr.index]))
                elif isinstance(hdr, (
                    HPackLitHdrFldWithIncrIndexing,
                    HPackLitHdrFldWithoutIndexing
                )):
                    if hdr.index != 0:
                        name = self[hdr.index].name()
                    else:
                        name = hdr.hdr_name.getfieldval('data').origin()
                    if name.startswith(':'):
                        lst.append(
                            '{} {}'.format(
                                name,
                                hdr.hdr_value.getfieldval('data').origin()
                            )
                        )
                    else:
                        lst.append(
                            '{}: {}'.format(
                                name,
                                hdr.hdr_value.getfieldval('data').origin()
                            )
                        )
                if register and isinstance(hdr, HPackLitHdrFldWithIncrIndexing):  # noqa: E501
                    self.register(hdr)
            except KeyError as e:  # raised when an index is out-of-bound
                print(e)
                continue
        return '\n'.join(lst)

Response: This function returns a textual representation of the provided headers.


Instruction:
Given the following Python 3 function, write the documentation
def _convert_a_header_to_a_h2_header(self, hdr_name, hdr_value, is_sensitive, should_index):  # noqa: E501
        # type: (str, str, Callable[[str, str], bool], Callable[[str], bool]) -> Tuple[HPackHeaders, int]  # noqa: E501
        """ _convert_a_header_to_a_h2_header builds a HPackHeaders from a header
        name and a value. It returns a HPackIndexedHdr whenever possible. If not,  # noqa: E501
        it returns a HPackLitHdrFldWithoutIndexing or a
        HPackLitHdrFldWithIncrIndexing, based on the should_index callback.
        HPackLitHdrFldWithoutIndexing is forced if the is_sensitive callback
        returns True and its never_index bit is set.
        """

        # If both name and value are already indexed
        idx = self.get_idx_by_name_and_value(hdr_name, hdr_value)
        if idx is not None:
            return HPackIndexedHdr(index=idx), len(self[idx])

        # The value is not indexed for this headers

        hdr_value = self._optimize_header_length_and_packetify(hdr_value)

        # Searching if the header name is indexed
        idx = self.get_idx_by_name(hdr_name)
        if idx is not None:
            if is_sensitive(
                hdr_name,
                hdr_value.getfieldval('data').origin()
            ):
                return HPackLitHdrFldWithoutIndexing(
                    never_index=1,
                    index=idx,
                    hdr_value=hdr_value
                ), len(
                    HPackHdrEntry(
                        self[idx].name(),
                        hdr_value.getfieldval('data').origin()
                    )
                )
            if should_index(hdr_name):
                return HPackLitHdrFldWithIncrIndexing(
                    index=idx,
                    hdr_value=hdr_value
                ), len(
                    HPackHdrEntry(
                        self[idx].name(),
                        hdr_value.getfieldval('data').origin()
                    )
                )
            return HPackLitHdrFldWithoutIndexing(
                index=idx,
                hdr_value=hdr_value
            ), len(
                HPackHdrEntry(
                    self[idx].name(),
                    hdr_value.getfieldval('data').origin()
                )
            )

        hdr_name = self._optimize_header_length_and_packetify(hdr_name)

        if is_sensitive(
            hdr_name.getfieldval('data').origin(),
            hdr_value.getfieldval('data').origin()
        ):
            return HPackLitHdrFldWithoutIndexing(
                never_index=1,
                index=0,
                hdr_name=hdr_name,
                hdr_value=hdr_value
            ), len(
                HPackHdrEntry(
                    hdr_name.getfieldval('data').origin(),
                    hdr_value.getfieldval('data').origin()
                )
            )
        if should_index(hdr_name.getfieldval('data').origin()):
            return HPackLitHdrFldWithIncrIndexing(
                index=0,
                hdr_name=hdr_name,
                hdr_value=hdr_value
            ), len(
                HPackHdrEntry(
                    hdr_name.getfieldval('data').origin(),
                    hdr_value.getfieldval('data').origin()
                )
            )
        return HPackLitHdrFldWithoutIndexing(
            index=0,
            hdr_name=hdr_name,
            hdr_value=hdr_value
        ), len(
            HPackHdrEntry(
                hdr_name.getfieldval('data').origin(),
                hdr_value.getfieldval('data').origin()
            )
        )

Response: This function converts a header name and value to a HPackHeader. It returns a HPackIndexedHdr if possible and a HPackLitHdrFldWithIncrIndexing if possible.


Instruction:
Create a Python 3 function to
parse the given string s into a series of H2Frames with the correct flags.

Response:
def parse_txt_hdrs(self,
                       s,  # type: str
                       stream_id=1,  # type: int
                       body=None,  # type: Optional[str]
                       max_frm_sz=4096,  # type: int
                       max_hdr_lst_sz=0,  # type: int
                       is_sensitive=lambda n, v: False,  # type: Callable[[str, str], bool]  # noqa: E501
                       should_index=lambda x: False,  # type: Callable[[str], bool]  # noqa: E501
                       register=True,  # type: bool
                       ):
        # type: (...) -> H2Seq
        """ parse_txt_hdrs parses headers expressed in text and converts them
        into a series of H2Frames with the "correct" flags. A body can be provided  # noqa: E501
        in which case, the data frames are added, bearing the End Stream flag,
        instead of the H2HeadersFrame/H2ContinuationFrame. The generated frames
        may respect max_frm_sz (SETTINGS_MAX_FRAME_SIZE) and
        max_hdr_lst_sz (SETTINGS_MAX_HEADER_LIST_SIZE) if provided. The headers
        are split into multiple headers fragment (and H2Frames) to respect these  # noqa: E501
        limits. Also, a callback can be provided to tell if a header should be
        never indexed (sensitive headers, such as cookies), and another callback  # noqa: E501
        say if the header should be registered into the index table at all.
        For an header to be registered, the is_sensitive callback must return
        False AND the should_index callback should return True. This is the
        default behavior.

        @param str s: the string to parse for headers
        @param int stream_id: the stream id to use in the generated H2Frames
        @param str|None body: the eventual body of the request, that is added to the generated frames  # noqa: E501
        @param int max_frm_sz: the maximum frame size. This is used to split the headers and data frames according to  # noqa: E501
        the maximum frame size negotiated for this connection
        @param int max_hdr_lst_sz: the maximum size of a "header fragment" as defined in RFC7540  # noqa: E501
        @param callable is_sensitive: callback that returns True if the provided header is sensible and must be stored  # noqa: E501
        in a header packet requesting this header never to be indexed
        @param callable should_index: callback that returns True if the provided header should be stored in a header  # noqa: E501
        packet requesting indexation in the dynamic header table.
        @param bool register: whether to register new headers with incremental indexing as we parse them  # noqa: E501
        @raise Exception
        """

        sio = BytesIO(s)

        base_frm_len = len(raw(H2Frame()))

        ret = H2Seq()
        cur_frm = H2HeadersFrame()  # type: Union[H2HeadersFrame, H2ContinuationFrame]  # noqa: E501
        cur_hdr_sz = 0

        # For each line in the headers str to parse
        for hdr_line in sio:
            hdr_name, hdr_value = self._parse_header_line(hdr_line)
            if hdr_name is None:
                continue

            new_hdr, new_hdr_len = self._convert_a_header_to_a_h2_header(
                hdr_name, hdr_value, is_sensitive, should_index
            )
            new_hdr_bin_len = len(raw(new_hdr))

            if register and isinstance(new_hdr, HPackLitHdrFldWithIncrIndexing):  # noqa: E501
                self.register(new_hdr)

            # The new header binary length (+ base frame size) must not exceed
            # the maximum frame size or it will just never fit. Also, the
            # header entry length (as specified in RFC7540 par6.5.2) must not
            # exceed the maximum length of a header fragment or it will just
            # never fit
            if (new_hdr_bin_len + base_frm_len > max_frm_sz or
                    (max_hdr_lst_sz != 0 and new_hdr_len > max_hdr_lst_sz)):
                raise Exception('Header too long: {}'.format(hdr_name))

            if (max_frm_sz < len(raw(cur_frm)) + base_frm_len + new_hdr_len or
                (
                    max_hdr_lst_sz != 0 and
                    max_hdr_lst_sz < cur_hdr_sz + new_hdr_len
            )
            ):
                flags = set()
                if isinstance(cur_frm, H2HeadersFrame) and not body:
                    flags.add('ES')
                ret.frames.append(H2Frame(stream_id=stream_id, flags=flags) / cur_frm)  # noqa: E501
                cur_frm = H2ContinuationFrame()
                cur_hdr_sz = 0

            hdr_list = cur_frm.hdrs
            hdr_list += new_hdr
            cur_hdr_sz += new_hdr_len

        flags = {'EH'}
        if isinstance(cur_frm, H2HeadersFrame) and not body:
            flags.add('ES')
        ret.frames.append(H2Frame(stream_id=stream_id, flags=flags) / cur_frm)

        if body:
            base_data_frm_len = len(raw(H2DataFrame()))
            sio = BytesIO(body)
            frgmt = sio.read(max_frm_sz - base_data_frm_len - base_frm_len)
            while frgmt:
                nxt_frgmt = sio.read(max_frm_sz - base_data_frm_len - base_frm_len)  # noqa: E501
                flags = set()
                if len(nxt_frgmt) == 0:
                    flags.add('ES')
                ret.frames.append(
                    H2Frame(stream_id=stream_id, flags=flags) / H2DataFrame(data=frgmt)  # noqa: E501
                )
                frgmt = nxt_frgmt
        return ret


Instruction:
Can you tell what is the following Python 3 function doing
def AVP(avpId, **fields):
    val = None
    classType = AVP_Unknown
    if isinstance(avpId, str):
        try:
            for vnd in AvpDefDict:
                for code in AvpDefDict[vnd]:
                    val = AvpDefDict[vnd][code]
                    if val[0][:len(
                            avpId)] == avpId:  # A prefix of the full name is considered valid  # noqa: E501
                        raise
            found = False
        except BaseException:
            found = True
    else:
        if isinstance(avpId, list):
            code = avpId[0]
            vnd = avpId[1]
        else:  # Assume this is an int
            code = avpId
            vnd = 0
        try:
            val = AvpDefDict[vnd][code]
            found = True
        except BaseException:
            found = False
    if not found:
        warning('The AVP identifier %s has not been found.' % str(avpId))
        if isinstance(avpId, str):  # The string input is not valid
            return None
    # At this point code, vnd are provisionned val may be set (if found is True)  # noqa: E501
    # Set/override AVP code
    fields['avpCode'] = code
    # Set vendor if not already defined and relevant
    if 'avpVnd' not in fields and vnd:
        fields['avpVnd'] = vnd
    # Set flags if not already defined and possible ...
    if 'avpFlags' not in fields:
        if val:
            fields['avpFlags'] = val[2]
        else:
            fields['avpFlags'] = vnd and 128 or 0
    # Finally, set the name and class if possible
    if val:
        classType = val[1]
    _ret = classType(**fields)
    if val:
        _ret.name = 'AVP ' + val[0]
    return _ret

Response: Craft an AVP based on its id and optional parameter fields


Instruction:
Can you generate the documentation for the following Python 3 function
def getCmdParams(cmd, request, **fields):
    drCode = None
    params = None
    drAppId = None
    # Fetch the parameters if cmd is found in dict
    if isinstance(cmd, int):
        drCode = cmd    # Enable to craft commands with non standard code
        if cmd in DR_cmd_def:
            params = DR_cmd_def[drCode]
        else:
            params = ('Unknown', 'UK', {0: (128, 0)})
            warning(
                'No Diameter command with code %d found in DR_cmd_def dictionary' %  # noqa: E501
                cmd)
    else:  # Assume command is a string
        if len(cmd) > 3:     # Assume full command name given
            fpos = 0
        else:         # Assume abbreviated name is given and take only the first two letters  # noqa: E501
            cmd = cmd[:2]
            fpos = 1
        for k, f in DR_cmd_def.items():
            if f[fpos][:len(
                    cmd)] == cmd:   # Accept only a prefix of the full name
                drCode = k
                params = f
                break
        if not drCode:
            warning(
                'Diameter command with name %s not found in DR_cmd_def dictionary.' %  # noqa: E501
                cmd)
            return (fields, 'Unknown')
    # The drCode is set/overridden in any case
    fields['drCode'] = drCode
    # Processing of drAppId
    if 'drAppId' in fields:
        val = fields['drAppId']
        if isinstance(val, str):   # Translate into application Id code
            found = False
            for k, v in six.iteritems(AppIDsEnum):
                if v.find(val) != -1:
                    drAppId = k
                    fields['drAppId'] = drAppId
                    found = True
                    break
            if not found:
                del(fields['drAppId'])
                warning(
                    'Application ID with name %s not found in AppIDsEnum dictionary.' %  # noqa: E501
                    val)
                return (fields, 'Unknown')
        else:   # Assume type is int
            drAppId = val
    else:  # Application Id shall be taken from the params found based on cmd
        drAppId = next(iter(params[2]))   # The first record is taken
        fields['drAppId'] = drAppId
    # Set the command name
    name = request and params[0] + '-Request' or params[0] + '-Answer'
    # Processing of flags (only if not provided manually)
    if 'drFlags' not in fields:
        if drAppId in params[2]:
            flags = params[2][drAppId]
            fields['drFlags'] = request and flags[0] or flags[1]
    return (fields, name)

Response: Update or fill the fields with the parameters depending on the command code.


Instruction:
Write a Python 3 function for
crafting Diameter request commands

Response:
def DiamReq(cmd, **fields):
    """Craft Diameter request commands"""
    upfields, name = getCmdParams(cmd, True, **fields)
    p = DiamG(**upfields)
    p.name = name
    return p


Instruction:
Make a summary of the following Python 3 code
def DiamAns(cmd, **fields):
    upfields, name = getCmdParams(cmd, False, **fields)
    p = DiamG(**upfields)
    p.name = name
    return p

Response: Craft Diameter answer commands


Instruction:
Can you tell what is the following Python 3 function doing
def i2m(self, pkt, x):
        if x is None:
            x = 0
        elif isinstance(x, str):
            return bytes_encode(x)
        return x

Response: Convert internal value to machine value


Instruction:
Make a summary of the following Python 3 code
def _find_fld_pkt_val(self, pkt, val):
        fld = self._iterate_fields_cond(pkt, val, True)
        # Default ? (in this case, let's make sure it's up-do-date)
        dflts_pkt = pkt.default_fields
        if val == dflts_pkt[self.name] and self.name not in pkt.fields:
            dflts_pkt[self.name] = fld.default
            val = fld.default
        return fld, val

Response: Given a Packet instance pkt and the value val to be set returns the Field subclass to be used and the updated val.


Instruction:
Create a Python 3 function for
returning the Field subclass to be used depending on the Packet instance.

Response:
def _find_fld(self):
        """Returns the Field subclass to be used, depending on the Packet
instance, or the default subclass.

DEV: since the Packet instance is not provided, we have to use a hack
to guess it. It should only be used if you cannot provide the current
Packet instance (for example, because of the current Scapy API).

If you have the current Packet instance, use ._find_fld_pkt_val() (if
the value to set is also known) of ._find_fld_pkt() instead.

        """
        # Hack to preserve current Scapy API
        # See https://stackoverflow.com/a/7272464/3223422
        frame = inspect.currentframe().f_back.f_back
        while frame is not None:
            try:
                pkt = frame.f_locals['self']
            except KeyError:
                pass
            else:
                if isinstance(pkt, tuple(self.dflt.owners)):
                    return self._find_fld_pkt(pkt)
            frame = frame.f_back
        return self.dflt


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _fixup_val(self, x):
        if isinstance(x, (list, tuple)):
            return type(x)(
                v if v is None or isinstance(v, FlagValue)
                else FlagValue(v, self.names)
                for v in x
            )
        return x if x is None or isinstance(x, FlagValue) else FlagValue(x, self.names)

Response:
Returns a FlagValue instance when needed. Internal method to be
used in i2i and i2o methods.


Instruction:
Here you have a function in Python 3, explain what it does
def _check_uuid_fmt(self):
        if self.uuid_fmt not in UUIDField.FORMATS:
            raise FieldValueRangeException(
                "Unsupported uuid_fmt ({})".format(self.uuid_fmt))

Response: Checks. uuid_fmt and raises an exception if it is not valid.


Instruction:
Given the following Python 3 function, write the documentation
def pre_dissect(self, s):
        if len(s) < 1:
            raise Exception("Invalid InnerPlaintext (too short).")

        tmp_len = len(s) - 1
        if s[-1] != b"\x00":
            msg_len = tmp_len
        else:
            n = 1
            while s[-n] != b"\x00" and n < tmp_len:
                n += 1
            msg_len = tmp_len - n
        self.fields_desc[0].length_from = lambda pkt: msg_len

        self.type = struct.unpack("B", s[msg_len:msg_len + 1])[0]

        return s

Response: Parse the message list and set the type field.


Instruction:
Can you generate the documentation for the following Python 3 function
def _tls_auth_decrypt(self, s):
        rcs = self.tls_session.rcs
        read_seq_num = struct.pack("!Q", rcs.seq_num)
        rcs.seq_num += 1
        try:
            return rcs.cipher.auth_decrypt(b"", s, read_seq_num)
        except CipherError as e:
            return e.args
        except AEADTagError as e:
            pkt_info = self.firstlayer().summary()
            log_runtime.info("TLS: record integrity check failed [%s]", pkt_info)  # noqa: E501
            return e.args

Response: Decrypt the input string s with AEAD - ciphered data and return the decrypted AEAD - encrypted data.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def pre_dissect(self, s):
        if len(s) < 5:
            raise Exception("Invalid record: header is too short.")

        if isinstance(self.tls_session.rcs.cipher, Cipher_NULL):
            self.deciphered_len = None
            return s
        else:
            msglen = struct.unpack('!H', s[3:5])[0]
            hdr, efrag, r = s[:5], s[5:5 + msglen], s[msglen + 5:]
            frag, auth_tag = self._tls_auth_decrypt(efrag)
            self.deciphered_len = len(frag)
            return hdr + frag + auth_tag + r

Response: Decrypt verify and decompress the message.


Instruction:
Here you have a function in Python 3, explain what it does
def post_dissect(self, s):
        if self.tls_session.triggered_prcs_commit:
            if self.tls_session.prcs is not None:
                self.tls_session.rcs = self.tls_session.prcs
                self.tls_session.prcs = None
            self.tls_session.triggered_prcs_commit = False
        return s

Response: Update the pending read state if the prcs has been set.


Instruction:
Given the following Python 3 function, write the documentation
def _tls_auth_encrypt(self, s):
        wcs = self.tls_session.wcs
        write_seq_num = struct.pack("!Q", wcs.seq_num)
        wcs.seq_num += 1
        return wcs.cipher.auth_encrypt(s, b"", write_seq_num)

Response: Encrypt a string with the AEAD ciphertext.


Instruction:
Write a Python 3 function that can
apply the previous methods according to the writing cipher type.

Response:
def post_build(self, pkt, pay):
        """
        Apply the previous methods according to the writing cipher type.
        """
        # Compute the length of TLSPlaintext fragment
        hdr, frag = pkt[:5], pkt[5:]
        if not isinstance(self.tls_session.rcs.cipher, Cipher_NULL):
            frag = self._tls_auth_encrypt(frag)

        if self.len is not None:
            # The user gave us a 'len', let's respect this ultimately
            hdr = hdr[:3] + struct.pack("!H", self.len)
        else:
            # Update header with the length of TLSCiphertext.inner
            hdr = hdr[:3] + struct.pack("!H", len(frag))

        # Now we commit the pending write state if it has been triggered. We
        # update nothing if the pwcs was not set. This probably means that
        # we're working out-of-context (and we need to keep the default wcs).
        if self.tls_session.triggered_pwcs_commit:
            if self.tls_session.pwcs is not None:
                self.tls_session.wcs = self.tls_session.pwcs
                self.tls_session.pwcs = None
            self.tls_session.triggered_pwcs_commit = False

        return hdr + frag + pay


Instruction:
How would you code a function in Python 3 to
encrypt data with key key.

Response:
def ARC4_encrypt(key, data, skip=0):
    """Encrypt data @data with key @key, skipping @skip first bytes of the
    keystream"""

    algorithm = algorithms.ARC4(key)
    cipher = Cipher(algorithm, mode=None, backend=default_backend())
    encryptor = cipher.encryptor()
    if skip:
        encryptor.update(b"\x00" * skip)
    return encryptor.update(data)


Instruction:
Write a Python 3 script for
implementing TKIP WEPSeed generation

Response:
def gen_TKIP_RC4_key(TSC, TA, TK):
    """Implement TKIP WEPSeed generation
    TSC: packet IV
    TA: target addr bytes
    TK: temporal key
    """

    assert len(TSC) == 6
    assert len(TA) == 6
    assert len(TK) == 16
    assert all(isinstance(x, six.integer_types) for x in TSC + TA + TK)

    # Phase 1
    # 802.11i p.54

    # Phase 1 - Step 1
    TTAK = []
    TTAK.append(_MK16(TSC[3], TSC[2]))
    TTAK.append(_MK16(TSC[5], TSC[4]))
    TTAK.append(_MK16(TA[1], TA[0]))
    TTAK.append(_MK16(TA[3], TA[2]))
    TTAK.append(_MK16(TA[5], TA[4]))

    # Phase 1 - Step 2
    for i in range(PHASE1_LOOP_CNT):
        j = 2 * (i & 1)
        TTAK[0] = _CAST16(TTAK[0] + _SBOX16(TTAK[4] ^ _MK16(TK[1 + j], TK[0 + j])))  # noqa: E501
        TTAK[1] = _CAST16(TTAK[1] + _SBOX16(TTAK[0] ^ _MK16(TK[5 + j], TK[4 + j])))  # noqa: E501
        TTAK[2] = _CAST16(TTAK[2] + _SBOX16(TTAK[1] ^ _MK16(TK[9 + j], TK[8 + j])))  # noqa: E501
        TTAK[3] = _CAST16(TTAK[3] + _SBOX16(TTAK[2] ^ _MK16(TK[13 + j], TK[12 + j])))  # noqa: E501
        TTAK[4] = _CAST16(TTAK[4] + _SBOX16(TTAK[3] ^ _MK16(TK[1 + j], TK[0 + j])) + i)  # noqa: E501

    # Phase 2
    # 802.11i p.56

    # Phase 2 - Step 1
    PPK = list(TTAK)
    PPK.append(_CAST16(TTAK[4] + _MK16(TSC[1], TSC[0])))

    # Phase 2 - Step 2
    PPK[0] = _CAST16(PPK[0] + _SBOX16(PPK[5] ^ _MK16(TK[1], TK[0])))
    PPK[1] = _CAST16(PPK[1] + _SBOX16(PPK[0] ^ _MK16(TK[3], TK[2])))
    PPK[2] = _CAST16(PPK[2] + _SBOX16(PPK[1] ^ _MK16(TK[5], TK[4])))
    PPK[3] = _CAST16(PPK[3] + _SBOX16(PPK[2] ^ _MK16(TK[7], TK[6])))
    PPK[4] = _CAST16(PPK[4] + _SBOX16(PPK[3] ^ _MK16(TK[9], TK[8])))
    PPK[5] = _CAST16(PPK[5] + _SBOX16(PPK[4] ^ _MK16(TK[11], TK[10])))

    PPK[0] = _CAST16(PPK[0] + _RotR1(PPK[5] ^ _MK16(TK[13], TK[12])))
    PPK[1] = _CAST16(PPK[1] + _RotR1(PPK[0] ^ _MK16(TK[15], TK[14])))
    PPK[2] = _CAST16(PPK[2] + _RotR1(PPK[1]))
    PPK[3] = _CAST16(PPK[3] + _RotR1(PPK[2]))
    PPK[4] = _CAST16(PPK[4] + _RotR1(PPK[3]))
    PPK[5] = _CAST16(PPK[5] + _RotR1(PPK[4]))

    # Phase 2 - Step 3
    WEPSeed = []
    WEPSeed.append(TSC[1])
    WEPSeed.append((TSC[1] | 0x20) & 0x7f)
    WEPSeed.append(TSC[0])
    WEPSeed.append(((PPK[5] ^ _MK16(TK[1], TK[0])) >> 1) & 0xFF)
    for i in range(6):
        WEPSeed.append(PPK[i] & 0xFF)
        WEPSeed.append(PPK[i] >> 8)

    assert len(WEPSeed) == 16

    return b"".join(chb(x) for x in WEPSeed)


Instruction:
Make a summary of the following Python 3 code
def _michael_b(m_l, m_r):
    m_r = m_r ^ _rotate_left32(m_l, 17)
    m_l = (m_l + m_r) % 2**32
    m_r = m_r ^ _XSWAP(m_l)
    m_l = (m_l + m_r) % 2**32
    m_r = m_r ^ _rotate_left32(m_l, 3)
    m_l = (m_l + m_r) % 2**32
    m_r = m_r ^ _rotate_right32(m_l, 2)
    m_l = (m_l + m_r) % 2**32
    return m_l, m_r

Response: Defined in 802. 11i p. 49


Instruction:
Given the following Python 3 function, write the documentation
def michael(key, to_hash):

    # Block size: 4
    nb_block, nb_extra_bytes = divmod(len(to_hash), 4)
    # Add padding
    data = to_hash + chb(0x5a) + b"\x00" * (7 - nb_extra_bytes)

    # Hash
    m_l, m_r = unpack('<II', key)
    for i in range(nb_block + 2):
        # Convert i-th block to int
        block_i = unpack('<I', data[i * 4:i * 4 + 4])[0]
        m_l ^= block_i
        m_l, m_r = _michael_b(m_l, m_r)
    return pack('<II', m_l, m_r)

Response: Defined in 802.11i p.48


Instruction:
Can you implement a function in Python 3 that
extracts TSCs TA and encoded - data from a packet.

Response:
def parse_TKIP_hdr(pkt):
    """Extract TSCs, TA and encoded-data from a packet @pkt"""
    # Note: FCS bit is not handled
    assert pkt.FCfield.protected

    # 802.11i - 8.3.2.2
    tkip_layer = pkt[Dot11TKIP]
    payload = tkip_layer.data

    # IV
    if not tkip_layer.ext_iv:
        # 802.11i p. 46
        raise ValueError("Extended IV must be set for TKIP")
    TSC0 = tkip_layer.TSC0
    TSC1 = tkip_layer.TSC1
    WEPseed = tkip_layer.WEPSeed

    # Extended IV
    TSC2 = tkip_layer.TSC2
    TSC3 = tkip_layer.TSC3
    TSC4 = tkip_layer.TSC4
    TSC5 = tkip_layer.TSC5

    # 802.11i p. 46
    assert (TSC1 | 0x20) & 0x7f == WEPseed

    TA = [orb(e) for e in mac2str(pkt.addr2)]
    TSC = [TSC0, TSC1, TSC2, TSC3, TSC4, TSC5]

    return TSC, TA, payload


Instruction:
How would you explain what the following Python 3 function does
def build_TKIP_payload(data, iv, mac, tk):
    TSC5, TSC4, TSC3, TSC2, TSC1, TSC0 = (
        (iv >> 40) & 0xFF,
        (iv >> 32) & 0xFF,
        (iv >> 24) & 0xFF,
        (iv >> 16) & 0xFF,
        (iv >> 8) & 0xFF,
        iv & 0xFF
    )
    bitfield = 1 << 5  # Extended IV
    TKIP_hdr = chb(TSC1) + chb((TSC1 | 0x20) & 0x7f) + chb(TSC0) + chb(bitfield)  # noqa: E501
    TKIP_hdr += chb(TSC2) + chb(TSC3) + chb(TSC4) + chb(TSC5)

    TA = [orb(e) for e in mac2str(mac)]
    TSC = [TSC0, TSC1, TSC2, TSC3, TSC4, TSC5]
    TK = [orb(x) for x in tk]

    rc4_key = gen_TKIP_RC4_key(TSC, TA, TK)
    return TKIP_hdr + ARC4_encrypt(rc4_key, data)

Response: Build a TKIP payload for IV and MAC and encrypt it based on temporal key tk.


Instruction:
Make a summary of the following Python 3 code
def parse_data_pkt(pkt, tk):
    TSC, TA, data = parse_TKIP_hdr(pkt)
    TK = [orb(x) for x in tk]

    rc4_key = gen_TKIP_RC4_key(TSC, TA, TK)
    return ARC4_decrypt(rc4_key, data)

Response: Extract data from a WPA packet with temporal key tk


Instruction:
Implement a Python 3 function for
checking MIC and ICV & return the data from a decrypted TKIP packet

Response:
def check_MIC_ICV(data, mic_key, source, dest):
    """Check MIC, ICV & return the data from a decrypted TKIP packet"""
    assert len(data) > 12

    # DATA - MIC(DA - SA - Priority=0 - 0 - 0 - 0 - DATA) - ICV
    # 802.11i p.47

    ICV = data[-4:]
    MIC = data[-12:-4]
    data_clear = data[:-12]

    expected_ICV = pack("<I", crc32(data_clear + MIC) & 0xFFFFFFFF)
    if expected_ICV != ICV:
        raise ICVError()

    sa = mac2str(source)  # Source MAC
    da = mac2str(dest)  # Dest MAC

    expected_MIC = michael(mic_key, da + sa + b"\x00" * 4 + data_clear)
    if expected_MIC != MIC:
        raise MICError()

    return data_clear


Instruction:
Can you write a function in Python 3 where it
computes and return the data with its MIC and ICV

Response:
def build_MIC_ICV(data, mic_key, source, dest):
    """Compute and return the data with its MIC and ICV"""
    # DATA - MIC(DA - SA - Priority=0 - 0 - 0 - 0 - DATA) - ICV
    # 802.11i p.47

    sa = mac2str(source)  # Source MAC
    da = mac2str(dest)  # Dest MAC
    MIC = michael(mic_key, da + sa + b"\x00" + b"\x00" * 3 + data)
    ICV = pack("<I", crc32(data + MIC) & 0xFFFFFFFF)

    return data + MIC + ICV


Instruction:
Given the following Python 3 function, write the documentation
def _lcm(a, b):
    if a == 0 or b == 0:
        return 0
    else:
        return abs(a * b) // gcd(a, b)

Response: Return the Least Common Multiple between 2 integers.


Instruction:
Here you have a function in Python 3, explain what it does
def split_for_transport(orig_pkt, transport_proto):
    # force resolution of default fields to avoid padding errors
    header = orig_pkt.__class__(raw(orig_pkt))
    next_hdr = header.payload
    nh = None

    if header.version == 4:
        nh = header.proto
        header.proto = transport_proto
        header.remove_payload()
        del header.chksum
        del header.len

        return header, nh, next_hdr
    else:
        found_rt_hdr = False
        prev = header

        # Since the RFC 4302 is vague about where the ESP/AH headers should be
        # inserted in IPv6, I chose to follow the linux implementation.
        while isinstance(next_hdr, (IPv6ExtHdrHopByHop, IPv6ExtHdrRouting, IPv6ExtHdrDestOpt)):  # noqa: E501
            if isinstance(next_hdr, IPv6ExtHdrHopByHop):
                pass
            if isinstance(next_hdr, IPv6ExtHdrRouting):
                found_rt_hdr = True
            elif isinstance(next_hdr, IPv6ExtHdrDestOpt) and found_rt_hdr:
                break

            prev = next_hdr
            next_hdr = next_hdr.payload

        nh = prev.nh
        prev.nh = transport_proto
        prev.remove_payload()
        del header.plen

        return header, nh, next_hdr

Response: Split an IP or IPv6 packet into two components.


Instruction:
Create a Python 3 function for
returning a new Cipher object for the current object.

Response:
def new_cipher(self, key, mode_iv, digest=None):
        """
        @param key:     the secret key, a byte string
        @param mode_iv: the initialization vector or nonce, a byte string.
                        Formatted by `format_mode_iv`.
        @param digest:  also known as tag or icv. A byte string containing the
                        digest of the encrypted data. Only use this during
                        decryption!

        @return:    an initialized cipher object for this algo
        """
        if self.is_aead and digest is not None:
            # With AEAD, the mode needs the digest during decryption.
            return Cipher(
                self.cipher(key),
                self.mode(mode_iv, digest, len(digest)),
                default_backend(),
            )
        else:
            return Cipher(
                self.cipher(key),
                self.mode(mode_iv),
                default_backend(),
            )


Instruction:
Can you generate the documentation for the following Python 3 function
def pad(self, esp):
        # 2 extra bytes for padlen and nh
        data_len = len(esp.data) + 2

        # according to the RFC4303, section 2.4. Padding (for Encryption)
        # the size of the ESP payload must be a multiple of 32 bits
        align = _lcm(self.block_size, 4)

        # pad for block size
        esp.padlen = -data_len % align

        # Still according to the RFC, the default value for padding *MUST* be an  # noqa: E501
        # array of bytes starting from 1 to padlen
        # TODO: Handle padding function according to the encryption algo
        esp.padding = struct.pack("B" * esp.padlen, *range(1, esp.padlen + 1))

        # If the following test fails, it means that this algo does not comply
        # with the RFC
        payload_len = len(esp.iv) + len(esp.data) + len(esp.padding) + 2
        if payload_len % 4 != 0:
            raise ValueError('The size of the ESP data is not aligned to 32 bits after padding.')  # noqa: E501

        return esp

Response:
Add the correct amount of padding so that the data to encrypt is
        exactly a multiple of the algorithm s block size.


Instruction:
Can you tell what is the following Python 3 function doing
def encrypt(self, sa, esp, key):
        data = esp.data_for_encryption()

        if self.cipher:
            mode_iv = self._format_mode_iv(algo=self, sa=sa, iv=esp.iv)
            cipher = self.new_cipher(key, mode_iv)
            encryptor = cipher.encryptor()

            if self.is_aead:
                aad = struct.pack('!LL', esp.spi, esp.seq)
                encryptor.authenticate_additional_data(aad)
                data = encryptor.update(data) + encryptor.finalize()
                data += encryptor.tag[:self.icv_size]
            else:
                data = encryptor.update(data) + encryptor.finalize()

        return ESP(spi=esp.spi, seq=esp.seq, data=esp.iv + data)

Response: Encrypt an ESP packet with this algorithm


Instruction:
Can you generate the documentation for the following Python 3 function
def check_key(self, key):
        if self.key_size and len(key) not in self.key_size:
            raise TypeError('invalid key size %s, must be one of %s' %
                            (len(key), self.key_size))

Response: Check that the key length is valid.


Instruction:
Can you tell what is the following Python 3 function doing
def sign(self, pkt, key):
        if not self.mac:
            return pkt

        mac = self.new_mac(key)

        if pkt.haslayer(ESP):
            mac.update(raw(pkt[ESP]))
            pkt[ESP].data += mac.finalize()[:self.icv_size]

        elif pkt.haslayer(AH):
            clone = zero_mutable_fields(pkt.copy(), sending=True)
            mac.update(raw(clone))
            pkt[AH].icv = mac.finalize()[:self.icv_size]

        return pkt

Response: Sign an IPsec packet with this algo.


Instruction:
Make a summary of the following Python 3 code
def verify(self, pkt, key):
        if not self.mac or self.icv_size == 0:
            return

        mac = self.new_mac(key)

        pkt_icv = 'not found'
        computed_icv = 'not computed'

        if isinstance(pkt, ESP):
            pkt_icv = pkt.data[len(pkt.data) - self.icv_size:]
            clone = pkt.copy()
            clone.data = clone.data[:len(clone.data) - self.icv_size]

        elif pkt.haslayer(AH):
            if len(pkt[AH].icv) != self.icv_size:
                # Fill padding since we know the actual icv_size
                pkt[AH].padding = pkt[AH].icv[self.icv_size:]
                pkt[AH].icv = pkt[AH].icv[:self.icv_size]
            pkt_icv = pkt[AH].icv
            clone = zero_mutable_fields(pkt.copy(), sending=False)

        mac.update(raw(clone))
        computed_icv = mac.finalize()[:self.icv_size]

        # XXX: Cannot use mac.verify because the ICV can be truncated
        if pkt_icv != computed_icv:
            raise IPSecIntegrityError('pkt_icv=%r, computed_icv=%r' %
                                      (pkt_icv, computed_icv))

Response: Verify that the ICV of a packet is valid.


Instruction:
How would you explain what the following Python 3 function does
def encrypt(self, pkt, seq_num=None, iv=None):
        if not isinstance(pkt, self.SUPPORTED_PROTOS):
            raise TypeError('cannot encrypt %s, supported protos are %s'
                            % (pkt.__class__, self.SUPPORTED_PROTOS))
        if self.proto is ESP:
            return self._encrypt_esp(pkt, seq_num=seq_num, iv=iv)
        else:
            return self._encrypt_ah(pkt, seq_num=seq_num)

Response: Encrypt an IP ( v6 packet with ESP or AH according to this SecurityAssociation.


Instruction:
Given the following Python 3 function, write the documentation
def decrypt(self, pkt, verify=True):
        if not isinstance(pkt, self.SUPPORTED_PROTOS):
            raise TypeError('cannot decrypt %s, supported protos are %s'
                            % (pkt.__class__, self.SUPPORTED_PROTOS))

        if self.proto is ESP and pkt.haslayer(ESP):
            return self._decrypt_esp(pkt, verify=verify)
        elif self.proto is AH and pkt.haslayer(AH):
            return self._decrypt_ah(pkt, verify=verify)
        else:
            raise TypeError('%s has no %s layer' % (pkt, self.proto.name))

Response: Decrypt an IP ( v6 packet and return the decrypted packet.


Instruction:
Can you write a function in Python 3 where it
updates the explicit nonce.

Response:
def _update_nonce_explicit(self):
        """
        Increment the explicit nonce while avoiding any overflow.
        """
        ne = self.nonce_explicit + 1
        self.nonce_explicit = ne % 2**(self.nonce_explicit_len * 8)


Instruction:
Write a Python 3 script to
encrypt the data then prepend the explicit part of the nonce.

Response:
def auth_encrypt(self, P, A, seq_num=None):
        """
        Encrypt the data then prepend the explicit part of the nonce. The
        authentication tag is directly appended with the most recent crypto
        API. Additional data may be authenticated without encryption (as A).

        The 'seq_num' should never be used here, it is only a safeguard needed
        because one cipher (ChaCha20Poly1305) using TLS 1.2 logic in record.py
        actually is a _AEADCipher_TLS13 (even though others are not).
        """
        if False in six.itervalues(self.ready):
            raise CipherError(P, A)

        if hasattr(self, "pc_cls"):
            self._cipher.mode._initialization_vector = self._get_nonce()
            self._cipher.mode._tag = None
            encryptor = self._cipher.encryptor()
            encryptor.authenticate_additional_data(A)
            res = encryptor.update(P) + encryptor.finalize()
            res += encryptor.tag
        else:
            res = self._cipher.encrypt(self._get_nonce(), P, A)

        nonce_explicit = pkcs_i2osp(self.nonce_explicit,
                                    self.nonce_explicit_len)
        self._update_nonce_explicit()
        return nonce_explicit + res


Instruction:
Can you create a Python 3 function that
encrypts the data and append the computed authentication code.

Response:
def auth_encrypt(self, P, A, seq_num):
        """
        Encrypt the data, and append the computed authentication code.
        TLS 1.3 does not use additional data, but we leave this option to the
        user nonetheless.

        Note that the cipher's authentication tag must be None when encrypting.
        """
        if False in six.itervalues(self.ready):
            raise CipherError(P, A)

        if hasattr(self, "pc_cls"):
            self._cipher.mode._tag = None
            self._cipher.mode._initialization_vector = self._get_nonce(seq_num)
            encryptor = self._cipher.encryptor()
            encryptor.authenticate_additional_data(A)
            res = encryptor.update(P) + encryptor.finalize()
            res += encryptor.tag
        else:
            if (conf.crypto_valid_advanced and
                    isinstance(self._cipher, AESCCM)):
                res = self._cipher.encrypt(self._get_nonce(seq_num), P, A,
                                           tag_length=self.tag_len)
            else:
                res = self._cipher.encrypt(self._get_nonce(seq_num), P, A)
        return res


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _tzsp_guess_next_tag(payload):

    if not payload:
        warning('missing payload')
        return None

    tag_type = orb(payload[0])

    try:
        tag_class_definition = _TZSP_TAG_CLASSES[tag_type]

    except KeyError:

        return _tzsp_handle_unknown_tag(payload, tag_type)

    if type(tag_class_definition) is not dict:
        return tag_class_definition

    try:
        length = orb(payload[1])
    except IndexError:
        length = None

    if not length:
        warning('no tag length given - packet to short')
        return Raw

    try:
        return tag_class_definition[length]
    except KeyError:
        warning('invalid tag length {} for tag type {}'.format(length, tag_type))  # noqa: E501
        return Raw

Response: Helper function to guess the next tag from a list of payload.


Instruction:
Write a Python 3 function for
getting the class that holds the encapsulated payload of the TZSP packet

Response:
def get_encapsulated_payload_class(self):
        """
        get the class that holds the encapsulated payload of the TZSP packet
        :return: class representing the payload, Raw() on error
        """

        try:
            return TZSP.ENCAPSULATED_PROTOCOL_CLASSES[self.encapsulated_protocol]  # noqa: E501
        except KeyError:
            warning(
                'unknown or invalid encapsulation type (%i) - returning payload as raw()' % self.encapsulated_protocol)  # noqa: E501
            return Raw


Instruction:
Create a Python 3 function for
guessing the type of the payload encapsulation is given be the outer TZSP layers attribute encapsulation_protocol

Response:
def guess_payload_class(self, payload):
        """
        the type of the payload encapsulation is given be the outer TZSP layers attribute encapsulation_protocol  # noqa: E501
        """

        under_layer = self.underlayer
        tzsp_header = None

        while under_layer:
            if isinstance(under_layer, TZSP):
                tzsp_header = under_layer
                break
            under_layer = under_layer.underlayer

        if tzsp_header:

            return tzsp_header.get_encapsulated_payload_class()
        else:
            raise TZSPStructureException('missing parent TZSP header')


Instruction:
Can you generate the documentation for the following Python 3 function
def h2i(self, pkt, x):

        if isinstance(x, str) and x.startswith("v") and len(x) <= 8:
            major = int(x.split(".")[0][1:])
            minor = int(x.split(".")[1])

            return (major << 8) | minor

        elif isinstance(x, int) and 0 <= x <= 65535:
            return x
        else:
            if not hasattr(self, "default"):
                return x
            if self.default is not None:
                warning("set value to default. Format of %r is invalid" % x)
                return self.default
            else:
                raise Scapy_Exception("Format of value is invalid")

Response: The field accepts string values like v12. 1. 255.


Instruction:
Make a summary of the following Python 3 code
def get_algs_from_ciphersuite_name(ciphersuite_name):
    tls1_3 = False
    if ciphersuite_name.startswith("TLS"):
        s = ciphersuite_name[4:]

        if s.endswith("CCM") or s.endswith("CCM_8"):
            kx_name, s = s.split("_WITH_")
            kx_alg = _tls_kx_algs.get(kx_name)
            hash_alg = _tls_hash_algs.get("SHA256")
            cipher_alg = _tls_cipher_algs.get(s)
            hmac_alg = None

        else:
            if "WITH" in s:
                kx_name, s = s.split("_WITH_")
                kx_alg = _tls_kx_algs.get(kx_name)
            else:
                tls1_3 = True
                kx_alg = _tls_kx_algs.get("TLS13")

            hash_name = s.split('_')[-1]
            hash_alg = _tls_hash_algs.get(hash_name)

            cipher_name = s[:-(len(hash_name) + 1)]
            if tls1_3:
                cipher_name += "_TLS13"
            cipher_alg = _tls_cipher_algs.get(cipher_name)

            hmac_alg = None
            if cipher_alg is not None and cipher_alg.type != "aead":
                hmac_name = "HMAC-%s" % hash_name
                hmac_alg = _tls_hmac_algs.get(hmac_name)

    elif ciphersuite_name.startswith("SSL"):
        s = ciphersuite_name[7:]
        kx_alg = _tls_kx_algs.get("SSLv2")
        cipher_name, hash_name = s.split("_WITH_")
        cipher_alg = _tls_cipher_algs.get(cipher_name.rstrip("_EXPORT40"))
        kx_alg.export = cipher_name.endswith("_EXPORT40")
        hmac_alg = _tls_hmac_algs.get("HMAC-NULL")
        hash_alg = _tls_hash_algs.get(hash_name)

    return kx_alg, cipher_alg, hmac_alg, hash_alg, tls1_3

Response: Returns the 3 - tuple made of the Key Exchange Algorithm class the CipherExchange Algorithm class and the HMAC class.


Instruction:
Make a summary of the following Python 3 code
def get_usable_ciphersuites(l, kx):
    res = []
    for c in l:
        if c in _tls_cipher_suites_cls:
            ciph = _tls_cipher_suites_cls[c]
            if ciph.usable:
                # XXX select among RSA and ECDSA cipher suites
                # according to the key(s) the server was given
                if ciph.kx_alg.anonymous or kx in ciph.kx_alg.name:
                    res.append(c)
    return res

Response: This function returns a list of usable cipher suites i. e. for which key exchange cipher and hash cipher algorithms are known to be implemented and usable in current version of the TLS extension.


Instruction:
Create a Python 3 function to
compute the checksum of an IPv4 upper layer.

Response:
def in4_chksum(proto, u, p):
    """
    As Specified in RFC 2460 - 8.1 Upper-Layer Checksums

    Performs IPv4 Upper Layer checksum computation. Provided parameters are:
    - 'proto' : value of upper layer protocol
    - 'u'  : IP upper layer instance
    - 'p'  : the payload of the upper layer provided as a string
    """
    if not isinstance(u, IP):
        warning("No IP underlayer to compute checksum. Leaving null.")
        return 0
    if u.len is not None:
        if u.ihl is None:
            olen = sum(len(x) for x in u.options)
            ihl = 5 + olen // 4 + (1 if olen % 4 else 0)
        else:
            ihl = u.ihl
        ln = max(u.len - 4 * ihl, 0)
    else:
        ln = len(p)
    psdhdr = struct.pack("!4s4sHH",
                         inet_pton(socket.AF_INET, u.src),
                         inet_pton(socket.AF_INET, u.dst),
                         proto,
                         ln)
    return checksum(psdhdr + p)


Instruction:
Can you generate the documentation for the following Python 3 function
def _defrag_list(lst, defrag, missfrag):
    p = lst[0]
    lastp = lst[-1]
    if p.frag > 0 or lastp.flags.MF:  # first or last fragment missing
        missfrag.append(lst)
        return
    p = p.copy()
    if conf.padding_layer in p:
        del(p[conf.padding_layer].underlayer.payload)
    ip = p[IP]
    if ip.len is None or ip.ihl is None:
        clen = len(ip.payload)
    else:
        clen = ip.len - (ip.ihl << 2)
    txt = conf.raw_layer()
    for q in lst[1:]:
        if clen != q.frag << 3:  # Wrong fragmentation offset
            if clen > q.frag << 3:
                warning("Fragment overlap (%i > %i) %r || %r ||  %r" % (clen, q.frag << 3, p, txt, q))  # noqa: E501
            missfrag.append(lst)
            break
        if q[IP].len is None or q[IP].ihl is None:
            clen += len(q[IP].payload)
        else:
            clen += q[IP].len - (q[IP].ihl << 2)
        if conf.padding_layer in q:
            del(q[conf.padding_layer].underlayer.payload)
        txt.add_payload(q[IP].payload.copy())
        if q.time > p.time:
            p.time = q.time
    else:
        ip.flags.MF = False
        del(ip.chksum)
        del(ip.len)
        p = p / txt
        p._defrag_pos = max(x._defrag_pos for x in lst)
        defrag.append(p)

Response: Internal usage only. Part of the _defrag_logic


Instruction:
Make a summary of the following Python 3 code
def _defrag_logic(plist, complete=False):
    frags = defaultdict(lambda: [])
    final = []
    pos = 0
    for p in plist:
        p._defrag_pos = pos
        pos += 1
        if IP in p:
            ip = p[IP]
            if ip.frag != 0 or ip.flags.MF:
                uniq = (ip.id, ip.src, ip.dst, ip.proto)
                frags[uniq].append(p)
                continue
        final.append(p)

    defrag = []
    missfrag = []
    for lst in six.itervalues(frags):
        lst.sort(key=lambda x: x.frag)
        _defrag_list(lst, defrag, missfrag)
    defrag2 = []
    for p in defrag:
        q = p.__class__(raw(p))
        q._defrag_pos = p._defrag_pos
        q.time = p.time
        defrag2.append(q)
    if complete:
        final.extend(defrag2)
        final.extend(missfrag)
        final.sort(key=lambda x: x._defrag_pos)
        if hasattr(plist, "listname"):
            name = "Defragmented %s" % plist.listname
        else:
            name = "Defragmented"
        return PacketList(final, name=name)
    else:
        return PacketList(final), PacketList(defrag2), PacketList(missfrag)

Response: Internal function used to defragment a list of packets.


Instruction:
Can you generate the documentation for the following Python 3 function
def _packetlist_timeskew_graph(self, ip, **kargs):

    # Filter TCP segments which source address is 'ip'
    tmp = (self._elt2pkt(x) for x in self.res)
    b = (x for x in tmp if IP in x and x[IP].src == ip and TCP in x)

    # Build a list of tuples (creation_time, replied_timestamp)
    c = []
    tsf = ICMPTimeStampField("", None)
    for p in b:
        opts = p.getlayer(TCP).options
        for o in opts:
            if o[0] == "Timestamp":
                c.append((p.time, tsf.any2i("", o[1][0])))

    # Stop if the list is empty
    if not c:
        warning("No timestamps found in packet list")
        return []

    # Prepare the data that will be plotted
    first_creation_time = c[0][0]
    first_replied_timestamp = c[0][1]

    def _wrap_data(ts_tuple, wrap_seconds=2000):
        """Wrap the list of tuples."""

        ct, rt = ts_tuple  # (creation_time, replied_timestamp)
        X = ct % wrap_seconds
        Y = ((ct - first_creation_time) - ((rt - first_replied_timestamp) / 1000.0))  # noqa: E501

        return X, Y

    data = [_wrap_data(e) for e in c]

    # Mimic the default gnuplot output
    if kargs == {}:
        kargs = MATPLOTLIB_DEFAULT_PLOT_KARGS
    lines = plt.plot(data, **kargs)

    # Call show() if matplotlib is not inlined
    if not MATPLOTLIB_INLINED:
        plt.show()

    return lines

Response: Tries to plot the timeskew between the timestamps and real time for a given ip


Instruction:
Can you generate the documentation for the following Python 3 function
def traceroute(target, dport=80, minttl=1, maxttl=30, sport=RandShort(), l4=None, filter=None, timeout=2, verbose=None, **kargs):  # noqa: E501
    if verbose is None:
        verbose = conf.verb
    if filter is None:
        # we only consider ICMP error packets and TCP packets with at
        # least the ACK flag set *and* either the SYN or the RST flag
        # set
        filter = "(icmp and (icmp[0]=3 or icmp[0]=4 or icmp[0]=5 or icmp[0]=11 or icmp[0]=12)) or (tcp and (tcp[13] & 0x16 > 0x10))"  # noqa: E501
    if l4 is None:
        a, b = sr(IP(dst=target, id=RandShort(), ttl=(minttl, maxttl)) / TCP(seq=RandInt(), sport=sport, dport=dport),  # noqa: E501
                  timeout=timeout, filter=filter, verbose=verbose, **kargs)
    else:
        # this should always work
        filter = "ip"
        a, b = sr(IP(dst=target, id=RandShort(), ttl=(minttl, maxttl)) / l4,
                  timeout=timeout, filter=filter, verbose=verbose, **kargs)

    a = TracerouteResult(a.res)
    if verbose:
        a.show()
    return a, b

Response:
Instant TCP traceroute
traceroute(target, [maxttl=30,] [dport=80,] [sport=80,] [verbose=conf.verb]) -> None  # noqa: E501


Instruction:
Can you generate a brief explanation for the following Python 3 code
def report_ports(target, ports):
    ans, unans = sr(IP(dst=target) / TCP(dport=ports), timeout=5)
    rep = "\\begin{tabular}{|r|l|l|}\n\\hline\n"
    for s, r in ans:
        if not r.haslayer(ICMP):
            if r.payload.flags == 0x12:
                rep += r.sprintf("%TCP.sport% & open & SA \\\\\n")
    rep += "\\hline\n"
    for s, r in ans:
        if r.haslayer(ICMP):
            rep += r.sprintf("%TCPerror.dport% & closed & ICMP type %ICMP.type%/%ICMP.code% from %IP.src% \\\\\n")  # noqa: E501
        elif r.payload.flags != 0x12:
            rep += r.sprintf("%TCP.sport% & closed & TCP %TCP.flags% \\\\\n")
    rep += "\\hline\n"
    for i in unans:
        rep += i.sprintf("%TCP.dport% & ? & unanswered \\\\\n")
    rep += "\\hline\n\\end{tabular}\n"
    return rep

Response:
portscan a target and output a LaTeX table
report_ports


Instruction:
Create a Python 3 function for
identifying IP id values classes in a list of packets lst a list of packets funcID a function that returns IP id values classes a list of packets lst a list of packets funcpres a function that returns IP id values classes a list of packets that return IP id values

Response:
def IPID_count(lst, funcID=lambda x: x[1].id, funcpres=lambda x: x[1].summary()):  # noqa: E501
    """Identify IP id values classes in a list of packets

lst:      a list of packets
funcID:   a function that returns IP id values
funcpres: a function used to summarize packets"""
    idlst = [funcID(e) for e in lst]
    idlst.sort()
    classes = [idlst[0]]
    classes += [t[1] for t in zip(idlst[:-1], idlst[1:]) if abs(t[0] - t[1]) > 50]  # noqa: E501
    lst = [(funcID(x), funcpres(x)) for x in lst]
    lst.sort()
    print("Probably %i classes:" % len(classes), classes)
    for id, pr in lst:
        print("%5i" % id, pr)


Instruction:
How would you code a function in Python 3 to
return ttl or hlim depending on the IP version

Response:
def _ttl(self):
        """Returns ttl or hlim, depending on the IP version"""
        return self.hlim if isinstance(self, scapy.layers.inet6.IPv6) else self.ttl


Instruction:
Here you have a function in Python 3, explain what it does
def trace3D(self, join=True):
        # When not ran from a notebook, vpython pooly closes itself
        # using os._exit once finished. We pack it into a Process
        import multiprocessing
        p = multiprocessing.Process(target=self.trace3D_notebook)
        p.start()
        if join:
            p.join()

Response: Give a 3D representation of the traceroute.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def trace3D_notebook(self):
        trace = self.get_trace()
        import vpython

        class IPsphere(vpython.sphere):
            def __init__(self, ip, **kargs):
                vpython.sphere.__init__(self, **kargs)
                self.ip = ip
                self.label = None
                self.setlabel(self.ip)
                self.last_clicked = None
                self.full = False
                self.savcolor = vpython.vec(*self.color.value)

            def fullinfos(self):
                self.full = True
                self.color = vpython.vec(1, 0, 0)
                a, b = sr(IP(dst=self.ip) / TCP(dport=[21, 22, 23, 25, 80, 443], flags="S"), timeout=2, verbose=0)  # noqa: E501
                if len(a) == 0:
                    txt = "%s:\nno results" % self.ip
                else:
                    txt = "%s:\n" % self.ip
                    for s, r in a:
                        txt += r.sprintf("{TCP:%IP.src%:%TCP.sport% %TCP.flags%}{TCPerror:%IPerror.dst%:%TCPerror.dport% %IP.src% %ir,ICMP.type%}\n")  # noqa: E501
                self.setlabel(txt, visible=1)

            def unfull(self):
                self.color = self.savcolor
                self.full = False
                self.setlabel(self.ip)

            def setlabel(self, txt, visible=None):
                if self.label is not None:
                    if visible is None:
                        visible = self.label.visible
                    self.label.visible = 0
                elif visible is None:
                    visible = 0
                self.label = vpython.label(text=txt, pos=self.pos, space=self.radius, xoffset=10, yoffset=20, visible=visible)  # noqa: E501

            def check_double_click(self):
                try:
                    if self.full or not self.label.visible:
                        return False
                    if self.last_clicked is not None:
                        return (time.time() - self.last_clicked) < 0.5
                    return False
                finally:
                    self.last_clicked = time.time()

            def action(self):
                self.label.visible ^= 1
                if self.full:
                    self.unfull()

        vpython.scene = vpython.canvas()
        vpython.scene.title = "%s" % self.listname  # noqa: E501
        vpython.scene.append_to_caption(
            re.sub(
                r'\%(.*)\%',
                r'\1',
                re.sub(
                    r'\`(.*)\`',
                    r'\1',
                    """Commands:
%Click% to toggle information about a node.
%Double click% to perform a quick web scan on this node.
Camera usage:
`Right button drag or Ctrl-drag` to rotate "camera" to view scene.
`Shift-drag` to move the object around.
`Middle button or Alt-drag` to drag up or down to zoom in or out.
  On a two-button mouse, `middle is wheel or left + right`.
Touch screen: pinch/extend to zoom, swipe or two-finger rotate."""
                )
            )
        )
        vpython.scene.exit = True
        start = vpython.box()
        rings = {}
        tr3d = {}
        for i in trace:
            tr = trace[i]
            tr3d[i] = []
            for t in range(1, max(tr) + 1):
                if t not in rings:
                    rings[t] = []
                if t in tr:
                    if tr[t] not in rings[t]:
                        rings[t].append(tr[t])
                    tr3d[i].append(rings[t].index(tr[t]))
                else:
                    rings[t].append(("unk", -1))
                    tr3d[i].append(len(rings[t]) - 1)

        for t in rings:
            r = rings[t]
            tmp_len = len(r)
            for i in range(tmp_len):
                if r[i][1] == -1:
                    col = vpython.vec(0.75, 0.75, 0.75)
                elif r[i][1]:
                    col = vpython.color.green
                else:
                    col = vpython.color.blue

                s = IPsphere(pos=vpython.vec((tmp_len - 1) * vpython.cos(2 * i * vpython.pi / tmp_len), (tmp_len - 1) * vpython.sin(2 * i * vpython.pi / tmp_len), 2 * t),  # noqa: E501
                             ip=r[i][0],
                             color=col)
                for trlst in six.itervalues(tr3d):
                    if t <= len(trlst):
                        if trlst[t - 1] == i:
                            trlst[t - 1] = s
        forecol = colgen(0.625, 0.4375, 0.25, 0.125)
        for trlst in six.itervalues(tr3d):
            col = vpython.vec(*next(forecol))
            start = vpython.vec(0, 0, 0)
            for ip in trlst:
                vpython.cylinder(pos=start, axis=ip.pos - start, color=col, radius=0.2)  # noqa: E501
                start = ip.pos

        vpython.rate(50)

        # Keys handling
        # TODO: there is currently no way of closing vpython correctly
        # https://github.com/BruceSherwood/vpython-jupyter/issues/36
        # def keyboard_press(ev):
        #     k = ev.key
        #     if k == "esc" or k == "q":
        #         pass  # TODO: close
        #
        # vpython.scene.bind('keydown', keyboard_press)

        # Mouse handling
        def mouse_click(ev):
            if ev.press == "left":
                o = vpython.scene.mouse.pick
                if o and isinstance(o, IPsphere):
                    if o.check_double_click():
                        if o.ip == "unk":
                            return
                        o.fullinfos()
                    else:
                        o.action()

        vpython.scene.bind('mousedown', mouse_click)

Response: Same than trace3D_notebook but used when ran from Jupyther notebooks


Instruction:
How would you implement a function in Python 3 that
displays traceroute results on a world map.

Response:
def world_trace(self):
        """Display traceroute results on a world map."""

        # Check that the geoip2 module can be imported
        # Doc: http://geoip2.readthedocs.io/en/latest/
        try:
            # GeoIP2 modules need to be imported as below
            import geoip2.database
            import geoip2.errors
        except ImportError:
            warning("Cannot import geoip2. Won't be able to plot the world.")
            return []
        # Check availability of database
        if not conf.geoip_city:
            warning("Cannot import the geolite2 CITY database.\n"
                    "Download it from http://dev.maxmind.com/geoip/geoip2/geolite2/"  # noqa: E501
                    " then set its path to conf.geoip_city")
            return []
        # Check availability of plotting devices
        try:
            import cartopy.crs as ccrs
        except ImportError:
            warning("Cannot import cartopy.\n"
                    "More infos on http://scitools.org.uk/cartopy/docs/latest/installing.html")  # noqa: E501
            return []
        if not MATPLOTLIB:
            warning("Matplotlib is not installed. Won't be able to plot the world.")  # noqa: E501
            return []

        # Open & read the GeoListIP2 database
        try:
            db = geoip2.database.Reader(conf.geoip_city)
        except Exception:
            warning("Cannot open geoip2 database at %s", conf.geoip_city)
            return []

        # Regroup results per trace
        ips = {}
        rt = {}
        ports_done = {}
        for s, r in self.res:
            ips[r.src] = None
            if s.haslayer(TCP) or s.haslayer(UDP):
                trace_id = (s.src, s.dst, s.proto, s.dport)
            elif s.haslayer(ICMP):
                trace_id = (s.src, s.dst, s.proto, s.type)
            else:
                trace_id = (s.src, s.dst, s.proto, 0)
            trace = rt.get(trace_id, {})
            if not r.haslayer(ICMP) or r.type != 11:
                if trace_id in ports_done:
                    continue
                ports_done[trace_id] = None
            trace[s.ttl] = r.src
            rt[trace_id] = trace

        # Get the addresses locations
        trt = {}
        for trace_id in rt:
            trace = rt[trace_id]
            loctrace = []
            for i in range(max(trace)):
                ip = trace.get(i, None)
                if ip is None:
                    continue
                # Fetch database
                try:
                    sresult = db.city(ip)
                except geoip2.errors.AddressNotFoundError:
                    continue
                loctrace.append((sresult.location.longitude, sresult.location.latitude))  # noqa: E501
            if loctrace:
                trt[trace_id] = loctrace

        # Load the map renderer
        plt.figure(num='Scapy')
        ax = plt.axes(projection=ccrs.PlateCarree())
        # Draw countries
        ax.coastlines()
        ax.stock_img()
        # Set normal size
        ax.set_global()
        # Add title
        plt.title("Scapy traceroute results")

        from matplotlib.collections import LineCollection
        from matplotlib import colors as mcolors
        colors_cycle = iter(mcolors.BASE_COLORS)
        lines = []

        # Split traceroute measurement
        for key, trc in six.iteritems(trt):
            # Get next color
            color = next(colors_cycle)
            # Gather mesurments data
            data_lines = [(trc[i], trc[i + 1]) for i in range(len(trc) - 1)]
            # Create line collection
            line_col = LineCollection(data_lines, linewidths=2,
                                      label=key[1],
                                      color=color)
            lines.append(line_col)
            ax.add_collection(line_col)
            # Create map points
            lines.extend([ax.plot(*x, marker='.', color=color) for x in trc])

        # Generate legend
        ax.legend()

        # Call show() if matplotlib is not inlined
        if not MATPLOTLIB_INLINED:
            plt.show()

        # Clean
        ax.remove()

        # Return the drawn lines
        return lines


Instruction:
Can you tell what is the following Python 3 function doing
def m2i(self, pkt, s):
        diff_tag, s = BER_tagging_dec(s, hidden_tag=self.ASN1_tag,
                                      implicit_tag=self.implicit_tag,
                                      explicit_tag=self.explicit_tag,
                                      safe=self.flexible_tag)
        if diff_tag is not None:
            # this implies that flexible_tag was True
            if self.implicit_tag is not None:
                self.implicit_tag = diff_tag
            elif self.explicit_tag is not None:
                self.explicit_tag = diff_tag
        codec = self.ASN1_tag.get_codec(pkt.ASN1_codec)
        if self.flexible_tag:
            return codec.safedec(s, context=self.context)
        else:
            return codec.dec(s, context=self.context)

Response: Decode a string into a single object.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def m2i(self, pkt, s):
        if len(s) == 0:
            raise ASN1_Error("ASN1F_CHOICE: got empty string")
        _, s = BER_tagging_dec(s, hidden_tag=self.ASN1_tag,
                               explicit_tag=self.explicit_tag)
        tag, _ = BER_id_dec(s)
        if tag not in self.choices:
            if self.flexible_tag:
                choice = ASN1F_field
            else:
                raise ASN1_Error("ASN1F_CHOICE: unexpected field")
        else:
            choice = self.choices[tag]
        if hasattr(choice, "ASN1_root"):
            # we don't want to import ASN1_Packet in this module...
            return self.extract_packet(choice, s)
        elif isinstance(choice, type):
            # XXX find a way not to instantiate the ASN1F_field
            return choice(self.name, b"").m2i(pkt, s)
        else:
            # XXX check properly if this is an ASN1F_PACKET
            return choice.m2i(pkt, s)

Response: This method will take a string and return the corresponding field or packet.


Instruction:
Explain what the following Python 3 code does
def igmpize(self):
        gaddr = self.gaddr if hasattr(self, "gaddr") and self.gaddr else "0.0.0.0"  # noqa: E501
        underlayer = self.underlayer
        if self.type not in [0x11, 0x30]:                               # General Rule 1  # noqa: E501
            self.mrcode = 0
        if isinstance(underlayer, IP):
            if (self.type == 0x11):
                if (gaddr == "0.0.0.0"):
                    underlayer.dst = "224.0.0.1"                        # IP rule 1  # noqa: E501
                elif isValidMCAddr(gaddr):
                    underlayer.dst = gaddr                              # IP rule 3a  # noqa: E501
                else:
                    warning("Invalid IGMP Group Address detected !")
                    return False
            elif ((self.type == 0x17) and isValidMCAddr(gaddr)):
                underlayer.dst = "224.0.0.2"                           # IP rule 2  # noqa: E501
            elif ((self.type == 0x12) or (self.type == 0x16)) and (isValidMCAddr(gaddr)):  # noqa: E501
                underlayer.dst = gaddr                                 # IP rule 3b  # noqa: E501
            else:
                warning("Invalid IGMP Type detected !")
                return False
            if not any(isinstance(x, IPOption_Router_Alert) for x in underlayer.options):  # noqa: E501
                underlayer.options.append(IPOption_Router_Alert())
            underlayer.ttl = 1                                         # IP rule 4
            _root = self.firstlayer()
            if _root.haslayer(Ether):
                # Force recalculate Ether dst
                _root[Ether].dst = getmacbyip(underlayer.dst)          # Ether rule 1  # noqa: E501
        from scapy.contrib.igmpv3 import IGMPv3
        if isinstance(self, IGMPv3):
            self.encode_maxrespcode()
        return True

Response: This function will attempt to fixup the IGMP message according to the RFC 2236 section 2. 1.


Instruction:
Explain what the following Python 3 code does
def _bgp_dispatcher(payload):

    cls = conf.raw_layer

    # By default, calling BGP() will build a BGPHeader.
    if payload is None:
        cls = _get_cls("BGPHeader", conf.raw_layer)

    else:
        if len(payload) >= _BGP_HEADER_SIZE and\
                payload[:16] == _BGP_HEADER_MARKER:

            # Get BGP message type
            message_type = orb(payload[18])
            if message_type == 4:
                cls = _get_cls("BGPKeepAlive")
            else:
                cls = _get_cls("BGPHeader")

    return cls

Response: Returns the right class for a given BGP message.


Instruction:
Can you generate the documentation for the following Python 3 function
def _bgp_capability_dispatcher(payload):

    cls = _capabilities_registry["BGPCapGeneric"]

    # By default, calling BGPCapability() will build a "generic" capability.
    if payload is None:
        cls = _capabilities_registry["BGPCapGeneric"]

    else:
        length = len(payload)
        if length >= _BGP_CAPABILITY_MIN_SIZE:
            code = orb(payload[0])
            cls = _get_cls(_capabilities_objects.get(code, "BGPCapGeneric"))

    return cls

Response: Returns the right class for a given BGP capability.


Instruction:
Make a summary of the following Python 3 code
def i2m(self, pkt, i):
        mask, ip = i
        ip = socket.inet_aton(ip)
        return struct.pack(">B", mask) + ip[:self.mask2iplen(mask)]

Response: Internal IP as bytes mask as int to machine name representation.


Instruction:
Can you tell what is the following Python 3 function doing
def i2m(self, pkt, i):
        mask, ip = i
        ip = pton_ntop.inet_pton(socket.AF_INET6, ip)
        return struct.pack(">B", mask) + ip[:self.mask2iplen(mask)]

Response: Internal representation of the internal entry.


Instruction:
How would you code a function in Python 3 to
check that the payload is long enough.

Response:
def pre_dissect(self, s):
        """
        Check that the payload is long enough (at least 2 bytes).
        """
        length = len(s)
        if length < _BGP_CAPABILITY_MIN_SIZE:
            err = " ({}".format(length) + " is < _BGP_CAPABILITY_MIN_SIZE "
            err += "({})).".format(_BGP_CAPABILITY_MIN_SIZE)
            raise _BGPInvalidDataException(err)
        return s


Instruction:
Can you generate a brief explanation for the following Python 3 code
def post_build(self, pkt, pay):
        if self.length is None:
            pkt = pkt[:4] + chb(len(pay)) + pkt[5:]
        return pkt + pay

Response: This method is called when the packet is built and the pay is added to the packet.


Instruction:
Can you generate the documentation for the following Python 3 function
def guess_payload_class(self, payload):
        t = (orb(payload[0]) & 0xf0) >> 4
        if t == 0:
            return ISOTP_SF
        elif t == 1:
            return ISOTP_FF
        elif t == 2:
            return ISOTP_CF
        else:
            return ISOTP_FC

Response: Guesses the ISOTP class from the payload.


Instruction:
Make a summary of the following Python 3 code
def feed(self, can):
        if not isinstance(can, CAN):
            raise Scapy_Exception("argument is not a CAN frame")
        identifier = can.identifier
        data = bytes(can.data)

        if len(data) > 1 and self.use_ext_addr is not True:
            self._try_feed(identifier, None, data)
        if len(data) > 2 and self.use_ext_addr is not False:
            ea = six.indexbytes(data, 0)
            self._try_feed(identifier, ea, data[1:])

Response: Attempt to feed an incoming CAN frame into the state machine.


Instruction:
Explain what the following Python 3 code does
def pop(self, identifier=None, ext_addr=None, basecls=ISOTP):

        if identifier is not None:
            for i in range(len(self.ready)):
                b = self.ready[i]
                identifier = b[0]
                ea = b[1]
                if identifier == identifier and ext_addr == ea:
                    return ISOTPMessageBuilder._build(self.ready.pop(i))
            return None

        if len(self.ready) > 0:
            return ISOTPMessageBuilder._build(self.ready.pop(0))
        return None

Response: Returns an ISOTP message with the specified identifier and extended address.


Instruction:
Here you have a function in Python 3, explain what it does
def begin_send(self, p):
        if hasattr(p, "sent_time"):
            p.sent_time = time.time()

        return self.outs.begin_send(bytes(p))

Response: Begin the transmission of a message p. This method returns after the message has been sent.


Instruction:
Can you generate the documentation for the following Python 3 function
def recv_with_timeout(self, timeout=1):
        msg = self.ins.recv(timeout)
        t = time.time()
        if msg is None:
            raise Scapy_Exception("Timeout")
        return self.basecls, msg, t

Response: Receive a complete ISOTP message blocking until a message is received or the specified timeout is reached.


Instruction:
Create a Python 3 function for
receiving a complete ISOTP message.

Response:
def recv_raw(self, x=0xffff):
        """Receive a complete ISOTP message, blocking until a message is
        received or the specified timeout is reached.
        If self.timeout is 0, then this function doesn't block and returns the
        first frame in the receive buffer or None if there isn't any."""
        msg = self.ins.recv()
        t = time.time()
        return self.basecls, msg, t


Instruction:
Can you generate the documentation for the following Python 3 function
def select(sockets, remain=None):
        blocking = remain is None or remain > 0

        def find_ready_sockets():
            return list(filter(lambda x: not x.ins.rx_queue.empty(), sockets))

        ready_sockets = find_ready_sockets()
        if len(ready_sockets) > 0 or not blocking:
            return ready_sockets, None

        exit_select = Event()

        def my_cb(msg):
            exit_select.set()

        try:
            for s in sockets:
                s.ins.rx_callbacks.append(my_cb)

            exit_select.wait(remain)

        finally:
            for s in sockets:
                try:
                    s.ins.rx_callbacks.remove(my_cb)
                except ValueError:
                    pass

        ready_sockets = find_ready_sockets()
        return ready_sockets, None

Response: This function is called during sendrecv routine to wait for a set of sockets to be ready to receive a new entry.


Instruction:
Explain what the following Python 3 code does
def set_timeout(self, timeout, callback):
        if not self._ready_sem.acquire(False):
            raise Scapy_Exception("Timer was already started")

        self._callback = callback
        self._timeout = timeout
        self._cancelled.clear()
        self._busy_sem.release()

Response: Call callback in timeout seconds unless cancelled.


Instruction:
Create a Python 3 function to
stop the timer without executing the callback.

Response:
def cancel(self):
        """Stop the timer without executing the callback."""
        self._cancelled.set()
        if not self._dead:
            self._ready_sem.acquire()
            self._ready_sem.release()


Instruction:
Here you have a function in Python 3, explain what it does
def stop(self):
        if not self._dead:
            self._killed = True
            self._cancelled.set()
            self._busy_sem.release()
            self.join()
            if not self._ready_sem.acquire(False):
                warning("ISOTP Timer thread may not have stopped "
                        "correctly")

Response: Stop the thread making this object unusable.


Instruction:
Can you create a Python 3 function that
functions that must be called every time a CAN frame is received. to is called every time a CAN frame is received. to is advance the state machine.

Response:
def on_recv(self, cf):
        """Function that must be called every time a CAN frame is received, to
        advance the state machine."""

        data = bytes(cf.data)

        if len(data) < 2:
            return

        ae = 0
        if self.extended_rx_addr is not None:
            ae = 1
            if len(data) < 3:
                return
            if six.indexbytes(data, 0) != self.extended_rx_addr:
                return

        n_pci = six.indexbytes(data, ae) & 0xf0

        if n_pci == N_PCI_FC:
            with self.tx_mutex:
                self._recv_fc(data[ae:])
        elif n_pci == N_PCI_SF:
            with self.rx_mutex:
                self._recv_sf(data[ae:])
        elif n_pci == N_PCI_FF:
            with self.rx_mutex:
                self._recv_ff(data[ae:])
        elif n_pci == N_PCI_CF:
            with self.rx_mutex:
                self._recv_cf(data[ae:])


Instruction:
Given the following Python 3 function, write the documentation
def _recv_fc(self, data):
        if (self.tx_state != ISOTP_WAIT_FC and
                self.tx_state != ISOTP_WAIT_FIRST_FC):
            return 0

        self.tx_timer.cancel()

        if len(data) < 3:
            self.tx_state = ISOTP_IDLE
            self.tx_exception = "CF frame discarded because it was too short"
            self.tx_done.set()
            raise Scapy_Exception(self.tx_exception)

        # get communication parameters only from the first FC frame
        if self.tx_state == ISOTP_WAIT_FIRST_FC:
            self.txfc_bs = six.indexbytes(data, 1)
            self.txfc_stmin = six.indexbytes(data, 2)

        if ((self.txfc_stmin > 0x7F) and
                ((self.txfc_stmin < 0xF1) or (self.txfc_stmin > 0xF9))):
            self.txfc_stmin = 0x7F

        if six.indexbytes(data, 2) <= 127:
            tx_gap = six.indexbytes(data, 2) / 1000.0
        elif 0xf1 <= six.indexbytes(data, 2) <= 0xf9:
            tx_gap = (six.indexbytes(data, 2) & 0x0f) / 10000.0
        else:
            tx_gap = 0
        self.tx_gap = tx_gap

        self.tx_state = ISOTP_WAIT_FC

        isotp_fc = six.indexbytes(data, 0) & 0x0f

        if isotp_fc == ISOTP_FC_CTS:
            self.tx_bs = 0
            self.tx_state = ISOTP_SENDING
            # start cyclic timer for sending CF frame
            self.tx_timer.set_timeout(self.tx_gap, self._tx_timer_handler)
        elif isotp_fc == ISOTP_FC_WT:
            # start timer to wait for next FC frame
            self.tx_state = ISOTP_WAIT_FC
            self.tx_timer.set_timeout(self.fc_timeout, self._tx_timer_handler)
        elif isotp_fc == ISOTP_FC_OVFLW:
            # overflow in receiver side
            self.tx_state = ISOTP_IDLE
            self.tx_exception = "Overflow happened at the receiver side"
            self.tx_done.set()
            raise Scapy_Exception(self.tx_exception)
        else:
            self.tx_state = ISOTP_IDLE
            self.tx_exception = "Unknown FC frame type"
            self.tx_done.set()
            raise Scapy_Exception(self.tx_exception)

        return 0

Response: Process a received Flow Control frame and return the corresponding ISO - 8601 version of the data.


Instruction:
Given the following Python 3 function, write the documentation
def _recv_sf(self, data):
        self.rx_timer.cancel()
        if self.rx_state != ISOTP_IDLE:
            warning("RX state was reset because single frame was received")
            self.rx_state = ISOTP_IDLE

        length = six.indexbytes(data, 0) & 0xf
        if len(data) - 1 < length:
            return 1

        msg = data[1:1 + length]
        self.rx_queue.put(msg)
        for cb in self.rx_callbacks:
            cb(msg)
        self.call_release()
        return 0

Response: Process a single frame from the broker.


Instruction:
Can you tell what is the following Python 3 function doing
def _recv_ff(self, data):
        self.rx_timer.cancel()
        if self.rx_state != ISOTP_IDLE:
            warning("RX state was reset because first frame was received")
            self.rx_state = ISOTP_IDLE

        if len(data) < 7:
            return 1
        self.rx_ll_dl = len(data)

        # get the FF_DL
        self.rx_len = (six.indexbytes(data, 0) & 0x0f) * 256 + six.indexbytes(
            data, 1)
        ff_pci_sz = 2

        # Check for FF_DL escape sequence supporting 32 bit PDU length
        if self.rx_len == 0:
            # FF_DL = 0 => get real length from next 4 bytes
            self.rx_len = six.indexbytes(data, 2) << 24
            self.rx_len += six.indexbytes(data, 3) << 16
            self.rx_len += six.indexbytes(data, 4) << 8
            self.rx_len += six.indexbytes(data, 5)
            ff_pci_sz = 6

        # copy the first received data bytes
        data_bytes = data[ff_pci_sz:]
        self.rx_idx = len(data_bytes)
        self.rx_buf = data_bytes

        # initial setup for this pdu reception
        self.rx_sn = 1
        self.rx_state = ISOTP_WAIT_DATA

        # no creation of flow control frames
        if not self.listen_mode:
            # send our first FC frame
            load = self.ea_hdr
            load += struct.pack("BBB", N_PCI_FC, self.rxfc_bs, self.rxfc_stmin)
            self.can_send(load)

        # wait for a CF
        self.rx_bs = 0
        self.rx_timer.set_timeout(self.cf_timeout, self._rx_timer_handler)

        return 0

Response: Process a first Frame frame from the packet.


Instruction:
Create a Python 3 function to
process a received Consecutive Frame frame and return the next CF.

Response:
def _recv_cf(self, data):
        """Process a received 'Consecutive Frame' frame"""
        if self.rx_state != ISOTP_WAIT_DATA:
            return 0

        self.rx_timer.cancel()

        # CFs are never longer than the FF
        if len(data) > self.rx_ll_dl:
            return 1

        # CFs have usually the LL_DL length
        if len(data) < self.rx_ll_dl:
            # this is only allowed for the last CF
            if self.rx_len - self.rx_idx > self.rx_ll_dl:
                warning("Received a CF with insuffifient length")
                return 1

        if six.indexbytes(data, 0) & 0x0f != self.rx_sn:
            # Wrong sequence number
            warning("RX state was reset because wrong sequence number was "
                    "received")
            self.rx_state = ISOTP_IDLE
            return 1

        self.rx_sn = (self.rx_sn + 1) % 16
        self.rx_buf += data[1:]
        self.rx_idx = len(self.rx_buf)

        if self.rx_idx >= self.rx_len:
            # we are done
            self.rx_buf = self.rx_buf[0:self.rx_len]
            self.rx_state = ISOTP_IDLE
            self.rx_queue.put(self.rx_buf)
            for cb in self.rx_callbacks:
                cb(self.rx_buf)
            self.call_release()
            self.rx_buf = None
            return 0

        # perform blocksize handling, if enabled
        if self.rxfc_bs != 0:
            self.rx_bs += 1

            # check if we reached the end of the block
            if self.rx_bs >= self.rxfc_bs and not self.listen_mode:
                # send our FC frame
                load = self.ea_hdr
                load += struct.pack("BBB", N_PCI_FC, self.rxfc_bs,
                                    self.rxfc_stmin)
                self.can_send(load)

        # wait for another CF
        self.rx_timer.set_timeout(self.cf_timeout, self._rx_timer_handler)
        return 0