~ubuntu-branches/debian/sid/waagent/sid

« back to all changes in this revision

Viewing changes to azurelinuxagent/utils/textutil.py

  • Committer: Package Import Robot
  • Author(s): Bastian Blank
  • Date: 2015-07-30 13:27:01 UTC
  • mfrom: (1.2.1) (3.1.1 experimental)
  • Revision ID: package-import@ubuntu.com-20150730132701-dvdym85n5twpucfk
Tags: 2.1.0-1
* New upstream version.
* Hijack package.
* Not longer try to install systemd stuff by package setup.
* Use own systemd service, use dh-systemd.
* Use own init script.
* Remove unused python3 support.
* Remove old postinst, postrm script.
* Remove upstart support, "It's dead, Jim".
* Make package arch-all.
* Disable environment monitor.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Windows Azure Linux Agent
 
2
#
 
3
# Copyright 2014 Microsoft Corporation
 
4
#
 
5
# Licensed under the Apache License, Version 2.0 (the "License");
 
6
# you may not use this file except in compliance with the License.
 
7
# You may obtain a copy of the License at
 
8
#
 
9
#     http://www.apache.org/licenses/LICENSE-2.0
 
10
#
 
11
# Unless required by applicable law or agreed to in writing, software
 
12
# distributed under the License is distributed on an "AS IS" BASIS,
 
13
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
14
# See the License for the specific language governing permissions and
 
15
# limitations under the License.
 
16
#
 
17
# Requires Python 2.4+ and Openssl 1.0+
 
18
import crypt
 
19
import random
 
20
import string
 
21
import struct
 
22
 
 
23
def FindFirstNode(xmlDoc, selector):
 
24
    nodes = FindAllNodes(xmlDoc, selector)
 
25
    if len(nodes) > 0:
 
26
        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):
 
41
    """
 
42
    Unpack bytes into python values.
 
43
    """
 
44
    result = 0
 
45
    for i in range:
 
46
        result = (result << 8) | Ord(buf[offset + i])
 
47
    return result
 
48
 
 
49
def UnpackLittleEndian(buf, offset, length):
 
50
    """
 
51
    Unpack little endian bytes into python values.
 
52
    """
 
53
    return Unpack(buf, offset, list(range(length - 1, -1, -1)))
 
54
 
 
55
def UnpackBigEndian(buf, offset, length):
 
56
    """
 
57
    Unpack big endian bytes into python values.
 
58
    """
 
59
    return Unpack(buf, offset, list(range(0, length)))
 
60
 
 
61
def HexDump3(buf, offset, length):
 
62
    """
 
63
    Dump range of buf in formatted hex.
 
64
    """
 
65
    return ''.join(['%02X' % Ord(char) for char in buf[offset:offset + length]])
 
66
 
 
67
def HexDump2(buf):
 
68
    """
 
69
    Dump buf in formatted hex.
 
70
    """
 
71
    return HexDump3(buf, 0, len(buf))
 
72
 
 
73
def IsInRangeInclusive(a, low, high):
 
74
    """
 
75
    Return True if 'a' in 'low' <= a >= 'high'
 
76
    """
 
77
    return (a >= low and a <= high)
 
78
 
 
79
def IsPrintable(ch):
 
80
    """
 
81
    Return True if character is displayable.
 
82
    """
 
83
    return (IsInRangeInclusive(ch, Ord('A'), Ord('Z')) 
 
84
           or IsInRangeInclusive(ch, Ord('a'), Ord('z')) 
 
85
           or IsInRangeInclusive(ch, Ord('0'), Ord('9')))
 
86
 
 
87
def HexDump(buffer, size):
 
88
    """
 
89
    Return Hex formated dump of a 'buffer' of 'size'.
 
90
    """
 
91
    if size < 0:
 
92
        size = len(buffer)
 
93
    result = ""
 
94
    for i in range(0, size):
 
95
        if (i % 16) == 0:
 
96
            result += "%06X: " % i
 
97
        byte = buffer[i]
 
98
        if type(byte) == str:
 
99
            byte = ord(byte.decode('latin1'))
 
100
        result += "%02X " % byte
 
101
        if (i & 15) == 7:
 
102
            result += " "
 
103
        if ((i + 1) % 16) == 0 or (i + 1) == size:
 
104
            j = i
 
105
            while ((j + 1) % 16) != 0:
 
106
                result += "   "
 
107
                if (j & 7) == 7:
 
108
                    result += " "
 
109
                j += 1
 
110
            result += " "
 
111
            for j in range(i - (i % 16), i + 1):
 
112
                byte=buffer[j]
 
113
                if type(byte) == str:
 
114
                    byte = ord(byte.decode('latin1'))
 
115
                k = '.'
 
116
                if IsPrintable(byte):
 
117
                    k = chr(byte)
 
118
                result += k
 
119
            if (i + 1) != size:
 
120
                result += "\n"
 
121
    return result
 
122
 
 
123
def Ord(a):
 
124
    """
 
125
    Allows indexing into a string or an array of integers transparently.
 
126
    Generic utility function.
 
127
    """
 
128
    if type(a) == type("a"):
 
129
        a = ord(a)
 
130
    return a
 
131
 
 
132
def CompareBytes(a, b, start, length):
 
133
    for offset in range(start, start + length):
 
134
        if Ord(a[offset]) != Ord(b[offset]):
 
135
            return False
 
136
    return True
 
137
 
 
138
def IntegerToIpAddressV4String(a):
 
139
    """
 
140
    Build DHCP request string.
 
141
    """
 
142
    return "%u.%u.%u.%u" % ((a >> 24) & 0xFF, 
 
143
                            (a >> 16) & 0xFF, 
 
144
                            (a >> 8) & 0xFF, 
 
145
                            (a) & 0xFF)
 
146
 
 
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):
 
159
    """
 
160
    Return hex string packed into a binary struct.
 
161
    """
 
162
    b = b""
 
163
    for c in range(0, len(a) // 2):
 
164
        b += struct.pack("B", int(a[c * 2:c * 2 + 2], 16))
 
165
    return b
 
166
 
 
167
def SetSshConfig(config, name, val):
 
168
    notfound = True
 
169
    for i in range(0, len(config)):
 
170
        if config[i].startswith(name):
 
171
            config[i] = "{0} {1}".format(name, val)
 
172
            notfound = False
 
173
        elif config[i].startswith("Match"):
 
174
            #Match block must be put in the end of sshd config
 
175
            break
 
176
    if notfound:
 
177
        config.insert(i, "{0} {1}".format(name, val))
 
178
    return config
 
179
 
 
180
def RemoveBom(c):
 
181
    if ord(c[0]) > 128 and ord(c[1]) > 128 and ord(c[2]) > 128:
 
182
        c = c[3:]
 
183
    return c
 
184
 
 
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
 
219