backup.py 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # The Qubes OS Project, http://www.qubes-os.org
  5. #
  6. # Copyright (C) 2013 Marek Marczykowski-Górecki <marmarek@invisiblethingslab.com>
  7. # Copyright (C) 2013 Olivier Médoc <o_medoc@yahoo.fr>
  8. #
  9. # This program is free software; you can redistribute it and/or
  10. # modify it under the terms of the GNU General Public License
  11. # as published by the Free Software Foundation; either version 2
  12. # of the License, or (at your option) any later version.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License
  20. # along with this program; if not, write to the Free Software
  21. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  22. #
  23. #
  24. from qubes import QubesException,QubesVmCollection
  25. from qubes import QubesVmClasses
  26. from qubes import system_path,vm_files
  27. from qubesutils import size_to_human, print_stdout, print_stderr
  28. import sys
  29. import os
  30. import subprocess
  31. import re
  32. import shutil
  33. import tempfile
  34. import time
  35. import grp,pwd
  36. import errno
  37. import datetime
  38. from multiprocessing import Queue,Process
  39. BACKUP_DEBUG = False
  40. HEADER_FILENAME = 'backup-header'
  41. DEFAULT_CRYPTO_ALGORITHM = 'aes-256-cbc'
  42. DEFAULT_HMAC_ALGORITHM = 'SHA1'
  43. # Maximum size of error message get from process stderr (including VM process)
  44. MAX_STDERR_BYTES = 1024
  45. # header + qubes.xml max size
  46. HEADER_QUBES_XML_MAX_SIZE = 1024 * 1024
  47. # global state for backup_cancel()
  48. running_backup_operation = None
  49. class BackupOperationInfo:
  50. def __init__(self):
  51. self.canceled = False
  52. self.processes_to_kill_on_cancel = []
  53. self.tmpdir_to_remove = None
  54. class BackupCanceledError(QubesException):
  55. def __init__(self, msg, tmpdir=None):
  56. super(BackupCanceledError, self).__init__(msg)
  57. self.tmpdir = tmpdir
  58. class BackupHeader:
  59. encrypted = 'encrypted'
  60. compressed = 'compressed'
  61. crypto_algorithm = 'crypto-algorithm'
  62. hmac_algorithm = 'hmac-algorithm'
  63. bool_options = ['encrypted', 'compressed']
  64. def get_disk_usage(file_or_dir):
  65. if not os.path.exists(file_or_dir):
  66. return 0
  67. p = subprocess.Popen (["du", "-s", "--block-size=1", file_or_dir],
  68. stdout=subprocess.PIPE)
  69. result = p.communicate()
  70. m = re.match(r"^(\d+)\s.*", result[0])
  71. sz = int(m.group(1)) if m is not None else 0
  72. return sz
  73. def file_to_backup (file_path, subdir = None):
  74. sz = get_disk_usage (file_path)
  75. if subdir is None:
  76. abs_file_path = os.path.abspath (file_path)
  77. abs_base_dir = os.path.abspath (system_path["qubes_base_dir"]) + '/'
  78. abs_file_dir = os.path.dirname (abs_file_path) + '/'
  79. (nothing, dir, subdir) = abs_file_dir.partition (abs_base_dir)
  80. assert nothing == ""
  81. assert dir == abs_base_dir
  82. else:
  83. if len(subdir) > 0 and not subdir.endswith('/'):
  84. subdir += '/'
  85. return [ { "path" : file_path, "size": sz, "subdir": subdir} ]
  86. def backup_cancel():
  87. """
  88. Cancel currently running backup/restore operation
  89. @return: True if any operation was signaled
  90. """
  91. if running_backup_operation is None:
  92. return False
  93. running_backup_operation.canceled = True
  94. for proc in running_backup_operation.processes_to_kill_on_cancel:
  95. try:
  96. proc.terminate()
  97. except:
  98. pass
  99. return True
  100. def backup_prepare(vms_list = None, exclude_list = None,
  101. print_callback = print_stdout, hide_vm_names=True):
  102. """If vms = None, include all (sensible) VMs; exclude_list is always applied"""
  103. files_to_backup = file_to_backup (system_path["qubes_store_filename"])
  104. if exclude_list is None:
  105. exclude_list = []
  106. qvm_collection = QubesVmCollection()
  107. qvm_collection.lock_db_for_writing()
  108. qvm_collection.load()
  109. if vms_list is None:
  110. all_vms = [vm for vm in qvm_collection.values()]
  111. selected_vms = [vm for vm in all_vms if vm.include_in_backups]
  112. appvms_to_backup = [vm for vm in selected_vms if vm.is_appvm() and not vm.internal]
  113. netvms_to_backup = [vm for vm in selected_vms if vm.is_netvm() and not vm.qid == 0]
  114. template_vms_worth_backingup = [vm for vm in selected_vms if (vm.is_template() and not vm.installed_by_rpm)]
  115. dom0 = [ qvm_collection[0] ]
  116. vms_list = appvms_to_backup + netvms_to_backup + template_vms_worth_backingup + dom0
  117. vms_for_backup = vms_list
  118. # Apply exclude list
  119. if exclude_list:
  120. vms_for_backup = [vm for vm in vms_list if vm.name not in exclude_list]
  121. no_vms = len (vms_for_backup)
  122. there_are_running_vms = False
  123. fields_to_display = [
  124. { "name": "VM", "width": 16},
  125. { "name": "type","width": 12 },
  126. { "name": "size", "width": 12}
  127. ]
  128. # Display the header
  129. s = ""
  130. for f in fields_to_display:
  131. fmt="{{0:-^{0}}}-+".format(f["width"] + 1)
  132. s += fmt.format('-')
  133. print_callback(s)
  134. s = ""
  135. for f in fields_to_display:
  136. fmt="{{0:>{0}}} |".format(f["width"] + 1)
  137. s += fmt.format(f["name"])
  138. print_callback(s)
  139. s = ""
  140. for f in fields_to_display:
  141. fmt="{{0:-^{0}}}-+".format(f["width"] + 1)
  142. s += fmt.format('-')
  143. print_callback(s)
  144. files_to_backup_index = 0
  145. for vm in vms_for_backup:
  146. if vm.is_template():
  147. # handle templates later
  148. continue
  149. if vm.qid == 0:
  150. # handle dom0 later
  151. continue
  152. if hide_vm_names:
  153. subdir = 'vm%d/' % vm.qid
  154. else:
  155. subdir = None
  156. if vm.private_img is not None:
  157. files_to_backup += file_to_backup(vm.private_img, subdir)
  158. if vm.is_appvm():
  159. files_to_backup += file_to_backup(vm.icon_path, subdir)
  160. if vm.updateable:
  161. if os.path.exists(vm.dir_path + "/apps.templates"):
  162. # template
  163. files_to_backup += file_to_backup(vm.dir_path + "/apps.templates", subdir)
  164. else:
  165. # standaloneVM
  166. files_to_backup += file_to_backup(vm.dir_path + "/apps", subdir)
  167. if os.path.exists(vm.dir_path + "/kernels"):
  168. files_to_backup += file_to_backup(vm.dir_path + "/kernels", subdir)
  169. if os.path.exists (vm.firewall_conf):
  170. files_to_backup += file_to_backup(vm.firewall_conf, subdir)
  171. if 'appmenus_whitelist' in vm_files and \
  172. os.path.exists(os.path.join(vm.dir_path, vm_files['appmenus_whitelist'])):
  173. files_to_backup += file_to_backup(
  174. os.path.join(vm.dir_path, vm_files['appmenus_whitelist']),
  175. subdir)
  176. if vm.updateable:
  177. files_to_backup += file_to_backup(vm.root_img, subdir)
  178. s = ""
  179. fmt="{{0:>{0}}} |".format(fields_to_display[0]["width"] + 1)
  180. s += fmt.format(vm.name)
  181. fmt="{{0:>{0}}} |".format(fields_to_display[1]["width"] + 1)
  182. if vm.is_netvm():
  183. s += fmt.format("NetVM" + (" + Sys" if vm.updateable else ""))
  184. else:
  185. s += fmt.format("AppVM" + (" + Sys" if vm.updateable else ""))
  186. vm_size = reduce(lambda x, y: x + y["size"],
  187. files_to_backup[files_to_backup_index:],
  188. 0)
  189. files_to_backup_index = len(files_to_backup)
  190. fmt="{{0:>{0}}} |".format(fields_to_display[2]["width"] + 1)
  191. s += fmt.format(size_to_human(vm_size))
  192. if vm.is_running():
  193. s += " <-- The VM is running, please shut it down before proceeding with the backup!"
  194. there_are_running_vms = True
  195. print_callback(s)
  196. for vm in vms_for_backup:
  197. if not vm.is_template():
  198. # already handled
  199. continue
  200. if vm.qid == 0:
  201. # handle dom0 later
  202. continue
  203. vm_sz = vm.get_disk_utilization()
  204. if hide_vm_names:
  205. template_subdir = 'vm%d/' % vm.qid
  206. else:
  207. template_subdir = os.path.relpath(
  208. vm.dir_path,
  209. system_path["qubes_base_dir"]) + '/'
  210. template_to_backup = [ {
  211. "path": vm.dir_path + '/.',
  212. "size": vm_sz,
  213. "subdir": template_subdir } ]
  214. files_to_backup += template_to_backup
  215. s = ""
  216. fmt="{{0:>{0}}} |".format(fields_to_display[0]["width"] + 1)
  217. s += fmt.format(vm.name)
  218. fmt="{{0:>{0}}} |".format(fields_to_display[1]["width"] + 1)
  219. s += fmt.format("Template VM")
  220. fmt="{{0:>{0}}} |".format(fields_to_display[2]["width"] + 1)
  221. s += fmt.format(size_to_human(vm_sz))
  222. if vm.is_running():
  223. s += " <-- The VM is running, please shut it down before proceeding with the backup!"
  224. there_are_running_vms = True
  225. print_callback(s)
  226. # Initialize backup flag on all VMs
  227. vms_for_backup_qid = [vm.qid for vm in vms_for_backup]
  228. for vm in qvm_collection.values():
  229. vm.backup_content = False
  230. if vm.qid == 0:
  231. # handle dom0 later
  232. continue
  233. if vm.qid in vms_for_backup_qid:
  234. vm.backup_content = True
  235. vm.backup_size = vm.get_disk_utilization()
  236. if hide_vm_names:
  237. vm.backup_path = 'vm%d' % vm.qid
  238. else:
  239. vm.backup_path = os.path.relpath(vm.dir_path, system_path["qubes_base_dir"])
  240. # Dom0 user home
  241. if 0 in vms_for_backup_qid:
  242. local_user = grp.getgrnam('qubes').gr_mem[0]
  243. home_dir = pwd.getpwnam(local_user).pw_dir
  244. # Home dir should have only user-owned files, so fix it now to prevent
  245. # permissions problems - some root-owned files can left after
  246. # 'sudo bash' and similar commands
  247. subprocess.check_call(['sudo', 'chown', '-R', local_user, home_dir])
  248. home_sz = get_disk_usage(home_dir)
  249. home_to_backup = [ { "path" : home_dir, "size": home_sz, "subdir": 'dom0-home/'} ]
  250. files_to_backup += home_to_backup
  251. vm = qvm_collection[0]
  252. vm.backup_content = True
  253. vm.backup_size = home_sz
  254. vm.backup_path = os.path.join('dom0-home', os.path.basename(home_dir))
  255. s = ""
  256. fmt="{{0:>{0}}} |".format(fields_to_display[0]["width"] + 1)
  257. s += fmt.format('Dom0')
  258. fmt="{{0:>{0}}} |".format(fields_to_display[1]["width"] + 1)
  259. s += fmt.format("User home")
  260. fmt="{{0:>{0}}} |".format(fields_to_display[2]["width"] + 1)
  261. s += fmt.format(size_to_human(home_sz))
  262. print_callback(s)
  263. qvm_collection.save()
  264. # FIXME: should be after backup completed
  265. qvm_collection.unlock_db()
  266. total_backup_sz = 0
  267. for file in files_to_backup:
  268. total_backup_sz += file["size"]
  269. s = ""
  270. for f in fields_to_display:
  271. fmt="{{0:-^{0}}}-+".format(f["width"] + 1)
  272. s += fmt.format('-')
  273. print_callback(s)
  274. s = ""
  275. fmt="{{0:>{0}}} |".format(fields_to_display[0]["width"] + 1)
  276. s += fmt.format("Total size:")
  277. fmt="{{0:>{0}}} |".format(fields_to_display[1]["width"] + 1 + 2 + fields_to_display[2]["width"] + 1)
  278. s += fmt.format(size_to_human(total_backup_sz))
  279. print_callback(s)
  280. s = ""
  281. for f in fields_to_display:
  282. fmt="{{0:-^{0}}}-+".format(f["width"] + 1)
  283. s += fmt.format('-')
  284. print_callback(s)
  285. vms_not_for_backup = [vm.name for vm in qvm_collection.values() if not vm
  286. .backup_content]
  287. print_callback("VMs not selected for backup: %s" % " ".join(
  288. vms_not_for_backup))
  289. if (there_are_running_vms):
  290. raise QubesException("Please shutdown all VMs before proceeding.")
  291. for fileinfo in files_to_backup:
  292. assert len(fileinfo["subdir"]) == 0 or fileinfo["subdir"][-1] == '/', \
  293. "'subdir' must ends with a '/': %s" % str(fileinfo)
  294. return files_to_backup
  295. class SendWorker(Process):
  296. def __init__(self, queue, base_dir, backup_stdout):
  297. super(SendWorker, self).__init__()
  298. self.queue = queue
  299. self.base_dir = base_dir
  300. self.backup_stdout = backup_stdout
  301. def run(self):
  302. if BACKUP_DEBUG:
  303. print "Started sending thread"
  304. if BACKUP_DEBUG:
  305. print "Moving to temporary dir", self.base_dir
  306. os.chdir(self.base_dir)
  307. for filename in iter(self.queue.get,None):
  308. if filename == "FINISHED" or filename == "ERROR":
  309. break
  310. if BACKUP_DEBUG:
  311. print "Sending file", filename
  312. # This tar used for sending data out need to be as simple, as
  313. # simple, as featureless as possible. It will not be
  314. # verified before untaring.
  315. tar_final_cmd = ["tar", "-cO", "--posix",
  316. "-C", self.base_dir, filename]
  317. final_proc = subprocess.Popen (tar_final_cmd,
  318. stdin=subprocess.PIPE, stdout=self.backup_stdout)
  319. if final_proc.wait() >= 2:
  320. # handle only exit code 2 (tar fatal error) or greater (call failed?)
  321. raise QubesException("ERROR: Failed to write the backup, out of disk space? "
  322. "Check console output or ~/.xsession-errors for details.")
  323. # Delete the file as we don't need it anymore
  324. if BACKUP_DEBUG:
  325. print "Removing file", filename
  326. os.remove(filename)
  327. if BACKUP_DEBUG:
  328. print "Finished sending thread"
  329. def prepare_backup_header(target_directory, passphrase, compressed=False,
  330. encrypted=False,
  331. hmac_algorithm=DEFAULT_HMAC_ALGORITHM,
  332. crypto_algorithm=DEFAULT_CRYPTO_ALGORITHM):
  333. header_file_path = os.path.join(target_directory, HEADER_FILENAME)
  334. with open(header_file_path, "w") as f:
  335. f.write("%s=%s\n" % (BackupHeader.hmac_algorithm, hmac_algorithm))
  336. f.write("%s=%s\n" % (BackupHeader.crypto_algorithm, crypto_algorithm))
  337. f.write("%s=%s\n" % (BackupHeader.encrypted, str(encrypted)))
  338. f.write("%s=%s\n" % (BackupHeader.compressed, str(compressed)))
  339. hmac = subprocess.Popen (["openssl", "dgst",
  340. "-" + hmac_algorithm, "-hmac", passphrase],
  341. stdin=open(header_file_path, "r"),
  342. stdout=open(header_file_path + ".hmac", "w"))
  343. if hmac.wait() != 0:
  344. raise QubesException("Failed to compute hmac of header file")
  345. return (HEADER_FILENAME, HEADER_FILENAME+".hmac")
  346. def backup_do(base_backup_dir, files_to_backup, passphrase,
  347. progress_callback = None, encrypted=False, appvm=None,
  348. compressed=False, hmac_algorithm=DEFAULT_HMAC_ALGORITHM,
  349. crypto_algorithm=DEFAULT_CRYPTO_ALGORITHM):
  350. global running_backup_operation
  351. total_backup_sz = 0
  352. passphrase = passphrase.encode('utf-8')
  353. for file in files_to_backup:
  354. total_backup_sz += file["size"]
  355. if compressed and encrypted:
  356. raise QubesException("Compressed and encrypted backups are not "
  357. "supported (yet).")
  358. running_backup_operation = BackupOperationInfo()
  359. vmproc = None
  360. if appvm != None:
  361. # Prepare the backup target (Qubes service call)
  362. backup_target = "QUBESRPC qubes.Backup dom0"
  363. # If APPVM, STDOUT is a PIPE
  364. vmproc = appvm.run(command=backup_target, passio_popen=True,
  365. passio_stderr=True)
  366. vmproc.stdin.write(base_backup_dir.
  367. replace("\r", "").replace("\n", "")+"\n")
  368. backup_stdout = vmproc.stdin
  369. running_backup_operation.processes_to_kill_on_cancel.append(vmproc)
  370. else:
  371. # Prepare the backup target (local file)
  372. if os.path.isdir(base_backup_dir):
  373. backup_target = base_backup_dir + "/qubes-{0}". \
  374. format(time.strftime("%Y-%m-%dT%H%M%S"))
  375. else:
  376. backup_target = base_backup_dir
  377. # Create the target directory
  378. if not os.path.exists (os.path.dirname(base_backup_dir)):
  379. raise QubesException(
  380. "ERROR: the backup directory for {0} does not exists".
  381. format(base_backup_dir))
  382. # If not APPVM, STDOUT is a local file
  383. backup_stdout = open(backup_target,'wb')
  384. global blocks_backedup
  385. blocks_backedup = 0
  386. progress = blocks_backedup * 11 / total_backup_sz
  387. progress_callback(progress)
  388. backup_tmpdir = tempfile.mkdtemp(prefix="/var/tmp/backup_")
  389. running_backup_operation.tmpdir_to_remove = backup_tmpdir
  390. # Tar with tapelength does not deals well with stdout (close stdout between
  391. # two tapes)
  392. # For this reason, we will use named pipes instead
  393. if BACKUP_DEBUG:
  394. print "Working in", backup_tmpdir
  395. backup_pipe = os.path.join(backup_tmpdir, "backup_pipe")
  396. if BACKUP_DEBUG:
  397. print "Creating pipe in:", backup_pipe
  398. os.mkfifo(backup_pipe)
  399. if BACKUP_DEBUG:
  400. print "Will backup:", files_to_backup
  401. header_files = prepare_backup_header(backup_tmpdir, passphrase,
  402. compressed=compressed,
  403. encrypted=encrypted,
  404. hmac_algorithm=hmac_algorithm,
  405. crypto_algorithm=crypto_algorithm)
  406. # Setup worker to send encrypted data chunks to the backup_target
  407. def compute_progress(new_size, total_backup_sz):
  408. global blocks_backedup
  409. blocks_backedup += new_size
  410. progress = blocks_backedup / float(total_backup_sz)
  411. progress_callback(int(round(progress*100,2)))
  412. to_send = Queue(10)
  413. send_proc = SendWorker(to_send, backup_tmpdir, backup_stdout)
  414. send_proc.start()
  415. for f in header_files:
  416. to_send.put(f)
  417. for filename in files_to_backup:
  418. if BACKUP_DEBUG:
  419. print "Backing up", filename
  420. backup_tempfile = os.path.join(backup_tmpdir,
  421. filename["subdir"],
  422. os.path.basename(filename["path"]))
  423. if BACKUP_DEBUG:
  424. print "Using temporary location:", backup_tempfile
  425. # Ensure the temporary directory exists
  426. if not os.path.isdir(os.path.dirname(backup_tempfile)):
  427. os.makedirs(os.path.dirname(backup_tempfile))
  428. # The first tar cmd can use any complex feature as we want. Files will
  429. # be verified before untaring this.
  430. # Prefix the path in archive with filename["subdir"] to have it verified during untar
  431. tar_cmdline = ["tar", "-Pc", '--sparse',
  432. "-f", backup_pipe,
  433. '--tape-length', str(100000),
  434. '-C', os.path.dirname(filename["path"]),
  435. '--xform', 's:^[^/]:%s\\0:' % filename["subdir"],
  436. os.path.basename(filename["path"])
  437. ]
  438. if BACKUP_DEBUG:
  439. print " ".join(tar_cmdline)
  440. # Tips: Popen(bufsize=0)
  441. # Pipe: tar-sparse | encryptor [| hmac] | tar | backup_target
  442. # Pipe: tar-sparse [| hmac] | tar | backup_target
  443. tar_sparse = subprocess.Popen (tar_cmdline, stdin=subprocess.PIPE,
  444. stderr=(open(os.devnull, 'w') if not BACKUP_DEBUG else None))
  445. running_backup_operation.processes_to_kill_on_cancel.append(tar_sparse)
  446. # Wait for compressor (tar) process to finish or for any error of other
  447. # subprocesses
  448. i = 0
  449. run_error = "paused"
  450. while run_error == "paused":
  451. pipe = open(backup_pipe,'rb')
  452. # Start HMAC
  453. hmac = subprocess.Popen (["openssl", "dgst",
  454. "-" + hmac_algorithm, "-hmac", passphrase],
  455. stdin=subprocess.PIPE, stdout=subprocess.PIPE)
  456. # Prepare a first chunk
  457. chunkfile = backup_tempfile + "." + "%03d" % i
  458. i += 1
  459. chunkfile_p = open(chunkfile,'wb')
  460. common_args = {
  461. 'backup_target': chunkfile_p,
  462. 'total_backup_sz': total_backup_sz,
  463. 'hmac': hmac,
  464. 'vmproc': vmproc,
  465. 'addproc': tar_sparse,
  466. 'progress_callback': compute_progress,
  467. }
  468. if encrypted:
  469. # Start encrypt
  470. # If no cipher is provided, the data is forwarded unencrypted !!!
  471. encryptor = subprocess.Popen (["openssl", "enc",
  472. "-e", "-" + crypto_algorithm,
  473. "-pass", "pass:"+passphrase] +
  474. (["-z"] if compressed else []),
  475. stdin=pipe, stdout=subprocess.PIPE)
  476. run_error = wait_backup_feedback(
  477. in_stream=encryptor.stdout, streamproc=encryptor,
  478. **common_args)
  479. elif compressed:
  480. compressor = subprocess.Popen (["gzip"],
  481. stdin=pipe, stdout=subprocess.PIPE)
  482. run_error = wait_backup_feedback(
  483. in_stream=compressor.stdout, streamproc=compressor,
  484. **common_args)
  485. else:
  486. run_error = wait_backup_feedback(
  487. in_stream=pipe, streamproc=None,
  488. **common_args)
  489. chunkfile_p.close()
  490. if BACKUP_DEBUG:
  491. print "Wait_backup_feedback returned:", run_error
  492. if running_backup_operation.canceled:
  493. try:
  494. tar_sparse.terminate()
  495. except:
  496. pass
  497. try:
  498. hmac.terminate()
  499. except:
  500. pass
  501. tar_sparse.wait()
  502. hmac.wait()
  503. to_send.put("ERROR")
  504. send_proc.join()
  505. shutil.rmtree(backup_tmpdir)
  506. running_backup_operation = None
  507. raise BackupCanceledError("Backup canceled")
  508. if len(run_error) > 0:
  509. send_proc.terminate()
  510. if run_error == "VM" and vmproc:
  511. raise QubesException("Failed to write the backup, VM output:\n" +
  512. vmproc.stderr.read(MAX_STDERR_BYTES))
  513. else:
  514. raise QubesException("Failed to perform backup: error in "+ \
  515. run_error)
  516. # Send the chunk to the backup target
  517. to_send.put(os.path.relpath(chunkfile, backup_tmpdir))
  518. # Close HMAC
  519. hmac.stdin.close()
  520. hmac.wait()
  521. if BACKUP_DEBUG:
  522. print "HMAC proc return code:", hmac.poll()
  523. # Write HMAC data next to the chunk file
  524. hmac_data = hmac.stdout.read()
  525. if BACKUP_DEBUG:
  526. print "Writing hmac to", chunkfile+".hmac"
  527. hmac_file = open(chunkfile+".hmac",'w')
  528. hmac_file.write(hmac_data)
  529. hmac_file.flush()
  530. hmac_file.close()
  531. pipe.close()
  532. # Send the HMAC to the backup target
  533. to_send.put(os.path.relpath(chunkfile, backup_tmpdir)+".hmac")
  534. if tar_sparse.poll() is None:
  535. # Release the next chunk
  536. if BACKUP_DEBUG:
  537. print "Release next chunk for process:", tar_sparse.poll()
  538. #tar_sparse.stdout = subprocess.PIPE
  539. tar_sparse.stdin.write("\n")
  540. tar_sparse.stdin.flush()
  541. run_error="paused"
  542. else:
  543. running_backup_operation.processes_to_kill_on_cancel.remove(
  544. tar_sparse)
  545. if BACKUP_DEBUG:
  546. print "Finished tar sparse with error", tar_sparse.poll()
  547. to_send.put("FINISHED")
  548. send_proc.join()
  549. shutil.rmtree(backup_tmpdir)
  550. if running_backup_operation.canceled:
  551. running_backup_operation = None
  552. raise BackupCanceledError("Backup canceled")
  553. running_backup_operation = None
  554. if send_proc.exitcode != 0:
  555. raise QubesException("Failed to send backup: error in the sending process")
  556. if vmproc:
  557. if BACKUP_DEBUG:
  558. print "VMProc1 proc return code:", vmproc.poll()
  559. print "Sparse1 proc return code:", tar_sparse.poll()
  560. vmproc.stdin.close()
  561. # Save date of last backup
  562. qvm_collection = QubesVmCollection()
  563. qvm_collection.lock_db_for_writing()
  564. qvm_collection.load()
  565. for vm in qvm_collection.values():
  566. if vm.backup_content:
  567. vm.backup_timestamp = datetime.datetime.now()
  568. qvm_collection.save()
  569. qvm_collection.unlock_db()
  570. '''
  571. ' Wait for backup chunk to finish
  572. ' - Monitor all the processes (streamproc, hmac, vmproc, addproc) for errors
  573. ' - Copy stdout of streamproc to backup_target and hmac stdin if available
  574. ' - Compute progress based on total_backup_sz and send progress to
  575. ' progress_callback function
  576. ' - Returns if
  577. ' - one of the monitored processes error out (streamproc, hmac, vmproc,
  578. ' addproc), along with the processe that failed
  579. ' - all of the monitored processes except vmproc finished successfully
  580. ' (vmproc termination is controlled by the python script)
  581. ' - streamproc does not delivers any data anymore (return with the error
  582. ' "")
  583. '''
  584. def wait_backup_feedback(progress_callback, in_stream, streamproc,
  585. backup_target, total_backup_sz, hmac=None, vmproc=None, addproc=None,
  586. remove_trailing_bytes=0):
  587. buffer_size = 409600
  588. run_error = None
  589. run_count = 1
  590. blocks_backedup = 0
  591. while run_count > 0 and run_error == None:
  592. buffer = in_stream.read(buffer_size)
  593. progress_callback(len(buffer), total_backup_sz)
  594. run_count = 0
  595. if hmac:
  596. retcode=hmac.poll()
  597. if retcode != None:
  598. if retcode != 0:
  599. run_error = "hmac"
  600. else:
  601. run_count += 1
  602. if addproc:
  603. retcode=addproc.poll()
  604. if retcode != None:
  605. if retcode != 0:
  606. run_error = "addproc"
  607. else:
  608. run_count += 1
  609. if vmproc:
  610. retcode = vmproc.poll()
  611. if retcode != None:
  612. if retcode != 0:
  613. run_error = "VM"
  614. if BACKUP_DEBUG:
  615. print vmproc.stdout.read()
  616. else:
  617. # VM should run until the end
  618. pass
  619. if streamproc:
  620. retcode=streamproc.poll()
  621. if retcode != None:
  622. if retcode != 0:
  623. run_error = "streamproc"
  624. break
  625. elif retcode == 0 and len(buffer) <= 0:
  626. return ""
  627. run_count += 1
  628. else:
  629. if len(buffer) <= 0:
  630. return ""
  631. backup_target.write(buffer)
  632. if hmac:
  633. hmac.stdin.write(buffer)
  634. return run_error
  635. def verify_hmac(filename, hmacfile, passphrase, algorithm):
  636. if BACKUP_DEBUG:
  637. print "Verifying file "+filename
  638. if hmacfile != filename + ".hmac":
  639. raise QubesException(
  640. "ERROR: expected hmac for {}, but got {}".\
  641. format(filename, hmacfile))
  642. hmac_proc = subprocess.Popen (["openssl", "dgst", "-" + algorithm,
  643. "-hmac", passphrase],
  644. stdin=open(filename,'rb'),
  645. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  646. hmac_stdout, hmac_stderr = hmac_proc.communicate()
  647. if len(hmac_stderr) > 0:
  648. raise QubesException("ERROR: verify file {0}: {1}".format(filename, hmac_stderr))
  649. else:
  650. if BACKUP_DEBUG:
  651. print "Loading hmac for file " + filename
  652. hmac = load_hmac(open(hmacfile,'r').read())
  653. if len(hmac) > 0 and load_hmac(hmac_stdout) == hmac:
  654. os.unlink(hmacfile)
  655. if BACKUP_DEBUG:
  656. print "File verification OK -> Sending file " + filename
  657. return True
  658. else:
  659. raise QubesException(
  660. "ERROR: invalid hmac for file {0}: {1}. " \
  661. "Is the passphrase correct?".\
  662. format(filename, load_hmac(hmac_stdout)))
  663. # Not reachable
  664. return False
  665. class ExtractWorker(Process):
  666. def __init__(self, queue, base_dir, passphrase, encrypted, total_size,
  667. print_callback, error_callback, progress_callback, vmproc=None,
  668. compressed = False, crypto_algorithm=DEFAULT_CRYPTO_ALGORITHM):
  669. super(ExtractWorker, self).__init__()
  670. self.queue = queue
  671. self.base_dir = base_dir
  672. self.passphrase = passphrase
  673. self.encrypted = encrypted
  674. self.compressed = compressed
  675. self.crypto_algorithm = crypto_algorithm
  676. self.total_size = total_size
  677. self.blocks_backedup = 0
  678. self.tar2_process = None
  679. self.tar2_current_file = None
  680. self.decompressor_process = None
  681. self.decryptor_process = None
  682. self.print_callback = print_callback
  683. self.error_callback = error_callback
  684. self.progress_callback = progress_callback
  685. self.vmproc = vmproc
  686. self.restore_pipe = os.path.join(self.base_dir,"restore_pipe")
  687. if BACKUP_DEBUG:
  688. print "Creating pipe in:", self.restore_pipe
  689. os.mkfifo(self.restore_pipe)
  690. def compute_progress(self, new_size, total_size):
  691. if self.progress_callback:
  692. self.blocks_backedup += new_size
  693. progress = self.blocks_backedup / float(self.total_size)
  694. progress = int(round(progress*100,2))
  695. self.progress_callback(progress)
  696. def run(self):
  697. try:
  698. self.__run__()
  699. except Exception as e:
  700. exc_type, exc_value, exc_traceback = sys.exc_info()
  701. # Cleanup children
  702. for process in [self.decompressor_process,
  703. self.decryptor_process,
  704. self.tar2_process]:
  705. if process:
  706. # FIXME: kill()?
  707. try:
  708. process.terminate()
  709. except OSError:
  710. pass
  711. process.wait()
  712. self.error_callback(str(e))
  713. raise e, None, exc_traceback
  714. def __run__(self):
  715. if BACKUP_DEBUG:
  716. self.print_callback("Started sending thread")
  717. self.print_callback("Moving to dir "+self.base_dir)
  718. os.chdir(self.base_dir)
  719. filename = None
  720. for filename in iter(self.queue.get, None):
  721. if filename == "FINISHED" or filename == "ERROR":
  722. break
  723. if BACKUP_DEBUG:
  724. self.print_callback("Extracting file "+filename)
  725. if filename.endswith('.000'):
  726. # next file
  727. if self.tar2_process != None:
  728. if self.tar2_process.wait() != 0:
  729. raise QubesException(
  730. "ERROR: unable to extract files for {0}.".\
  731. format(self.tar2_current_file))
  732. else:
  733. # Finished extracting the tar file
  734. self.tar2_process = None
  735. self.tar2_current_file = None
  736. tar2_cmdline = ['tar',
  737. '-xMk%sf' % ("v" if BACKUP_DEBUG else ""), self.restore_pipe,
  738. os.path.relpath(filename.rstrip('.000'))]
  739. if BACKUP_DEBUG:
  740. self.print_callback("Running command "+str(tar2_cmdline))
  741. self.tar2_process = subprocess.Popen(tar2_cmdline,
  742. stdin=subprocess.PIPE,
  743. stderr=(None if BACKUP_DEBUG else open('/dev/null', 'w')))
  744. else:
  745. if BACKUP_DEBUG:
  746. self.print_callback("Releasing next chunck")
  747. self.tar2_process.stdin.write("\n")
  748. self.tar2_process.stdin.flush()
  749. self.tar2_current_file = filename
  750. pipe = open(self.restore_pipe,'wb')
  751. common_args = {
  752. 'backup_target': pipe,
  753. 'total_backup_sz': self.total_size,
  754. 'hmac': None,
  755. 'vmproc': self.vmproc,
  756. 'addproc': self.tar2_process
  757. }
  758. if self.encrypted:
  759. # Start decrypt
  760. self.decryptor_process = subprocess.Popen (["openssl", "enc",
  761. "-d", "-" + self.crypto_algorithm,
  762. "-pass", "pass:"+self.passphrase] +
  763. (["-z"] if self.compressed else []),
  764. stdin=open(filename,'rb'),
  765. stdout=subprocess.PIPE)
  766. run_error = wait_backup_feedback(
  767. progress_callback=self.compute_progress,
  768. in_stream=self.decryptor_process.stdout,
  769. streamproc=self.decryptor_process,
  770. **common_args)
  771. elif self.compressed:
  772. self.decompressor_process = subprocess.Popen (["gzip", "-d"],
  773. stdin=open(filename,'rb'),
  774. stdout=subprocess.PIPE)
  775. run_error = wait_backup_feedback(
  776. progress_callback=self.compute_progress,
  777. in_stream=self.decompressor_process.stdout,
  778. streamproc=self.decompressor_process,
  779. **common_args)
  780. else:
  781. run_error = wait_backup_feedback(
  782. progress_callback=self.compute_progress,
  783. in_stream=open(filename,"rb"), streamproc=None,
  784. **common_args)
  785. try:
  786. pipe.close()
  787. except IOError as e:
  788. if e.errno == errno.EPIPE:
  789. if BACKUP_DEBUG:
  790. self.error_callback("Got EPIPE while closing pipe to the inner tar process")
  791. # ignore the error
  792. else:
  793. raise
  794. if len(run_error):
  795. raise QubesException("Error while processing '%s': %s failed" % \
  796. (self.tar2_current_file, run_error))
  797. # Delete the file as we don't need it anymore
  798. if BACKUP_DEBUG:
  799. self.print_callback("Removing file "+filename)
  800. os.remove(filename)
  801. os.unlink(self.restore_pipe)
  802. if self.tar2_process is not None:
  803. if filename == "ERROR":
  804. self.tar2_process.terminate()
  805. self.tar2_process.wait()
  806. elif self.tar2_process.wait() != 0:
  807. raise QubesException(
  808. "ERROR: unable to extract files for {0}.{1}".
  809. format(self.tar2_current_file,
  810. (" Perhaps the backup is encrypted?"
  811. if not self.encrypted else "")))
  812. else:
  813. # Finished extracting the tar file
  814. self.tar2_process = None
  815. if BACKUP_DEBUG:
  816. self.print_callback("Finished extracting thread")
  817. def get_supported_hmac_algo(hmac_algorithm):
  818. # Start with provided default
  819. if hmac_algorithm:
  820. yield hmac_algorithm
  821. proc = subprocess.Popen(['openssl', 'list-message-digest-algorithms'],
  822. stdout=subprocess.PIPE)
  823. for algo in proc.stdout.readlines():
  824. if '=>' in algo:
  825. continue
  826. yield algo.strip()
  827. proc.wait()
  828. def parse_backup_header(filename):
  829. header_data = {}
  830. with open(filename, 'r') as f:
  831. for line in f.readlines():
  832. if line.count('=') != 1:
  833. raise QubesException("Invalid backup header (line %s)" % line)
  834. (key, value) = line.strip().split('=')
  835. if not any([key == getattr(BackupHeader, attr) for attr in dir(
  836. BackupHeader)]):
  837. # Ignoring unknown option
  838. continue
  839. if key in BackupHeader.bool_options:
  840. value = value.lower() in ["1", "true", "yes"]
  841. header_data[key] = value
  842. return header_data
  843. def restore_vm_dirs (backup_source, restore_tmpdir, passphrase, vms_dirs, vms,
  844. vms_size, print_callback=None, error_callback=None,
  845. progress_callback=None, encrypted=False, appvm=None,
  846. compressed = False, hmac_algorithm=DEFAULT_HMAC_ALGORITHM,
  847. crypto_algorithm=DEFAULT_CRYPTO_ALGORITHM):
  848. global running_backup_operation
  849. if BACKUP_DEBUG:
  850. print_callback("Working in temporary dir:"+restore_tmpdir)
  851. print_callback("Extracting data: " + size_to_human(vms_size)+" to restore")
  852. passphrase = passphrase.encode('utf-8')
  853. header_data = None
  854. vmproc = None
  855. if appvm != None:
  856. # Prepare the backup target (Qubes service call)
  857. backup_target = "QUBESRPC qubes.Restore dom0"
  858. # If APPVM, STDOUT is a PIPE
  859. vmproc = appvm.run(command = backup_target, passio_popen = True, passio_stderr=True)
  860. vmproc.stdin.write(backup_source.replace("\r","").replace("\n","")+"\n")
  861. # Send to tar2qfile the VMs that should be extracted
  862. vmproc.stdin.write(" ".join(vms_dirs)+"\n")
  863. if running_backup_operation:
  864. running_backup_operation.processes_to_kill_on_cancel.append(vmproc)
  865. backup_stdin = vmproc.stdout
  866. tar1_command = ['/usr/libexec/qubes/qfile-dom0-unpacker',
  867. str(os.getuid()), restore_tmpdir, '-v']
  868. else:
  869. backup_stdin = open(backup_source,'rb')
  870. tar1_command = ['tar',
  871. '-ixvf', backup_source,
  872. '-C', restore_tmpdir] + vms_dirs
  873. tar1_env = os.environ.copy()
  874. # TODO: add some safety margin?
  875. tar1_env['UPDATES_MAX_BYTES'] = str(vms_size)
  876. # Restoring only header
  877. if vms_dirs and vms_dirs[0] == HEADER_FILENAME:
  878. # backup-header, backup-header.hmac, qubes-xml.000, qubes-xml.000.hmac
  879. tar1_env['UPDATES_MAX_FILES'] = '4'
  880. else:
  881. # Currently each VM consists of at most 7 archives (count
  882. # file_to_backup calls in backup_prepare()), but add some safety
  883. # margin for further extensions. Each archive is divided into 100MB
  884. # chunks. Additionally each file have own hmac file. So assume upper
  885. # limit as 2*(10*COUNT_OF_VMS+TOTAL_SIZE/100MB)
  886. tar1_env['UPDATES_MAX_FILES'] = str(2*(10*len(vms_dirs) +
  887. int(vms_size/(100*1024*1024))))
  888. if BACKUP_DEBUG:
  889. print_callback("Run command"+str(tar1_command))
  890. command = subprocess.Popen(tar1_command,
  891. stdin=backup_stdin,
  892. stdout=vmproc.stdin if vmproc else subprocess.PIPE,
  893. stderr=subprocess.PIPE,
  894. env=tar1_env)
  895. if running_backup_operation:
  896. running_backup_operation.processes_to_kill_on_cancel.append(command)
  897. # qfile-dom0-unpacker output filelist on stderr (and have stdout connected
  898. # to the VM), while tar output filelist on stdout
  899. if appvm:
  900. filelist_pipe = command.stderr
  901. else:
  902. filelist_pipe = command.stdout
  903. expect_tar_error = False
  904. to_extract = Queue()
  905. nextfile = None
  906. # If want to analyze backup header, do it now
  907. if vms_dirs and vms_dirs[0] == HEADER_FILENAME:
  908. filename = filelist_pipe.readline().strip()
  909. hmacfile = filelist_pipe.readline().strip()
  910. if not appvm:
  911. nextfile = filelist_pipe.readline().strip()
  912. if BACKUP_DEBUG:
  913. print_callback("Got backup header and hmac: %s, %s" % (filename,
  914. hmacfile))
  915. if not filename or filename=="EOF" or \
  916. not hmacfile or hmacfile == "EOF":
  917. if appvm:
  918. vmproc.wait()
  919. proc_error_msg = vmproc.stderr.read(MAX_STDERR_BYTES)
  920. else:
  921. command.wait()
  922. proc_error_msg = command.stderr.read(MAX_STDERR_BYTES)
  923. raise QubesException("Premature end of archive while receiving "
  924. "backup header. Process output:\n" +
  925. proc_error_msg)
  926. filename = os.path.join(restore_tmpdir, filename)
  927. hmacfile = os.path.join(restore_tmpdir, hmacfile)
  928. file_ok = False
  929. for hmac_algo in get_supported_hmac_algo(hmac_algorithm):
  930. try:
  931. if verify_hmac(filename, hmacfile, passphrase, hmac_algo):
  932. file_ok = True
  933. hmac_algorithm = hmac_algo
  934. break
  935. except QubesException:
  936. # Ignore exception here, try the next algo
  937. pass
  938. if not file_ok:
  939. raise QubesException("Corrupted backup header (hmac verification "
  940. "failed). Is the password correct?")
  941. if os.path.basename(filename) == HEADER_FILENAME:
  942. header_data = parse_backup_header(filename)
  943. if BackupHeader.crypto_algorithm in header_data:
  944. crypto_algorithm = header_data[BackupHeader.crypto_algorithm]
  945. if BackupHeader.hmac_algorithm in header_data:
  946. hmac_algorithm = header_data[BackupHeader.hmac_algorithm]
  947. if BackupHeader.compressed in header_data:
  948. compressed = header_data[BackupHeader.compressed]
  949. if BackupHeader.encrypted in header_data:
  950. encrypted = header_data[BackupHeader.encrypted]
  951. os.unlink(filename)
  952. else:
  953. # If this isn't backup header, pass it to ExtractWorker
  954. to_extract.put(filename)
  955. # when tar do not find expected file in archive, it exit with
  956. # code 2. This will happen because we've requested backup-header
  957. # file, but the archive do not contain it. Ignore this particular
  958. # error.
  959. if not appvm:
  960. expect_tar_error = True
  961. # Setup worker to extract encrypted data chunks to the restore dirs
  962. # Create the process here to pass it options extracted from backup header
  963. extract_proc = ExtractWorker(queue=to_extract,
  964. base_dir=restore_tmpdir,
  965. passphrase=passphrase,
  966. encrypted=encrypted,
  967. compressed=compressed,
  968. crypto_algorithm = crypto_algorithm,
  969. total_size=vms_size,
  970. print_callback=print_callback,
  971. error_callback=error_callback,
  972. progress_callback=progress_callback)
  973. extract_proc.start()
  974. try:
  975. filename = None
  976. while True:
  977. if running_backup_operation and running_backup_operation.canceled:
  978. break
  979. if nextfile is not None:
  980. filename = nextfile
  981. else:
  982. filename = filelist_pipe.readline().strip()
  983. if BACKUP_DEBUG:
  984. print_callback("Getting new file:"+filename)
  985. if not filename or filename=="EOF":
  986. break
  987. hmacfile = filelist_pipe.readline().strip()
  988. if running_backup_operation and running_backup_operation.canceled:
  989. break
  990. # if reading archive directly with tar, wait for next filename -
  991. # tar prints filename before processing it, so wait for the next one to be
  992. # sure that whole file was extracted
  993. if not appvm:
  994. nextfile = filelist_pipe.readline().strip()
  995. if BACKUP_DEBUG:
  996. print_callback("Getting hmac:"+hmacfile)
  997. if not hmacfile or hmacfile=="EOF":
  998. # Premature end of archive, either of tar1_command or vmproc exited with error
  999. break
  1000. if not any(map(lambda x: filename.startswith(x), vms_dirs)):
  1001. if BACKUP_DEBUG:
  1002. print_callback("Ignoring VM not selected for restore")
  1003. os.unlink(os.path.join(restore_tmpdir, filename))
  1004. os.unlink(os.path.join(restore_tmpdir, hmacfile))
  1005. continue
  1006. if verify_hmac(os.path.join(restore_tmpdir,filename),
  1007. os.path.join(restore_tmpdir,hmacfile),
  1008. passphrase, hmac_algorithm):
  1009. to_extract.put(os.path.join(restore_tmpdir, filename))
  1010. if running_backup_operation and running_backup_operation.canceled:
  1011. raise BackupCanceledError("Restore canceled",
  1012. tmpdir=restore_tmpdir)
  1013. if command.wait() != 0 and not expect_tar_error:
  1014. raise QubesException(
  1015. "ERROR: unable to read the qubes backup file {0} ({1}). " \
  1016. "Is it really a backup?".format(backup_source, command.wait()))
  1017. if vmproc:
  1018. if vmproc.wait() != 0:
  1019. raise QubesException(
  1020. "ERROR: unable to read the qubes backup {0} " \
  1021. "because of a VM error: {1}".format(
  1022. backup_source, vmproc.stderr.read(MAX_STDERR_BYTES)))
  1023. if filename and filename!="EOF":
  1024. raise QubesException("Premature end of archive, the last file was %s" % filename)
  1025. except:
  1026. to_extract.put("ERROR")
  1027. extract_proc.join()
  1028. running_backup_operation = None
  1029. raise
  1030. else:
  1031. to_extract.put("FINISHED")
  1032. if BACKUP_DEBUG:
  1033. print_callback("Waiting for the extraction process to finish...")
  1034. extract_proc.join()
  1035. if BACKUP_DEBUG:
  1036. print_callback("Extraction process finished with code:" + \
  1037. str(extract_proc.exitcode))
  1038. if extract_proc.exitcode != 0:
  1039. raise QubesException(
  1040. "ERROR: unable to extract the qubes backup. " \
  1041. "Check extracting process errors.")
  1042. return header_data
  1043. def backup_restore_set_defaults(options):
  1044. if 'use-default-netvm' not in options:
  1045. options['use-default-netvm'] = False
  1046. if 'use-none-netvm' not in options:
  1047. options['use-none-netvm'] = False
  1048. if 'use-default-template' not in options:
  1049. options['use-default-template'] = False
  1050. if 'dom0-home' not in options:
  1051. options['dom0-home'] = True
  1052. if 'replace-template' not in options:
  1053. options['replace-template'] = []
  1054. return options
  1055. def load_hmac(hmac):
  1056. hmac = hmac.strip().split("=")
  1057. if len(hmac) > 1:
  1058. hmac = hmac[1].strip()
  1059. else:
  1060. raise QubesException("ERROR: invalid hmac file content")
  1061. return hmac
  1062. def backup_detect_format_version(backup_location):
  1063. if os.path.exists(os.path.join(backup_location, 'qubes.xml')):
  1064. return 1
  1065. else:
  1066. return 2
  1067. def backup_restore_header(source, passphrase,
  1068. print_callback = print_stdout, error_callback = print_stderr,
  1069. encrypted=False, appvm=None, compressed = False, format_version = None,
  1070. hmac_algorithm = DEFAULT_HMAC_ALGORITHM,
  1071. crypto_algorithm = DEFAULT_CRYPTO_ALGORITHM):
  1072. global running_backup_operation
  1073. vmproc = None
  1074. running_backup_operation = None
  1075. restore_tmpdir = tempfile.mkdtemp(prefix="/var/tmp/restore_")
  1076. if format_version == None:
  1077. format_version = backup_detect_format_version(source)
  1078. if format_version == 1:
  1079. return (restore_tmpdir, os.path.join(source, 'qubes.xml'), None)
  1080. # tar2qfile matches only beginnings, while tar full path
  1081. if appvm:
  1082. extract_filter = [HEADER_FILENAME, 'qubes.xml.000']
  1083. else:
  1084. extract_filter = [HEADER_FILENAME, HEADER_FILENAME+'.hmac',
  1085. 'qubes.xml.000', 'qubes.xml.000.hmac']
  1086. header_data = restore_vm_dirs (source,
  1087. restore_tmpdir,
  1088. passphrase=passphrase,
  1089. vms_dirs=extract_filter,
  1090. vms=None,
  1091. vms_size=HEADER_QUBES_XML_MAX_SIZE,
  1092. hmac_algorithm=hmac_algorithm,
  1093. crypto_algorithm=crypto_algorithm,
  1094. print_callback=print_callback,
  1095. error_callback=error_callback,
  1096. progress_callback=None,
  1097. encrypted=encrypted,
  1098. compressed=compressed,
  1099. appvm=appvm)
  1100. return (restore_tmpdir, os.path.join(restore_tmpdir, "qubes.xml"),
  1101. header_data)
  1102. def restore_info_verify(restore_info, host_collection):
  1103. options = restore_info['$OPTIONS$']
  1104. for vm in restore_info.keys():
  1105. if vm in ['$OPTIONS$', 'dom0']:
  1106. continue
  1107. vm_info = restore_info[vm]
  1108. vm_info.pop('excluded', None)
  1109. if 'exclude' in options.keys():
  1110. if vm in options['exclude']:
  1111. vm_info['excluded'] = True
  1112. vm_info.pop('already-exists', None)
  1113. if host_collection.get_vm_by_name (vm) is not None:
  1114. vm_info['already-exists'] = True
  1115. # check template
  1116. vm_info.pop('missing-template', None)
  1117. if vm_info['template']:
  1118. template_name = vm_info['template']
  1119. host_template = host_collection.get_vm_by_name(template_name)
  1120. if not host_template or not host_template.is_template():
  1121. # Maybe the (custom) template is in the backup?
  1122. if not (template_name in restore_info.keys() and
  1123. restore_info[template_name]['vm'].is_template()):
  1124. if options['use-default-template']:
  1125. if 'orig-template' not in vm_info.keys():
  1126. vm_info['orig-template'] = template_name
  1127. vm_info['template'] = host_collection\
  1128. .get_default_template().name
  1129. else:
  1130. vm_info['missing-template'] = True
  1131. # check netvm
  1132. vm_info.pop('missing-netvm', None)
  1133. if vm_info['netvm']:
  1134. netvm_name = vm_info['netvm']
  1135. netvm_on_host = host_collection.get_vm_by_name (netvm_name)
  1136. # No netvm on the host?
  1137. if not ((netvm_on_host is not None) and netvm_on_host.is_netvm()):
  1138. # Maybe the (custom) netvm is in the backup?
  1139. if not (netvm_name in restore_info.keys() and \
  1140. restore_info[netvm_name]['vm'].is_netvm()):
  1141. if options['use-default-netvm']:
  1142. vm_info['netvm'] = host_collection\
  1143. .get_default_netvm().name
  1144. vm_info['vm'].uses_default_netvm = True
  1145. elif options['use-none-netvm']:
  1146. vm_info['netvm'] = None
  1147. else:
  1148. vm_info['missing-netvm'] = True
  1149. vm_info['good-to-go'] = not any([(prop in vm_info.keys()) for
  1150. prop in ['missing-netvm',
  1151. 'missing-template',
  1152. 'already-exists',
  1153. 'excluded']])
  1154. return restore_info
  1155. def backup_restore_prepare(backup_location, passphrase, options = {},
  1156. host_collection = None, encrypted=False, appvm=None,
  1157. compressed = False, print_callback = print_stdout, error_callback = print_stderr,
  1158. format_version=None, hmac_algorithm=DEFAULT_HMAC_ALGORITHM,
  1159. crypto_algorithm=DEFAULT_CRYPTO_ALGORITHM):
  1160. # Defaults
  1161. backup_restore_set_defaults(options)
  1162. #### Private functions begin
  1163. def is_vm_included_in_backup_v1 (backup_dir, vm):
  1164. if vm.qid == 0:
  1165. return os.path.exists(os.path.join(backup_dir,'dom0-home'))
  1166. backup_vm_dir_path = vm.dir_path.replace (system_path["qubes_base_dir"], backup_dir)
  1167. if os.path.exists (backup_vm_dir_path):
  1168. return True
  1169. else:
  1170. return False
  1171. def is_vm_included_in_backup_v2 (backup_dir, vm):
  1172. if vm.backup_content:
  1173. return True
  1174. else:
  1175. return False
  1176. def find_template_name(template, replaces):
  1177. rx_replace = re.compile("(.*):(.*)")
  1178. for r in replaces:
  1179. m = rx_replace.match(r)
  1180. if m.group(1) == template:
  1181. return m.group(2)
  1182. return template
  1183. #### Private functions end
  1184. # Format versions:
  1185. # 1 - Qubes R1, Qubes R2 beta1, beta2
  1186. # 2 - Qubes R2 beta3+
  1187. if format_version is None:
  1188. format_version = backup_detect_format_version(backup_location)
  1189. if format_version == 1:
  1190. is_vm_included_in_backup = is_vm_included_in_backup_v1
  1191. elif format_version == 2:
  1192. is_vm_included_in_backup = is_vm_included_in_backup_v2
  1193. if not appvm:
  1194. if not os.path.isfile(backup_location):
  1195. raise QubesException("Invalid backup location (not a file or "
  1196. "directory with qubes.xml)"
  1197. ": %s" % str(
  1198. backup_location))
  1199. else:
  1200. raise QubesException("Unknown backup format version: %s" % str(format_version))
  1201. (restore_tmpdir, qubes_xml, header_data) = backup_restore_header(
  1202. backup_location,
  1203. passphrase,
  1204. encrypted=encrypted,
  1205. appvm=appvm,
  1206. compressed=compressed,
  1207. hmac_algorithm=hmac_algorithm,
  1208. crypto_algorithm=crypto_algorithm,
  1209. print_callback=print_callback,
  1210. error_callback=error_callback,
  1211. format_version=format_version)
  1212. if header_data:
  1213. if BackupHeader.crypto_algorithm in header_data:
  1214. crypto_algorithm = header_data[BackupHeader.crypto_algorithm]
  1215. if BackupHeader.hmac_algorithm in header_data:
  1216. hmac_algorithm = header_data[BackupHeader.hmac_algorithm]
  1217. if BackupHeader.compressed in header_data:
  1218. compressed = header_data[BackupHeader.compressed]
  1219. if BackupHeader.encrypted in header_data:
  1220. encrypted = header_data[BackupHeader.encrypted]
  1221. if BACKUP_DEBUG:
  1222. print "Loading file", qubes_xml
  1223. backup_collection = QubesVmCollection(store_filename = qubes_xml)
  1224. backup_collection.lock_db_for_reading()
  1225. backup_collection.load()
  1226. if host_collection is None:
  1227. host_collection = QubesVmCollection()
  1228. host_collection.lock_db_for_reading()
  1229. host_collection.load()
  1230. host_collection.unlock_db()
  1231. backup_vms_list = [vm for vm in backup_collection.values()]
  1232. vms_to_restore = {}
  1233. # ... and the actual data
  1234. for vm in backup_vms_list:
  1235. if vm.qid == 0:
  1236. # Handle dom0 as special case later
  1237. continue
  1238. if is_vm_included_in_backup (backup_location, vm):
  1239. if BACKUP_DEBUG:
  1240. print vm.name,"is included in backup"
  1241. vms_to_restore[vm.name] = {}
  1242. vms_to_restore[vm.name]['vm'] = vm;
  1243. if vm.template is None:
  1244. vms_to_restore[vm.name]['template'] = None
  1245. else:
  1246. templatevm_name = find_template_name(vm.template.name, options['replace-template'])
  1247. vms_to_restore[vm.name]['template'] = templatevm_name
  1248. if vm.netvm is None:
  1249. vms_to_restore[vm.name]['netvm'] = None
  1250. else:
  1251. netvm_name = vm.netvm.name
  1252. vms_to_restore[vm.name]['netvm'] = netvm_name
  1253. # Set to None to not confuse QubesVm object from backup
  1254. # collection with host collection (further in clone_attrs). Set
  1255. # directly _netvm to suppress setter action, especially
  1256. # modifying firewall
  1257. vm._netvm = None
  1258. # Store restore parameters
  1259. options['location'] = backup_location
  1260. options['restore_tmpdir'] = restore_tmpdir
  1261. options['passphrase'] = passphrase
  1262. options['encrypted'] = encrypted
  1263. options['compressed'] = compressed
  1264. options['hmac_algorithm'] = hmac_algorithm
  1265. options['crypto_algorithm'] = crypto_algorithm
  1266. options['appvm'] = appvm
  1267. options['format_version'] = format_version
  1268. vms_to_restore['$OPTIONS$'] = options
  1269. vms_to_restore = restore_info_verify(vms_to_restore, host_collection)
  1270. # ...and dom0 home
  1271. if options['dom0-home'] and \
  1272. is_vm_included_in_backup(backup_location, backup_collection[0]):
  1273. vm = backup_collection[0]
  1274. vms_to_restore['dom0'] = {}
  1275. if format_version == 1:
  1276. vms_to_restore['dom0']['subdir'] = \
  1277. os.listdir(os.path.join(backup_location, 'dom0-home'))[0]
  1278. vms_to_restore['dom0']['size'] = 0 # unknown
  1279. else:
  1280. vms_to_restore['dom0']['subdir'] = vm.backup_path
  1281. vms_to_restore['dom0']['size'] = vm.backup_size
  1282. local_user = grp.getgrnam('qubes').gr_mem[0]
  1283. dom0_home = vms_to_restore['dom0']['subdir']
  1284. vms_to_restore['dom0']['username'] = os.path.basename(dom0_home)
  1285. if vms_to_restore['dom0']['username'] != local_user:
  1286. vms_to_restore['dom0']['username-mismatch'] = True
  1287. if not options['ignore-dom0-username-mismatch']:
  1288. vms_to_restore['dom0']['good-to-go'] = False
  1289. if 'good-to-go' not in vms_to_restore['dom0']:
  1290. vms_to_restore['dom0']['good-to-go'] = True
  1291. # Not needed - all the data stored in vms_to_restore
  1292. if format_version == 2:
  1293. os.unlink(qubes_xml)
  1294. return vms_to_restore
  1295. def backup_restore_print_summary(restore_info, print_callback = print_stdout):
  1296. fields = {
  1297. "qid": {"func": "vm.qid"},
  1298. "name": {"func": "('[' if vm.is_template() else '')\
  1299. + ('{' if vm.is_netvm() else '')\
  1300. + vm.name \
  1301. + (']' if vm.is_template() else '')\
  1302. + ('}' if vm.is_netvm() else '')"},
  1303. "type": {"func": "'Tpl' if vm.is_template() else \
  1304. 'HVM' if vm.type == 'HVM' else \
  1305. vm.type.replace('VM','')"},
  1306. "updbl" : {"func": "'Yes' if vm.updateable else ''"},
  1307. "template": {"func": "'n/a' if vm.is_template() or vm.template is None else\
  1308. vm_info['template']"},
  1309. "netvm": {"func": "'n/a' if vm.is_netvm() and not vm.is_proxyvm() else\
  1310. ('*' if vm.uses_default_netvm else '') +\
  1311. vm_info['netvm'] if vm_info['netvm'] is not None else '-'"},
  1312. "label" : {"func" : "vm.label.name"},
  1313. }
  1314. fields_to_display = ["name", "type", "template", "updbl", "netvm", "label" ]
  1315. # First calculate the maximum width of each field we want to display
  1316. total_width = 0
  1317. for f in fields_to_display:
  1318. fields[f]["max_width"] = len(f)
  1319. for vm_info in restore_info.values():
  1320. if 'vm' in vm_info.keys():
  1321. vm = vm_info['vm']
  1322. l = len(str(eval(fields[f]["func"])))
  1323. if l > fields[f]["max_width"]:
  1324. fields[f]["max_width"] = l
  1325. total_width += fields[f]["max_width"]
  1326. print_callback("")
  1327. print_callback("The following VMs are included in the backup:")
  1328. print_callback("")
  1329. # Display the header
  1330. s = ""
  1331. for f in fields_to_display:
  1332. fmt="{{0:-^{0}}}-+".format(fields[f]["max_width"] + 1)
  1333. s += fmt.format('-')
  1334. print_callback(s)
  1335. s = ""
  1336. for f in fields_to_display:
  1337. fmt="{{0:>{0}}} |".format(fields[f]["max_width"] + 1)
  1338. s += fmt.format(f)
  1339. print_callback(s)
  1340. s = ""
  1341. for f in fields_to_display:
  1342. fmt="{{0:-^{0}}}-+".format(fields[f]["max_width"] + 1)
  1343. s += fmt.format('-')
  1344. print_callback(s)
  1345. for vm_info in restore_info.values():
  1346. # Skip non-VM here
  1347. if not 'vm' in vm_info:
  1348. continue
  1349. vm = vm_info['vm']
  1350. s = ""
  1351. for f in fields_to_display:
  1352. fmt="{{0:>{0}}} |".format(fields[f]["max_width"] + 1)
  1353. s += fmt.format(eval(fields[f]["func"]))
  1354. if 'excluded' in vm_info and vm_info['excluded']:
  1355. s += " <-- Excluded from restore"
  1356. elif 'already-exists' in vm_info:
  1357. s += " <-- A VM with the same name already exists on the host!"
  1358. elif 'missing-template' in vm_info:
  1359. s += " <-- No matching template on the host or in the backup found!"
  1360. elif 'missing-netvm' in vm_info:
  1361. s += " <-- No matching netvm on the host or in the backup found!"
  1362. elif 'orig-template' in vm_info:
  1363. s += " <-- Original template was '%s'" % (vm_info['orig-template'])
  1364. print_callback(s)
  1365. if 'dom0' in restore_info.keys():
  1366. s = ""
  1367. for f in fields_to_display:
  1368. fmt="{{0:>{0}}} |".format(fields[f]["max_width"] + 1)
  1369. if f == "name":
  1370. s += fmt.format("Dom0")
  1371. elif f == "type":
  1372. s += fmt.format("Home")
  1373. else:
  1374. s += fmt.format("")
  1375. if 'username-mismatch' in restore_info['dom0']:
  1376. s += " <-- username in backup and dom0 mismatch"
  1377. print_callback(s)
  1378. def backup_restore_do(restore_info,
  1379. host_collection = None, print_callback = print_stdout,
  1380. error_callback = print_stderr, progress_callback = None,
  1381. ):
  1382. global running_backup_operation
  1383. ### Private functions begin
  1384. def restore_vm_dir_v1 (backup_dir, src_dir, dst_dir):
  1385. backup_src_dir = src_dir.replace (system_path["qubes_base_dir"], backup_dir)
  1386. # We prefer to use Linux's cp, because it nicely handles sparse files
  1387. retcode = subprocess.call (["cp", "-rp", backup_src_dir, dst_dir])
  1388. if retcode != 0:
  1389. raise QubesException(
  1390. "*** Error while copying file {0} to {1}".format(backup_src_dir,
  1391. dst_dir))
  1392. ### Private functions end
  1393. options = restore_info['$OPTIONS$']
  1394. backup_location = options['location']
  1395. restore_tmpdir = options['restore_tmpdir']
  1396. passphrase = options['passphrase']
  1397. encrypted = options['encrypted']
  1398. compressed = options['compressed']
  1399. hmac_algorithm = options['hmac_algorithm']
  1400. crypto_algorithm = options['crypto_algorithm']
  1401. appvm = options['appvm']
  1402. format_version = options['format_version']
  1403. if format_version is None:
  1404. format_version = backup_detect_format_version(backup_location)
  1405. lock_obtained = False
  1406. if host_collection is None:
  1407. host_collection = QubesVmCollection()
  1408. host_collection.lock_db_for_writing()
  1409. host_collection.load()
  1410. lock_obtained = True
  1411. # Perform VM restoration in backup order
  1412. vms_dirs = []
  1413. vms_size = 0
  1414. vms = {}
  1415. for vm_info in restore_info.values():
  1416. if 'vm' not in vm_info:
  1417. continue
  1418. if not vm_info['good-to-go']:
  1419. continue
  1420. vm = vm_info['vm']
  1421. if format_version == 2:
  1422. vms_size += vm.backup_size
  1423. vms_dirs.append(vm.backup_path)
  1424. vms[vm.name] = vm
  1425. running_backup_operation = BackupOperationInfo()
  1426. if format_version == 2:
  1427. if 'dom0' in restore_info.keys() and restore_info['dom0']['good-to-go']:
  1428. vms_dirs.append('dom0-home')
  1429. vms_size += restore_info['dom0']['size']
  1430. restore_vm_dirs (backup_location,
  1431. restore_tmpdir,
  1432. passphrase=passphrase,
  1433. vms_dirs=vms_dirs,
  1434. vms=vms,
  1435. vms_size=vms_size,
  1436. hmac_algorithm=hmac_algorithm,
  1437. crypto_algorithm=crypto_algorithm,
  1438. print_callback=print_callback,
  1439. error_callback=error_callback,
  1440. progress_callback=progress_callback,
  1441. encrypted=encrypted,
  1442. compressed=compressed,
  1443. appvm=appvm)
  1444. # Add VM in right order
  1445. for (vm_class_name, vm_class) in sorted(QubesVmClasses.items(),
  1446. key=lambda _x: _x[1].load_order):
  1447. if running_backup_operation.canceled:
  1448. break
  1449. for vm in vms.values():
  1450. if running_backup_operation.canceled:
  1451. # only break the loop to save qubes.xml with already restored
  1452. # VMs
  1453. break
  1454. if not vm.__class__ == vm_class:
  1455. continue
  1456. print_callback("-> Restoring {type} {0}...".format(vm.name, type=vm_class_name))
  1457. retcode = subprocess.call (["mkdir", "-p", os.path.dirname(vm.dir_path)])
  1458. if retcode != 0:
  1459. error_callback("*** Cannot create directory: {0}?!".format(
  1460. vm.dir_path))
  1461. error_callback("Skipping...")
  1462. continue
  1463. template = None
  1464. if vm.template is not None:
  1465. template_name = restore_info[vm.name]['template']
  1466. template = host_collection.get_vm_by_name(template_name)
  1467. new_vm = None
  1468. try:
  1469. new_vm = host_collection.add_new_vm(vm_class_name, name=vm.name,
  1470. conf_file=vm.conf_file,
  1471. dir_path=vm.dir_path,
  1472. template=template,
  1473. installed_by_rpm=False)
  1474. if format_version == 1:
  1475. restore_vm_dir_v1(backup_location,
  1476. vm.dir_path,
  1477. os.path.dirname(new_vm.dir_path))
  1478. elif format_version == 2:
  1479. shutil.move(os.path.join(restore_tmpdir, vm.backup_path),
  1480. new_vm.dir_path)
  1481. new_vm.verify_files()
  1482. except Exception as err:
  1483. error_callback("ERROR: {0}".format(err))
  1484. error_callback("*** Skipping VM: {0}".format(vm.name))
  1485. if new_vm:
  1486. host_collection.pop(new_vm.qid)
  1487. continue
  1488. try:
  1489. new_vm.clone_attrs(vm)
  1490. except Exception as err:
  1491. error_callback("ERROR: {0}".format(err))
  1492. error_callback("*** Some VM property will not be restored")
  1493. try:
  1494. new_vm.appmenus_create(verbose=True)
  1495. except Exception as err:
  1496. error_callback("ERROR during appmenu restore: {0}".format(err))
  1497. error_callback("*** VM '{0}' will not have appmenus".format(vm.name))
  1498. # Set network dependencies - only non-default netvm setting
  1499. for vm in vms.values():
  1500. host_vm = host_collection.get_vm_by_name(vm.name)
  1501. if host_vm is None:
  1502. # Failed/skipped VM
  1503. continue
  1504. if not vm.uses_default_netvm:
  1505. if restore_info[vm.name]['netvm'] is not None:
  1506. host_vm.netvm = host_collection.get_vm_by_name (
  1507. restore_info[vm.name]['netvm'])
  1508. else:
  1509. host_vm.netvm = None
  1510. host_collection.save()
  1511. if lock_obtained:
  1512. host_collection.unlock_db()
  1513. if running_backup_operation.canceled:
  1514. if format_version == 2:
  1515. raise BackupCanceledError("Restore canceled",
  1516. tmpdir=restore_tmpdir)
  1517. else:
  1518. raise BackupCanceledError("Restore canceled")
  1519. # ... and dom0 home as last step
  1520. if 'dom0' in restore_info.keys() and restore_info['dom0']['good-to-go']:
  1521. backup_path = restore_info['dom0']['subdir']
  1522. local_user = grp.getgrnam('qubes').gr_mem[0]
  1523. home_dir = pwd.getpwnam(local_user).pw_dir
  1524. if format_version == 1:
  1525. backup_dom0_home_dir = os.path.join(backup_location, backup_path)
  1526. else:
  1527. backup_dom0_home_dir = os.path.join(restore_tmpdir, backup_path)
  1528. restore_home_backupdir = "home-pre-restore-{0}".format (time.strftime("%Y-%m-%d-%H%M%S"))
  1529. print_callback("-> Restoring home of user '{0}'...".format(local_user))
  1530. print_callback("--> Existing files/dirs backed up in '{0}' dir".format(restore_home_backupdir))
  1531. os.mkdir(home_dir + '/' + restore_home_backupdir)
  1532. for f in os.listdir(backup_dom0_home_dir):
  1533. home_file = home_dir + '/' + f
  1534. if os.path.exists(home_file):
  1535. os.rename(home_file, home_dir + '/' + restore_home_backupdir + '/' + f)
  1536. if format_version == 1:
  1537. retcode = subprocess.call (["cp", "-nrp", backup_dom0_home_dir + '/' + f, home_file])
  1538. elif format_version == 2:
  1539. shutil.move(backup_dom0_home_dir + '/' + f, home_file)
  1540. retcode = subprocess.call(['sudo', 'chown', '-R', local_user, home_dir])
  1541. if retcode != 0:
  1542. error_callback("*** Error while setting home directory owner")
  1543. shutil.rmtree(restore_tmpdir)
  1544. # vim:sw=4:et: