backup.py 88 KB

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