dispvm.py 12 KB

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