backup.py 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126
  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. else:
  1105. filelist_pipe = command.stdout
  1106. expect_tar_error = False
  1107. to_extract = Queue()
  1108. nextfile = None
  1109. # If want to analyze backup header, do it now
  1110. if vms_dirs and vms_dirs[0] == HEADER_FILENAME:
  1111. filename = filelist_pipe.readline().strip()
  1112. hmacfile = filelist_pipe.readline().strip()
  1113. if not appvm:
  1114. nextfile = filelist_pipe.readline().strip()
  1115. if BACKUP_DEBUG and callable(print_callback):
  1116. print_callback("Got backup header and hmac: %s, %s" % (filename,
  1117. hmacfile))
  1118. if not filename or filename=="EOF" or \
  1119. not hmacfile or hmacfile == "EOF":
  1120. if appvm:
  1121. vmproc.wait()
  1122. proc_error_msg = vmproc.stderr.read(MAX_STDERR_BYTES)
  1123. else:
  1124. command.wait()
  1125. proc_error_msg = command.stderr.read(MAX_STDERR_BYTES)
  1126. raise QubesException("Premature end of archive while receiving "
  1127. "backup header. Process output:\n" +
  1128. proc_error_msg)
  1129. filename = os.path.join(restore_tmpdir, filename)
  1130. hmacfile = os.path.join(restore_tmpdir, hmacfile)
  1131. file_ok = False
  1132. for hmac_algo in get_supported_hmac_algo(hmac_algorithm):
  1133. try:
  1134. if verify_hmac(filename, hmacfile, passphrase, hmac_algo):
  1135. file_ok = True
  1136. hmac_algorithm = hmac_algo
  1137. break
  1138. except QubesException:
  1139. # Ignore exception here, try the next algo
  1140. pass
  1141. if not file_ok:
  1142. raise QubesException("Corrupted backup header (hmac verification "
  1143. "failed). Is the password correct?")
  1144. if os.path.basename(filename) == HEADER_FILENAME:
  1145. header_data = parse_backup_header(filename)
  1146. if BackupHeader.version in header_data:
  1147. format_version = header_data[BackupHeader.version]
  1148. if BackupHeader.crypto_algorithm in header_data:
  1149. crypto_algorithm = header_data[BackupHeader.crypto_algorithm]
  1150. if BackupHeader.hmac_algorithm in header_data:
  1151. hmac_algorithm = header_data[BackupHeader.hmac_algorithm]
  1152. if BackupHeader.compressed in header_data:
  1153. compressed = header_data[BackupHeader.compressed]
  1154. if BackupHeader.encrypted in header_data:
  1155. encrypted = header_data[BackupHeader.encrypted]
  1156. if BackupHeader.compression_filter in header_data:
  1157. compression_filter = header_data[BackupHeader.compression_filter]
  1158. os.unlink(filename)
  1159. else:
  1160. # if no header found, create one with guessed HMAC algo
  1161. header_data = { BackupHeader.hmac_algorithm: hmac_algorithm }
  1162. # If this isn't backup header, pass it to ExtractWorker
  1163. to_extract.put(filename)
  1164. # when tar do not find expected file in archive, it exit with
  1165. # code 2. This will happen because we've requested backup-header
  1166. # file, but the archive do not contain it. Ignore this particular
  1167. # error.
  1168. if not appvm:
  1169. expect_tar_error = True
  1170. # Setup worker to extract encrypted data chunks to the restore dirs
  1171. # Create the process here to pass it options extracted from backup header
  1172. extractor_params = {
  1173. 'queue': to_extract,
  1174. 'base_dir': restore_tmpdir,
  1175. 'passphrase': passphrase,
  1176. 'encrypted': encrypted,
  1177. 'compressed': compressed,
  1178. 'crypto_algorithm': crypto_algorithm,
  1179. 'verify_only': verify_only,
  1180. 'total_size': vms_size,
  1181. 'print_callback': print_callback,
  1182. 'error_callback': error_callback,
  1183. 'progress_callback': progress_callback,
  1184. }
  1185. if format_version == 2:
  1186. extract_proc = ExtractWorker2(**extractor_params)
  1187. elif format_version == 3:
  1188. extractor_params['compression_filter'] = compression_filter
  1189. extract_proc = ExtractWorker3(**extractor_params)
  1190. else:
  1191. raise NotImplemented("Backup format version %d not supported" % format_version)
  1192. extract_proc.start()
  1193. try:
  1194. filename = None
  1195. while True:
  1196. if running_backup_operation and running_backup_operation.canceled:
  1197. break
  1198. if not extract_proc.is_alive():
  1199. command.terminate()
  1200. command.wait()
  1201. expect_tar_error = True
  1202. if vmproc:
  1203. vmproc.terminate()
  1204. vmproc.wait()
  1205. vmproc = None
  1206. break
  1207. if nextfile is not None:
  1208. filename = nextfile
  1209. else:
  1210. filename = filelist_pipe.readline().strip()
  1211. if BACKUP_DEBUG and callable(print_callback):
  1212. print_callback("Getting new file:"+filename)
  1213. if not filename or filename=="EOF":
  1214. break
  1215. hmacfile = filelist_pipe.readline().strip()
  1216. if running_backup_operation and running_backup_operation.canceled:
  1217. break
  1218. # if reading archive directly with tar, wait for next filename -
  1219. # tar prints filename before processing it, so wait for the next one to be
  1220. # sure that whole file was extracted
  1221. if not appvm:
  1222. nextfile = filelist_pipe.readline().strip()
  1223. if BACKUP_DEBUG and callable(print_callback):
  1224. print_callback("Getting hmac:"+hmacfile)
  1225. if not hmacfile or hmacfile=="EOF":
  1226. # Premature end of archive, either of tar1_command or vmproc exited with error
  1227. break
  1228. if not any(map(lambda x: filename.startswith(x), vms_dirs)):
  1229. if BACKUP_DEBUG and callable(print_callback):
  1230. print_callback("Ignoring VM not selected for restore")
  1231. os.unlink(os.path.join(restore_tmpdir, filename))
  1232. os.unlink(os.path.join(restore_tmpdir, hmacfile))
  1233. continue
  1234. if verify_hmac(os.path.join(restore_tmpdir,filename),
  1235. os.path.join(restore_tmpdir,hmacfile),
  1236. passphrase, hmac_algorithm):
  1237. to_extract.put(os.path.join(restore_tmpdir, filename))
  1238. if running_backup_operation and running_backup_operation.canceled:
  1239. raise BackupCanceledError("Restore canceled",
  1240. tmpdir=restore_tmpdir)
  1241. if command.wait() != 0 and not expect_tar_error:
  1242. raise QubesException(
  1243. "unable to read the qubes backup file {0} ({1}). " \
  1244. "Is it really a backup?".format(backup_source, command.wait()))
  1245. if vmproc:
  1246. if vmproc.wait() != 0:
  1247. raise QubesException(
  1248. "unable to read the qubes backup {0} " \
  1249. "because of a VM error: {1}".format(
  1250. backup_source, vmproc.stderr.read(MAX_STDERR_BYTES)))
  1251. if filename and filename!="EOF":
  1252. raise QubesException("Premature end of archive, the last file was %s" % filename)
  1253. except:
  1254. to_extract.put("ERROR")
  1255. extract_proc.join()
  1256. raise
  1257. else:
  1258. to_extract.put("FINISHED")
  1259. if BACKUP_DEBUG and callable(print_callback):
  1260. print_callback("Waiting for the extraction process to finish...")
  1261. extract_proc.join()
  1262. if BACKUP_DEBUG and callable(print_callback):
  1263. print_callback("Extraction process finished with code:" + \
  1264. str(extract_proc.exitcode))
  1265. if extract_proc.exitcode != 0:
  1266. raise QubesException(
  1267. "unable to extract the qubes backup. " \
  1268. "Check extracting process errors.")
  1269. return header_data
  1270. def backup_restore_set_defaults(options):
  1271. if 'use-default-netvm' not in options:
  1272. options['use-default-netvm'] = False
  1273. if 'use-none-netvm' not in options:
  1274. options['use-none-netvm'] = False
  1275. if 'use-default-template' not in options:
  1276. options['use-default-template'] = False
  1277. if 'dom0-home' not in options:
  1278. options['dom0-home'] = True
  1279. if 'replace-template' not in options:
  1280. options['replace-template'] = []
  1281. if 'ignore-username-mismatch' not in options:
  1282. options['ignore-username-mismatch'] = False
  1283. if 'verify-only' not in options:
  1284. options['verify-only'] = False
  1285. return options
  1286. def load_hmac(hmac):
  1287. hmac = hmac.strip().split("=")
  1288. if len(hmac) > 1:
  1289. hmac = hmac[1].strip()
  1290. else:
  1291. raise QubesException("ERROR: invalid hmac file content")
  1292. return hmac
  1293. def backup_detect_format_version(backup_location):
  1294. if os.path.exists(os.path.join(backup_location, 'qubes.xml')):
  1295. return 1
  1296. else:
  1297. # this could mean also 3, but not distinguishable until backup header
  1298. # is read
  1299. return 2
  1300. def backup_restore_header(source, passphrase,
  1301. print_callback = print_stdout, error_callback = print_stderr,
  1302. encrypted=False, appvm=None, compressed = False, format_version = None,
  1303. hmac_algorithm = DEFAULT_HMAC_ALGORITHM,
  1304. crypto_algorithm = DEFAULT_CRYPTO_ALGORITHM):
  1305. global running_backup_operation
  1306. vmproc = None
  1307. running_backup_operation = None
  1308. restore_tmpdir = tempfile.mkdtemp(prefix="/var/tmp/restore_")
  1309. if format_version == None:
  1310. format_version = backup_detect_format_version(source)
  1311. if format_version == 1:
  1312. return (restore_tmpdir, os.path.join(source, 'qubes.xml'), None)
  1313. # tar2qfile matches only beginnings, while tar full path
  1314. if appvm:
  1315. extract_filter = [HEADER_FILENAME, 'qubes.xml.000']
  1316. else:
  1317. extract_filter = [HEADER_FILENAME, HEADER_FILENAME+'.hmac',
  1318. 'qubes.xml.000', 'qubes.xml.000.hmac']
  1319. header_data = restore_vm_dirs (source,
  1320. restore_tmpdir,
  1321. passphrase=passphrase,
  1322. vms_dirs=extract_filter,
  1323. vms=None,
  1324. vms_size=HEADER_QUBES_XML_MAX_SIZE,
  1325. format_version=format_version,
  1326. hmac_algorithm=hmac_algorithm,
  1327. crypto_algorithm=crypto_algorithm,
  1328. print_callback=print_callback,
  1329. error_callback=error_callback,
  1330. progress_callback=None,
  1331. encrypted=encrypted,
  1332. compressed=compressed,
  1333. appvm=appvm)
  1334. return (restore_tmpdir, os.path.join(restore_tmpdir, "qubes.xml"),
  1335. header_data)
  1336. def restore_info_verify(restore_info, host_collection):
  1337. options = restore_info['$OPTIONS$']
  1338. for vm in restore_info.keys():
  1339. if vm in ['$OPTIONS$', 'dom0']:
  1340. continue
  1341. vm_info = restore_info[vm]
  1342. vm_info.pop('excluded', None)
  1343. if 'exclude' in options.keys():
  1344. if vm in options['exclude']:
  1345. vm_info['excluded'] = True
  1346. vm_info.pop('already-exists', None)
  1347. if not options['verify-only'] and \
  1348. host_collection.get_vm_by_name (vm) is not None:
  1349. vm_info['already-exists'] = True
  1350. # check template
  1351. vm_info.pop('missing-template', None)
  1352. if vm_info['template']:
  1353. template_name = vm_info['template']
  1354. host_template = host_collection.get_vm_by_name(template_name)
  1355. if not host_template or not host_template.is_template():
  1356. # Maybe the (custom) template is in the backup?
  1357. if not (template_name in restore_info.keys() and
  1358. restore_info[template_name]['vm'].is_template()):
  1359. if options['use-default-template']:
  1360. if 'orig-template' not in vm_info.keys():
  1361. vm_info['orig-template'] = template_name
  1362. vm_info['template'] = host_collection\
  1363. .get_default_template().name
  1364. else:
  1365. vm_info['missing-template'] = True
  1366. # check netvm
  1367. vm_info.pop('missing-netvm', None)
  1368. if vm_info['netvm']:
  1369. netvm_name = vm_info['netvm']
  1370. netvm_on_host = host_collection.get_vm_by_name (netvm_name)
  1371. # No netvm on the host?
  1372. if not ((netvm_on_host is not None) and netvm_on_host.is_netvm()):
  1373. # Maybe the (custom) netvm is in the backup?
  1374. if not (netvm_name in restore_info.keys() and \
  1375. restore_info[netvm_name]['vm'].is_netvm()):
  1376. if options['use-default-netvm']:
  1377. vm_info['netvm'] = host_collection\
  1378. .get_default_netvm().name
  1379. vm_info['vm'].uses_default_netvm = True
  1380. elif options['use-none-netvm']:
  1381. vm_info['netvm'] = None
  1382. else:
  1383. vm_info['missing-netvm'] = True
  1384. vm_info['good-to-go'] = not any([(prop in vm_info.keys()) for
  1385. prop in ['missing-netvm',
  1386. 'missing-template',
  1387. 'already-exists',
  1388. 'excluded']])
  1389. return restore_info
  1390. def backup_restore_prepare(backup_location, passphrase, options = None,
  1391. host_collection = None, encrypted=False, appvm=None,
  1392. compressed = False, print_callback = print_stdout, error_callback = print_stderr,
  1393. format_version=None, hmac_algorithm=DEFAULT_HMAC_ALGORITHM,
  1394. crypto_algorithm=DEFAULT_CRYPTO_ALGORITHM):
  1395. if options is None:
  1396. options = {}
  1397. # Defaults
  1398. backup_restore_set_defaults(options)
  1399. # Options introduced in backup format 3+, which always have a header,
  1400. # so no need for fallback in function parameter
  1401. compression_filter = DEFAULT_COMPRESSION_FILTER
  1402. #### Private functions begin
  1403. def is_vm_included_in_backup_v1 (backup_dir, vm):
  1404. if vm.qid == 0:
  1405. return os.path.exists(os.path.join(backup_dir,'dom0-home'))
  1406. backup_vm_dir_path = vm.dir_path.replace (system_path["qubes_base_dir"], backup_dir)
  1407. if os.path.exists (backup_vm_dir_path):
  1408. return True
  1409. else:
  1410. return False
  1411. def is_vm_included_in_backup_v2 (backup_dir, vm):
  1412. if vm.backup_content:
  1413. return True
  1414. else:
  1415. return False
  1416. def find_template_name(template, replaces):
  1417. rx_replace = re.compile("(.*):(.*)")
  1418. for r in replaces:
  1419. m = rx_replace.match(r)
  1420. if m.group(1) == template:
  1421. return m.group(2)
  1422. return template
  1423. #### Private functions end
  1424. # Format versions:
  1425. # 1 - Qubes R1, Qubes R2 beta1, beta2
  1426. # 2 - Qubes R2 beta3+
  1427. if format_version is None:
  1428. format_version = backup_detect_format_version(backup_location)
  1429. if format_version == 1:
  1430. is_vm_included_in_backup = is_vm_included_in_backup_v1
  1431. elif format_version in [2, 3]:
  1432. is_vm_included_in_backup = is_vm_included_in_backup_v2
  1433. if not appvm:
  1434. if not os.path.isfile(backup_location):
  1435. raise QubesException("Invalid backup location (not a file or "
  1436. "directory with qubes.xml)"
  1437. ": %s" % unicode(
  1438. backup_location))
  1439. else:
  1440. raise QubesException("Unknown backup format version: %s" % str(format_version))
  1441. (restore_tmpdir, qubes_xml, header_data) = backup_restore_header(
  1442. backup_location,
  1443. passphrase,
  1444. encrypted=encrypted,
  1445. appvm=appvm,
  1446. compressed=compressed,
  1447. hmac_algorithm=hmac_algorithm,
  1448. crypto_algorithm=crypto_algorithm,
  1449. print_callback=print_callback,
  1450. error_callback=error_callback,
  1451. format_version=format_version)
  1452. if header_data:
  1453. if BackupHeader.version in header_data:
  1454. format_version = header_data[BackupHeader.version]
  1455. if BackupHeader.crypto_algorithm in header_data:
  1456. crypto_algorithm = header_data[BackupHeader.crypto_algorithm]
  1457. if BackupHeader.hmac_algorithm in header_data:
  1458. hmac_algorithm = header_data[BackupHeader.hmac_algorithm]
  1459. if BackupHeader.compressed in header_data:
  1460. compressed = header_data[BackupHeader.compressed]
  1461. if BackupHeader.encrypted in header_data:
  1462. encrypted = header_data[BackupHeader.encrypted]
  1463. if BackupHeader.compression_filter in header_data:
  1464. compression_filter = header_data[BackupHeader.compression_filter]
  1465. if BACKUP_DEBUG:
  1466. print "Loading file", qubes_xml
  1467. backup_collection = QubesVmCollection(store_filename = qubes_xml)
  1468. backup_collection.lock_db_for_reading()
  1469. backup_collection.load()
  1470. if host_collection is None:
  1471. host_collection = QubesVmCollection()
  1472. host_collection.lock_db_for_reading()
  1473. host_collection.load()
  1474. host_collection.unlock_db()
  1475. backup_vms_list = [vm for vm in backup_collection.values()]
  1476. vms_to_restore = {}
  1477. # ... and the actual data
  1478. for vm in backup_vms_list:
  1479. if vm.qid == 0:
  1480. # Handle dom0 as special case later
  1481. continue
  1482. if is_vm_included_in_backup (backup_location, vm):
  1483. if BACKUP_DEBUG:
  1484. print vm.name,"is included in backup"
  1485. vms_to_restore[vm.name] = {}
  1486. vms_to_restore[vm.name]['vm'] = vm
  1487. if vm.template is None:
  1488. vms_to_restore[vm.name]['template'] = None
  1489. else:
  1490. templatevm_name = find_template_name(vm.template.name, options['replace-template'])
  1491. vms_to_restore[vm.name]['template'] = templatevm_name
  1492. if vm.netvm is None:
  1493. vms_to_restore[vm.name]['netvm'] = None
  1494. else:
  1495. netvm_name = vm.netvm.name
  1496. vms_to_restore[vm.name]['netvm'] = netvm_name
  1497. # Set to None to not confuse QubesVm object from backup
  1498. # collection with host collection (further in clone_attrs). Set
  1499. # directly _netvm to suppress setter action, especially
  1500. # modifying firewall
  1501. vm._netvm = None
  1502. # Store restore parameters
  1503. options['location'] = backup_location
  1504. options['restore_tmpdir'] = restore_tmpdir
  1505. options['passphrase'] = passphrase
  1506. options['encrypted'] = encrypted
  1507. options['compressed'] = compressed
  1508. options['compression_filter'] = compression_filter
  1509. options['hmac_algorithm'] = hmac_algorithm
  1510. options['crypto_algorithm'] = crypto_algorithm
  1511. options['appvm'] = appvm
  1512. options['format_version'] = format_version
  1513. vms_to_restore['$OPTIONS$'] = options
  1514. vms_to_restore = restore_info_verify(vms_to_restore, host_collection)
  1515. # ...and dom0 home
  1516. if options['dom0-home'] and \
  1517. is_vm_included_in_backup(backup_location, backup_collection[0]):
  1518. vm = backup_collection[0]
  1519. vms_to_restore['dom0'] = {}
  1520. if format_version == 1:
  1521. vms_to_restore['dom0']['subdir'] = \
  1522. os.listdir(os.path.join(backup_location, 'dom0-home'))[0]
  1523. vms_to_restore['dom0']['size'] = 0 # unknown
  1524. else:
  1525. vms_to_restore['dom0']['subdir'] = vm.backup_path
  1526. vms_to_restore['dom0']['size'] = vm.backup_size
  1527. local_user = grp.getgrnam('qubes').gr_mem[0]
  1528. dom0_home = vms_to_restore['dom0']['subdir']
  1529. vms_to_restore['dom0']['username'] = os.path.basename(dom0_home)
  1530. if vms_to_restore['dom0']['username'] != local_user:
  1531. vms_to_restore['dom0']['username-mismatch'] = True
  1532. if options['ignore-username-mismatch']:
  1533. vms_to_restore['dom0']['ignore-username-mismatch'] = True
  1534. else:
  1535. vms_to_restore['dom0']['good-to-go'] = False
  1536. if 'good-to-go' not in vms_to_restore['dom0']:
  1537. vms_to_restore['dom0']['good-to-go'] = True
  1538. # Not needed - all the data stored in vms_to_restore
  1539. if format_version >= 2:
  1540. os.unlink(qubes_xml)
  1541. return vms_to_restore
  1542. def backup_restore_print_summary(restore_info, print_callback = print_stdout):
  1543. fields = {
  1544. "qid": {"func": "vm.qid"},
  1545. "name": {"func": "('[' if vm.is_template() else '')\
  1546. + ('{' if vm.is_netvm() else '')\
  1547. + vm.name \
  1548. + (']' if vm.is_template() else '')\
  1549. + ('}' if vm.is_netvm() else '')"},
  1550. "type": {"func": "'Tpl' if vm.is_template() else \
  1551. 'HVM' if vm.type == 'HVM' else \
  1552. vm.type.replace('VM','')"},
  1553. "updbl" : {"func": "'Yes' if vm.updateable else ''"},
  1554. "template": {"func": "'n/a' if vm.is_template() or vm.template is None else\
  1555. vm_info['template']"},
  1556. "netvm": {"func": "'n/a' if vm.is_netvm() and not vm.is_proxyvm() else\
  1557. ('*' if vm.uses_default_netvm else '') +\
  1558. vm_info['netvm'] if vm_info['netvm'] is not None else '-'"},
  1559. "label" : {"func" : "vm.label.name"},
  1560. }
  1561. fields_to_display = ["name", "type", "template", "updbl", "netvm", "label" ]
  1562. # First calculate the maximum width of each field we want to display
  1563. total_width = 0
  1564. for f in fields_to_display:
  1565. fields[f]["max_width"] = len(f)
  1566. for vm_info in restore_info.values():
  1567. if 'vm' in vm_info.keys():
  1568. vm = vm_info['vm']
  1569. l = len(unicode(eval(fields[f]["func"])))
  1570. if l > fields[f]["max_width"]:
  1571. fields[f]["max_width"] = l
  1572. total_width += fields[f]["max_width"]
  1573. print_callback("")
  1574. print_callback("The following VMs are included in the backup:")
  1575. print_callback("")
  1576. # Display the header
  1577. s = ""
  1578. for f in fields_to_display:
  1579. fmt="{{0:-^{0}}}-+".format(fields[f]["max_width"] + 1)
  1580. s += fmt.format('-')
  1581. print_callback(s)
  1582. s = ""
  1583. for f in fields_to_display:
  1584. fmt="{{0:>{0}}} |".format(fields[f]["max_width"] + 1)
  1585. s += fmt.format(f)
  1586. print_callback(s)
  1587. s = ""
  1588. for f in fields_to_display:
  1589. fmt="{{0:-^{0}}}-+".format(fields[f]["max_width"] + 1)
  1590. s += fmt.format('-')
  1591. print_callback(s)
  1592. for vm_info in restore_info.values():
  1593. # Skip non-VM here
  1594. if not 'vm' in vm_info:
  1595. continue
  1596. vm = vm_info['vm']
  1597. s = ""
  1598. for f in fields_to_display:
  1599. fmt="{{0:>{0}}} |".format(fields[f]["max_width"] + 1)
  1600. s += fmt.format(eval(fields[f]["func"]))
  1601. if 'excluded' in vm_info and vm_info['excluded']:
  1602. s += " <-- Excluded from restore"
  1603. elif 'already-exists' in vm_info:
  1604. s += " <-- A VM with the same name already exists on the host!"
  1605. elif 'missing-template' in vm_info:
  1606. s += " <-- No matching template on the host or in the backup found!"
  1607. elif 'missing-netvm' in vm_info:
  1608. s += " <-- No matching netvm on the host or in the backup found!"
  1609. elif 'orig-template' in vm_info:
  1610. s += " <-- Original template was '%s'" % (vm_info['orig-template'])
  1611. print_callback(s)
  1612. if 'dom0' in restore_info.keys():
  1613. s = ""
  1614. for f in fields_to_display:
  1615. fmt="{{0:>{0}}} |".format(fields[f]["max_width"] + 1)
  1616. if f == "name":
  1617. s += fmt.format("Dom0")
  1618. elif f == "type":
  1619. s += fmt.format("Home")
  1620. else:
  1621. s += fmt.format("")
  1622. if 'username-mismatch' in restore_info['dom0']:
  1623. s += " <-- username in backup and dom0 mismatch"
  1624. if 'ignore-username-mismatch' in restore_info['dom0']:
  1625. s += " (ignored)"
  1626. print_callback(s)
  1627. def backup_restore_do(restore_info,
  1628. host_collection = None, print_callback = print_stdout,
  1629. error_callback = print_stderr, progress_callback = None,
  1630. ):
  1631. global running_backup_operation
  1632. ### Private functions begin
  1633. def restore_vm_dir_v1 (backup_dir, src_dir, dst_dir):
  1634. backup_src_dir = src_dir.replace (system_path["qubes_base_dir"], backup_dir)
  1635. # We prefer to use Linux's cp, because it nicely handles sparse files
  1636. retcode = subprocess.call (["cp", "-rp", backup_src_dir, dst_dir])
  1637. if retcode != 0:
  1638. raise QubesException(
  1639. "*** Error while copying file {0} to {1}".format(backup_src_dir,
  1640. dst_dir))
  1641. ### Private functions end
  1642. options = restore_info['$OPTIONS$']
  1643. backup_location = options['location']
  1644. restore_tmpdir = options['restore_tmpdir']
  1645. passphrase = options['passphrase']
  1646. encrypted = options['encrypted']
  1647. compressed = options['compressed']
  1648. compression_filter = options['compression_filter']
  1649. hmac_algorithm = options['hmac_algorithm']
  1650. crypto_algorithm = options['crypto_algorithm']
  1651. verify_only = options['verify-only']
  1652. appvm = options['appvm']
  1653. format_version = options['format_version']
  1654. if format_version is None:
  1655. format_version = backup_detect_format_version(backup_location)
  1656. lock_obtained = False
  1657. if host_collection is None:
  1658. host_collection = QubesVmCollection()
  1659. host_collection.lock_db_for_writing()
  1660. host_collection.load()
  1661. lock_obtained = True
  1662. # Perform VM restoration in backup order
  1663. vms_dirs = []
  1664. vms_size = 0
  1665. vms = {}
  1666. for vm_info in restore_info.values():
  1667. if 'vm' not in vm_info:
  1668. continue
  1669. if not vm_info['good-to-go']:
  1670. continue
  1671. vm = vm_info['vm']
  1672. if format_version >= 2:
  1673. vms_size += vm.backup_size
  1674. vms_dirs.append(vm.backup_path)
  1675. vms[vm.name] = vm
  1676. running_backup_operation = BackupOperationInfo()
  1677. if format_version >= 2:
  1678. if 'dom0' in restore_info.keys() and restore_info['dom0']['good-to-go']:
  1679. vms_dirs.append(os.path.dirname(restore_info['dom0']['subdir']))
  1680. vms_size += restore_info['dom0']['size']
  1681. try:
  1682. restore_vm_dirs (backup_location,
  1683. restore_tmpdir,
  1684. passphrase=passphrase,
  1685. vms_dirs=vms_dirs,
  1686. vms=vms,
  1687. vms_size=vms_size,
  1688. format_version=format_version,
  1689. hmac_algorithm=hmac_algorithm,
  1690. crypto_algorithm=crypto_algorithm,
  1691. verify_only=verify_only,
  1692. print_callback=print_callback,
  1693. error_callback=error_callback,
  1694. progress_callback=progress_callback,
  1695. encrypted=encrypted,
  1696. compressed=compressed,
  1697. compression_filter=compression_filter,
  1698. appvm=appvm)
  1699. except QubesException as e:
  1700. if verify_only:
  1701. raise
  1702. else:
  1703. if callable(print_callback):
  1704. print_callback("Some errors occurred during data extraction, "
  1705. "continuing anyway to restore at least some "
  1706. "VMs")
  1707. else:
  1708. if verify_only:
  1709. if callable(print_callback):
  1710. print_callback("WARNING: Backup verification not supported for "
  1711. "this backup format.")
  1712. if verify_only:
  1713. shutil.rmtree(restore_tmpdir)
  1714. return
  1715. # Add VM in right order
  1716. for (vm_class_name, vm_class) in sorted(QubesVmClasses.items(),
  1717. key=lambda _x: _x[1].load_order):
  1718. if running_backup_operation.canceled:
  1719. break
  1720. for vm in vms.values():
  1721. if running_backup_operation.canceled:
  1722. # only break the loop to save qubes.xml with already restored
  1723. # VMs
  1724. break
  1725. if not vm.__class__ == vm_class:
  1726. continue
  1727. if callable(print_callback):
  1728. print_callback("-> Restoring {type} {0}...".format(vm.name, type=vm_class_name))
  1729. retcode = subprocess.call (["mkdir", "-p", os.path.dirname(vm.dir_path)])
  1730. if retcode != 0:
  1731. error_callback("*** Cannot create directory: {0}?!".format(
  1732. vm.dir_path))
  1733. error_callback("Skipping...")
  1734. continue
  1735. template = None
  1736. if vm.template is not None:
  1737. template_name = restore_info[vm.name]['template']
  1738. template = host_collection.get_vm_by_name(template_name)
  1739. new_vm = None
  1740. try:
  1741. new_vm = host_collection.add_new_vm(vm_class_name, name=vm.name,
  1742. conf_file=vm.conf_file,
  1743. dir_path=vm.dir_path,
  1744. template=template,
  1745. installed_by_rpm=False)
  1746. if format_version == 1:
  1747. restore_vm_dir_v1(backup_location,
  1748. vm.dir_path,
  1749. os.path.dirname(new_vm.dir_path))
  1750. elif format_version >= 2:
  1751. shutil.move(os.path.join(restore_tmpdir, vm.backup_path),
  1752. new_vm.dir_path)
  1753. new_vm.verify_files()
  1754. except Exception as err:
  1755. error_callback("ERROR: {0}".format(err))
  1756. error_callback("*** Skipping VM: {0}".format(vm.name))
  1757. if new_vm:
  1758. host_collection.pop(new_vm.qid)
  1759. continue
  1760. # FIXME: cannot check for 'kernel' property, because it is always
  1761. # defined - accessing it touches non-existent '_kernel'
  1762. if not isinstance(vm, QubesVmClasses['QubesHVm']):
  1763. # TODO: add a setting for this?
  1764. if vm.kernel and vm.kernel not in os.listdir(system_path[
  1765. 'qubes_kernels_base_dir']):
  1766. if callable(print_callback):
  1767. print_callback("WARNING: Kernel %s not installed, "
  1768. "using default one" % vm.kernel)
  1769. vm.uses_default_kernel = True
  1770. vm.kernel = host_collection.get_default_kernel()
  1771. try:
  1772. new_vm.clone_attrs(vm)
  1773. except Exception as err:
  1774. error_callback("ERROR: {0}".format(err))
  1775. error_callback("*** Some VM property will not be restored")
  1776. try:
  1777. new_vm.appmenus_create(verbose=callable(print_callback))
  1778. except Exception as err:
  1779. error_callback("ERROR during appmenu restore: {0}".format(err))
  1780. error_callback("*** VM '{0}' will not have appmenus".format(vm.name))
  1781. # Set network dependencies - only non-default netvm setting
  1782. for vm in vms.values():
  1783. host_vm = host_collection.get_vm_by_name(vm.name)
  1784. if host_vm is None:
  1785. # Failed/skipped VM
  1786. continue
  1787. if not vm.uses_default_netvm:
  1788. if restore_info[vm.name]['netvm'] is not None:
  1789. host_vm.netvm = host_collection.get_vm_by_name (
  1790. restore_info[vm.name]['netvm'])
  1791. else:
  1792. host_vm.netvm = None
  1793. host_collection.save()
  1794. if lock_obtained:
  1795. host_collection.unlock_db()
  1796. if running_backup_operation.canceled:
  1797. if format_version >= 2:
  1798. raise BackupCanceledError("Restore canceled",
  1799. tmpdir=restore_tmpdir)
  1800. else:
  1801. raise BackupCanceledError("Restore canceled")
  1802. # ... and dom0 home as last step
  1803. if 'dom0' in restore_info.keys() and restore_info['dom0']['good-to-go']:
  1804. backup_path = restore_info['dom0']['subdir']
  1805. local_user = grp.getgrnam('qubes').gr_mem[0]
  1806. home_dir = pwd.getpwnam(local_user).pw_dir
  1807. if format_version == 1:
  1808. backup_dom0_home_dir = os.path.join(backup_location, backup_path)
  1809. else:
  1810. backup_dom0_home_dir = os.path.join(restore_tmpdir, backup_path)
  1811. restore_home_backupdir = "home-pre-restore-{0}".format (time.strftime("%Y-%m-%d-%H%M%S"))
  1812. if callable(print_callback):
  1813. print_callback("-> Restoring home of user '{0}'...".format(local_user))
  1814. print_callback("--> Existing files/dirs backed up in '{0}' dir".format(restore_home_backupdir))
  1815. os.mkdir(home_dir + '/' + restore_home_backupdir)
  1816. for f in os.listdir(backup_dom0_home_dir):
  1817. home_file = home_dir + '/' + f
  1818. if os.path.exists(home_file):
  1819. os.rename(home_file, home_dir + '/' + restore_home_backupdir + '/' + f)
  1820. if format_version == 1:
  1821. retcode = subprocess.call (["cp", "-nrp", backup_dom0_home_dir + '/' + f, home_file])
  1822. elif format_version >= 2:
  1823. shutil.move(backup_dom0_home_dir + '/' + f, home_file)
  1824. retcode = subprocess.call(['sudo', 'chown', '-R', local_user, home_dir])
  1825. if retcode != 0:
  1826. error_callback("*** Error while setting home directory owner")
  1827. shutil.rmtree(restore_tmpdir)
  1828. # vim:sw=4:et: