dispvm.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # The Qubes OS Project, http://www.qubes-os.org
  5. #
  6. # Copyright (C) 2016 Marek Marczykowski-Górecki
  7. # <marmarek@invisiblethingslab.com>
  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 distutils import spawn
  25. import qubes.tests
  26. import subprocess
  27. import tempfile
  28. import unittest
  29. import os
  30. import time
  31. class TC_04_DispVM(qubes.tests.SystemTestsMixin,
  32. qubes.tests.QubesTestCase):
  33. def setUp(self):
  34. super(TC_04_DispVM, self).setUp()
  35. self.init_default_template()
  36. self.disp_base = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  37. name=self.make_vm_name('dvm'),
  38. label='red',
  39. )
  40. self.disp_base.create_on_disk()
  41. self.app.default_dispvm = self.disp_base
  42. self.testvm = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  43. name=self.make_vm_name('vm'),
  44. label='red',
  45. )
  46. self.testvm.create_on_disk()
  47. self.app.save()
  48. def test_002_cleanup(self):
  49. self.testvm.start()
  50. p = self.testvm.run("qvm-run --dispvm bash", passio_popen=True)
  51. (stdout, _) = p.communicate(input="echo test; qubesdb-read /name; "
  52. "echo ERROR\n")
  53. self.assertEquals(p.returncode, 0)
  54. lines = stdout.splitlines()
  55. self.assertEqual(lines[0], "test")
  56. dispvm_name = lines[1]
  57. # wait for actual DispVM destruction
  58. time.sleep(1)
  59. self.reload_db()
  60. self.assertNotIn(dispvm_name, self.app.domains)
  61. def test_003_cleanup_destroyed(self):
  62. """
  63. Check if DispVM is properly removed even if it terminated itself (#1660)
  64. :return:
  65. """
  66. self.testvm.start()
  67. p = self.testvm.run("qvm-run --dispvm bash; true", passio_popen=True)
  68. p.stdin.write("qubesdb-read /name\n")
  69. p.stdin.write("echo ERROR\n")
  70. p.stdin.write("sudo poweroff\n")
  71. # do not close p.stdin on purpose - wait to automatic disconnect when
  72. # domain is destroyed
  73. timeout = 30
  74. while timeout > 0:
  75. if p.poll():
  76. break
  77. time.sleep(1)
  78. timeout -= 1
  79. # includes check for None - timeout
  80. self.assertEquals(p.returncode, 0)
  81. lines = p.stdout.read().splitlines()
  82. self.assertTrue(lines, 'No output received from DispVM')
  83. dispvm_name = lines[0]
  84. self.assertNotEquals(dispvm_name, "ERROR")
  85. self.reload_db()
  86. self.assertNotIn(dispvm_name, self.app.domains)
  87. class TC_20_DispVMMixin(qubes.tests.SystemTestsMixin):
  88. def setUp(self):
  89. super(TC_20_DispVMMixin, self).setUp()
  90. self.init_default_template(self.template)
  91. self.disp_base = self.app.add_new_vm(qubes.vm.appvm.AppVM,
  92. name=self.make_vm_name('dvm'),
  93. label='red',
  94. )
  95. self.disp_base.create_on_disk()
  96. self.app.default_dispvm = self.disp_base
  97. self.app.save()
  98. def test_010_simple_dvm_run(self):
  99. dispvm = qubes.vm.dispvm.DispVM.from_appvm(self.disp_base)
  100. try:
  101. dispvm.start()
  102. p = dispvm.run_service('qubes.VMShell', passio_popen=True)
  103. (stdout, _) = p.communicate(input="echo test")
  104. self.assertEqual(stdout, "test\n")
  105. finally:
  106. dispvm.cleanup()
  107. @unittest.skipUnless(spawn.find_executable('xdotool'),
  108. "xdotool not installed")
  109. def test_020_gui_app(self):
  110. dispvm = qubes.vm.dispvm.DispVM.from_appvm(self.disp_base)
  111. try:
  112. dispvm.start()
  113. p = dispvm.run_service('qubes.VMShell', passio_popen=True)
  114. # wait for DispVM startup:
  115. p.stdin.write("echo test\n")
  116. p.stdin.flush()
  117. l = p.stdout.readline()
  118. self.assertEqual(l, "test\n")
  119. self.assertTrue(dispvm.is_running())
  120. try:
  121. window_title = 'user@%s' % (dispvm.name,)
  122. p.stdin.write("xterm -e "
  123. "\"sh -c 'echo \\\"\033]0;{}\007\\\";read x;'\"\n".
  124. format(window_title))
  125. self.wait_for_window(window_title)
  126. time.sleep(0.5)
  127. self.enter_keys_in_window(window_title, ['Return'])
  128. # Wait for window to close
  129. self.wait_for_window(window_title, show=False)
  130. finally:
  131. p.stdin.close()
  132. finally:
  133. dispvm.cleanup()
  134. self.reload_db()
  135. self.assertNotIn(dispvm.name, self.app.domains,
  136. "DispVM not removed from qubes.xml")
  137. def _handle_editor(self, winid):
  138. (window_title, _) = subprocess.Popen(
  139. ['xdotool', 'getwindowname', winid], stdout=subprocess.PIPE).\
  140. communicate()
  141. window_title = window_title.strip().\
  142. replace('(', '\(').replace(')', '\)')
  143. time.sleep(1)
  144. if "gedit" in window_title:
  145. subprocess.check_call(['xdotool', 'windowactivate', '--sync', winid,
  146. 'type', 'Test test 2'])
  147. subprocess.check_call(['xdotool', 'key', '--window', winid,
  148. 'key', 'Return'])
  149. time.sleep(0.5)
  150. subprocess.check_call(['xdotool',
  151. 'key', 'ctrl+s', 'ctrl+q'])
  152. elif "LibreOffice" in window_title:
  153. # wait for actual editor (we've got splash screen)
  154. search = subprocess.Popen(['xdotool', 'search', '--sync',
  155. '--onlyvisible', '--all', '--name', '--class', 'disp*|Writer'],
  156. stdout=subprocess.PIPE,
  157. stderr=open(os.path.devnull, 'w'))
  158. retcode = search.wait()
  159. if retcode == 0:
  160. winid = search.stdout.read().strip()
  161. time.sleep(0.5)
  162. subprocess.check_call(['xdotool', 'windowactivate', '--sync', winid,
  163. 'type', 'Test test 2'])
  164. subprocess.check_call(['xdotool', 'key', '--window', winid,
  165. 'key', 'Return'])
  166. time.sleep(0.5)
  167. subprocess.check_call(['xdotool',
  168. 'key', '--delay', '100', 'ctrl+s',
  169. 'Return', 'ctrl+q'])
  170. elif "emacs" in window_title:
  171. subprocess.check_call(['xdotool', 'windowactivate', '--sync', winid,
  172. 'type', 'Test test 2'])
  173. subprocess.check_call(['xdotool', 'key', '--window', winid,
  174. 'key', 'Return'])
  175. time.sleep(0.5)
  176. subprocess.check_call(['xdotool',
  177. 'key', 'ctrl+x', 'ctrl+s'])
  178. subprocess.check_call(['xdotool',
  179. 'key', 'ctrl+x', 'ctrl+c'])
  180. elif "vim" in window_title or "user@" in window_title:
  181. subprocess.check_call(['xdotool', 'windowactivate', '--sync', winid,
  182. 'key', 'i', 'type', 'Test test 2'])
  183. subprocess.check_call(['xdotool', 'key', '--window', winid,
  184. 'key', 'Return'])
  185. subprocess.check_call(
  186. ['xdotool',
  187. 'key', 'Escape', 'colon', 'w', 'q', 'Return'])
  188. else:
  189. self.fail("Unknown editor window: {}".format(window_title))
  190. @unittest.skipUnless(spawn.find_executable('xdotool'),
  191. "xdotool not installed")
  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.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('\xef\xbb\xbf'):
  235. test_txt_content = test_txt_content[3:]
  236. self.assertEqual(test_txt_content, "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