mime.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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 library is free software; you can redistribute it and/or
  10. # modify it under the terms of the GNU Lesser General Public
  11. # License as published by the Free Software Foundation; either
  12. # version 2.1 of the License, or (at your option) any later version.
  13. #
  14. # This library 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 GNU
  17. # Lesser General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU Lesser General Public
  20. # License along with this library; if not, see <https://www.gnu.org/licenses/>.
  21. #
  22. #
  23. import os
  24. from distutils import spawn
  25. import re
  26. import subprocess
  27. import time
  28. import unittest
  29. import itertools
  30. import asyncio
  31. import sys
  32. import qubes.tests
  33. import qubes
  34. @unittest.skipUnless(
  35. spawn.find_executable('xprop') and
  36. spawn.find_executable('xdotool') and
  37. spawn.find_executable('wmctrl'),
  38. "xprop or xdotool or wmctrl not installed")
  39. class TC_50_MimeHandlers:
  40. def setUp(self):
  41. super(TC_50_MimeHandlers, self).setUp()
  42. if self.template.startswith('whonix-gw') or 'minimal' in self.template:
  43. raise unittest.SkipTest(
  44. 'Template {} not supported by this test'.format(self.template))
  45. self.source_vmname = self.make_vm_name('source')
  46. self.source_vm = self.app.add_new_vm("AppVM",
  47. template=self.template,
  48. name=self.source_vmname,
  49. label='red')
  50. self.loop.run_until_complete(self.source_vm.create_on_disk())
  51. self.target_vmname = self.make_vm_name('target')
  52. self.target_vm = self.app.add_new_vm("AppVM",
  53. template=self.template,
  54. name=self.target_vmname,
  55. label='red')
  56. self.loop.run_until_complete(self.target_vm.create_on_disk())
  57. self.target_vm.template_for_dispvms = True
  58. self.source_vm.default_dispvm = self.target_vm
  59. done, not_done = self.loop.run_until_complete(asyncio.wait([
  60. self.source_vm.start(),
  61. self.target_vm.start()]))
  62. for result in itertools.chain(done, not_done):
  63. # catch any exceptions
  64. result.result()
  65. def get_window_class(self, winid, dispvm=False):
  66. (vm_winid, _) = subprocess.Popen(
  67. ['xprop', '-id', winid, '_QUBES_VMWINDOWID'],
  68. stdout=subprocess.PIPE
  69. ).communicate()
  70. vm_winid = vm_winid.decode().split("#")[1].strip('\n" ')
  71. if dispvm:
  72. (vmname, _) = subprocess.Popen(
  73. ['xprop', '-id', winid, '_QUBES_VMNAME'],
  74. stdout=subprocess.PIPE
  75. ).communicate()
  76. vmname = vmname.decode().split("=")[1].strip('\n" ')
  77. vm = self.app.domains[vmname]
  78. else:
  79. vm = self.target_vm
  80. window_class = None
  81. while window_class is None:
  82. try:
  83. window_class, _ = self.loop.run_until_complete(
  84. vm.run_for_stdio('xprop -id {} WM_CLASS'.format(vm_winid)))
  85. except subprocess.CalledProcessError as e:
  86. if e.returncode == 127:
  87. self.skipTest('xprop not installed')
  88. self.fail(
  89. "xprop -id {} WM_CLASS failed: {}".format(
  90. vm_winid, e.stderr.decode()))
  91. if b'not found' in window_class:
  92. # WM_CLASS not set yet, wait a little
  93. time.sleep(0.1)
  94. window_class = None
  95. # output: WM_CLASS(STRING) = "gnome-terminal-server", "Gnome-terminal"
  96. try:
  97. window_class = window_class.decode()
  98. window_class = window_class.split("=")[1].split(",")[0].strip('\n" ')
  99. except IndexError:
  100. raise Exception(
  101. "Unexpected output from xprop: '{}'".format(window_class))
  102. return window_class
  103. def open_file_and_check_viewer(self, filename, expected_app_titles,
  104. expected_app_classes, dispvm=False):
  105. if dispvm:
  106. p = self.loop.run_until_complete(self.source_vm.run(
  107. "qvm-open-in-dvm {}".format(filename), stdout=subprocess.PIPE))
  108. vmpattern = "disp[0-9]*"
  109. else:
  110. p = self.loop.run_until_complete(self.source_vm.run(
  111. "qvm-open-in-vm {} {}".format(self.target_vmname, filename),
  112. stdout=subprocess.PIPE))
  113. vmpattern = self.target_vmname
  114. wait_count = 0
  115. winid = None
  116. with self.qrexec_policy('qubes.OpenInVM', self.source_vm.name,
  117. self.target_vmname):
  118. with self.qrexec_policy('qubes.OpenURL', self.source_vm.name,
  119. self.target_vmname):
  120. while True:
  121. search = subprocess.Popen(['xdotool', 'search',
  122. '--onlyvisible', '--class', vmpattern],
  123. stdout=subprocess.PIPE,
  124. stderr=subprocess.DEVNULL)
  125. retcode = search.wait()
  126. if retcode == 0:
  127. winid = search.stdout.read().strip()
  128. # get window title
  129. (window_title, _) = subprocess.Popen(
  130. ['xdotool', 'getwindowname', winid], stdout=subprocess.PIPE). \
  131. communicate()
  132. window_title = window_title.decode('utf8').strip()
  133. # ignore LibreOffice splash screen and window with no title
  134. # set yet
  135. if window_title and \
  136. not window_title.startswith("LibreOffice") and\
  137. not window_title.startswith("NetworkManager") and\
  138. not window_title == 'VMapp command':
  139. break
  140. wait_count += 1
  141. if wait_count > 100:
  142. self.fail("Timeout while waiting for editor window")
  143. self.loop.run_until_complete(asyncio.sleep(0.3))
  144. # get window class
  145. window_class = self.get_window_class(winid, dispvm)
  146. # close the window - we've got the window class, it is no longer needed
  147. subprocess.check_call(['wmctrl', '-i', '-c', winid])
  148. p.wait()
  149. self.wait_for_window(window_title, show=False)
  150. def check_matches(obj, patterns):
  151. return any((pat.search(obj) if isinstance(pat, type(re.compile('')))
  152. else pat in obj) for pat in patterns)
  153. if not check_matches(window_title, expected_app_titles) and \
  154. not check_matches(window_class, expected_app_classes):
  155. self.fail("Opening file {} resulted in window '{} ({})', which is "
  156. "none of {!r} ({!r})".format(
  157. filename, window_title, window_class,
  158. expected_app_titles, expected_app_classes))
  159. def prepare_txt(self, filename):
  160. self.loop.run_until_complete(
  161. self.source_vm.run_for_stdio("cat > {}".format(filename),
  162. input=b'This is test\n'))
  163. def prepare_pdf(self, filename):
  164. self.prepare_txt("/tmp/source.txt")
  165. cmd = "convert text:/tmp/source.txt {}".format(filename)
  166. try:
  167. self.loop.run_until_complete(
  168. self.source_vm.run_for_stdio(cmd))
  169. except subprocess.CalledProcessError as e:
  170. self.fail('{} failed: {}'.format(cmd, e.stderr.decode()))
  171. def prepare_doc(self, filename):
  172. self.prepare_txt("/tmp/source.txt")
  173. cmd = "unoconv -f doc -o {} /tmp/source.txt".format(filename)
  174. try:
  175. self.loop.run_until_complete(
  176. self.source_vm.run_for_stdio(cmd))
  177. except subprocess.CalledProcessError as e:
  178. if e.returncode == 127:
  179. self.skipTest("unoconv not installed".format(cmd))
  180. self.skipTest("Failed to run '{}': {}".format(cmd,
  181. e.stderr.decode()))
  182. def prepare_pptx(self, filename):
  183. self.prepare_txt("/tmp/source.txt")
  184. cmd = "unoconv -f pptx -o {} /tmp/source.txt".format(filename)
  185. try:
  186. self.loop.run_until_complete(
  187. self.source_vm.run_for_stdio(cmd))
  188. except subprocess.CalledProcessError as e:
  189. if e.returncode == 127:
  190. self.skipTest("unoconv not installed".format(cmd))
  191. self.skipTest("Failed to run '{}': {}".format(cmd,
  192. e.stderr.decode()))
  193. def prepare_png(self, filename):
  194. self.prepare_txt("/tmp/source.txt")
  195. cmd = "convert text:/tmp/source.txt {}".format(filename)
  196. try:
  197. self.loop.run_until_complete(
  198. self.source_vm.run_for_stdio(cmd))
  199. except subprocess.CalledProcessError as e:
  200. if e.returncode == 127:
  201. self.skipTest("convert not installed".format(cmd))
  202. self.skipTest("Failed to run '{}': {}".format(cmd,
  203. e.stderr.decode()))
  204. def prepare_jpg(self, filename):
  205. self.prepare_txt("/tmp/source.txt")
  206. cmd = "convert text:/tmp/source.txt {}".format(filename)
  207. try:
  208. self.loop.run_until_complete(
  209. self.source_vm.run_for_stdio(cmd))
  210. except subprocess.CalledProcessError as e:
  211. if e.returncode == 127:
  212. self.skipTest("convert not installed".format(cmd))
  213. self.skipTest("Failed to run '{}': {}".format(cmd,
  214. e.stderr.decode()))
  215. def test_000_txt(self):
  216. filename = "/home/user/test_file.txt"
  217. self.prepare_txt(filename)
  218. self.open_file_and_check_viewer(filename, ["vim", "user@"],
  219. ["gedit", "emacs", "libreoffice"])
  220. def test_001_pdf(self):
  221. filename = "/home/user/test_file.pdf"
  222. self.prepare_pdf(filename)
  223. self.open_file_and_check_viewer(filename, [],
  224. ["evince"])
  225. def test_002_doc(self):
  226. filename = "/home/user/test_file.doc"
  227. self.prepare_doc(filename)
  228. self.open_file_and_check_viewer(filename, [],
  229. ["libreoffice", "abiword"])
  230. def test_003_pptx(self):
  231. filename = "/home/user/test_file.pptx"
  232. self.prepare_pptx(filename)
  233. self.open_file_and_check_viewer(filename, [],
  234. ["libreoffice"])
  235. def test_004_png(self):
  236. filename = "/home/user/test_file.png"
  237. self.prepare_png(filename)
  238. self.open_file_and_check_viewer(filename, [],
  239. ["shotwell", "eog", "display"])
  240. def test_005_jpg(self):
  241. filename = "/home/user/test_file.jpg"
  242. self.prepare_jpg(filename)
  243. self.open_file_and_check_viewer(filename, [],
  244. ["shotwell", "eog", "display"])
  245. def test_006_jpeg(self):
  246. filename = "/home/user/test_file.jpeg"
  247. self.prepare_jpg(filename)
  248. self.open_file_and_check_viewer(filename, [],
  249. ["shotwell", "eog", "display"])
  250. def test_010_url(self):
  251. self.open_file_and_check_viewer("https://www.qubes-os.org/", [],
  252. ["Firefox", "Iceweasel", "Navigator"])
  253. def test_100_txt_dispvm(self):
  254. filename = "/home/user/test_file.txt"
  255. self.prepare_txt(filename)
  256. self.open_file_and_check_viewer(filename, ["vim", "user@"],
  257. ["gedit", "emacs", "libreoffice"],
  258. dispvm=True)
  259. def test_101_pdf_dispvm(self):
  260. filename = "/home/user/test_file.pdf"
  261. self.prepare_pdf(filename)
  262. self.open_file_and_check_viewer(filename, [],
  263. ["evince"],
  264. dispvm=True)
  265. def test_102_doc_dispvm(self):
  266. filename = "/home/user/test_file.doc"
  267. self.prepare_doc(filename)
  268. self.open_file_and_check_viewer(filename, [],
  269. ["libreoffice", "abiword"],
  270. dispvm=True)
  271. def test_103_pptx_dispvm(self):
  272. filename = "/home/user/test_file.pptx"
  273. self.prepare_pptx(filename)
  274. self.open_file_and_check_viewer(filename, [],
  275. ["libreoffice"],
  276. dispvm=True)
  277. def test_104_png_dispvm(self):
  278. filename = "/home/user/test_file.png"
  279. self.prepare_png(filename)
  280. self.open_file_and_check_viewer(filename, [],
  281. ["shotwell", "eog", "display"],
  282. dispvm=True)
  283. def test_105_jpg_dispvm(self):
  284. filename = "/home/user/test_file.jpg"
  285. self.prepare_jpg(filename)
  286. self.open_file_and_check_viewer(filename, [],
  287. ["shotwell", "eog", "display"],
  288. dispvm=True)
  289. def test_106_jpeg_dispvm(self):
  290. filename = "/home/user/test_file.jpeg"
  291. self.prepare_jpg(filename)
  292. self.open_file_and_check_viewer(filename, [],
  293. ["shotwell", "eog", "display"],
  294. dispvm=True)
  295. def test_110_url_dispvm(self):
  296. self.open_file_and_check_viewer("https://www.qubes-os.org/", [],
  297. ["Firefox", "Iceweasel", "Navigator"],
  298. dispvm=True)
  299. def create_testcases_for_templates():
  300. return qubes.tests.create_testcases_for_templates('TC_50_MimeHandlers',
  301. TC_50_MimeHandlers, qubes.tests.SystemTestCase,
  302. module=sys.modules[__name__])
  303. def load_tests(loader, tests, pattern):
  304. tests.addTests(loader.loadTestsFromNames(
  305. create_testcases_for_templates()))
  306. return tests
  307. qubes.tests.maybe_create_testcases_on_import(create_testcases_for_templates)