Debian Codegraph @

ansible_collections/community/libvirt/plugins/module_utils/powershell.py

raw
1 # Copyright (c) 2014, Chris Church <[email protected]>
2 # Copyright (c) 2017 Ansible Project
3 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
4
5 """PowerShell compatibility utilities vendored from ansible-core.
6
7 The _parse_clixml() function was extracted from
8 ansible.plugins.shell.powershell in ansible-core stable-2.20 (the last
9 release that carried it). Starting with ansible-core devel (2.21+) the
10 function was removed and the underlying logic refactored into the private
11 ansible._internal._powershell._clixml module.
12
13 Upstream reference (stable-2.20):
14 https://github.com/ansible/ansible/blob/stable-2.20/lib/ansible/plugins/shell/powershell.py
15
16 This shim should be removed once the collection's minimum supported
17 ansible-core version ships its own public replacement.
18 """
19
20 from __future__ import (absolute_import, division, print_function)
21 __metaclass__ = type
22
23 import base64
24 import re
25 import xml.etree.ElementTree as ET
26
27 from ansible.module_utils._text import to_bytes
28
29 _STRING_DESERIAL_FIND = re.compile(rb"\x00_\x00x((?:\x00[a-fA-F0-9]){4})\x00_")
30
31
32 def _parse_clixml(data, stream="Error"):
33 """Parse CLIXML-encoded PowerShell output and return the stream message.
34
35 Takes a byte string like ``b'#< CLIXML\\r\\n<Objs...'`` and extracts the
36 stream message encoded in the XML data. CLIXML is used by PowerShell to
37 encode multiple objects in stderr.
38 """
39 lines = []
40
41 def rplcr(matchobj):
42 match_hex = matchobj.group(1)
43 hex_string = match_hex.decode("utf-16-be")
44 return base64.b16decode(hex_string.upper())
45
46 while data:
47 start_idx = data.find(b"<Objs ")
48 end_idx = data.find(b"</Objs>")
49 if start_idx == -1 or end_idx == -1:
50 break
51
52 end_idx += 7
53 current_element = data[start_idx:end_idx]
54 data = data[end_idx:]
55
56 clixml = ET.fromstring(current_element)
57 namespace_match = re.match(r'{(.*)}', clixml.tag)
58 namespace = "{%s}" % namespace_match.group(1) if namespace_match else ""
59
60 entries = clixml.findall("./%sS" % namespace)
61 if not entries:
62 continue
63
64 if lines:
65 lines.append("\r\n")
66
67 for string_entry in entries:
68 actual_stream = string_entry.attrib.get('S', None)
69 if actual_stream != stream:
70 continue
71
72 b_line = (string_entry.text or "").encode("utf-16-be")
73 b_escaped = re.sub(_STRING_DESERIAL_FIND, rplcr, b_line)
74
75 lines.append(b_escaped.decode("utf-16-be", errors="surrogatepass"))
76
77 return to_bytes(''.join(lines), errors="surrogatepass")