qubesutils.py 32 KB

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