backup.py 67 KB

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