Esempio n. 1
0
    def __repr__(self) -> str:
        element_list = []

        if self.typecode == Typecode.DATETIME:
            element_list.append("data={:s}".format(str(self.data)))
        else:
            try:
                element_list.append("data=" + self.to_str())
            except UnicodeEncodeError:
                element_list.append("data={}".format(MultiByteStrDecoder(self.data).unicode_str))

        element_list.extend(
            [
                "type={:s}".format(self.typename),
                "align={}".format(self.align.align_string),
                "ascii_width={:d}".format(self.ascii_char_width),
            ]
        )

        if Integer(self.length).is_type():
            element_list.append("length={}".format(self.length))

        if Integer(self.integer_digits).is_type():
            element_list.append("int_digits={}".format(self.integer_digits))

        if Integer(self.decimal_places).is_type():
            element_list.append("decimal_places={}".format(self.decimal_places))

        if Integer(self.additional_format_len).is_type():
            element_list.append("extra_len={}".format(self.additional_format_len))

        return ", ".join(element_list)
Esempio n. 2
0
    def get_decimal_places(self, value):
        from typepy import Integer

        int_type = Integer(value)

        float_digit_len = 0
        if int_type.is_type():
            abs_value = abs(int_type.convert())
        else:
            abs_value = abs(float(value))
            text_value = text_type(abs_value)
            float_text = 0
            if text_value.find(".") != -1:
                float_text = text_value.split(".")[1]
                float_digit_len = len(float_text)
            elif text_value.find("e-") != -1:
                float_text = text_value.split("e-")[1]
                float_digit_len = int(float_text) - 1

        abs_digit = self.__min_digit_len
        for treshold in self.__tresholds:
            if abs_value < math.pow(10, treshold.pow):
                abs_digit = treshold.digit_len
                break

        return min(abs_digit, float_digit_len)
Esempio n. 3
0
    def get_decimal_places(self, value):
        from typepy import Integer

        int_type = Integer(value)

        float_digit_len = 0
        if int_type.is_type():
            abs_value = abs(int_type.convert())
        else:
            abs_value = abs(float(value))
            text_value = text_type(abs_value)
            float_text = 0
            if text_value.find(".") != -1:
                float_text = text_value.split(".")[1]
                float_digit_len = len(float_text)
            elif text_value.find("e-") != -1:
                float_text = text_value.split("e-")[1]
                float_digit_len = int(float_text) - 1

        abs_digit = self.__min_digit_len
        for treshold in self.__tresholds:
            if abs_value < math.pow(10, treshold.pow):
                abs_digit = treshold.digit_len
                break

        return min(abs_digit, float_digit_len)
Esempio n. 4
0
    def __get_filter_key(self, filter_param):
        src_network_format = Tc.Param.SRC_NETWORK + "={:s}"
        dst_network_format = Tc.Param.DST_NETWORK + "={:s}"
        protocol_format = Tc.Param.PROTOCOL + "={:s}"
        key_item_list = []

        if Tc.Param.HANDLE in filter_param:
            handle = filter_param.get(Tc.Param.HANDLE)
            Integer(handle).validate()
            handle = int(handle)

            for mangle in self.__iptables_ctrl.parse():
                if mangle.mark_id != handle:
                    continue

                key_item_list.append(
                    dst_network_format.format(mangle.destination))
                if typepy.is_not_null_string(mangle.source):
                    key_item_list.append("{:s}={:s}".format(
                        Tc.Param.SRC_NETWORK, mangle.source))
                key_item_list.append(protocol_format.format(mangle.protocol))

                break
            else:
                raise ValueError("mangle mark not found: {}".format(mangle))
        else:
            src_network = filter_param.get(Tc.Param.SRC_NETWORK)
            if typepy.is_not_null_string(
                    src_network) and not is_anywhere_network(
                        src_network, self.__ip_version):
                key_item_list.append(src_network_format.format(src_network))

            dst_network = filter_param.get(Tc.Param.DST_NETWORK)
            if typepy.is_not_null_string(
                    dst_network) and not is_anywhere_network(
                        dst_network, self.__ip_version):
                key_item_list.append(dst_network_format.format(dst_network))

            src_port = filter_param.get(Tc.Param.SRC_PORT)
            if Integer(src_port).is_type():
                port_format = Tc.Param.SRC_PORT + "={:d}"
                key_item_list.append(port_format.format(src_port))

            dst_port = filter_param.get(Tc.Param.DST_PORT)
            if Integer(dst_port).is_type():
                port_format = Tc.Param.DST_PORT + "={:d}"
                key_item_list.append(port_format.format(dst_port))

            protocol = filter_param.get(Tc.Param.PROTOCOL)
            if typepy.is_not_null_string(protocol):
                key_item_list.append(protocol_format.format(protocol))

        return ", ".join(key_item_list)
Esempio n. 5
0
    def _parse_icmp_reply(self, ping_line_list):
        icmp_reply_regexp = re.compile(self._icmp_reply_pattern, re.IGNORECASE)
        duplicate_packet_regexp = re.compile(self._duplicate_packet_pattern)
        icmp_reply_list = []

        for line in ping_line_list:
            match = icmp_reply_regexp.search(line)
            if not match:
                continue

            reply = match.groupdict()

            if reply.get("timestamp"):
                reply["timestamp"] = datetime.fromtimestamp(
                    Integer(reply["timestamp"].lstrip("[").rstrip(
                        "]")).force_convert())

            if reply.get("icmp_seq"):
                reply["icmp_seq"] = int(reply["icmp_seq"])

            if reply.get("ttl"):
                reply["ttl"] = int(reply["ttl"])

            if reply.get("time"):
                reply["time"] = float(reply["time"])

            if duplicate_packet_regexp.search(line):
                reply["duplicate"] = True
            else:
                reply["duplicate"] = False

            icmp_reply_list.append(reply)

        return icmp_reply_list
Esempio n. 6
0
    def to_append_command(self):
        Integer(self.mark_id).validate()

        command_item_list = [
            "{:s} -A {:s} -t mangle -j MARK".format(get_iptables_base_command(), self.chain),
            "--set-mark {}".format(self.mark_id),
        ]

        if typepy.is_not_null_string(self.protocol) or Integer(self.protocol).is_type():
            command_item_list.append("-p {}".format(self.protocol))
        if self.__is_valid_srcdst(self.source):
            command_item_list.append("-s {:s}".format(self.source))
        if self.__is_valid_srcdst(self.destination):
            command_item_list.append("-d {:s}".format(self.destination))

        return " ".join(command_item_list)
Esempio n. 7
0
    def __get_cell_style(self, col):
        import xlwt

        if col in self.__col_style_table:
            return self.__col_style_table.get(col)

        try:
            col_dp = self._column_dp_list[col]
        except KeyError:
            return {}

        if col_dp.typecode not in [typepy.Typecode.REAL_NUMBER]:
            raise ValueError()

        if not Integer(col_dp.minmax_decimal_places.max_value).is_type():
            raise ValueError()

        float_digit = col_dp.minmax_decimal_places.max_value
        if float_digit <= 0:
            raise ValueError()

        num_format_str = "#,{:s}0.{:s}".format("#" * int(float_digit),
                                               "0" * int(float_digit))
        cell_style = xlwt.easyxf(num_format_str=num_format_str)
        self.__col_style_table[col] = cell_style

        return cell_style
Esempio n. 8
0
    def _get_count_option(self) -> str:
        try:
            count = Integer(self.count).convert()
        except TypeConversionError:
            return ""

        return "-n {:d}".format(count)
Esempio n. 9
0
    def __get_number_property(self, col):
        if col in self.__col_numprops_table:
            return self.__col_numprops_table.get(col)

        try:
            col_dp = self._column_dp_list[col]
        except KeyError:
            return {}

        if col_dp.typecode not in [
                typepy.Typecode.INTEGER, typepy.Typecode.REAL_NUMBER
        ]:
            return {}

        num_props = {}
        if Integer(col_dp.minmax_decimal_places.max_value).is_type():
            float_digit = col_dp.minmax_decimal_places.max_value
            if float_digit > 0:
                num_props = {
                    "num_format": "0.{:s}".format("0" * int(float_digit))
                }

        self.__col_numprops_table[col] = num_props

        return num_props
Esempio n. 10
0
    def __exeute_method(self, method, value):
        try:
            result = getattr(self.typeclass(value, self.strict_level),
                             method)()
            if method == "validate":
                result = "-"
        except (TypeError, typepy.TypeConversionError):
            return '"E"'

        # for string tests
        if NullString(result, StrictLevel.MAX).is_type():
            return '""'

        strict_level = StrictLevel.MAX

        typeobj = Integer(result, strict_level)
        if typeobj.is_type():
            return typeobj.convert()

        typeobj = RealNumber(result, strict_level)
        if typeobj.is_type():
            return typeobj.convert()

        if String(result, strict_level).is_type():
            return '"{}"'.format(result)

        if Infinity(result, strict_level).is_type():
            return '"inf"'

        if Nan(result, strict_level).is_type():
            return '"nan"'

        return result
Esempio n. 11
0
    def __set_cell_width(self):
        font_size = self.__cell_format_property.get("font_size")

        if not Integer(font_size).is_type():
            return

        for col_idx, col_dp in enumerate(self._column_dp_list):
            width = min(col_dp.ascii_char_width, self.MAX_CELL_WIDTH) * (font_size / 10.0) + 2
            self.stream.set_column(col_idx, col_idx, width=width)
Esempio n. 12
0
    def __get_count_option(self):
        try:
            count = Integer(self.count).convert()
        except TypeConversionError:
            return ""

        if self.__is_windows():
            return "-n {:d}".format(count)

        return "-c {:d}".format(count)
Esempio n. 13
0
    def __validate_deadline(self):
        if self.deadline is None:
            return

        try:
            deadline = Integer(self.deadline).convert()
        except typepy.TypeConversionError:
            raise ValueError("deadline must be an integer: actual={}".format(self.deadline))

        if deadline <= 0:
            raise ValueError("deadline must be greater than zero: actual={}".format(self.deadline))
Esempio n. 14
0
    def __validate_count(self) -> None:
        if self.count is None:
            return

        try:
            count = Integer(self.count).convert()
        except TypeConversionError as e:
            raise ValueError("count must be an integer: {}".format(e))

        if count <= 0:
            raise ValueError("count must be greater than zero")
Esempio n. 15
0
    def __validate_count(self):
        if self.count is None:
            return

        try:
            count = Integer(self.count).convert()
        except typepy.TypeConversionError:
            raise ValueError("count must be an integer: actual={}".format(self.count))

        if count <= 0:
            raise ValueError("count must be greater than zero")
Esempio n. 16
0
    def __repr__(self, *args, **kwargs):
        str_list = []

        if Integer(self.line_number).is_type():
            str_list.append("line-num={}".format(self.line_number))

        str_list.extend([
            "protocol={:s}".format(self.protocol),
            "source={:s}".format(self.source),
            "destination={:s}".format(self.destination),
            "mark_id={:d}".format(self.mark_id),
            "chain={:s}".format(self.chain),
        ])

        return ", ".join(str_list)
Esempio n. 17
0
    def __repr__(self):
        element_list = []

        if self.column_index is not None:
            element_list.append("column={}".format(self.column_index))

        element_list.extend([
            "type={}".format(self.typename),
            "align={}".format(self.align.align_string),
            "ascii_width={}".format(six.text_type(self.ascii_char_width)),
        ])

        if Integer(self.bit_length).is_type():
            element_list.append("bit_len={:d}".format(self.bit_length))

        if self.minmax_integer_digits.has_value():
            if self.minmax_integer_digits.is_same_value():
                value = "int_digits={}".format(
                    self.minmax_integer_digits.min_value)
            else:
                value = "int_digits=({})".format(self.minmax_integer_digits)

            element_list.append(value)

        if self.minmax_decimal_places.has_value():
            if self.minmax_decimal_places.is_same_value():
                value = "decimal_places={}".format(
                    self.minmax_decimal_places.min_value)
            else:
                value = "decimal_places=({})".format(
                    self.minmax_decimal_places)

            element_list.append(value)

        if not self.minmax_additional_format_len.is_zero():
            if self.minmax_additional_format_len.is_same_value():
                value = "extra_len={}".format(
                    self.minmax_additional_format_len.min_value)
            else:
                value = "extra_len=({})".format(
                    self.minmax_additional_format_len)

            element_list.append(value)

        return ", ".join(element_list)
Esempio n. 18
0
    def __get_deadline_option(self):
        try:
            deadline = Integer(self.deadline).convert()
        except typepy.TypeConversionError:
            if self.count:
                return ""

            deadline = DEFAULT_DEADLINE

        if self.__is_windows():
            # ping for Windows not have the option with equals to the deadline
            # option.
            return "-n {:d}".format(deadline)
        elif self.__is_macos():
            if self.__is_ipv6():
                # there is no timeout option for macOS ping6.
                # so, using -i and -c option to simulate timeout.
                return "-i 1 -c {:d}".format(deadline)

            return "-t {:d}".format(deadline)

        return "-w {:d}".format(deadline)
Esempio n. 19
0
def get_integer_digit(value) -> int:
    float_type = RealNumber(value)

    try:
        abs_value = abs(float_type.convert())
    except TypeConversionError:
        try:
            abs_value = abs(Integer(value).convert())
        except TypeConversionError:
            raise ValueError(
                "the value must be a number: value='{}' type='{}'".format(
                    value, type(value)))

        return len(str(abs_value))

    if abs_value.is_zero():
        return 1

    try:
        return len(
            str(abs_value.quantize(Decimal("1."),
                                   rounding=decimal.ROUND_DOWN)))
    except decimal.InvalidOperation:
        return len(str(abs_value))
Esempio n. 20
0
def _to_int(value) -> Optional[int]:
    try:
        return Integer(value, strict_level=StrictLevel.MIN).convert()
    except TypeConversionError:
        return None
Esempio n. 21
0
    def to_delete_command(self):
        Integer(self.line_number).validate()

        return "{:s} -t mangle -D {:s} {}".format(
            get_iptables_base_command(), self.chain, self.line_number
        )