Passed
Pull Request — master (#202)
by
unknown
01:23
created

ospd.xml   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 136
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 60
dl 0
loc 136
rs 10
c 0
b 0
f 0
wmc 17

4 Functions

Rating   Name   Duplication   Size   Complexity  
A get_elements_from_dict() 0 26 5
B simple_response_str() 0 32 6
A get_result_xml() 0 23 2
A elements_as_text() 0 20 4
1
# Copyright (C) 2014-2020 Greenbone Networks GmbH
2
#
3
# SPDX-License-Identifier: GPL-2.0-or-later
4
#
5
# This program is free software; you can redistribute it and/or
6
# modify it under the terms of the GNU General Public License
7
# as published by the Free Software Foundation; either version 2
8
# of the License, or (at your option) any later version.
9
#
10
# This program is distributed in the hope that it will be useful,
11
# but WITHOUT ANY WARRANTY; without even the implied warranty of
12
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
# GNU General Public License for more details.
14
#
15
# You should have received a copy of the GNU General Public License
16
# along with this program; if not, write to the Free Software
17
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18
19
""" OSP XML utils class.
20
"""
21
22
from typing import List, Dict, Any, Union
23
24
from xml.etree.ElementTree import tostring, Element
25
26
from ospd.misc import ResultType
27
28
29
def get_result_xml(result):
30
    """ Formats a scan result to XML format.
31
32
    Arguments:
33
        result (dict): Dictionary with a scan result.
34
35
    Return:
36
        Result as xml element object.
37
    """
38
    result_xml = Element('result')
39
    for name, value in [
40
        ('name', result['name']),
41
        ('type', ResultType.get_str(result['type'])),
42
        ('severity', result['severity']),
43
        ('host', result['host']),
44
        ('hostname', result['hostname']),
45
        ('test_id', result['test_id']),
46
        ('port', result['port']),
47
        ('qod', result['qod']),
48
    ]:
49
        result_xml.set(name, str(value))
50
    result_xml.text = result['value']
51
    return result_xml
52
53
54
def simple_response_str(
55
    command: str,
56
    status: int,
57
    status_text: str,
58
    content: Union[str, Element, List[str], List[Element]] = "",
59
) -> str:
60
    """ Creates an OSP response XML string.
61
62
    Arguments:
63
        command (str): OSP Command to respond to.
64
        status (int): Status of the response.
65
        status_text (str): Status text of the response.
66
        content (str): Text part of the response XML element.
67
68
    Return:
69
        String of response in xml format.
70
    """
71
    response = Element('%s_response' % command)
72
73
    for name, value in [('status', str(status)), ('status_text', status_text)]:
74
        response.set(name, str(value))
75
76
    if isinstance(content, list):
77
        for elem in content:
78
            if isinstance(elem, Element):
79
                response.append(elem)
80
    elif isinstance(content, Element):
81
        response.append(content)
82
    else:
83
        response.text = content
84
85
    return tostring(response)
86
87
88
def get_elements_from_dict(data: Dict[str, Any]) -> List[Element]:
89
    """ Creates a list of etree elements from a dictionary
90
91
    Args:
92
        Dictionary of tags and their elements.
93
94
    Return:
95
        List of xml elements.
96
    """
97
98
    responses = []
99
100
    for tag, value in data.items():
101
        elem = Element(tag)
102
103
        if isinstance(value, dict):
104
            for val in get_elements_from_dict(value):
105
                elem.append(val)
106
        elif isinstance(value, list):
107
            elem.text = ', '.join(value)
108
        else:
109
            elem.text = value
110
111
        responses.append(elem)
112
113
    return responses
114
115
116
def elements_as_text(
117
    elements: Dict[str, Union[str, Dict]], indent: int = 2
118
) -> str:
119
    """ Returns the elements dictionary as formatted plain text. """
120
121
    text = ""
122
    for elename, eledesc in elements.items():
123
        if isinstance(eledesc, dict):
124
            desc_txt = elements_as_text(eledesc, indent + 2)
125
            desc_txt = ''.join(['\n', desc_txt])
126
        elif isinstance(eledesc, str):
127
            desc_txt = ''.join([eledesc, '\n'])
128
        else:
129
            assert False, "Only string or dictionary"
130
131
        ele_txt = "\t{0}{1: <22} {2}".format(' ' * indent, elename, desc_txt)
0 ignored issues
show
introduced by
The variable desc_txt does not seem to be defined for all execution paths.
Loading history...
132
133
        text = ''.join([text, ele_txt])
134
135
    return text
136