~ubuntu-branches/debian/stretch/waagent/stretch

« back to all changes in this revision

Viewing changes to azurelinuxagent/utils/textutil.py

  • Committer: Package Import Robot
  • Author(s): Bastian Blank
  • Date: 2016-02-01 13:11:28 UTC
  • mfrom: (1.2.2)
  • Revision ID: package-import@ubuntu.com-20160201131128-4wxc2tklmq3x40xe
Tags: 2.1.2-1
* New upstream version.
* Depend on host, needed by Microsofts custom script stuff.
* Use cloud-init:
  - Use Ubuntu provisioning handler, disable provisioning.
  - Depend on new enough version of cloud-init.
  - Update dependencies in init script and service.
  - Disable recursive agent invocation and hostname bounce in clout-init.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Windows Azure Linux Agent
 
1
# Microsoft Azure Linux Agent
2
2
#
3
3
# Copyright 2014 Microsoft Corporation
4
4
#
15
15
# limitations under the License.
16
16
#
17
17
# Requires Python 2.4+ and Openssl 1.0+
 
18
 
18
19
import crypt
19
20
import random
20
21
import string
21
22
import struct
22
 
 
23
 
def FindFirstNode(xmlDoc, selector):
24
 
    nodes = FindAllNodes(xmlDoc, selector)
25
 
    if len(nodes) > 0:
 
23
import xml.dom.minidom as minidom
 
24
import sys
 
25
from distutils.version import LooseVersion
 
26
 
 
27
def parse_doc(xml_text):
 
28
    """
 
29
    Parse xml document from string
 
30
    """
 
31
    #The minidom lib has some issue with unicode in python2.
 
32
    #Encode the string into utf-8 first
 
33
    xml_text = xml_text.encode('utf-8')
 
34
    return minidom.parseString(xml_text)
 
35
 
 
36
def findall(root, tag, namespace=None):
 
37
    """
 
38
    Get all nodes by tag and namespace under Node root.
 
39
    """
 
40
    if root is None:
 
41
        return []
 
42
 
 
43
    if namespace is None:
 
44
        return root.getElementsByTagName(tag)
 
45
    else:
 
46
        return root.getElementsByTagNameNS(namespace, tag)
 
47
 
 
48
def find(root, tag, namespace=None):
 
49
    """
 
50
    Get first node by tag and namespace under Node root.
 
51
    """
 
52
    nodes = findall(root, tag, namespace=namespace)
 
53
    if nodes is not None and len(nodes) >= 1:
26
54
        return nodes[0]
27
 
 
28
 
def FindAllNodes(xmlDoc, selector):
29
 
    nodes = xmlDoc.findall(selector)
30
 
    return nodes
31
 
 
32
 
def GetNodeTextData(a):
33
 
    """
34
 
    Filter non-text nodes from DOM tree
35
 
    """
36
 
    for b in a.childNodes:
37
 
        if b.nodeType == b.TEXT_NODE:
38
 
            return b.data
39
 
 
40
 
def Unpack(buf, offset, range):
 
55
    else:
 
56
        return None
 
57
 
 
58
def gettext(node):
 
59
    """
 
60
    Get node text
 
61
    """
 
62
    if node is None:
 
63
        return None
 
64
    
 
65
    for child in node.childNodes:
 
66
        if child.nodeType == child.TEXT_NODE:
 
67
            return child.data
 
68
    return None
 
69
 
 
70
def findtext(root, tag, namespace=None):
 
71
    """
 
72
    Get text of node by tag and namespace under Node root.
 
73
    """
 
74
    node = find(root, tag, namespace=namespace)
 
75
    return gettext(node)
 
76
 
 
77
def getattrib(node, attr_name):
 
78
    """
 
79
    Get attribute of xml node
 
80
    """
 
81
    if node is not None:
 
82
        return node.getAttribute(attr_name)
 
83
    else:
 
84
        return None
 
85
 
 
86
def unpack(buf, offset, range):
41
87
    """
42
88
    Unpack bytes into python values.
43
89
    """
44
90
    result = 0
45
91
    for i in range:
46
 
        result = (result << 8) | Ord(buf[offset + i])
 
92
        result = (result << 8) | str_to_ord(buf[offset + i])
47
93
    return result
48
94
 
49
 
def UnpackLittleEndian(buf, offset, length):
 
95
def unpack_little_endian(buf, offset, length):
50
96
    """
51
97
    Unpack little endian bytes into python values.
52
98
    """
53
 
    return Unpack(buf, offset, list(range(length - 1, -1, -1)))
 
99
    return unpack(buf, offset, list(range(length - 1, -1, -1)))
54
100
 
55
 
def UnpackBigEndian(buf, offset, length):
 
101
def unpack_big_endian(buf, offset, length):
56
102
    """
57
103
    Unpack big endian bytes into python values.
58
104
    """
59
 
    return Unpack(buf, offset, list(range(0, length)))
 
105
    return unpack(buf, offset, list(range(0, length)))
60
106
 
61
 
def HexDump3(buf, offset, length):
 
107
def hex_dump3(buf, offset, length):
62
108
    """
63
109
    Dump range of buf in formatted hex.
64
110
    """
65
 
    return ''.join(['%02X' % Ord(char) for char in buf[offset:offset + length]])
 
111
    return ''.join(['%02X' % str_to_ord(char) for char in buf[offset:offset + length]])
66
112
 
67
 
def HexDump2(buf):
 
113
def hex_dump2(buf):
68
114
    """
69
115
    Dump buf in formatted hex.
70
116
    """
71
 
    return HexDump3(buf, 0, len(buf))
 
117
    return hex_dump3(buf, 0, len(buf))
72
118
 
73
 
def IsInRangeInclusive(a, low, high):
 
119
def is_in_range(a, low, high):
74
120
    """
75
121
    Return True if 'a' in 'low' <= a >= 'high'
76
122
    """
77
123
    return (a >= low and a <= high)
78
124
 
79
 
def IsPrintable(ch):
 
125
def is_printable(ch):
80
126
    """
81
127
    Return True if character is displayable.
82
128
    """
83
 
    return (IsInRangeInclusive(ch, Ord('A'), Ord('Z')) 
84
 
           or IsInRangeInclusive(ch, Ord('a'), Ord('z')) 
85
 
           or IsInRangeInclusive(ch, Ord('0'), Ord('9')))
 
129
    return (is_in_range(ch, str_to_ord('A'), str_to_ord('Z'))
 
130
           or is_in_range(ch, str_to_ord('a'), str_to_ord('z'))
 
131
           or is_in_range(ch, str_to_ord('0'), str_to_ord('9')))
86
132
 
87
 
def HexDump(buffer, size):
 
133
def hex_dump(buffer, size):
88
134
    """
89
135
    Return Hex formated dump of a 'buffer' of 'size'.
90
136
    """
111
157
            for j in range(i - (i % 16), i + 1):
112
158
                byte=buffer[j]
113
159
                if type(byte) == str:
114
 
                    byte = ord(byte.decode('latin1'))
 
160
                    byte = str_to_ord(byte.decode('latin1'))
115
161
                k = '.'
116
 
                if IsPrintable(byte):
 
162
                if is_printable(byte):
117
163
                    k = chr(byte)
118
164
                result += k
119
165
            if (i + 1) != size:
120
166
                result += "\n"
121
167
    return result
122
168
 
123
 
def Ord(a):
 
169
def str_to_ord(a):
124
170
    """
125
171
    Allows indexing into a string or an array of integers transparently.
126
172
    Generic utility function.
127
173
    """
128
 
    if type(a) == type("a"):
 
174
    if type(a) == type(b'') or type(a) == type(u''):
129
175
        a = ord(a)
130
176
    return a
131
177
 
132
 
def CompareBytes(a, b, start, length):
 
178
def compare_bytes(a, b, start, length):
133
179
    for offset in range(start, start + length):
134
 
        if Ord(a[offset]) != Ord(b[offset]):
 
180
        if str_to_ord(a[offset]) != str_to_ord(b[offset]):
135
181
            return False
136
182
    return True
137
183
 
138
 
def IntegerToIpAddressV4String(a):
 
184
def int_to_ip4_addr(a):
139
185
    """
140
186
    Build DHCP request string.
141
187
    """
142
 
    return "%u.%u.%u.%u" % ((a >> 24) & 0xFF, 
143
 
                            (a >> 16) & 0xFF, 
144
 
                            (a >> 8) & 0xFF, 
 
188
    return "%u.%u.%u.%u" % ((a >> 24) & 0xFF,
 
189
                            (a >> 16) & 0xFF,
 
190
                            (a >> 8) & 0xFF,
145
191
                            (a) & 0xFF)
146
192
 
147
 
def Ascii(val):
148
 
    uni = None
149
 
    if type(val) == str:
150
 
        uni = unicode(val, 'utf-8', errors='ignore') 
151
 
    else:
152
 
        uni = unicode(val)
153
 
    if uni is None:
154
 
        raise ValueError('<Unsupported charset>')
155
 
    else:
156
 
        return uni.encode('ascii', 'backslashreplace')
157
 
 
158
 
def HexStringToByteArray(a):
 
193
def hexstr_to_bytearray(a):
159
194
    """
160
195
    Return hex string packed into a binary struct.
161
196
    """
164
199
        b += struct.pack("B", int(a[c * 2:c * 2 + 2], 16))
165
200
    return b
166
201
 
167
 
def SetSshConfig(config, name, val):
 
202
def set_ssh_config(config, name, val):
168
203
    notfound = True
169
204
    for i in range(0, len(config)):
170
205
        if config[i].startswith(name):
177
212
        config.insert(i, "{0} {1}".format(name, val))
178
213
    return config
179
214
 
180
 
def RemoveBom(c):
181
 
    if ord(c[0]) > 128 and ord(c[1]) > 128 and ord(c[2]) > 128:
 
215
def remove_bom(c):
 
216
    if str_to_ord(c[0]) > 128 and str_to_ord(c[1]) > 128 and \
 
217
            str_to_ord(c[2]) > 128:
182
218
        c = c[3:]
183
219
    return c
184
220
 
185
 
def GetPasswordHash(password, useSalt, saltType, saltLength):
186
 
        salt="$6$" 
187
 
        if useSalt:
188
 
            collection = string.ascii_letters + string.digits
189
 
            salt = ''.join(random.choice(collection) for _ in range(saltLength))
190
 
            salt = "${0}${1}".format(saltType, salt)
191
 
        return crypt.crypt(password, salt)
192
 
 
193
 
def NumberToBytes(i):
194
 
        """
195
 
        Pack number into bytes.  Retun as string.
196
 
        """
197
 
        result = []
198
 
        while i:
199
 
            result.append(chr(i & 0xFF))
200
 
            i >>= 8
201
 
        result.reverse()
202
 
        return ''.join(result)
203
 
 
204
 
def BitsToString(a):
205
 
    """
206
 
    Return string representation of bits in a.
207
 
    """
208
 
    index=7
209
 
    s = ""
210
 
    c = 0
211
 
    for bit in a:
212
 
        c = c | (bit << index)
213
 
        index = index - 1
214
 
        if index == -1:
215
 
            s = s + struct.pack('>B', c)
216
 
            c = 0
217
 
            index = 7
218
 
    return s
 
221
def gen_password_hash(password, crypt_id, salt_len):
 
222
    collection = string.ascii_letters + string.digits
 
223
    salt = ''.join(random.choice(collection) for _ in range(salt_len))
 
224
    salt = "${0}${1}".format(crypt_id, salt)
 
225
    return crypt.crypt(password, salt)
 
226
 
 
227
Version = LooseVersion
219
228