backup.py 89 KB

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