qubesutils.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  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. if vm.qid == 0:
  286. # Connecting devices to dom0 not supported
  287. continue
  288. try:
  289. libvirt_domain = vm.libvirt_domain
  290. if libvirt_domain:
  291. xml = libvirt_domain.XMLDesc()
  292. else:
  293. xml = None
  294. except libvirt.libvirtError:
  295. if vmm.libvirt_conn.virConnGetLastError()[0] == libvirt.VIR_ERR_NO_DOMAIN:
  296. xml = None
  297. else:
  298. raise
  299. if xml:
  300. parsed_xml = etree.fromstring(xml)
  301. disks = parsed_xml.xpath("//domain/devices/disk")
  302. for disk in disks:
  303. backend_name = 'dom0'
  304. # FIXME: move <domain/> into <source/>
  305. if disk.find('domain') is not None:
  306. backend_name = disk.find('domain').get('name')
  307. source = disk.find('source')
  308. if disk.get('type') == 'file':
  309. path = source.get('file')
  310. elif disk.get('type') == 'block':
  311. path = source.get('dev')
  312. else:
  313. # TODO: logger
  314. print >>sys.stderr, "Unknown disk type '%s' attached to " \
  315. "VM '%s'" % (source.get('type'),
  316. vm.name)
  317. continue
  318. if backend_name == device['vm'] and path == device['device']:
  319. return {
  320. "frontend": disk.find('target').get('dev'),
  321. "vm": vm}
  322. return None
  323. def device_attach_check(vm, backend_vm, device, frontend, mode):
  324. """ Checks all the parameters, dies on errors """
  325. if not vm.is_running():
  326. raise QubesException("VM %s not running" % vm.name)
  327. if not backend_vm.is_running():
  328. raise QubesException("VM %s not running" % backend_vm.name)
  329. if device['mode'] == 'r' and mode == 'w':
  330. raise QubesException("Cannot attach read-only device in read-write "
  331. "mode")
  332. def block_attach(qvmc, vm, device, frontend=None, mode="w", auto_detach=False, wait=True):
  333. backend_vm = qvmc.get_vm_by_name(device['vm'])
  334. device_attach_check(vm, backend_vm, device, frontend, mode)
  335. if frontend is None:
  336. frontend = block_find_unused_frontend(vm)
  337. if frontend is None:
  338. raise QubesException("No unused frontend found")
  339. else:
  340. # Check if any device attached at this frontend
  341. xml = vm.libvirt_domain.XMLDesc()
  342. parsed_xml = etree.fromstring(xml)
  343. disks = parsed_xml.xpath("//domain/devices/disk/target[@dev='%s']" %
  344. frontend)
  345. if len(disks):
  346. raise QubesException("Frontend %s busy in VM %s, detach it first" % (frontend, vm.name))
  347. # Check if this device is attached to some domain
  348. attached_vm = block_check_attached(qvmc, device)
  349. if attached_vm:
  350. if auto_detach:
  351. block_detach(attached_vm['vm'], attached_vm['frontend'])
  352. else:
  353. raise QubesException("Device %s from %s already connected to VM "
  354. "%s as %s" % (device['device'],
  355. backend_vm.name, attached_vm['vm'], attached_vm['frontend']))
  356. disk = Element("disk")
  357. disk.set('type', 'block')
  358. disk.set('device', 'disk')
  359. SubElement(disk, 'driver').set('name', 'phy')
  360. SubElement(disk, 'source').set('dev', device['device'])
  361. SubElement(disk, 'target').set('dev', frontend)
  362. if backend_vm.qid != 0:
  363. SubElement(disk, 'backenddomain').set('name', device['vm'])
  364. vm.libvirt_domain.attachDevice(etree.tostring(disk, encoding='utf-8'))
  365. try:
  366. # trigger watches to update device status
  367. # FIXME: this should be removed once libvirt will report such
  368. # events itself
  369. vm.qdb.write('/qubes-block-devices', '')
  370. except Error:
  371. pass
  372. def block_detach(vm, frontend = "xvdi"):
  373. xml = vm.libvirt_domain.XMLDesc()
  374. parsed_xml = etree.fromstring(xml)
  375. attached = parsed_xml.xpath("//domain/devices/disk")
  376. for disk in attached:
  377. if frontend is not None and disk.find('target').get('dev') != frontend:
  378. # Not the device we are looking for
  379. continue
  380. if frontend is None:
  381. # ignore system disks
  382. if disk.find('domain') == None and \
  383. disk.find('source').get('dev').startswith(system_path[
  384. "qubes_base_dir"]):
  385. continue
  386. vm.libvirt_domain.detachDevice(etree.tostring(disk, encoding='utf-8'))
  387. try:
  388. # trigger watches to update device status
  389. # FIXME: this should be removed once libvirt will report such
  390. # events itself
  391. vm.qdb.write('/qubes-block-devices', '')
  392. except Error:
  393. pass
  394. def block_detach_all(vm):
  395. """ Detach all non-system devices"""
  396. block_detach(vm, None)
  397. ####### USB devices ######
  398. usb_ver_re = re.compile(r"^(1|2)$")
  399. usb_device_re = re.compile(r"^[0-9]+-[0-9]+(_[0-9]+)?$")
  400. usb_port_re = re.compile(r"^$|^[0-9]+-[0-9]+(\.[0-9]+)?$")
  401. def usb_setup(backend_vm_xid, vm_xid, devid, usb_ver):
  402. """
  403. Attach frontend to the backend.
  404. backend_vm_xid - id of the backend domain
  405. vm_xid - id of the frontend domain
  406. devid - id of the pvusb controller
  407. """
  408. num_ports = 8
  409. trans = vmm.xs.transaction_start()
  410. be_path = "/local/domain/%d/backend/vusb/%d/%d" % (backend_vm_xid, vm_xid, devid)
  411. fe_path = "/local/domain/%d/device/vusb/%d" % (vm_xid, devid)
  412. be_perm = [{'dom': backend_vm_xid}, {'dom': vm_xid, 'read': True} ]
  413. fe_perm = [{'dom': vm_xid}, {'dom': backend_vm_xid, 'read': True} ]
  414. # Create directories and set permissions
  415. vmm.xs.write(trans, be_path, "")
  416. vmm.xs.set_permissions(trans, be_path, be_perm)
  417. vmm.xs.write(trans, fe_path, "")
  418. vmm.xs.set_permissions(trans, fe_path, fe_perm)
  419. # Write backend information into the location that frontend looks for
  420. vmm.xs.write(trans, "%s/backend-id" % fe_path, str(backend_vm_xid))
  421. vmm.xs.write(trans, "%s/backend" % fe_path, be_path)
  422. # Write frontend information into the location that backend looks for
  423. vmm.xs.write(trans, "%s/frontend-id" % be_path, str(vm_xid))
  424. vmm.xs.write(trans, "%s/frontend" % be_path, fe_path)
  425. # Write USB Spec version field.
  426. vmm.xs.write(trans, "%s/usb-ver" % be_path, usb_ver)
  427. # Write virtual root hub field.
  428. vmm.xs.write(trans, "%s/num-ports" % be_path, str(num_ports))
  429. for port in range(1, num_ports+1):
  430. # Set all port to disconnected state
  431. vmm.xs.write(trans, "%s/port/%d" % (be_path, port), "")
  432. # Set state to XenbusStateInitialising
  433. vmm.xs.write(trans, "%s/state" % fe_path, "1")
  434. vmm.xs.write(trans, "%s/state" % be_path, "1")
  435. vmm.xs.write(trans, "%s/online" % be_path, "1")
  436. vmm.xs.transaction_end(trans)
  437. def usb_decode_device_from_xs(xs_encoded_device):
  438. """ recover actual device name (xenstore doesn't allow dot in key names, so it was translated to underscore) """
  439. return xs_encoded_device.replace('_', '.')
  440. def usb_encode_device_for_xs(device):
  441. """ encode actual device name (xenstore doesn't allow dot in key names, so translated it into underscore) """
  442. return device.replace('.', '_')
  443. def usb_list():
  444. """
  445. Returns a dictionary of USB devices (for PVUSB backends running in all VM).
  446. The dictionary is keyed by 'name' (see below), each element is a dictionary itself:
  447. vm = name of the backend domain
  448. xid = xid of the backend domain
  449. device = <frontend device number>-<frontend port number>
  450. name = <name of backend domain>:<frontend device number>-<frontend port number>
  451. desc = description
  452. """
  453. # FIXME: any better idea of desc_re?
  454. desc_re = re.compile(r"^.{1,255}$")
  455. devices_list = {}
  456. xs_trans = vmm.xs.transaction_start()
  457. vm_list = vmm.xs.ls(xs_trans, '/local/domain')
  458. for xid in vm_list:
  459. vm_name = vmm.xs.read(xs_trans, '/local/domain/%s/name' % xid)
  460. vm_devices = vmm.xs.ls(xs_trans, '/local/domain/%s/qubes-usb-devices' % xid)
  461. if vm_devices is None:
  462. continue
  463. # when listing devices in xenstore we get encoded names
  464. for xs_encoded_device in vm_devices:
  465. # Sanitize device id
  466. if not usb_device_re.match(xs_encoded_device):
  467. print >> sys.stderr, "Invalid device id in backend VM '%s'" % vm_name
  468. continue
  469. device = usb_decode_device_from_xs(xs_encoded_device)
  470. device_desc = vmm.xs.read(xs_trans, '/local/domain/%s/qubes-usb-devices/%s/desc' % (xid, xs_encoded_device))
  471. if not desc_re.match(device_desc):
  472. print >> sys.stderr, "Invalid %s device desc in VM '%s'" % (device, vm_name)
  473. continue
  474. visible_name = "%s:%s" % (vm_name, device)
  475. # grab version
  476. usb_ver = vmm.xs.read(xs_trans, '/local/domain/%s/qubes-usb-devices/%s/usb-ver' % (xid, xs_encoded_device))
  477. if usb_ver is None or not usb_ver_re.match(usb_ver):
  478. print >> sys.stderr, "Invalid %s device USB version in VM '%s'" % (device, vm_name)
  479. continue
  480. devices_list[visible_name] = {"name": visible_name, "xid":int(xid),
  481. "vm": vm_name, "device":device,
  482. "desc":device_desc,
  483. "usb_ver":usb_ver}
  484. vmm.xs.transaction_end(xs_trans)
  485. return devices_list
  486. def usb_check_attached(xs_trans, backend_vm, device):
  487. """
  488. Checks if the given device in the given backend attached to any frontend.
  489. Parameters:
  490. backend_vm - xid of the backend domain
  491. device - device name in the backend domain
  492. Returns None or a dictionary:
  493. vm - the name of the frontend domain
  494. xid - xid of the frontend domain
  495. frontend - frontend device number FIXME
  496. devid - frontend port number FIXME
  497. """
  498. # sample xs content: /local/domain/0/backend/vusb/4/0/port/1 = "7-5"
  499. attached_dev = None
  500. vms = vmm.xs.ls(xs_trans, '/local/domain/%d/backend/vusb' % backend_vm)
  501. if vms is None:
  502. return None
  503. for vm in vms:
  504. if not vm.isdigit():
  505. print >> sys.stderr, "Invalid VM id"
  506. continue
  507. frontend_devs = vmm.xs.ls(xs_trans, '/local/domain/%d/backend/vusb/%s' % (backend_vm, vm))
  508. if frontend_devs is None:
  509. continue
  510. for frontend_dev in frontend_devs:
  511. if not frontend_dev.isdigit():
  512. print >> sys.stderr, "Invalid frontend in VM %s" % vm
  513. continue
  514. ports = vmm.xs.ls(xs_trans, '/local/domain/%d/backend/vusb/%s/%s/port' % (backend_vm, vm, frontend_dev))
  515. if ports is None:
  516. continue
  517. for port in ports:
  518. # FIXME: refactor, see similar loop in usb_find_unused_frontend(), use usb_list() instead?
  519. if not port.isdigit():
  520. print >> sys.stderr, "Invalid port in VM %s frontend %s" % (vm, frontend)
  521. continue
  522. dev = vmm.xs.read(xs_trans, '/local/domain/%d/backend/vusb/%s/%s/port/%s' % (backend_vm, vm, frontend_dev, port))
  523. if dev == "":
  524. continue
  525. # Sanitize device id
  526. if not usb_port_re.match(dev):
  527. print >> sys.stderr, "Invalid device id in backend VM %d @ %s/%s/port/%s" % \
  528. (backend_vm, vm, frontend_dev, port)
  529. continue
  530. if dev == device:
  531. frontend = "%s-%s" % (frontend_dev, port)
  532. #TODO
  533. vm_name = xl_ctx.domid_to_name(int(vm))
  534. if vm_name is None:
  535. # FIXME: should we wipe references to frontends running on nonexistent VMs?
  536. continue
  537. attached_dev = {"xid":int(vm), "frontend": frontend, "devid": device, "vm": vm_name}
  538. break
  539. return attached_dev
  540. #def usb_check_frontend_busy(vm, front_dev, port):
  541. # devport = frontend.split("-")
  542. # if len(devport) != 2:
  543. # raise QubesException("Malformed frontend syntax, must be in device-port format")
  544. # # FIXME:
  545. # # return vmm.xs.read('', '/local/domain/%d/device/vusb/%d/state' % (vm.xid, frontend)) == '4'
  546. # return False
  547. def usb_find_unused_frontend(xs_trans, backend_vm_xid, vm_xid, usb_ver):
  548. """
  549. Find an unused frontend/port to link the given backend with the given frontend.
  550. Creates new frontend if needed.
  551. Returns frontend specification in <device>-<port> format.
  552. """
  553. # This variable holds an index of last frontend scanned by the loop below.
  554. # If nothing found, this value will be used to derive the index of a new frontend.
  555. last_frontend_dev = -1
  556. frontend_devs = vmm.xs.ls(xs_trans, "/local/domain/%d/device/vusb" % vm_xid)
  557. if frontend_devs is not None:
  558. for frontend_dev in frontend_devs:
  559. if not frontend_dev.isdigit():
  560. print >> sys.stderr, "Invalid frontend_dev in VM %d" % vm_xid
  561. continue
  562. frontend_dev = int(frontend_dev)
  563. fe_path = "/local/domain/%d/device/vusb/%d" % (vm_xid, frontend_dev)
  564. if vmm.xs.read(xs_trans, "%s/backend-id" % fe_path) == str(backend_vm_xid):
  565. if vmm.xs.read(xs_trans, '/local/domain/%d/backend/vusb/%d/%d/usb-ver' % (backend_vm_xid, vm_xid, frontend_dev)) != usb_ver:
  566. last_frontend_dev = frontend_dev
  567. continue
  568. # here: found an existing frontend already connected to right backend using an appropriate USB version
  569. ports = vmm.xs.ls(xs_trans, '/local/domain/%d/backend/vusb/%d/%d/port' % (backend_vm_xid, vm_xid, frontend_dev))
  570. if ports is None:
  571. print >> sys.stderr, "No ports in VM %d frontend_dev %d?" % (vm_xid, frontend_dev)
  572. last_frontend_dev = frontend_dev
  573. continue
  574. for port in ports:
  575. # FIXME: refactor, see similar loop in usb_check_attached(), use usb_list() instead?
  576. if not port.isdigit():
  577. print >> sys.stderr, "Invalid port in VM %d frontend_dev %d" % (vm_xid, frontend_dev)
  578. continue
  579. port = int(port)
  580. dev = vmm.xs.read(xs_trans, '/local/domain/%d/backend/vusb/%d/%s/port/%s' % (backend_vm_xid, vm_xid, frontend_dev, port))
  581. # Sanitize device id
  582. if not usb_port_re.match(dev):
  583. print >> sys.stderr, "Invalid device id in backend VM %d @ %d/%d/port/%d" % \
  584. (backend_vm_xid, vm_xid, frontend_dev, port)
  585. continue
  586. if dev == "":
  587. return '%d-%d' % (frontend_dev, port)
  588. last_frontend_dev = frontend_dev
  589. # create a new frontend_dev and link it to the backend
  590. frontend_dev = last_frontend_dev + 1
  591. usb_setup(backend_vm_xid, vm_xid, frontend_dev, usb_ver)
  592. return '%d-%d' % (frontend_dev, 1)
  593. def usb_attach(vm, backend_vm, device, frontend=None, auto_detach=False, wait=True):
  594. device_attach_check(vm, backend_vm, device, frontend)
  595. xs_trans = vmm.xs.transaction_start()
  596. xs_encoded_device = usb_encode_device_for_xs(device)
  597. usb_ver = vmm.xs.read(xs_trans, '/local/domain/%s/qubes-usb-devices/%s/usb-ver' % (backend_vm.xid, xs_encoded_device))
  598. if usb_ver is None or not usb_ver_re.match(usb_ver):
  599. vmm.xs.transaction_end(xs_trans)
  600. raise QubesException("Invalid %s device USB version in VM '%s'" % (device, backend_vm.name))
  601. if frontend is None:
  602. frontend = usb_find_unused_frontend(xs_trans, backend_vm.xid, vm.xid, usb_ver)
  603. else:
  604. # Check if any device attached at this frontend
  605. #if usb_check_frontend_busy(vm, frontend):
  606. # raise QubesException("Frontend %s busy in VM %s, detach it first" % (frontend, vm.name))
  607. vmm.xs.transaction_end(xs_trans)
  608. raise NotImplementedError("Explicit USB frontend specification is not implemented yet")
  609. # Check if this device is attached to some domain
  610. attached_vm = usb_check_attached(xs_trans, backend_vm.xid, device)
  611. vmm.xs.transaction_end(xs_trans)
  612. if attached_vm:
  613. if auto_detach:
  614. usb_detach(backend_vm, attached_vm)
  615. else:
  616. raise QubesException("Device %s from %s already connected to VM %s as %s" % (device, backend_vm.name, attached_vm['vm'], attached_vm['frontend']))
  617. # Run helper script
  618. xl_cmd = [ '/usr/lib/qubes/xl-qvm-usb-attach.py', str(vm.xid), device, frontend, str(backend_vm.xid) ]
  619. subprocess.check_call(xl_cmd)
  620. def usb_detach(backend_vm, attachment):
  621. xl_cmd = [ '/usr/lib/qubes/xl-qvm-usb-detach.py', str(attachment['xid']), attachment['devid'], attachment['frontend'], str(backend_vm.xid) ]
  622. subprocess.check_call(xl_cmd)
  623. def usb_detach_all(vm):
  624. raise NotImplementedError("Detaching all devices from a given VM is not implemented yet")
  625. ####### QubesWatch ######
  626. def only_in_first_list(l1, l2):
  627. ret=[]
  628. for i in l1:
  629. if not i in l2:
  630. ret.append(i)
  631. return ret
  632. class QubesWatch(object):
  633. def __init__(self):
  634. self._qdb = {}
  635. self._qdb_events = {}
  636. self.block_callback = None
  637. self.meminfo_callback = None
  638. self.domain_callback = None
  639. vmm.libvirt_conn.domainEventRegisterAny(
  640. None,
  641. libvirt.VIR_DOMAIN_EVENT_ID_LIFECYCLE,
  642. self._domain_list_changed, None)
  643. vmm.libvirt_conn.domainEventRegisterAny(
  644. None,
  645. libvirt.VIR_DOMAIN_EVENT_ID_DEVICE_REMOVED,
  646. self._device_removed, None)
  647. # TODO: device attach libvirt event
  648. for vm in vmm.libvirt_conn.listAllDomains():
  649. try:
  650. if vm.isActive():
  651. self._register_watches(vm)
  652. except libvirt.libvirtError:
  653. # this will happen if we loose a race with another tool,
  654. # which can just remove the domain
  655. if vmm.libvirt_conn.virConnGetLastError()[0] == libvirt.VIR_ERR_NO_DOMAIN:
  656. pass
  657. raise
  658. # and for dom0
  659. self._register_watches(None)
  660. def _qdb_handler(self, watch, fd, events, domain_name):
  661. try:
  662. path = self._qdb[domain_name].read_watch()
  663. except DisconnectedError:
  664. libvirt.virEventRemoveHandle(watch)
  665. del(self._qdb_events[domain_name])
  666. self._qdb[domain_name].close()
  667. del(self._qdb[domain_name])
  668. return
  669. if path.startswith('/qubes-block-devices'):
  670. if self.block_callback is not None:
  671. self.block_callback(domain_name)
  672. def setup_block_watch(self, callback):
  673. self.block_callback = callback
  674. def setup_meminfo_watch(self, callback):
  675. raise NotImplementedError
  676. def setup_domain_watch(self, callback):
  677. self.domain_callback = callback
  678. def get_meminfo_key(self, xid):
  679. return '/local/domain/%s/memory/meminfo' % xid
  680. def _register_watches(self, libvirt_domain):
  681. if libvirt_domain:
  682. name = libvirt_domain.name()
  683. if name in self._qdb:
  684. return
  685. # open separate connection to Qubes DB:
  686. # 1. to not confuse pull() with responses to real commands sent from
  687. # other threads (like read, write etc) with watch events
  688. # 2. to not think whether QubesDB is thread-safe (it isn't)
  689. while libvirt_domain.isActive() and name not in self._qdb:
  690. try:
  691. self._qdb[name] = QubesDB(name)
  692. except Error as e:
  693. if e.args[0] != 2:
  694. raise
  695. time.sleep(0.5)
  696. if name not in self._qdb:
  697. # domain no longer active
  698. return
  699. else:
  700. name = "dom0"
  701. self._qdb[name] = QubesDB(name)
  702. self._qdb[name].watch('/qubes-block-devices')
  703. self._qdb_events[name] = libvirt.virEventAddHandle(
  704. self._qdb[name].watch_fd(),
  705. libvirt.VIR_EVENT_HANDLE_READABLE,
  706. self._qdb_handler, name)
  707. def _unregister_watches(self, libvirt_domain):
  708. name = libvirt_domain.name()
  709. if name in self._qdb_events:
  710. libvirt.virEventRemoveHandle(self._qdb_events[name])
  711. del(self._qdb_events[name])
  712. if name in self._qdb:
  713. self._qdb[name].close()
  714. del(self._qdb[name])
  715. def _domain_list_changed(self, conn, domain, event, reason, param):
  716. if event == libvirt.VIR_DOMAIN_EVENT_STARTED:
  717. self._register_watches(domain)
  718. elif event == libvirt.VIR_DOMAIN_EVENT_STOPPED:
  719. self._unregister_watches(domain)
  720. else:
  721. # ignore other events for now
  722. return None
  723. if self.domain_callback:
  724. self.domain_callback(name=domain.name(), uuid=domain.UUID())
  725. def _device_removed(self, conn, domain, device, param):
  726. if self.block_callback is not None:
  727. self.block_callback(domain.name())
  728. def watch_loop(self):
  729. while True:
  730. libvirt.virEventRunDefaultImpl()
  731. ##### updates check #####
  732. UPDATES_DOM0_DISABLE_FLAG='/var/lib/qubes/updates/disable-updates'
  733. def updates_vms_toggle(qvm_collection, value):
  734. for vm in qvm_collection.values():
  735. if vm.qid == 0:
  736. continue
  737. if value:
  738. vm.services.pop('qubes-update-check', None)
  739. if vm.is_running():
  740. try:
  741. vm.run("systemctl start qubes-update-check.timer",
  742. user="root")
  743. except:
  744. pass
  745. else:
  746. vm.services['qubes-update-check'] = False
  747. if vm.is_running():
  748. try:
  749. vm.run("systemctl stop qubes-update-check.timer",
  750. user="root")
  751. except:
  752. pass
  753. def updates_dom0_toggle(qvm_collection, value):
  754. if value:
  755. if os.path.exists(UPDATES_DOM0_DISABLE_FLAG):
  756. os.unlink(UPDATES_DOM0_DISABLE_FLAG)
  757. else:
  758. open(UPDATES_DOM0_DISABLE_FLAG, "w").close()
  759. def updates_dom0_status(qvm_collection):
  760. return not os.path.exists(UPDATES_DOM0_DISABLE_FLAG)
  761. # vim:sw=4:et: