backup.py 82 KB

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