qubesutils.py 33 KB

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