Skip to content

# Rpz policy2subject

The tool to check the availability or syntax of domain, IP or URL.

::

    ██████╗ ██╗   ██╗███████╗██╗   ██╗███╗   ██╗ ██████╗███████╗██████╗ ██╗     ███████╗
    ██╔══██╗╚██╗ ██╔╝██╔════╝██║   ██║████╗  ██║██╔════╝██╔════╝██╔══██╗██║     ██╔════╝
    ██████╔╝ ╚████╔╝ █████╗  ██║   ██║██╔██╗ ██║██║     █████╗  ██████╔╝██║     █████╗
    ██╔═══╝   ╚██╔╝  ██╔══╝  ██║   ██║██║╚██╗██║██║     ██╔══╝  ██╔══██╗██║     ██╔══╝
    ██║        ██║   ██║     ╚██████╔╝██║ ╚████║╚██████╗███████╗██████╔╝███████╗███████╗
    ╚═╝        ╚═╝   ╚═╝      ╚═════╝ ╚═╝  ╚═══╝ ╚═════╝╚══════╝╚═════╝ ╚══════╝╚══════╝

Provides the conversion of the an RPZ POlicy into testable subjects.

Author: Nissar Chababy, @funilrys, contactTATAfunilrysTODTODcom

Special thanks: https://pyfunceble.github.io/#/special-thanks

Contributors: https://pyfunceble.github.io/#/contributors

Project link: https://github.com/funilrys/PyFunceble

Project documentation: https://docs.pyfunceble.com

Project homepage: https://pyfunceble.github.io/

License: ::

    Copyright 2017, 2018, 2019, 2020, 2022, 2023, 2024 Nissar Chababy

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        https://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

## `RPZPolicy2Subject`

Bases: `RPZInputLine2Subject`

Converts/Extracts the subject from the given RPZ Policy into a subject.

Source code in `PyFunceble/converter/rpz_policy2subject.py`

     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308

    class RPZPolicy2Subject(RPZInputLine2Subject):
        """
        Converts/Extracts the subject from the given RPZ Policy into a subject.
        """

        CLEANUP_MARKERS: list = [".rpz-nsdname"]
        IP_MARKERS: list = [".rpz-client-ip", ".rpz-ip", ".rpz-nsip"]

        _soa: Optional[str] = None
        _soas: List[str] = []
        wilcard2subject: Optional[Wildcard2Subject] = None

        def __init__(
            self,
            data_to_convert: Optional[Any] = None,
            soas: Optional[List[str]] = None,
            soa: Optional[str] = None,
            *,
            wildcard2subject: Optional[Wildcard2Subject] = None,
        ) -> None:
            if soas is not None:
                self.soas = soas

            if soa is not None:
                self.soa = soa

            if wildcard2subject is not None:
                self.wilcard2subject = wildcard2subject
            else:
                self.wilcard2subject = Wildcard2Subject()

            super().__init__(data_to_convert=data_to_convert)

        @property
        def soa(self) -> Optional[str]:
            """
            Provides the currently set SOA.
            """

            return self._soa

        @soa.setter
        def soa(self, value: str) -> None:
            """
            Sets the current SOA.

            :param value:
                The value to set.

            :raise TypeError:
                When the given :code:`value` is not a :py:class`str`.
            :raise ValueError:
                When the given :code:`value` is empty.
            """

            if not isinstance(value, str):
                raise TypeError(f"<value> should be {str}, {type(value)} given.")

            if not value:
                raise ValueError("<value> should not be empty.")

            self._soa = value

            if value not in self._soas:
                self._soas.append(value)

        def set_soa(self, value: str) -> "RPZPolicy2Subject":
            """
            Sets the current SOA.

            :param value:
                The value to set.
            """

            self.soa = value

            return self

        @property
        def soas(self) -> Optional[str]:
            """
            Provides the currently set SOAs.
            """

            return self._soas

        @soas.setter
        def soas(self, value: List[str]) -> None:
            """
            Sets the current SOAs.

            :param value:
                The value to set.

            :raise TypeError:
                When the given :code:`value` is not a :py:class`list`.
            :raise ValueError:
                When one of the given value is not a string.
            """

            if not isinstance(value, list):
                raise TypeError(f"<value> should be {list}, {type(value)} given.")

            if any(not isinstance(x, str) for x in value):
                raise ValueError(f"<value> {value!r} should only contain strings.")

            self._soas = value

        def set_soas(self, value: List[str]) -> "RPZPolicy2Subject":
            """
            Sets the current SOAs.

            :param value:
                The value to set.
            """

            self.soas = value

            return self

        @staticmethod
        def remove_marker(subject: str, marker: str) -> str:
            """
            Removes the given marker from the given subject.
            """

            if marker in subject:
                return subject[: subject.find(marker)]
            return subject

        @classmethod
        def get_matching_cleanup_marker(cls, subject: str) -> Optional[str]:
            """
            Checks if the given subject has a cleanup marker and provides it if found.
            """

            for marker in cls.CLEANUP_MARKERS:
                if subject.endswith(marker):
                    return marker
            return None

        @classmethod
        def get_matching_ip_marker(cls, subject: str) -> Optional[str]:
            """
            Checks if the given subject has an IP marker and provides it if found.
            """

            for marker in cls.IP_MARKERS:
                if subject.endswith(marker):
                    return marker
            return None

        @classmethod
        def get_subject_from_ip_marker(cls, subject: str, marker: str) -> str:
            """
            Removes the ip marker and converts the IP into a testable subject.
            """

            result = cls.remove_marker(subject, marker)

            splitted_reversed_result = list(reversed(result.split(".")))

            if (
                len(splitted_reversed_result) > 4
                and splitted_reversed_result[-1].isdigit()
                and len(splitted_reversed_result[-1]) <= 2
                and 0 <= int(splitted_reversed_result[-1]) <= 32
            ):
                result = (
                    ".".join(splitted_reversed_result[:-1])
                    + f"/{splitted_reversed_result[-1]}"
                )
            else:
                result = ".".join(splitted_reversed_result)

            possible_range = result[result.rfind(".") + 1 :]

            if (
                ".zz." in result
                and possible_range.isdigit()
                and len(possible_range) <= 3
                and 0 <= int(possible_range) <= 128
            ):
                result = "/".join(result.rsplit(".", 1)).replace(".", ":")

            if "zz" in result:
                result = (
                    result.replace(".zz.", "::")
                    .replace(":zz:", "::")
                    .replace(".zz", "::")
                    .replace(":zz", "::")
                    .replace("zz.", "::")
                    .replace("zz:", "::")
                    .replace(".", ":")
                )

            if any(x.isalpha() for x in result):
                result = result.replace(".", ":")

            return result

        def get_converted(self) -> Optional[str]:
            """
            Provides the converted data.
            """

            return self.convert(self.data_to_convert)

        def convert(self, data: Any, *, aggressive: bool = False) -> Optional[str]:
            """
            Converts the given dataset.

            :param data:
                The data to convert.
            """

            _ = aggressive
            subject = data.strip()

            if (
                subject
                and not any(subject.startswith(x) for x in self.COMMENT)
                and not any(subject.startswith(x) for x in self.SPECIAL)
            ):
                for comment_sign in self.COMMENT:
                    if comment_sign in subject:
                        subject = self.remove_marker(subject, comment_sign).strip()

                subject = self.wilcard2subject.convert(subject)

                if self._soas:
                    for soa in self._soas:
                        subject = self.remove_marker(subject, f".{soa}")
                        subject = self.remove_marker(subject, soa)

                found_cleanup_marker = self.get_matching_cleanup_marker(subject)

                if found_cleanup_marker:
                    return self.remove_marker(subject, found_cleanup_marker)

                found_ip_marker = self.get_matching_ip_marker(subject)

                if found_ip_marker:
                    return self.get_subject_from_ip_marker(subject, found_ip_marker)

                return subject

            return None

### `soa: Optional[str]` `property` `writable`

Provides the currently set SOA.

### `soas: Optional[str]` `property` `writable`

Provides the currently set SOAs.

### `convert(data, *, aggressive=False)`

Converts the given dataset.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`data` | `Any` | The data to convert. | required

Source code in `PyFunceble/converter/rpz_policy2subject.py`

    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308

    def convert(self, data: Any, *, aggressive: bool = False) -> Optional[str]:
        """
        Converts the given dataset.

        :param data:
            The data to convert.
        """

        _ = aggressive
        subject = data.strip()

        if (
            subject
            and not any(subject.startswith(x) for x in self.COMMENT)
            and not any(subject.startswith(x) for x in self.SPECIAL)
        ):
            for comment_sign in self.COMMENT:
                if comment_sign in subject:
                    subject = self.remove_marker(subject, comment_sign).strip()

            subject = self.wilcard2subject.convert(subject)

            if self._soas:
                for soa in self._soas:
                    subject = self.remove_marker(subject, f".{soa}")
                    subject = self.remove_marker(subject, soa)

            found_cleanup_marker = self.get_matching_cleanup_marker(subject)

            if found_cleanup_marker:
                return self.remove_marker(subject, found_cleanup_marker)

            found_ip_marker = self.get_matching_ip_marker(subject)

            if found_ip_marker:
                return self.get_subject_from_ip_marker(subject, found_ip_marker)

            return subject

        return None

### `get_converted()`

Provides the converted data.

Source code in `PyFunceble/converter/rpz_policy2subject.py`

    262
    263
    264
    265
    266
    267

    def get_converted(self) -> Optional[str]:
        """
        Provides the converted data.
        """

        return self.convert(self.data_to_convert)

### `get_matching_cleanup_marker(subject)` `classmethod`

Checks if the given subject has a cleanup marker and provides it if found.

Source code in `PyFunceble/converter/rpz_policy2subject.py`

    191
    192
    193
    194
    195
    196
    197
    198
    199
    200

    @classmethod
    def get_matching_cleanup_marker(cls, subject: str) -> Optional[str]:
        """
        Checks if the given subject has a cleanup marker and provides it if found.
        """

        for marker in cls.CLEANUP_MARKERS:
            if subject.endswith(marker):
                return marker
        return None

### `get_matching_ip_marker(subject)` `classmethod`

Checks if the given subject has an IP marker and provides it if found.

Source code in `PyFunceble/converter/rpz_policy2subject.py`

    202
    203
    204
    205
    206
    207
    208
    209
    210
    211

    @classmethod
    def get_matching_ip_marker(cls, subject: str) -> Optional[str]:
        """
        Checks if the given subject has an IP marker and provides it if found.
        """

        for marker in cls.IP_MARKERS:
            if subject.endswith(marker):
                return marker
        return None

### `get_subject_from_ip_marker(subject, marker)` `classmethod`

Removes the ip marker and converts the IP into a testable subject.

Source code in `PyFunceble/converter/rpz_policy2subject.py`

    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260

    @classmethod
    def get_subject_from_ip_marker(cls, subject: str, marker: str) -> str:
        """
        Removes the ip marker and converts the IP into a testable subject.
        """

        result = cls.remove_marker(subject, marker)

        splitted_reversed_result = list(reversed(result.split(".")))

        if (
            len(splitted_reversed_result) > 4
            and splitted_reversed_result[-1].isdigit()
            and len(splitted_reversed_result[-1]) <= 2
            and 0 <= int(splitted_reversed_result[-1]) <= 32
        ):
            result = (
                ".".join(splitted_reversed_result[:-1])
                + f"/{splitted_reversed_result[-1]}"
            )
        else:
            result = ".".join(splitted_reversed_result)

        possible_range = result[result.rfind(".") + 1 :]

        if (
            ".zz." in result
            and possible_range.isdigit()
            and len(possible_range) <= 3
            and 0 <= int(possible_range) <= 128
        ):
            result = "/".join(result.rsplit(".", 1)).replace(".", ":")

        if "zz" in result:
            result = (
                result.replace(".zz.", "::")
                .replace(":zz:", "::")
                .replace(".zz", "::")
                .replace(":zz", "::")
                .replace("zz.", "::")
                .replace("zz:", "::")
                .replace(".", ":")
            )

        if any(x.isalpha() for x in result):
            result = result.replace(".", ":")

        return result

### `remove_marker(subject, marker)` `staticmethod`

Removes the given marker from the given subject.

Source code in `PyFunceble/converter/rpz_policy2subject.py`

    181
    182
    183
    184
    185
    186
    187
    188
    189

    @staticmethod
    def remove_marker(subject: str, marker: str) -> str:
        """
        Removes the given marker from the given subject.
        """

        if marker in subject:
            return subject[: subject.find(marker)]
        return subject

### `set_soa(value)`

Sets the current SOA.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`value` | `str` | The value to set. | required

Source code in `PyFunceble/converter/rpz_policy2subject.py`

    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137

    def set_soa(self, value: str) -> "RPZPolicy2Subject":
        """
        Sets the current SOA.

        :param value:
            The value to set.
        """

        self.soa = value

        return self

### `set_soas(value)`

Sets the current SOAs.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`value` | `List[str]` | The value to set. | required

Source code in `PyFunceble/converter/rpz_policy2subject.py`

    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179

    def set_soas(self, value: List[str]) -> "RPZPolicy2Subject":
        """
        Sets the current SOAs.

        :param value:
            The value to set.
        """

        self.soas = value

        return self