backup.py 82 KB

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