qubesutils.py 30 KB

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