backup.py 84 KB

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