dispvm.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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. from distutils import spawn
  22. import qubes.tests
  23. import subprocess
  24. import tempfile
  25. import unittest
  26. import os
  27. import time
  28. class TC_04_DispVM(qubes.tests.SystemTestsMixin,
  29. qubes.tests.QubesTestCase):
  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.disp_base.create_on_disk()
  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.testvm.create_on_disk()
  44. self.app.save()
  45. @unittest.expectedFailure
  46. def test_002_cleanup(self):
  47. self.testvm.start()
  48. p = self.testvm.run("qvm-run --dispvm bash", passio_popen=True)
  49. (stdout, _) = p.communicate(input=b"echo test; qubesdb-read /name; "
  50. b"echo ERROR\n")
  51. self.assertEquals(p.returncode, 0)
  52. lines = stdout.decode('ascii').splitlines()
  53. self.assertEqual(lines[0], "test")
  54. dispvm_name = lines[1]
  55. # wait for actual DispVM destruction
  56. time.sleep(1)
  57. self.reload_db()
  58. self.assertNotIn(dispvm_name, self.app.domains)
  59. @unittest.expectedFailure
  60. def test_003_cleanup_destroyed(self):
  61. """
  62. Check if DispVM is properly removed even if it terminated itself (#1660)
  63. :return:
  64. """
  65. self.testvm.start()
  66. p = self.testvm.run("qvm-run --dispvm bash; true", passio_popen=True)
  67. p.stdin.write(b"qubesdb-read /name\n")
  68. p.stdin.write(b"echo ERROR\n")
  69. p.stdin.write(b"sudo poweroff\n")
  70. # do not close p.stdin on purpose - wait to automatic disconnect when
  71. # domain is destroyed
  72. timeout = 30
  73. while timeout > 0:
  74. if p.poll():
  75. break
  76. time.sleep(1)
  77. timeout -= 1
  78. # includes check for None - timeout
  79. self.assertEquals(p.returncode, 0)
  80. lines = p.stdout.read().splitlines()
  81. self.assertTrue(lines, 'No output received from DispVM')
  82. dispvm_name = lines[0]
  83. self.assertNotEquals(dispvm_name, b"ERROR")
  84. self.reload_db()
  85. self.assertNotIn(dispvm_name, self.app.domains)
  86. class TC_20_DispVMMixin(qubes.tests.SystemTestsMixin):
  87. def setUp(self):
  88. super(TC_20_DispVMMixin, self).setUp()
  89. self.init_default_template(self.template)
  90. self.disp_base = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  91. name=self.make_vm_name('dvm'),
  92. label='red',
  93. )
  94. self.disp_base.create_on_disk()
  95. self.app.default_dispvm = self.disp_base
  96. self.app.save()
  97. def test_010_simple_dvm_run(self):
  98. dispvm = qubes.vm.dispvm.DispVM.from_appvm(self.disp_base)
  99. try:
  100. dispvm.start()
  101. p = dispvm.run_service('qubes.VMShell', passio_popen=True)
  102. (stdout, _) = p.communicate(input=b"echo test")
  103. self.assertEqual(stdout, b"test\n")
  104. finally:
  105. dispvm.cleanup()
  106. @unittest.skipUnless(spawn.find_executable('xdotool'),
  107. "xdotool not installed")
  108. def test_020_gui_app(self):
  109. dispvm = qubes.vm.dispvm.DispVM.from_appvm(self.disp_base)
  110. try:
  111. dispvm.start()
  112. p = dispvm.run_service('qubes.VMShell', passio_popen=True)
  113. # wait for DispVM startup:
  114. p.stdin.write(b"echo test\n")
  115. p.stdin.flush()
  116. l = p.stdout.readline()
  117. self.assertEqual(l, b"test\n")
  118. self.assertTrue(dispvm.is_running())
  119. try:
  120. window_title = 'user@%s' % (dispvm.name,)
  121. p.stdin.write("xterm -e "
  122. "\"sh -c 'echo \\\"\033]0;{}\007\\\";read x;'\"\n".
  123. format(window_title).encode())
  124. self.wait_for_window(window_title)
  125. time.sleep(0.5)
  126. self.enter_keys_in_window(window_title, ['Return'])
  127. # Wait for window to close
  128. self.wait_for_window(window_title, show=False)
  129. finally:
  130. p.stdin.close()
  131. finally:
  132. dispvm.cleanup()
  133. self.reload_db()
  134. self.assertNotIn(dispvm.name, self.app.domains,
  135. "DispVM not removed from qubes.xml")
  136. def _handle_editor(self, winid):
  137. (window_title, _) = subprocess.Popen(
  138. ['xdotool', 'getwindowname', winid], stdout=subprocess.PIPE).\
  139. communicate()
  140. window_title = window_title.decode().strip().\
  141. replace('(', '\(').replace(')', '\)')
  142. time.sleep(1)
  143. if "gedit" in window_title:
  144. subprocess.check_call(['xdotool', 'windowactivate', '--sync', winid,
  145. 'type', 'Test test 2'])
  146. subprocess.check_call(['xdotool', 'key', '--window', winid,
  147. 'key', 'Return'])
  148. time.sleep(0.5)
  149. subprocess.check_call(['xdotool',
  150. 'key', 'ctrl+s', 'ctrl+q'])
  151. elif "LibreOffice" in window_title:
  152. # wait for actual editor (we've got splash screen)
  153. search = subprocess.Popen(['xdotool', 'search', '--sync',
  154. '--onlyvisible', '--all', '--name', '--class', 'disp*|Writer'],
  155. stdout=subprocess.PIPE,
  156. stderr=open(os.path.devnull, 'w'))
  157. retcode = search.wait()
  158. if retcode == 0:
  159. winid = search.stdout.read().strip()
  160. time.sleep(0.5)
  161. subprocess.check_call(['xdotool', 'windowactivate', '--sync', winid,
  162. 'type', 'Test test 2'])
  163. subprocess.check_call(['xdotool', 'key', '--window', winid,
  164. 'key', 'Return'])
  165. time.sleep(0.5)
  166. subprocess.check_call(['xdotool',
  167. 'key', '--delay', '100', 'ctrl+s',
  168. 'Return', 'ctrl+q'])
  169. elif "emacs" in window_title:
  170. subprocess.check_call(['xdotool', 'windowactivate', '--sync', winid,
  171. 'type', 'Test test 2'])
  172. subprocess.check_call(['xdotool', 'key', '--window', winid,
  173. 'key', 'Return'])
  174. time.sleep(0.5)
  175. subprocess.check_call(['xdotool',
  176. 'key', 'ctrl+x', 'ctrl+s'])
  177. subprocess.check_call(['xdotool',
  178. 'key', 'ctrl+x', 'ctrl+c'])
  179. elif "vim" in window_title or "user@" in window_title:
  180. subprocess.check_call(['xdotool', 'windowactivate', '--sync', winid,
  181. 'key', 'i', 'type', 'Test test 2'])
  182. subprocess.check_call(['xdotool', 'key', '--window', winid,
  183. 'key', 'Return'])
  184. subprocess.check_call(
  185. ['xdotool',
  186. 'key', 'Escape', 'colon', 'w', 'q', 'Return'])
  187. else:
  188. self.fail("Unknown editor window: {}".format(window_title))
  189. @unittest.skipUnless(spawn.find_executable('xdotool'),
  190. "xdotool not installed")
  191. @unittest.expectedFailure
  192. def test_030_edit_file(self):
  193. testvm1 = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  194. name=self.make_vm_name('vm1'),
  195. label='red',
  196. template=self.app.domains[self.template])
  197. testvm1.create_on_disk()
  198. self.app.save()
  199. testvm1.start()
  200. testvm1.run("echo test1 > /home/user/test.txt", wait=True)
  201. p = testvm1.run("qvm-open-in-dvm /home/user/test.txt",
  202. passio_popen=True)
  203. wait_count = 0
  204. winid = None
  205. while True:
  206. search = subprocess.Popen(['xdotool', 'search',
  207. '--onlyvisible', '--class', 'disp*'],
  208. stdout=subprocess.PIPE,
  209. stderr=open(os.path.devnull, 'w'))
  210. retcode = search.wait()
  211. if retcode == 0:
  212. winid = search.stdout.read().strip()
  213. # get window title
  214. (window_title, _) = subprocess.Popen(
  215. ['xdotool', 'getwindowname', winid], stdout=subprocess.PIPE). \
  216. communicate()
  217. window_title = window_title.decode().strip()
  218. # ignore LibreOffice splash screen and window with no title
  219. # set yet
  220. if window_title and not window_title.startswith("LibreOffice")\
  221. and not window_title == 'VMapp command':
  222. break
  223. wait_count += 1
  224. if wait_count > 100:
  225. self.fail("Timeout while waiting for editor window")
  226. time.sleep(0.3)
  227. time.sleep(0.5)
  228. self._handle_editor(winid)
  229. p.wait()
  230. p = testvm1.run("cat /home/user/test.txt",
  231. passio_popen=True)
  232. (test_txt_content, _) = p.communicate()
  233. # Drop BOM if added by editor
  234. if test_txt_content.startswith(b'\xef\xbb\xbf'):
  235. test_txt_content = test_txt_content[3:]
  236. self.assertEqual(test_txt_content, b"Test test 2\ntest1\n")
  237. def load_tests(loader, tests, pattern):
  238. try:
  239. app = qubes.Qubes()
  240. templates = [vm.name for vm in app.domains if
  241. isinstance(vm, qubes.vm.templatevm.TemplateVM)]
  242. except OSError:
  243. templates = []
  244. for template in templates:
  245. tests.addTests(loader.loadTestsFromTestCase(
  246. type(
  247. 'TC_20_DispVM_' + template,
  248. (TC_20_DispVMMixin, qubes.tests.QubesTestCase),
  249. {'template': template})))
  250. return tests