dispvm.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. #
  2. # The Qubes OS Project, http://www.qubes-os.org
  3. #
  4. # Copyright (C) 2016 Marek Marczykowski-Górecki
  5. # <marmarek@invisiblethingslab.com>
  6. #
  7. # This library is free software; you can redistribute it and/or
  8. # modify it under the terms of the GNU Lesser General Public
  9. # License as published by the Free Software Foundation; either
  10. # version 2.1 of the License, or (at your option) any later version.
  11. #
  12. # This library is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. # Lesser General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Lesser General Public
  18. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  19. #
  20. import os
  21. import subprocess
  22. import tempfile
  23. import time
  24. import unittest
  25. from distutils import spawn
  26. import asyncio
  27. import qubes.tests
  28. class TC_04_DispVM(qubes.tests.SystemTestCase):
  29. def setUp(self):
  30. super(TC_04_DispVM, self).setUp()
  31. self.init_default_template()
  32. self.disp_base = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  33. name=self.make_vm_name('dvm'),
  34. label='red',
  35. )
  36. self.loop.run_until_complete(self.disp_base.create_on_disk())
  37. self.disp_base.template_for_dispvms = True
  38. self.app.default_dispvm = self.disp_base
  39. self.testvm = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  40. name=self.make_vm_name('vm'),
  41. label='red',
  42. )
  43. self.loop.run_until_complete(self.testvm.create_on_disk())
  44. self.app.save()
  45. def tearDown(self):
  46. self.app.default_dispvm = None
  47. super(TC_04_DispVM, self).tearDown()
  48. @unittest.expectedFailure
  49. def test_002_cleanup(self):
  50. self.loop.run_until_complete(self.testvm.start())
  51. try:
  52. (stdout, _) = self.loop.run_until_complete(
  53. self.testvm.run_for_stdio("qvm-run-vm --dispvm bash",
  54. input=b"echo test; qubesdb-read /name; echo ERROR\n"))
  55. except subprocess.CalledProcessError as err:
  56. self.fail('qvm-run-vm failed with {} code, stderr: {}'.format(
  57. err.returncode, err.stderr))
  58. lines = stdout.decode('ascii').splitlines()
  59. self.assertEqual(lines[0], "test")
  60. dispvm_name = lines[1]
  61. # wait for actual DispVM destruction
  62. self.loop.run_until_complete(asyncio.sleep(1))
  63. self.assertNotIn(dispvm_name, self.app.domains)
  64. @unittest.expectedFailure
  65. def test_003_cleanup_destroyed(self):
  66. """
  67. Check if DispVM is properly removed even if it terminated itself (#1660)
  68. :return:
  69. """
  70. self.loop.run_until_complete(self.testvm.start())
  71. p = self.loop.run_until_complete(
  72. self.testvm.run("qvm-run-vm --dispvm bash; true",
  73. stdin=subprocess.PIPE, stdout=subprocess.PIPE))
  74. p.stdin.write(b"qubesdb-read /name\n")
  75. p.stdin.write(b"echo ERROR\n")
  76. p.stdin.write(b"sudo poweroff\n")
  77. # do not close p.stdin on purpose - wait to automatic disconnect when
  78. # domain is destroyed
  79. timeout = 30
  80. lines_task = asyncio.ensure_future(p.stdout.read())
  81. self.loop.run_until_complete(asyncio.wait_for(p.wait(), timeout))
  82. self.loop.run_until_complete(lines_task)
  83. lines = lines_task.result().splitlines()
  84. self.assertTrue(lines, 'No output received from DispVM')
  85. dispvm_name = lines[0]
  86. self.assertNotEquals(dispvm_name, b"ERROR")
  87. self.assertNotIn(dispvm_name, self.app.domains)
  88. class TC_20_DispVMMixin(object):
  89. def setUp(self):
  90. super(TC_20_DispVMMixin, self).setUp()
  91. self.init_default_template(self.template)
  92. self.disp_base = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  93. name=self.make_vm_name('dvm'),
  94. label='red', template_for_dispvms=True,
  95. )
  96. self.loop.run_until_complete(self.disp_base.create_on_disk())
  97. self.app.default_dispvm = self.disp_base
  98. self.app.save()
  99. def tearDown(self):
  100. self.app.default_dispvm = None
  101. super(TC_20_DispVMMixin, self).tearDown()
  102. def test_010_simple_dvm_run(self):
  103. dispvm = self.loop.run_until_complete(
  104. qubes.vm.dispvm.DispVM.from_appvm(self.disp_base))
  105. try:
  106. self.loop.run_until_complete(dispvm.start())
  107. (stdout, _) = self.loop.run_until_complete(
  108. dispvm.run_service_for_stdio('qubes.VMShell',
  109. input=b"echo test"))
  110. self.assertEqual(stdout, b"test\n")
  111. finally:
  112. self.loop.run_until_complete(dispvm.cleanup())
  113. @unittest.skipUnless(spawn.find_executable('xdotool'),
  114. "xdotool not installed")
  115. def test_020_gui_app(self):
  116. dispvm = self.loop.run_until_complete(
  117. qubes.vm.dispvm.DispVM.from_appvm(self.disp_base))
  118. try:
  119. self.loop.run_until_complete(dispvm.start())
  120. self.loop.run_until_complete(self.wait_for_session(dispvm))
  121. p = self.loop.run_until_complete(
  122. dispvm.run_service('qubes.VMShell',
  123. stdin=subprocess.PIPE,
  124. stdout=subprocess.PIPE))
  125. # wait for DispVM startup:
  126. p.stdin.write(b"echo test\n")
  127. self.loop.run_until_complete(p.stdin.drain())
  128. l = self.loop.run_until_complete(p.stdout.readline())
  129. self.assertEqual(l, b"test\n")
  130. self.assertTrue(dispvm.is_running())
  131. try:
  132. window_title = 'user@%s' % (dispvm.name,)
  133. p.stdin.write("xterm -e "
  134. "\"sh -c 'echo \\\"\033]0;{}\007\\\";read x;'\"\n".
  135. format(window_title).encode())
  136. self.wait_for_window(window_title)
  137. time.sleep(0.5)
  138. self.enter_keys_in_window(window_title, ['Return'])
  139. # Wait for window to close
  140. self.wait_for_window(window_title, show=False)
  141. finally:
  142. p.stdin.close()
  143. finally:
  144. self.loop.run_until_complete(dispvm.cleanup())
  145. dispvm_name = dispvm.name
  146. del dispvm
  147. self.assertNotIn(dispvm_name, self.app.domains,
  148. "DispVM not removed from qubes.xml")
  149. def _handle_editor(self, winid):
  150. (window_title, _) = subprocess.Popen(
  151. ['xdotool', 'getwindowname', winid], stdout=subprocess.PIPE).\
  152. communicate()
  153. window_title = window_title.decode().strip().\
  154. replace('(', '\(').replace(')', '\)')
  155. time.sleep(1)
  156. if "gedit" in window_title:
  157. subprocess.check_call(['xdotool', 'windowactivate', '--sync', winid,
  158. 'type', 'Test test 2'])
  159. subprocess.check_call(['xdotool', 'key', '--window', winid,
  160. 'key', 'Return'])
  161. time.sleep(0.5)
  162. subprocess.check_call(['xdotool',
  163. 'key', 'ctrl+s', 'ctrl+q'])
  164. elif "LibreOffice" in window_title:
  165. # wait for actual editor (we've got splash screen)
  166. search = subprocess.Popen(['xdotool', 'search', '--sync',
  167. '--onlyvisible', '--all', '--name', '--class', 'disp*|Writer'],
  168. stdout=subprocess.PIPE,
  169. stderr=open(os.path.devnull, 'w'))
  170. retcode = search.wait()
  171. if retcode == 0:
  172. winid = search.stdout.read().strip()
  173. time.sleep(0.5)
  174. subprocess.check_call(['xdotool', 'windowactivate', '--sync', winid,
  175. 'type', 'Test test 2'])
  176. subprocess.check_call(['xdotool', 'key', '--window', winid,
  177. 'key', 'Return'])
  178. time.sleep(0.5)
  179. subprocess.check_call(['xdotool',
  180. 'key', '--delay', '100', 'ctrl+s',
  181. 'Return', 'ctrl+q'])
  182. elif "emacs" in window_title:
  183. subprocess.check_call(['xdotool', 'windowactivate', '--sync', winid,
  184. 'type', 'Test test 2'])
  185. subprocess.check_call(['xdotool', 'key', '--window', winid,
  186. 'key', 'Return'])
  187. time.sleep(0.5)
  188. subprocess.check_call(['xdotool',
  189. 'key', 'ctrl+x', 'ctrl+s'])
  190. subprocess.check_call(['xdotool',
  191. 'key', 'ctrl+x', 'ctrl+c'])
  192. elif "vim" in window_title or "user@" in window_title:
  193. subprocess.check_call(['xdotool', 'windowactivate', '--sync', winid,
  194. 'key', 'i', 'type', 'Test test 2'])
  195. subprocess.check_call(['xdotool', 'key', '--window', winid,
  196. 'key', 'Return'])
  197. subprocess.check_call(
  198. ['xdotool',
  199. 'key', 'Escape', 'colon', 'w', 'q', 'Return'])
  200. else:
  201. self.fail("Unknown editor window: {}".format(window_title))
  202. @unittest.skipUnless(spawn.find_executable('xdotool'),
  203. "xdotool not installed")
  204. @unittest.expectedFailure
  205. def test_030_edit_file(self):
  206. self.testvm1 = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  207. name=self.make_vm_name('vm1'),
  208. label='red',
  209. template=self.app.domains[self.template])
  210. self.loop.run_until_complete(self.testvm1.create_on_disk())
  211. self.app.save()
  212. self.loop.run_until_complete(self.testvm1.start())
  213. self.loop.run_until_complete(
  214. self.testvm1.run_for_stdio("echo test1 > /home/user/test.txt"))
  215. p = self.loop.run_until_complete(
  216. self.testvm1.run("qvm-open-in-dvm /home/user/test.txt"))
  217. wait_count = 0
  218. winid = None
  219. while True:
  220. search = self.loop.run_until_complete(
  221. asyncio.create_subprocess_exec(
  222. 'xdotool', 'search', '--onlyvisible', '--class', 'disp*',
  223. stdout=subprocess.PIPE,
  224. stderr=subprocess.DEVNULL))
  225. stdout, _ = self.loop.run_until_complete(search.communicate())
  226. if search.returncode == 0:
  227. winid = stdout.strip()
  228. # get window title
  229. (window_title, _) = subprocess.Popen(
  230. ['xdotool', 'getwindowname', winid], stdout=subprocess.PIPE). \
  231. communicate()
  232. window_title = window_title.decode().strip()
  233. # ignore LibreOffice splash screen and window with no title
  234. # set yet
  235. if window_title and not window_title.startswith("LibreOffice")\
  236. and not window_title == 'VMapp command':
  237. break
  238. wait_count += 1
  239. if wait_count > 100:
  240. self.fail("Timeout while waiting for editor window")
  241. self.loop.run_until_complete(asyncio.sleep(0.3))
  242. time.sleep(0.5)
  243. self._handle_editor(winid)
  244. self.loop.run_until_complete(p.wait())
  245. (test_txt_content, _) = self.loop.run_until_complete(
  246. self.testvm1.run_for_stdio("cat /home/user/test.txt"))
  247. # Drop BOM if added by editor
  248. if test_txt_content.startswith(b'\xef\xbb\xbf'):
  249. test_txt_content = test_txt_content[3:]
  250. self.assertEqual(test_txt_content, b"Test test 2\ntest1\n")
  251. def load_tests(loader, tests, pattern):
  252. for template in qubes.tests.list_templates():
  253. tests.addTests(loader.loadTestsFromTestCase(
  254. type(
  255. 'TC_20_DispVM_' + template,
  256. (TC_20_DispVMMixin, qubes.tests.SystemTestCase),
  257. {'template': template})))
  258. return tests