qubesutils.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # The Qubes OS Project, http://www.qubes-os.org
  5. #
  6. # Copyright (C) 2011 Marek Marczykowski <marmarek@invisiblethingslab.com>
  7. # Copyright (C) 2014 Wojciech Porczyk <wojciech@porczyk.eu>
  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 absolute_import
  25. import string
  26. from lxml import etree
  27. from lxml.etree import ElementTree, SubElement, Element
  28. from qubes.qubes import QubesException
  29. from qubes.qubes import vmm
  30. from qubes.qubes import system_path,vm_files
  31. import sys
  32. import os
  33. import subprocess
  34. import re
  35. import time
  36. import stat
  37. import libvirt
  38. from qubes.qdb import QubesDB,Error,DisconnectedError
  39. import xen.lowlevel.xc
  40. import xen.lowlevel.xs
  41. BLKSIZE = 512
  42. # all frontends, prefer xvdi
  43. # TODO: get this from libvirt driver?
  44. AVAILABLE_FRONTENDS = ['xvd'+c for c in
  45. string.lowercase[8:]+string.lowercase[:8]]
  46. def mbytes_to_kmg(size):
  47. if size > 1024:
  48. return "%d GiB" % (size/1024)
  49. else:
  50. return "%d MiB" % size
  51. def kbytes_to_kmg(size):
  52. if size > 1024:
  53. return mbytes_to_kmg(size/1024)
  54. else:
  55. return "%d KiB" % size
  56. def bytes_to_kmg(size):
  57. if size > 1024:
  58. return kbytes_to_kmg(size/1024)
  59. else:
  60. return "%d B" % size
  61. def size_to_human (size):
  62. """Humane readable size, with 1/10 precission"""
  63. if size < 1024:
  64. return str (size);
  65. elif size < 1024*1024:
  66. return str(round(size/1024.0,1)) + ' KiB'
  67. elif size < 1024*1024*1024:
  68. return str(round(size/(1024.0*1024),1)) + ' MiB'
  69. else:
  70. return str(round(size/(1024.0*1024*1024),1)) + ' GiB'
  71. def parse_size(size):
  72. units = [ ('K', 1024), ('KB', 1024),
  73. ('M', 1024*1024), ('MB', 1024*1024),
  74. ('G', 1024*1024*1024), ('GB', 1024*1024*1024),
  75. ]
  76. size = size.strip().upper()
  77. if size.isdigit():
  78. return int(size)
  79. for unit, multiplier in units:
  80. if size.endswith(unit):
  81. size = size[:-len(unit)].strip()
  82. return int(size)*multiplier
  83. raise QubesException("Invalid size: {0}.".format(size))
  84. def get_disk_usage_one(st):
  85. try:
  86. return st.st_blocks * BLKSIZE
  87. except AttributeError:
  88. return st.st_size
  89. def get_disk_usage(path):
  90. try:
  91. st = os.lstat(path)
  92. except OSError:
  93. return 0
  94. ret = get_disk_usage_one(st)
  95. # if path is not a directory, this is skipped
  96. for dirpath, dirnames, filenames in os.walk(path):
  97. for name in dirnames + filenames:
  98. ret += get_disk_usage_one(os.lstat(os.path.join(dirpath, name)))
  99. return ret
  100. def print_stdout(text):
  101. print (text)
  102. def print_stderr(text):
  103. print >> sys.stderr, (text)
  104. ###### Block devices ########
  105. def block_devid_to_name(devid):
  106. major = devid / 256
  107. minor = devid % 256
  108. dev_class = ""
  109. if major == 202:
  110. dev_class = "xvd"
  111. elif major == 8:
  112. dev_class = "sd"
  113. else:
  114. raise QubesException("Unknown device class %d" % major)
  115. if minor % 16 == 0:
  116. return "%s%c" % (dev_class, ord('a')+minor/16)
  117. else:
  118. return "%s%c%d" % (dev_class, ord('a')+minor/16, minor%16)
  119. def block_name_to_majorminor(name):
  120. # check if it is already devid
  121. if isinstance(name, int):
  122. return (name / 256, name % 256)
  123. if name.isdigit():
  124. return (int(name) / 256, int(name) % 256)
  125. if os.path.exists('/dev/%s' % name):
  126. blk_info = os.stat(os.path.realpath('/dev/%s' % name))
  127. if stat.S_ISBLK(blk_info.st_mode):
  128. return (blk_info.st_rdev / 256, blk_info.st_rdev % 256)
  129. major = 0
  130. minor = 0
  131. dXpY_style = False
  132. disk = True
  133. if name.startswith("xvd"):
  134. major = 202
  135. elif name.startswith("sd"):
  136. major = 8
  137. elif name.startswith("mmcblk"):
  138. dXpY_style = True
  139. major = 179
  140. elif name.startswith("scd"):
  141. disk = False
  142. major = 11
  143. elif name.startswith("sr"):
  144. disk = False
  145. major = 11
  146. elif name.startswith("loop"):
  147. dXpY_style = True
  148. disk = False
  149. major = 7
  150. elif name.startswith("md"):
  151. dXpY_style = True
  152. major = 9
  153. elif name.startswith("dm-"):
  154. disk = False
  155. major = 253
  156. else:
  157. # Unknown device
  158. return (0, 0)
  159. if not dXpY_style:
  160. name_match = re.match(r"^([a-z]+)([a-z-])([0-9]*)$", name)
  161. else:
  162. name_match = re.match(r"^([a-z]+)([0-9]*)(?:p([0-9]+))?$", name)
  163. if not name_match:
  164. raise QubesException("Invalid device name: %s" % name)
  165. if disk:
  166. if dXpY_style:
  167. minor = int(name_match.group(2))*8
  168. else:
  169. minor = (ord(name_match.group(2))-ord('a')) * 16
  170. else:
  171. minor = 0
  172. if name_match.group(3):
  173. minor += int(name_match.group(3))
  174. return (major, minor)
  175. def block_name_to_devid(name):
  176. # check if it is already devid
  177. if isinstance(name, int):
  178. return name
  179. if name.isdigit():
  180. return int(name)
  181. (major, minor) = block_name_to_majorminor(name)
  182. return major << 8 | minor
  183. def block_find_unused_frontend(vm = None):
  184. assert vm is not None
  185. assert vm.is_running()
  186. xml = vm.libvirt_domain.XMLDesc()
  187. parsed_xml = etree.fromstring(xml)
  188. used = [target.get('dev', None) for target in
  189. parsed_xml.xpath("//domain/devices/disk/target")]
  190. for dev in AVAILABLE_FRONTENDS:
  191. if dev not in used:
  192. return dev
  193. return None
  194. def block_list_vm(vm, system_disks = False):
  195. name_re = re.compile(r"^[a-z0-9-]{1,12}$")
  196. device_re = re.compile(r"^[a-z0-9/-]{1,64}$")
  197. # FIXME: any better idea of desc_re?
  198. desc_re = re.compile(r"^.{1,255}$")
  199. mode_re = re.compile(r"^[rw]$")
  200. assert vm is not None
  201. if not vm.is_running():
  202. return []
  203. devices_list = {}
  204. try:
  205. untrusted_devices = vm.qdb.multiread('/qubes-block-devices/')
  206. except Error:
  207. vm.refresh()
  208. return {}
  209. def get_dev_item(dev, item):
  210. return untrusted_devices.get(
  211. '/qubes-block-devices/%s/%s' % (dev, item),
  212. None)
  213. untrusted_devices_names = list(set(map(lambda x: x.split("/")[2],
  214. untrusted_devices.keys())))
  215. for untrusted_dev_name in untrusted_devices_names:
  216. if name_re.match(untrusted_dev_name):
  217. dev_name = untrusted_dev_name
  218. untrusted_device_size = get_dev_item(dev_name, 'size')
  219. untrusted_device_desc = get_dev_item(dev_name, 'desc')
  220. untrusted_device_mode = get_dev_item(dev_name, 'mode')
  221. untrusted_device_device = get_dev_item(dev_name, 'device')
  222. if untrusted_device_desc is None or untrusted_device_mode is None\
  223. or untrusted_device_size is None:
  224. print >>sys.stderr, "Missing field in %s device parameters" %\
  225. dev_name
  226. continue
  227. if untrusted_device_device is None:
  228. untrusted_device_device = '/dev/' + dev_name
  229. if not device_re.match(untrusted_device_device):
  230. print >> sys.stderr, "Invalid %s device path in VM '%s'" % (
  231. dev_name, vm.name)
  232. continue
  233. device_device = untrusted_device_device
  234. if not untrusted_device_size.isdigit():
  235. print >> sys.stderr, "Invalid %s device size in VM '%s'" % (
  236. dev_name, vm.name)
  237. continue
  238. device_size = int(untrusted_device_size)
  239. if not desc_re.match(untrusted_device_desc):
  240. print >> sys.stderr, "Invalid %s device desc in VM '%s'" % (
  241. dev_name, vm.name)
  242. continue
  243. device_desc = untrusted_device_desc
  244. if not mode_re.match(untrusted_device_mode):
  245. print >> sys.stderr, "Invalid %s device mode in VM '%s'" % (
  246. dev_name, vm.name)
  247. continue
  248. device_mode = untrusted_device_mode
  249. if not system_disks:
  250. if vm.qid == 0 and device_desc.startswith(system_path[
  251. "qubes_base_dir"]):
  252. continue
  253. visible_name = "%s:%s" % (vm.name, dev_name)
  254. devices_list[visible_name] = {
  255. "name": visible_name,
  256. "vm": vm.name,
  257. "device": device_device,
  258. "size": device_size,
  259. "desc": device_desc,
  260. "mode": device_mode
  261. }
  262. return devices_list
  263. def block_list(qvmc = None, vm = None, system_disks = False):
  264. if vm is not None:
  265. if not vm.is_running():
  266. return []
  267. else:
  268. vm_list = [ vm ]
  269. else:
  270. if qvmc is None:
  271. raise QubesException("You must pass either qvm or vm argument")
  272. vm_list = qvmc.values()
  273. devices_list = {}
  274. for vm in vm_list:
  275. devices_list.update(block_list_vm(vm, system_disks))
  276. return devices_list
  277. def block_check_attached(qvmc, device):
  278. """
  279. @type qvmc: QubesVmCollection
  280. """
  281. if qvmc is None:
  282. # TODO: ValueError
  283. raise QubesException("You need to pass qvmc argument")
  284. for vm in qvmc.values():
  285. try:
  286. libvirt_domain = vm.libvirt_domain
  287. if libvirt_domain:
  288. xml = libvirt_domain.XMLDesc()
  289. else:
  290. xml = None
  291. except libvirt.libvirtError:
  292. if vmm.libvirt_conn.virConnGetLastError()[0] == libvirt.VIR_ERR_NO_DOMAIN:
  293. libvirt_domain = None
  294. else:
  295. raise
  296. if xml:
  297. parsed_xml = etree.fromstring(xml)
  298. disks = parsed_xml.xpath("//domain/devices/disk")
  299. for disk in disks:
  300. backend_name = 'dom0'
  301. # FIXME: move <domain/> into <source/>
  302. if disk.find('domain') is not None:
  303. backend_name = disk.find('domain').get('name')
  304. source = disk.find('source')
  305. if disk.get('type') == 'file':
  306. path = source.get('file')
  307. elif disk.get('type') == 'block':
  308. path = source.get('dev')
  309. else:
  310. # TODO: logger
  311. print >>sys.stderr, "Unknown disk type '%s' attached to " \
  312. "VM '%s'" % (source.get('type'),
  313. vm.name)
  314. continue
  315. if backend_name == device['vm'] and path == device['device']:
  316. return {
  317. "frontend": disk.find('target').get('dev'),
  318. "vm": vm}
  319. return None
  320. def device_attach_check(vm, backend_vm, device, frontend, mode):
  321. """ Checks all the parameters, dies on errors """
  322. if not vm.is_running():
  323. raise QubesException("VM %s not running" % vm.name)
  324. if not backend_vm.is_running():
  325. raise QubesException("VM %s not running" % backend_vm.name)
  326. if device['mode'] == 'r' and mode == 'w':
  327. raise QubesException("Cannot attach read-only device in read-write "
  328. "mode")
  329. def block_attach(qvmc, vm, device, frontend=None, mode="w", auto_detach=False, wait=True):
  330. backend_vm = qvmc.get_vm_by_name(device['vm'])
  331. device_attach_check(vm, backend_vm, device, frontend, mode)
  332. if frontend is None:
  333. frontend = block_find_unused_frontend(vm)
  334. if frontend is None:
  335. raise QubesException("No unused frontend found")
  336. else:
  337. # Check if any device attached at this frontend
  338. xml = vm.libvirt_domain.XMLDesc()
  339. parsed_xml = etree.fromstring(xml)
  340. disks = parsed_xml.xpath("//domain/devices/disk/target[@dev='%s']" %
  341. frontend)
  342. if len(disks):
  343. raise QubesException("Frontend %s busy in VM %s, detach it first" % (frontend, vm.name))
  344. # Check if this device is attached to some domain
  345. attached_vm = block_check_attached(qvmc, device)
  346. if attached_vm:
  347. if auto_detach:
  348. block_detach(attached_vm['vm'], attached_vm['frontend'])
  349. else:
  350. raise QubesException("Device %s from %s already connected to VM "
  351. "%s as %s" % (device['device'],
  352. backend_vm.name, attached_vm['vm'], attached_vm['frontend']))
  353. disk = Element("disk")
  354. disk.set('type', 'block')
  355. disk.set('device', 'disk')
  356. SubElement(disk, 'driver').set('name', 'phy')
  357. SubElement(disk, 'source').set('dev', device['device'])
  358. SubElement(disk, 'target').set('dev', frontend)
  359. if backend_vm.qid != 0:
  360. SubElement(disk, 'domain').set('name', device['vm'])
  361. vm.libvirt_domain.attachDevice(etree.tostring(disk, encoding='utf-8'))
  362. def block_detach(vm, frontend = "xvdi"):
  363. xml = vm.libvirt_domain.XMLDesc()
  364. parsed_xml = etree.fromstring(xml)
  365. attached = parsed_xml.xpath("//domain/devices/disk")
  366. for disk in attached:
  367. if frontend is not None and disk.find('target').get('dev') != frontend:
  368. # Not the device we are looking for
  369. continue
  370. if frontend is None:
  371. # ignore system disks
  372. if disk.find('domain') == None and \
  373. disk.find('source').get('dev').startswith(system_path[
  374. "qubes_base_dir"]):
  375. continue
  376. vm.libvirt_domain.detachDevice(etree.tostring(disk, encoding='utf-8'))
  377. def block_detach_all(vm):
  378. """ Detach all non-system devices"""
  379. block_detach(vm, None)
  380. ####### USB devices ######
  381. usb_ver_re = re.compile(r"^(1|2)$")
  382. usb_device_re = re.compile(r"^[0-9]+-[0-9]+(_[0-9]+)?$")
  383. usb_port_re = re.compile(r"^$|^[0-9]+-[0-9]+(\.[0-9]+)?$")
  384. def usb_setup(backend_vm_xid, vm_xid, devid, usb_ver):
  385. """
  386. Attach frontend to the backend.
  387. backend_vm_xid - id of the backend domain
  388. vm_xid - id of the frontend domain
  389. devid - id of the pvusb controller
  390. """
  391. num_ports = 8
  392. trans = vmm.xs.transaction_start()
  393. be_path = "/local/domain/%d/backend/vusb/%d/%d" % (backend_vm_xid, vm_xid, devid)
  394. fe_path = "/local/domain/%d/device/vusb/%d" % (vm_xid, devid)
  395. be_perm = [{'dom': backend_vm_xid}, {'dom': vm_xid, 'read': True} ]
  396. fe_perm = [{'dom': vm_xid}, {'dom': backend_vm_xid, 'read': True} ]
  397. # Create directories and set permissions
  398. vmm.xs.write(trans, be_path, "")
  399. vmm.xs.set_permissions(trans, be_path, be_perm)
  400. vmm.xs.write(trans, fe_path, "")
  401. vmm.xs.set_permissions(trans, fe_path, fe_perm)
  402. # Write backend information into the location that frontend looks for
  403. vmm.xs.write(trans, "%s/backend-id" % fe_path, str(backend_vm_xid))
  404. vmm.xs.write(trans, "%s/backend" % fe_path, be_path)
  405. # Write frontend information into the location that backend looks for
  406. vmm.xs.write(trans, "%s/frontend-id" % be_path, str(vm_xid))
  407. vmm.xs.write(trans, "%s/frontend" % be_path, fe_path)
  408. # Write USB Spec version field.
  409. vmm.xs.write(trans, "%s/usb-ver" % be_path, usb_ver)
  410. # Write virtual root hub field.
  411. vmm.xs.write(trans, "%s/num-ports" % be_path, str(num_ports))
  412. for port in range(1, num_ports+1):
  413. # Set all port to disconnected state
  414. vmm.xs.write(trans, "%s/port/%d" % (be_path, port), "")
  415. # Set state to XenbusStateInitialising
  416. vmm.xs.write(trans, "%s/state" % fe_path, "1")
  417. vmm.xs.write(trans, "%s/state" % be_path, "1")
  418. vmm.xs.write(trans, "%s/online" % be_path, "1")
  419. vmm.xs.transaction_end(trans)
  420. def usb_decode_device_from_xs(xs_encoded_device):
  421. """ recover actual device name (xenstore doesn't allow dot in key names, so it was translated to underscore) """
  422. return xs_encoded_device.replace('_', '.')
  423. def usb_encode_device_for_xs(device):
  424. """ encode actual device name (xenstore doesn't allow dot in key names, so translated it into underscore) """
  425. return device.replace('.', '_')
  426. def usb_list():
  427. """
  428. Returns a dictionary of USB devices (for PVUSB backends running in all VM).
  429. The dictionary is keyed by 'name' (see below), each element is a dictionary itself:
  430. vm = name of the backend domain
  431. xid = xid of the backend domain
  432. device = <frontend device number>-<frontend port number>
  433. name = <name of backend domain>:<frontend device number>-<frontend port number>
  434. desc = description
  435. """
  436. # FIXME: any better idea of desc_re?
  437. desc_re = re.compile(r"^.{1,255}$")
  438. devices_list = {}
  439. xs_trans = vmm.xs.transaction_start()
  440. vm_list = vmm.xs.ls(xs_trans, '/local/domain')
  441. for xid in vm_list:
  442. vm_name = vmm.xs.read(xs_trans, '/local/domain/%s/name' % xid)
  443. vm_devices = vmm.xs.ls(xs_trans, '/local/domain/%s/qubes-usb-devices' % xid)
  444. if vm_devices is None:
  445. continue
  446. # when listing devices in xenstore we get encoded names
  447. for xs_encoded_device in vm_devices:
  448. # Sanitize device id
  449. if not usb_device_re.match(xs_encoded_device):
  450. print >> sys.stderr, "Invalid device id in backend VM '%s'" % vm_name
  451. continue
  452. device = usb_decode_device_from_xs(xs_encoded_device)
  453. device_desc = vmm.xs.read(xs_trans, '/local/domain/%s/qubes-usb-devices/%s/desc' % (xid, xs_encoded_device))
  454. if not desc_re.match(device_desc):
  455. print >> sys.stderr, "Invalid %s device desc in VM '%s'" % (device, vm_name)
  456. continue
  457. visible_name = "%s:%s" % (vm_name, device)
  458. # grab version
  459. usb_ver = vmm.xs.read(xs_trans, '/local/domain/%s/qubes-usb-devices/%s/usb-ver' % (xid, xs_encoded_device))
  460. if usb_ver is None or not usb_ver_re.match(usb_ver):
  461. print >> sys.stderr, "Invalid %s device USB version in VM '%s'" % (device, vm_name)
  462. continue
  463. devices_list[visible_name] = {"name": visible_name, "xid":int(xid),
  464. "vm": vm_name, "device":device,
  465. "desc":device_desc,
  466. "usb_ver":usb_ver}
  467. vmm.xs.transaction_end(xs_trans)
  468. return devices_list
  469. def usb_check_attached(xs_trans, backend_vm, device):
  470. """
  471. Checks if the given device in the given backend attached to any frontend.
  472. Parameters:
  473. backend_vm - xid of the backend domain
  474. device - device name in the backend domain
  475. Returns None or a dictionary:
  476. vm - the name of the frontend domain
  477. xid - xid of the frontend domain
  478. frontend - frontend device number FIXME
  479. devid - frontend port number FIXME
  480. """
  481. # sample xs content: /local/domain/0/backend/vusb/4/0/port/1 = "7-5"
  482. attached_dev = None
  483. vms = vmm.xs.ls(xs_trans, '/local/domain/%d/backend/vusb' % backend_vm)
  484. if vms is None:
  485. return None
  486. for vm in vms:
  487. if not vm.isdigit():
  488. print >> sys.stderr, "Invalid VM id"
  489. continue
  490. frontend_devs = vmm.xs.ls(xs_trans, '/local/domain/%d/backend/vusb/%s' % (backend_vm, vm))
  491. if frontend_devs is None:
  492. continue
  493. for frontend_dev in frontend_devs:
  494. if not frontend_dev.isdigit():
  495. print >> sys.stderr, "Invalid frontend in VM %s" % vm
  496. continue
  497. ports = vmm.xs.ls(xs_trans, '/local/domain/%d/backend/vusb/%s/%s/port' % (backend_vm, vm, frontend_dev))
  498. if ports is None:
  499. continue
  500. for port in ports:
  501. # FIXME: refactor, see similar loop in usb_find_unused_frontend(), use usb_list() instead?
  502. if not port.isdigit():
  503. print >> sys.stderr, "Invalid port in VM %s frontend %s" % (vm, frontend)
  504. continue
  505. dev = vmm.xs.read(xs_trans, '/local/domain/%d/backend/vusb/%s/%s/port/%s' % (backend_vm, vm, frontend_dev, port))
  506. if dev == "":
  507. continue
  508. # Sanitize device id
  509. if not usb_port_re.match(dev):
  510. print >> sys.stderr, "Invalid device id in backend VM %d @ %s/%s/port/%s" % \
  511. (backend_vm, vm, frontend_dev, port)
  512. continue
  513. if dev == device:
  514. frontend = "%s-%s" % (frontend_dev, port)
  515. #TODO
  516. vm_name = xl_ctx.domid_to_name(int(vm))
  517. if vm_name is None:
  518. # FIXME: should we wipe references to frontends running on nonexistent VMs?
  519. continue
  520. attached_dev = {"xid":int(vm), "frontend": frontend, "devid": device, "vm": vm_name}
  521. break
  522. return attached_dev
  523. #def usb_check_frontend_busy(vm, front_dev, port):
  524. # devport = frontend.split("-")
  525. # if len(devport) != 2:
  526. # raise QubesException("Malformed frontend syntax, must be in device-port format")
  527. # # FIXME:
  528. # # return vmm.xs.read('', '/local/domain/%d/device/vusb/%d/state' % (vm.xid, frontend)) == '4'
  529. # return False
  530. def usb_find_unused_frontend(xs_trans, backend_vm_xid, vm_xid, usb_ver):
  531. """
  532. Find an unused frontend/port to link the given backend with the given frontend.
  533. Creates new frontend if needed.
  534. Returns frontend specification in <device>-<port> format.
  535. """
  536. # This variable holds an index of last frontend scanned by the loop below.
  537. # If nothing found, this value will be used to derive the index of a new frontend.
  538. last_frontend_dev = -1
  539. frontend_devs = vmm.xs.ls(xs_trans, "/local/domain/%d/device/vusb" % vm_xid)
  540. if frontend_devs is not None:
  541. for frontend_dev in frontend_devs:
  542. if not frontend_dev.isdigit():
  543. print >> sys.stderr, "Invalid frontend_dev in VM %d" % vm_xid
  544. continue
  545. frontend_dev = int(frontend_dev)
  546. fe_path = "/local/domain/%d/device/vusb/%d" % (vm_xid, frontend_dev)
  547. if vmm.xs.read(xs_trans, "%s/backend-id" % fe_path) == str(backend_vm_xid):
  548. if vmm.xs.read(xs_trans, '/local/domain/%d/backend/vusb/%d/%d/usb-ver' % (backend_vm_xid, vm_xid, frontend_dev)) != usb_ver:
  549. last_frontend_dev = frontend_dev
  550. continue
  551. # here: found an existing frontend already connected to right backend using an appropriate USB version
  552. ports = vmm.xs.ls(xs_trans, '/local/domain/%d/backend/vusb/%d/%d/port' % (backend_vm_xid, vm_xid, frontend_dev))
  553. if ports is None:
  554. print >> sys.stderr, "No ports in VM %d frontend_dev %d?" % (vm_xid, frontend_dev)
  555. last_frontend_dev = frontend_dev
  556. continue
  557. for port in ports:
  558. # FIXME: refactor, see similar loop in usb_check_attached(), use usb_list() instead?
  559. if not port.isdigit():
  560. print >> sys.stderr, "Invalid port in VM %d frontend_dev %d" % (vm_xid, frontend_dev)
  561. continue
  562. port = int(port)
  563. dev = vmm.xs.read(xs_trans, '/local/domain/%d/backend/vusb/%d/%s/port/%s' % (backend_vm_xid, vm_xid, frontend_dev, port))
  564. # Sanitize device id
  565. if not usb_port_re.match(dev):
  566. print >> sys.stderr, "Invalid device id in backend VM %d @ %d/%d/port/%d" % \
  567. (backend_vm_xid, vm_xid, frontend_dev, port)
  568. continue
  569. if dev == "":
  570. return '%d-%d' % (frontend_dev, port)
  571. last_frontend_dev = frontend_dev
  572. # create a new frontend_dev and link it to the backend
  573. frontend_dev = last_frontend_dev + 1
  574. usb_setup(backend_vm_xid, vm_xid, frontend_dev, usb_ver)
  575. return '%d-%d' % (frontend_dev, 1)
  576. def usb_attach(vm, backend_vm, device, frontend=None, auto_detach=False, wait=True):
  577. device_attach_check(vm, backend_vm, device, frontend)
  578. xs_trans = vmm.xs.transaction_start()
  579. xs_encoded_device = usb_encode_device_for_xs(device)
  580. usb_ver = vmm.xs.read(xs_trans, '/local/domain/%s/qubes-usb-devices/%s/usb-ver' % (backend_vm.xid, xs_encoded_device))
  581. if usb_ver is None or not usb_ver_re.match(usb_ver):
  582. vmm.xs.transaction_end(xs_trans)
  583. raise QubesException("Invalid %s device USB version in VM '%s'" % (device, backend_vm.name))
  584. if frontend is None:
  585. frontend = usb_find_unused_frontend(xs_trans, backend_vm.xid, vm.xid, usb_ver)
  586. else:
  587. # Check if any device attached at this frontend
  588. #if usb_check_frontend_busy(vm, frontend):
  589. # raise QubesException("Frontend %s busy in VM %s, detach it first" % (frontend, vm.name))
  590. vmm.xs.transaction_end(xs_trans)
  591. raise NotImplementedError("Explicit USB frontend specification is not implemented yet")
  592. # Check if this device is attached to some domain
  593. attached_vm = usb_check_attached(xs_trans, backend_vm.xid, device)
  594. vmm.xs.transaction_end(xs_trans)
  595. if attached_vm:
  596. if auto_detach:
  597. usb_detach(backend_vm, attached_vm)
  598. else:
  599. raise QubesException("Device %s from %s already connected to VM %s as %s" % (device, backend_vm.name, attached_vm['vm'], attached_vm['frontend']))
  600. # Run helper script
  601. xl_cmd = [ '/usr/lib/qubes/xl-qvm-usb-attach.py', str(vm.xid), device, frontend, str(backend_vm.xid) ]
  602. subprocess.check_call(xl_cmd)
  603. def usb_detach(backend_vm, attachment):
  604. xl_cmd = [ '/usr/lib/qubes/xl-qvm-usb-detach.py', str(attachment['xid']), attachment['devid'], attachment['frontend'], str(backend_vm.xid) ]
  605. subprocess.check_call(xl_cmd)
  606. def usb_detach_all(vm):
  607. raise NotImplementedError("Detaching all devices from a given VM is not implemented yet")
  608. ####### QubesWatch ######
  609. def only_in_first_list(l1, l2):
  610. ret=[]
  611. for i in l1:
  612. if not i in l2:
  613. ret.append(i)
  614. return ret
  615. class QubesWatch(object):
  616. def __init__(self):
  617. self._qdb = {}
  618. self._qdb_events = {}
  619. self.block_callback = None
  620. self.meminfo_callback = None
  621. self.domain_callback = None
  622. vmm.libvirt_conn.domainEventRegisterAny(
  623. None,
  624. libvirt.VIR_DOMAIN_EVENT_ID_LIFECYCLE,
  625. self._domain_list_changed, None)
  626. vmm.libvirt_conn.domainEventRegisterAny(
  627. None,
  628. libvirt.VIR_DOMAIN_EVENT_ID_DEVICE_REMOVED,
  629. self._device_removed, None)
  630. # TODO: device attach libvirt event
  631. for vm in vmm.libvirt_conn.listAllDomains():
  632. try:
  633. if vm.isActive():
  634. self._register_watches(vm)
  635. except libvirt.libvirtError:
  636. # this will happen if we loose a race with another tool,
  637. # which can just remove the domain
  638. if vmm.libvirt_conn.virConnGetLastError()[0] == libvirt.VIR_ERR_NO_DOMAIN:
  639. pass
  640. raise
  641. # and for dom0
  642. self._register_watches(None)
  643. def _qdb_handler(self, watch, fd, events, domain_name):
  644. try:
  645. path = self._qdb[domain_name].read_watch()
  646. except DisconnectedError:
  647. libvirt.virEventRemoveHandle(watch)
  648. del(self._qdb_events[domain_name])
  649. self._qdb[domain_name].close()
  650. del(self._qdb[domain_name])
  651. return
  652. if path.startswith('/qubes-block-devices'):
  653. if self.block_callback is not None:
  654. self.block_callback(domain_name)
  655. def setup_block_watch(self, callback):
  656. self.block_callback = callback
  657. def setup_meminfo_watch(self, callback):
  658. raise NotImplementedError
  659. def setup_domain_watch(self, callback):
  660. self.domain_callback = callback
  661. def get_meminfo_key(self, xid):
  662. return '/local/domain/%s/memory/meminfo' % xid
  663. def _register_watches(self, libvirt_domain):
  664. if libvirt_domain:
  665. name = libvirt_domain.name()
  666. if name in self._qdb:
  667. return
  668. # open separate connection to Qubes DB:
  669. # 1. to not confuse pull() with responses to real commands sent from
  670. # other threads (like read, write etc) with watch events
  671. # 2. to not think whether QubesDB is thread-safe (it isn't)
  672. while libvirt_domain.isActive() and name not in self._qdb:
  673. try:
  674. self._qdb[name] = QubesDB(name)
  675. except Error as e:
  676. if e.args[0] != 2:
  677. raise
  678. time.sleep(0.5)
  679. else:
  680. name = "dom0"
  681. self._qdb[name] = QubesDB(name)
  682. self._qdb[name].watch('/qubes-block-devices')
  683. self._qdb_events[name] = libvirt.virEventAddHandle(
  684. self._qdb[name].watch_fd(),
  685. libvirt.VIR_EVENT_HANDLE_READABLE,
  686. self._qdb_handler, name)
  687. def _unregister_watches(self, libvirt_domain):
  688. name = libvirt_domain.name()
  689. if name in self._qdb_events:
  690. libvirt.virEventRemoveHandle(self._qdb_events[name])
  691. del(self._qdb_events[name])
  692. if name in self._qdb:
  693. self._qdb[name].close()
  694. del(self._qdb[name])
  695. def _domain_list_changed(self, conn, domain, event, reason, param):
  696. if event == libvirt.VIR_DOMAIN_EVENT_STARTED:
  697. self._register_watches(domain)
  698. elif event == libvirt.VIR_DOMAIN_EVENT_STOPPED:
  699. self._unregister_watches(domain)
  700. else:
  701. # ignore other events for now
  702. return None
  703. if self.domain_callback:
  704. self.domain_callback(name=domain.name(), uuid=domain.UUID())
  705. def _device_removed(self, conn, domain, device, param):
  706. if self.block_callback is not None:
  707. self.block_callback(domain.name())
  708. def watch_loop(self):
  709. while True:
  710. libvirt.virEventRunDefaultImpl()
  711. ##### updates check #####
  712. UPDATES_DOM0_DISABLE_FLAG='/var/lib/qubes/updates/disable-updates'
  713. def updates_vms_toggle(qvm_collection, value):
  714. for vm in qvm_collection.values():
  715. if vm.qid == 0:
  716. continue
  717. if value:
  718. vm.services.pop('qubes-update-check', None)
  719. if vm.is_running():
  720. try:
  721. vm.run("systemctl start qubes-update-check.timer",
  722. user="root")
  723. except:
  724. pass
  725. else:
  726. vm.services['qubes-update-check'] = False
  727. if vm.is_running():
  728. try:
  729. vm.run("systemctl stop qubes-update-check.timer",
  730. user="root")
  731. except:
  732. pass
  733. def updates_dom0_toggle(qvm_collection, value):
  734. if value:
  735. if os.path.exists(UPDATES_DOM0_DISABLE_FLAG):
  736. os.unlink(UPDATES_DOM0_DISABLE_FLAG)
  737. else:
  738. open(UPDATES_DOM0_DISABLE_FLAG, "w").close()
  739. def updates_dom0_status(qvm_collection):
  740. return not os.path.exists(UPDATES_DOM0_DISABLE_FLAG)
  741. # vim:sw=4:et: