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