-
Notifications
You must be signed in to change notification settings - Fork 8
/
iceshelf-restore
executable file
·372 lines (324 loc) · 12.3 KB
/
iceshelf-restore
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
#!/usr/bin/env python
#
# This tool will take a iceshelf backup and restore it to a
# designated folder, following any directives stored in the
# manifest file.
#
# NOTE! Will not do anything if a manifest is missing.
#
##############################################################################
import logging
import argparse
import sys
import os.path
import json
from datetime import datetime
import time
import shutil
import tarfile
import gnupg
import re
from subprocess import Popen, PIPE
import modules.configuration as configuration
import modules.fileutils as fileutils
import modules.helper as helper
def validArchive(baseDir, filelist, corruptFiles, files):
"""
Start with validating all files and confirm existance of files, using the filelist.txt
"""
p = re.compile('([a-f0-9]+)\s+([^\s]+)')
criticalerror = False
archivecorrupt = False
paritycount = 0
del files[:]
with open( os.path.join(baseDir, filelist), "r") as f:
for line in f:
res = p.match(line)
if res:
if os.path.exists(os.path.join(baseDir, res.group(2))):
files.append(res.group(2))
sha = fileutils.hashFile(os.path.join(baseDir, res.group(2)), 'sha1')
if sha != res.group(1):
corruptFiles.append(res.group(2))
if ".json" in line:
logging.error('Manifest is corrupt, please restore manually')
criticalerror = True
elif ".tar" in line:
archivecorrupt = True
elif ".par2" in line:
logging.warn('Parity file "%s" is corrupt and will not be used' % res.group(2))
elif ".par2" in line:
paritycount += 1
else:
logging.error('File "%s" is missing from backup' % res.group(2))
return False
else:
logging.error("filelist.txt is corrupt")
return False
if archivecorrupt and paritycount == 0:
logging.error('Archive is corrupt and no available parity files')
criticalerror = True
elif archivecorrupt:
logging.warn('Archive is corrupt, but parity is available making repair a possibility')
return criticalerror == False
def validateFile(filename):
global config
gpg = gnupg.GPG()
destfile = filename
logging.debug('Validating "%s"' % filename)
if filename.endswith('.sig') or filename.endswith('.asc'):
verification = None
with open(filename, 'rb') as f:
verification = gpg.verify_file(f)
if verification is None or verification.trust_level < verification.TRUST_FULLY:
logging.error('Signature isn\'t trusted (%s): %s' % (verification.status, filename))
return False
return True
def stripFile(filename):
global config
gpg = gnupg.GPG()
destfile = filename
logging.debug('Processing "%s"' % filename)
while destfile.endswith('.sig') or destfile.endswith('.asc') or destfile.endswith('.gpg'):
ext = destfile[-4:]
destfile = destfile[0:-4]
if destfile[-4:] == '.gpg' and ext == '.asc':
destfile = destfile[0:-4] + ext
result = None
if os.path.exists(destfile):
os.remove(destfile)
with open(filename, 'rb') as f:
result = gpg.decrypt_file(f,
always_trust=True,
passphrase=config['encrypt-pw'],
output=destfile)
if result is None:
logging.error('Unable to decrypt (unknown reason): %s' % filename)
return None
if result is None or not os.path.exists(destfile):
logging.error('Unable to decrypt (%s): %s' % (result.status, filename))
return None
filename = destfile
if filename != destfile:
fileutils.copy(filename, destfile)
return destfile
def getBackupFiles(itemFromBackup):
# Get the files in that folder and filter out the ones not part of the backup
basename, ignore = os.path.basename(itemFromBackup).split('.', 1)
basepath = os.path.dirname(itemFromBackup)
if basepath == '':
basepath = './'
unfiltered = os.listdir(basepath)
files = []
for f in unfiltered:
if os.path.basename(f).startswith(basename) or f == "filelist.txt":
logging.debug('Found backup file "%s"' % f)
files.append(f)
return (basepath, files)
""" Parse command line """
parser = argparse.ArgumentParser(description="Iceshelf Restore - Restores the contents of an iceshelf backup", formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--logfile', metavar="FILE", help="Log to file instead of stdout")
parser.add_argument('--debug', action='store_true', default=False, help='Adds more details to the log output')
parser.add_argument('--restore', metavar="DEST", default=None, help='Extracts the backup')
parser.add_argument('--list', action='store_true', default=False, help='List contents of backup (will not extract)')
parser.add_argument('--lastbackup', metavar='LAST', help='If set, requires the backup to be the successor of LAST')
parser.add_argument('--force', action='store_true', default=False, help='Even if manifest is missing, it will at least try to verify and repair archive')
parser.add_argument('config', metavar="CONFIG", help="Which config file to load")
parser.add_argument('backup', metavar="BACKUP", help="File from an iceshelf backup")
cmdline = parser.parse_args()
""" Setup logging first """
logging.getLogger('').handlers = []
loglevel=logging.INFO
if cmdline.logfile:
logformat=u'%(asctime)s - %(levelname)s - %(message)s'
else:
logformat=u'%(message)s'
if cmdline.debug:
loglevel=logging.DEBUG
logformat=u'%(asctime)s - %(filename)s@%(lineno)d - %(levelname)s - %(message)s'
logging.basicConfig(stream=sys.stdout, filename=cmdline.logfile, level=loglevel, format=logformat)
logging.getLogger("gnupg").setLevel(logging.WARNING)
logging.getLogger("shutil").setLevel(logging.WARNING)
# Make sure we have the correct gnupg module
if not "encrypt_file" in dir(gnupg.GPG()):
logging.error("Current GnuPG python module does not support file encryption, please check FAQ section in documentation")
sys.exit(255)
#######################
config = configuration.parse(cmdline.config, True)
if config is None:
logging.error("Configuration is broken, please check %s" % cmdline.config)
sys.exit(1)
if not os.path.isfile(cmdline.backup):
logging.error('"%s" is not a file' % cmdline.backup.decode('UTF-8'))
sys.exit(1)
basepath, files = getBackupFiles(cmdline.backup)
fileManifest = None
fileArchive = None
fileParity = None
filelist = None
oldfilelist = False
corruptFiles = []
processedFiles = []
skipParity = False
for f in files:
if ".json" in f:
fileManifest = f
elif ".par2" in f:
fileParity = f
elif ".tar" in f:
fileArchive = f
elif f.endswith(".lst"):
filelist = f
elif f == "filelist.txt":
oldfilelist = True
if fileManifest is None:
if cmdline.force:
logging.error("No manifest found, unable to restore. Will try to verify and repair if needed")
else:
logging.error("No manifest found, unable to restore (use --force to do as much as possible)")
sys.exit(1)
if fileArchive is None:
logging.error("No archive found, unable to continue")
sys.exit(1)
if fileManifest is not None:
logging.debug('Using manifest "%s"' % fileManifest)
if fileParity is not None:
logging.debug("Parity is available")
# If we have a filelist, use it to confirm files
if filelist and not validArchive(basepath, filelist, corruptFiles, files) and not cmdline.force:
sys.exit(1)
elif oldfilelist:
logging.warn('Using older "filelist.txt" instead of new format using file ending in ".lst"')
if not validArchive(basepath, "filelist.txt", corruptFiles, files) and not cmdline.force:
sys.exit(1)
# Strip all files except archive (ie, verify signature and decrypt)
# since archive might need repairs and for that we need PAR2
for f in files:
if f in corruptFiles:
continue
if f == fileArchive:
continue
if not validateFile(os.path.join(basepath, f)):
logging.error('File "%s" signature does not match' % f)
if not cmdline.force:
sys.exit(1)
# Do not extract files we don't need (ie, when not extracting)
if not cmdline.list and not cmdline.restore:
continue
if f != fileManifest and not cmdline.restore:
continue
n = stripFile(os.path.join(basepath, f))
if n is None:
logging.error('Unable to process "%s"' % f)
sys.exit(1)
else:
processedFiles.append(n)
if n.endswith('.json'):
fileManifest = n
if not cmdline.list and not cmdline.restore:
sys.exit(0)
if cmdline.restore and fileParity is not None and len(corruptFiles) > 0:
logging.info('Repairing corrupted archive file "%s"' % fileArchive)
for f in processedFiles:
if f.endswith(fileArchive + '.par2'):
if not fileutils.repairParity(f):
logging.error("Failed to repair file, not enough parity material")
sys.exit(1)
else:
logging.info('File was repaired successfully')
break
# Strip the archive
if cmdline.restore:
if not validateFile(os.path.join(basepath, fileArchive)):
logging.error('File "%s" signature does not match' % fileArchive)
if not cmdline.force:
sys.exit(1)
archive = stripFile(os.path.join(basepath, fileArchive))
if archive is None:
logging.error('Unable to process "%s"' % fileArchive)
sys.exit(1)
else:
logging.info('No restore directory given. Exit.')
sys.exit(0)
if fileManifest is None:
logging.info('This is as much as can be done. You can now manually extract the files')
sys.exit(0)
# And now... restore
manifest = None
with open(fileManifest) as fp:
manifest = json.load(fp)
# If last backup is defined, check it
if cmdline.lastbackup is not None:
if 'lastbackup' not in manifest:
logging.debug('This backup does not specify a previous backup (made with an older version of iceshelf)')
if 'lastbackup' not in manifest or manifest['lastbackup'] != cmdline.lastbackup:
logging.error('Backup "%s" is not the successor of "%s"' % (os.path.basename(fileManifest)[0:-5], cmdline.lastbackup))
sys.exit(1)
# If available, show which backup that preceeded it
if cmdline.list:
if 'lastbackup' in manifest:
logging.info('Manifest: Parent backup is "%s"' % manifest['lastbackup'])
else:
logging.debug('Manifest: Does not contain parent reference')
# Now, print the files we're changing or creating
filecount = 0
fileerror = 0
for k in manifest['modified']:
v = manifest['modified'][k]
src = os.path.normpath(cmdline.restore + k)
if cmdline.list:
logging.info('Manifest: Modified or new file "%s" in "%s"' % (os.path.basename(k), os.path.dirname(k)))
filecount += 1
# Iterate the archive and make sure we know what's in it
if cmdline.restore:
with tarfile.open(archive, "r:*") as tar:
item = tar.next()
while item != None:
if '/' + item.name.decode('UTF-8') not in manifest['modified']:
logging.error('Archive contains "%s", not listed in the manifest' % item.name.decode('UTF-8'))
fileerror += 1
else:
manifest['modified']['/' + item.name.decode('UTF-8')]['found'] = True
filecount -= 1
item = tar.next()
# Check that all files we were looking for was in the archive
for k in manifest['modified']:
if not 'found' in manifest['modified'][k]:
logging.error('Archive is missing "%s"' % k)
fileerror += 1
if fileerror != 0 or filecount != 0:
logging.error("Archive contains errors, aborting")
sys.exit(1)
# Step 1: Remove any files that were deleted
for f in manifest['deleted']:
src = os.path.normpath(cmdline.restore + f)
if cmdline.list:
logging.info('Manifest: Deleting "%s"' % src)
if cmdline.restore:
try:
os.unlink(src);
except:
logging.warn('Unable to remove "%s"' % src)
for k in manifest['moved']:
v = manifest['moved'][k]
src = os.path.normpath(cmdline.restore + v['original'])
dst = os.path.normpath(cmdline.restore + k)
if cmdline.list:
logging.info('Manifest: Moving "%s" to "%s"' % (src, dst))
if cmdline.restore:
try:
os.rename(src, dst)
except:
logging.warn('Unable to move "%s" to "%s"' % (src, dst))
# Finally, if not a dryrun
if not cmdline.restore:
sys.exit(0)
# Time to extract the files
with tarfile.open(archive, "r:*") as tar:
item = tar.next()
while item != None:
filename = os.path.normpath(cmdline.restore + "/" + item.name.decode('UTF-8'))
logging.info('Extracting "%s" to "%s"' % (os.path.basename(filename), os.path.dirname(filename)))
tar.extract(item, cmdline.restore)
item = tar.next()
logging.info("Backup has been restored")