backup.py 88 KB

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