qubesutils.py 31 KB

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