File: transforms.py

package info (click to toggle)
python-gvm 26.5.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 5,132 kB
  • sloc: python: 44,662; makefile: 18
file content (70 lines) | stat: -rw-r--r-- 1,874 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# SPDX-FileCopyrightText: 2018-2024 Greenbone AG
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
"""
Module for transforming responses
"""
from lxml import etree

from gvm.protocols.core import Response

from .errors import GvmError, GvmResponseError, GvmServerError
from .xml import Element, create_parser


class EtreeTransform:
    """
    Transform a response into a lxml.etree root element
    """

    def __init__(self):
        self._parser = create_parser()

    def _convert_response(self, response: Response) -> Element:
        return etree.XML(bytes(response), parser=self._parser)

    def __call__(self, response: Response) -> Element:
        return self._convert_response(response)


def check_command_status(root: Element):
    status = root.get("status")

    if status is None:
        raise GvmServerError("No status in response.", str(root))

    if status[0] == "4":
        raise GvmResponseError(status=status, message=root.get("status_text"))
    elif status[0] == "5":
        raise GvmServerError(status=status, message=root.get("status_text"))
    elif status[0] != "2":
        raise GvmError(f"Error in response. {root.get('status_text')}", root)


class CheckCommandTransform(EtreeTransform):
    """
    Check the response code of a response and raise GmpError if
    response was an error response
    """

    def __call__(self, response: Response) -> Response:  # type: ignore[override]
        root = self._convert_response(response)

        check_command_status(root)

        return response


class EtreeCheckCommandTransform(EtreeTransform):
    """
    Transform a response into a lxml.etree root element and raise GmpError if
    response was an error response
    """

    def __call__(self, response: Response) -> Element:
        root = self._convert_response(response)

        check_command_status(root)

        return root