This repository has been archived by the owner on Sep 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 132
/
Copy pathnxArchive.py
394 lines (361 loc) · 15 KB
/
nxArchive.py
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
#!/usr/bin/env python
# ===================================
# Copyright (c) Microsoft Corporation. All rights reserved.
# See license.txt for license information.
# ===================================
from __future__ import print_function
from __future__ import with_statement
from contextlib import contextmanager
import os
import sys
import imp
import tarfile
import zipfile
protocol = imp.load_source('protocol', '../protocol.py')
nxDSCLog = imp.load_source('nxDSCLog', '../nxDSCLog.py')
LG = nxDSCLog.DSCLog
try:
import hashlib
md5const = hashlib.md5
except ImportError:
import md5
md5const = md5.md5
BLOCK_SIZE = 8192
cache_file_dir = '/var/opt/microsoft/dsc/cache/nxArchive/'
# [ClassVersion("1.1.0"),FriendlyName("nxArchive")]
# class OMI_nxArchiveResource : OMI_BaseResource
# {
# [Key] string SourcePath;
# [Key] string DestinationPath;
# [write,ValueMap{"ctime", "mtime", "md5"},Values{"ctime", "mtime","md5"}] string Checksum;
# [write] boolean Force;
# [Write,ValueMap{"Present", "Absent"},Values{"Present", "Absent"}] string Ensure;
# };
def init_vars(DestinationPath, SourcePath, Ensure, Force, Checksum):
if DestinationPath is None:
DestinationPath = ''
if SourcePath is None:
SourcePath = ''
if Ensure is None or Ensure == '':
Ensure = 'present'
if Force is None:
Force = False
if Checksum is None or Checksum == '':
Checksum = 'md5'
return DestinationPath, SourcePath, Ensure.lower(), Force, Checksum.lower()
def Set_Marshall(DestinationPath, SourcePath, Ensure, Force, Checksum):
(DestinationPath, SourcePath, Ensure, Force, Checksum) = init_vars(
DestinationPath, SourcePath, Ensure, Force, Checksum)
retval = Set(DestinationPath, SourcePath, Ensure, Force, Checksum)
if retval is False:
retval = [-1]
else:
retval = [0]
return retval
def Test_Marshall(DestinationPath, SourcePath, Ensure, Force, Checksum):
(DestinationPath, SourcePath, Ensure, Force, Checksum) = init_vars(
DestinationPath, SourcePath, Ensure, Force, Checksum)
retval = Test(DestinationPath, SourcePath, Ensure, Force, Checksum)
if retval is False:
retval = [-1]
else:
retval = [0]
return retval
def Get_Marshall(DestinationPath, SourcePath, Ensure, Force, Checksum):
arg_names = list(locals().keys())
(DestinationPath, SourcePath, Ensure, Force, Checksum) = init_vars(
DestinationPath, SourcePath, Ensure, Force, Checksum)
retval = 0
(DestinationPath, SourcePath, Ensure, Force, Checksum) = Get(
DestinationPath, SourcePath, Ensure, Force, Checksum)
DestinationPath = protocol.MI_String(DestinationPath)
Ensure = protocol.MI_String(Ensure)
SourcePath = protocol.MI_String(SourcePath)
Force = protocol.MI_Boolean(Force)
Checksum = protocol.MI_String(Checksum)
retd = {}
ld = locals()
for k in arg_names:
retd[k] = ld[k]
return retval, retd
############################################################
# Begin user defined DSC functions
############################################################
def LStatFile(path):
"""
LStat the file. Do not follow the symlink.
"""
d = None
error = None
try:
d = os.lstat(path)
except OSError as error:
print("Exception lstating file " + path + " Error Code: " + str(error.errno) +
" Error: " + error.strerror, file=sys.stderr)
LG().Log('ERROR', "Exception lstating file " + path + " Error Code: " + str(error.errno) +
" Error: " + error.strerror)
return d, error
except IOError as error:
print("Exception lstating file " + path + " Error Code: " + str(error.errno) +
" Error: " + error.strerror, file=sys.stderr)
LG().Log('ERROR', "Exception lstating file " + path + " Error Code: " + str(error.errno) +
" Error: " + error.strerror)
return d, error
return d, error
def MakeDirs(path):
error = None
try:
os.makedirs(path)
except OSError as error:
print("Exception making dir" + path + " Error Code: " + str(error.errno) +
" Error: " + error.strerror, file=sys.stderr)
LG().Log('ERROR', "Exception making dir" + path + " Error Code: " + str(error.errno) +
" Error: " + error.strerror)
return error
except IOError as error:
print("Exception making dir" + path + " Error Code: " + str(error.errno) +
" Error: " + error.strerror, file=sys.stderr)
LG().Log('ERROR', "Exception making dir" + path + " Error Code: " + str(error.errno) +
" Error: " + error.strerror)
return error
return error
def RemoveFile(path):
error = None
try:
os.remove(path)
except OSError as error:
print("Exception removing file" + path + " Error Code: " + str(error.errno) +
" Error: " + error.strerror, file=sys.stderr)
LG().Log('ERROR', "Exception removing file" + path + " Error Code: " + str(error.errno) +
" Error: " + error.strerror)
return error
except IOError as error:
print("Exception removing file" + path + " Error Code: " + str(error.errno) +
" Error: " + error.strerror, file=sys.stderr)
LG().Log('ERROR', "Exception removing file" + path + " Error Code: " + str(error.errno) +
" Error: " + error.strerror)
return error
return error
@contextmanager
def opened_w_error(filename, mode="rb"):
"""
This context ensures the file is closed.
"""
try:
f = open(filename, mode)
except IOError as err:
yield None, err
else:
try:
yield f, None
finally:
f.close()
def ReadCacheInfo(SourcePath, DestinationPath):
cache_file_path = cache_file_dir + \
SourcePath.replace('/', '_') + DestinationPath.replace('/', '_')
with opened_w_error(cache_file_path, 'r') as (F, error):
if error:
print("Exception opening file " + cache_file_path + " Error Code: " +
str(error.errno) + " Error: " + error.strerror, file=sys.stderr)
LG().Log('ERROR', "Exception opening file " + cache_file_path + " Error Code: " +
str(error.errno) + " Error: " + error.strerror)
return False, 0.0, 0.0, ''
ln = (F.read()).splitlines()
F.close()
if len(ln) != 3:
print("Exception reading file " + cache_file_path, file=sys.stderr)
LG().Log('ERROR', "Exception reading file " + cache_file_path)
return False, 0.0, 0.0, ''
ctime = float(ln[0])
mtime = float(ln[1])
chksum = ln[2]
return True, ctime, mtime, chksum
def WriteCacheInfo(SourcePath, DestinationPath):
src_hash = md5const()
src_block = b'loopme'
with opened_w_error(SourcePath, 'rb') as (src_file, src_error):
if src_error:
print("Exception opening source file " + SourcePath + " Error Code: " + str(src_error.errno) +
" Error: " + src_error.message + src_error.strerror, file=sys.stderr)
LG().Log('ERROR', "Exception opening source file " + SourcePath + " Error Code: " + str(src_error.errno) +
" Error: " + src_error.message + src_error.strerror)
return -1
while src_block:
src_block = src_file.read(BLOCK_SIZE)
src_hash.update(src_block)
chksum = src_hash.hexdigest()
st, error = LStatFile(SourcePath)
cache_file_path = cache_file_dir + \
SourcePath.replace('/', '_') + DestinationPath.replace('/', '_')
with opened_w_error(cache_file_path, 'w+') as (F, error):
if error:
print("Exception opening file " + cache_file_path + " Error Code: " +
str(error.errno) + " Error: " + error.strerror, file=sys.stderr)
LG().Log('ERROR', "Exception opening file " + cache_file_path + " Error Code: " +
str(error.errno) + " Error: " + error.strerror)
return False
F.write(
repr(st.st_ctime) + '\n' + repr(st.st_mtime) + '\n' + chksum + '\n')
F.close()
return True
def CompareFileWithCacheFile(SourcePath, DestinationPath, Checksum):
"""
Reading and computing the hash here is done in a block-by-block manner,
in case the file is quite large.
"""
retval, stat_cache_st_ctime, stat_cache_st_mtime, cache_hash = ReadCacheInfo(
SourcePath, DestinationPath)
if retval is False:
return False
stat_src, error = LStatFile(SourcePath)
if stat_src is None:
print("Exception opening SourcePath " + SourcePath + " Error Code: " +
str(error.errno) + " Error: " + error.strerror, file=sys.stderr)
LG().Log('ERROR', "Exception opening SourcePath " + SourcePath + " Error Code: " +
str(error.errno) + " Error: " + error.strerror)
return False
if Checksum == "md5":
src_error = None
src_hash = md5const()
src_block = b'loopme'
with opened_w_error(SourcePath, 'rb') as (src_file, src_error):
if src_error:
print("Exception opening source file " + SourcePath + " Error Code: " + str(src_error.errno) +
" Error: " + src_error.message + src_error.strerror, file=sys.stderr)
LG().Log('ERROR', "Exception opening source file " + SourcePath + " Error Code: " + str(src_error.errno) +
" Error: " + src_error.message + src_error.strerror)
return -1
while src_block:
src_block = src_file.read(BLOCK_SIZE)
src_hash.update(src_block)
if src_hash.hexdigest() == cache_hash:
return True
else:
return False
elif Checksum == "ctime":
if stat_src.st_ctime > stat_cache_st_ctime:
return False
else:
return True
elif Checksum == "mtime":
if stat_src.st_mtime > stat_cache_st_mtime:
return False
else:
return True
def Set(DestinationPath, SourcePath, Ensure, Force, Checksum):
# Do nothing. Set should not get called as previous Test will evaluate to
# True
if Ensure == 'absent':
return True
# if the sourcepath is not valid file return False
if not os.path.isfile(SourcePath):
print('ERROR: SourcePath<' + SourcePath + '> is not a valid file')
LG().Log('ERROR', 'ERROR: SourcePath<' +
SourcePath + '> is not a valid file')
return False
if not os.path.exists(DestinationPath):
if MakeDirs(DestinationPath) is not None:
return False
if not os.path.isdir(DestinationPath):
if Force == False: # Force is False, return False
print(
'ERROR: Force must be True if DestinationPath is not a directory.')
LG().Log(
'ERROR', 'ERROR: Force must be True if DestinationPath is not a directory.')
return False
if RemoveFile(DestinationPath) is not None: # error
return False
# if the dircache is not present create if error return False
if not os.path.isdir(cache_file_dir):
if MakeDirs(cache_file_dir) is not None:
return False
# is the sourcepath a valid archive?
archive_type = 'tar'
ext = os.path.splitext(SourcePath)
if len(ext) > 1 and ext[1].lower() == '.zip':
archive_type = 'zip'
if archive_type == 'zip':
try:
arch = zipfile.ZipFile(SourcePath)
# Exploit check - make sure no names start with '/' or '..'
for n in arch.namelist():
if n.startswith('/') or n.startswith('..'):
raise Exception(
'Error: corrupted filename "' + n + '" in zipfile!')
bad = arch.testzip()
if bad is not None:
raise Exception('Error: First bad filename is "' + bad + '"')
except Exception as error:
print("Exception opening zipfile" + SourcePath +
" Error: " + error.message, file=sys.stderr)
LG().Log('ERROR', "Exception opening zipfile" + SourcePath +
" Error: " + error.message)
return False
# extract archive to destinationpath if error return False
try:
arch.extractall(DestinationPath)
except Exception as error:
print("Exception extracting zipfile" + SourcePath + " to " +
DestinationPath + " Error: " + error.message, file=sys.stderr)
LG().Log('ERROR', "Exception extracting zipfile" + SourcePath + " to " +
DestinationPath + " Error: " + error.message)
return False
else: # tarfile
if not tarfile.is_tarfile(SourcePath):
print(
'ERROR: SourcePath<' + SourcePath + '> is not a valid tarfile')
LG().Log('ERROR', 'ERROR: SourcePath<' +
SourcePath + '> is not a valid tarfile')
arch = None
try:
arch = tarfile.open(SourcePath, 'r')
except Exception as error:
if arch is not None:
arch.close()
print("Exception opening tarfile" + SourcePath +
" Error: " + error.message, file=sys.stderr)
LG().Log('ERROR', "Exception opening tarfile" + SourcePath +
" Error: " + error.message)
return False
for n in arch.getnames():
if n.startswith('/') or n.startswith('..'):
arch.close()
raise Exception(
'Error: corrupted filename "' + n + '" in tarfile!')
try:
arch.extractall(DestinationPath)
except Exception as error:
arch.close()
print("Exception extracting tarfile" + SourcePath + " to " +
DestinationPath + " Error: " + error.message, file=sys.stderr)
LG().Log('ERROR', "Exception extracting tarfile" + SourcePath + " to " +
DestinationPath + " Error: " + error.message)
return False
arch.close()
os.system('touch '+DestinationPath) # existing dirs won't get an updated time, so update it.
if WriteCacheInfo(SourcePath, DestinationPath) is False:
return False
return True
def Test(DestinationPath, SourcePath, Ensure, Force, Checksum):
if not os.path.isdir(cache_file_dir):
return False
if not os.path.isfile(SourcePath):
return False
if not os.path.isdir(DestinationPath):
return False
if CompareFileWithCacheFile(SourcePath, DestinationPath, Checksum) is True:
if Ensure == 'present':
return True
else:
return False
else:
if Ensure == 'present':
return False
else:
return True
def Get(DestinationPath, SourcePath, Ensure, Force, Checksum):
if Test(DestinationPath, SourcePath, Ensure, Force, Checksum) is False:
Ensure = 'absent'
else:
Ensure = 'present'
return DestinationPath, SourcePath, Ensure, Force, Checksum