Beispiel #1
0
 def __exit__(self, *_args):
     if self.xvfb_process:
         self.xvfb_process.terminate()
         self.xvfb_process = None
         self.stu.tearDown()
         ProcessTestUtil.tearDownClass()
     OSEnvContext.__exit__(self)
Beispiel #2
0
 def __enter__(self):
     OSEnvContext.__enter__(self)
     if POSIX and not OSX:
         ProcessTestUtil.setUpClass()
         self.stu = ProcessTestUtil()
         self.stu.setUp()
         self.xvfb_process = self.stu.start_Xvfb()
         os.environ["GDK_BACKEND"] = "x11"
         os.environ["DISPLAY"] = self.xvfb_process.display
         from xpra.x11.gtk_x11.gdk_display_source import init_gdk_display_source
         init_gdk_display_source()
Beispiel #3
0
 def test_env_handler(self):
     from xpra.client.auth.env_handler import Handler
     with OSEnvContext():
         os.environ["XPRA_PASSWORD"] = "******"
         self._test_handler(True, "password1", Handler)
     with OSEnvContext():
         os.environ["XPRA_PASSWORD2"] = "password2"
         self._test_handler(True,
                            "password2",
                            Handler,
                            name="XPRA_PASSWORD2")
     with OSEnvContext():
         name = "XPRA_TEST_VARIABLE_DOES_NOT_EXIST"
         os.environ.pop(name, None)
         self._test_handler(False, None, Handler, name=name)
Beispiel #4
0
 def test_env_context(self):
     import os
     env = os.environ.copy()
     with OSEnvContext():
         os.environ["foo"] = "bar"
     assert os.environ.get("foo") != "bar"
     assert os.environ == env
Beispiel #5
0
    def test_notification(self):
        with OSEnvContext():
            #remove any existing dbus environment so we don't pollute it:
            for k in tuple(os.environ.keys()):
                if k.startswith("DBUS"):
                    del os.environ[k]
            #start a dbus server:
            from xpra.server.dbus.dbus_start import start_dbus
            dbus_pid, dbus_env = start_dbus(
                "dbus-launch --sh-syntax --close-stderr")
            try:
                if dbus_env:
                    os.environ.update(dbus_env)

                from xpra.server.mixins.notification_forwarder import NotificationForwarder, log
                opts = AdHocStruct()
                opts.notifications = "yes"
                with silence_info(log):
                    self._test_mixin_class(NotificationForwarder, opts)
                self.verify_packet_error(
                    ("notification-close", 1, "test", "hello"))
                self.verify_packet_error(("notification-action", 1))
                self.handle_packet(("set-notify", False))
                self.mixin.cleanup()
                time.sleep(0.1)
            finally:
                if dbus_pid:
                    import signal
                    os.kill(dbus_pid, signal.SIGINT)
Beispiel #6
0
 def init(self, opts):
     self.webcam_option = opts.webcam
     self.webcam_forwarding = self.webcam_option.lower(
     ) not in FALSE_OPTIONS
     self.server_webcam = False
     self.server_virtual_video_devices = 0
     if self.webcam_forwarding:
         with OSEnvContext():
             os.environ["LANG"] = "C"
             os.environ["LC_ALL"] = "C"
             try:
                 import cv2
                 from PIL import Image
                 assert cv2 and Image
             except ImportError as e:
                 log("init webcam failure", exc_info=True)
                 if WIN32 and BITS == 32:
                     log.info(
                         "32-bit builds do not support webcam forwarding")
                 else:
                     log.warn("Warning: failed to import opencv:")
                     log.warn(" %s", e)
                     log.warn(" webcam forwarding is disabled")
                 self.webcam_forwarding = False
     log("webcam forwarding: %s", self.webcam_forwarding)
Beispiel #7
0
 def test_env_log(self):
     with OSEnvContext():
         os.environ["XPRA_LOG_PACKETS"] = "info,ping,-bell"
         for log_packet_type in (False, True):
             os.environ["XPRA_LOG_PACKET_TYPE"] = str(int(log_packet_type))
             common.init()
             inc = int(log_packet_type)
             logged = 1+inc
             for sending in (True, False):
                 self.setup_log_intercept()
                 def t(packet_type, *args):
                     return self.t(sending, packet_type, *args)  #pylint: disable=cell-var-from-loop
                 self.lm()
                 t("hello", {})
                 self.lm(inc)
                 t("info", {"foo" : "bar"})
                 self.lm(logged)
                 t("ping", 1, 2, 3)
                 self.lm(logged)
                 t("ping-echo", 1, 2, 3)
                 self.lm(inc)
                 t("bell", 100)
                 self.lm(inc)
                 t("info", "0"*common.PACKET_LOG_MAX_SIZE*2)
                 assert len(self.log_messages[-1])<=common.PACKET_LOG_MAX_SIZE
                 self.lm(logged)
Beispiel #8
0
    def test_start_dbus(self):
        from xpra.server.dbus.dbus_start import start_dbus

        def f(v):
            r, d = start_dbus(v)
            assert r == 0 and not d, "dbus should not have started for '%s'" % v

        def w(v):
            r, d = start_dbus(v)
            assert r > 0 and d, "dbus should have started for '%s'" % v

        def rm():
            os.environ.pop("DBUS_SESSION_BUS_ADDRESS", None)

        with OSEnvContext():
            rm()
            f("no")
            f("0")
            os.environ["DBUS_SESSION_BUS_ADDRESS"] = "whatever"
            w("dbus-launch")
            rm()
            f("this-is-not-a-valid-command")
            f("shlex-parsing-error '")
            f("echo set DBUS_SESSION_BUS_PID")
            w("echo set DBUS_SESSION_BUS_PID=50")
            w("echo \"set DBUS_SESSION_BUS_PID='100';\"")
            w("echo set DBUS_SESSION_BUS_PID=150;")
            w("echo setenv DBUS_SESSION_BUS_PID 200")
            w("printf \"export DBUS_SESSION_BUS_PID\nset DBUS_SESSION_BUS_PID=250\n\""
              )
Beispiel #9
0
 def start_Xvfb(cls, display=None, screens=[(1024, 768)]):
     assert os.name == "posix"
     if display is None:
         display = cls.find_free_display()
     with OSEnvContext():
         os.environ["DISPLAY"] = display
         XAUTHORITY = os.environ.get("XAUTHORITY",
                                     os.path.expanduser("~/.Xauthority"))
         if len(screens) > 1:
             cmd = [
                 "Xvfb", "+extension", "Composite", "-nolisten", "tcp",
                 "-noreset", "-auth", XAUTHORITY
             ]
             for i, screen in enumerate(screens):
                 (w, h) = screen
                 cmd += ["-screen", "%i" % i, "%ix%ix24+32" % (w, h)]
         else:
             xvfb_cmd = cls.default_config.get("xvfb")
             assert xvfb_cmd, "no 'xvfb' command in default config"
             import shlex
             cmd = shlex.split(osexpand(xvfb_cmd))
             if "/etc/xpra/xorg.conf" in cmd:
                 cmd[cmd.index(
                     "/etc/xpra/xorg.conf")] = "./etc/xpra/xorg.conf"
         cmd.append(display)
         xvfb = cls.run_command(cmd)
         assert pollwait(
             xvfb, XVFB_TIMEOUT
         ) is None, "xvfb command %s failed and returned %s" % (cmd,
                                                                xvfb.poll())
         return xvfb
Beispiel #10
0
    def test_xsettings(self):
        from xpra.x11.xsettings_prop import (
            get_settings, set_settings,
            get_local_byteorder,
            XSettingsTypeInteger, XSettingsTypeString, XSettingsTypeColor,
            )
        disp = AdHocStruct()
        for DEBUG_XSETTINGS in (True, False):
            with OSEnvContext():
                os.environ["XPRA_XSETTINGS_DEBUG"] = str(int(DEBUG_XSETTINGS))
                serial = 1
                data = b""
                l = len(data)
                v = struct.pack(b"=BBBBII", get_local_byteorder(), 0, 0, 0, serial, l)+data+b"\0"
                v1 = get_settings(disp, v)
                assert v
                #get from cache:
                v2 = get_settings(disp, v)
                assert v1==v2

                #test all types, set then get:
                #setting_type, prop_name, value, last_change_serial = setting
                settings = (
                    (XSettingsTypeInteger, "int1", 1, 0),
                    (XSettingsTypeString, "str1", "1", 0),
                    (XSettingsTypeColor, "color1", (128, 128, 64, 32), 0),
                    )
                serial = 2
                data = set_settings(disp, (serial, settings))
                assert data
                #parse it back:
                v = get_settings(disp, data)
                rserial, rsettings = v
                assert rserial==serial
                assert len(rsettings)==len(settings)
        #test error handling:
        for settings in (
            (
                #invalid color causes exception
                (XSettingsTypeColor, "bad-color", (128, ), 0),
            ),
            (
                #invalid setting type is skipped with an error message:
                (255, "invalid-setting-type", 0, 0),
            ),
            ):
            serial = 3
            data = set_settings(disp, (serial, settings))
            assert data
            v = get_settings(disp, data)
            rserial, rsettings = v
            assert rserial==serial
            assert len(rsettings)==0
        #parsing an invalid data type (9) should fail:
        hexdata = b"000000000200000001000000090004007374723100000000010000003100000000"
        data = binascii.unhexlify(hexdata)
        v = get_settings(disp, data)
        rserial, rsettings = v
        assert len(rsettings)==0
Beispiel #11
0
 def test_default_nolog(self):
     with OSEnvContext():
         os.environ.pop("XPRA_LOG_PACKETS", None)
         self.setup_log_intercept()
         for pt in common.PACKET_TYPES:
             self.t(True, pt, (1, 2))
             self.t(False, pt, (1, 2))
             self.lm(0)
Beispiel #12
0
def do_load_xdg_menu_data():
    try:
        from xdg.Menu import parse, Menu, ParsingError
    except ImportError:
        log("do_load_xdg_menu_data()", exc_info=True)
        if first_time("no-python-xdg"):
            log.warn("Warning: cannot use application menu data:")
            log.warn(" no python-xdg module")
        return None
    menu = None
    error = None
    with OSEnvContext():
        #see ticket #2340,
        #invalid values for XDG_CONFIG_DIRS can cause problems,
        #so try unsetting it if we can't load the menus with it:
        for cd in (False, True):
            if cd:
                try:
                    del os.environ["XDG_CONFIG_DIRS"]
                except KeyError:
                    continue
            #see ticket #2174,
            #things may break if the prefix is not set,
            #and it isn't set when logging in via ssh
            for prefix in (None, "", "gnome-", "kde-"):
                if prefix is not None:
                    os.environ["XDG_MENU_PREFIX"] = prefix
                try:
                    menu = parse()
                    break
                except Exception as e:
                    log("do_load_xdg_menu_data()", exc_info=True)
                    error = e
                    menu = None
    if menu is None:
        if error:
            log.error("Error parsing xdg menu data:")
            log.error(" %s", error)
            log.error(" this is either a bug in python-xdg,")
            log.error(" or an invalid system menu configuration")
        return None
    menu_data = {}
    for submenu in menu.getEntries():
        if isinstance(submenu, Menu) and submenu.Visible:
            name = submenu.getName()
            try:
                menu_data[name] = load_xdg_menu(submenu)
            except Exception as e:
                log("load_xdg_menu_data()", exc_info=True)
                log.error("Error loading submenu '%s':", name)
                log.error(" %s", e)
    return menu_data
Beispiel #13
0
 def start_Xvfb(cls, display=None, screens=[(1024, 768)]):
     assert POSIX
     if display is None:
         display = cls.find_free_display()
     with OSEnvContext():
         XAUTHORITY = os.environ.get("XAUTHORITY",
                                     os.path.expanduser("~/.Xauthority"))
         for x in list(os.environ.keys()):
             if x in ("LOGNAME", "USER", "PATH", "LANG", "TERM", "HOME",
                      "USERNAME", "PYTHONPATH",
                      "HOSTNAME"):  #DBUS_SESSION_BUS_ADDRESS
                 #keep it
                 continue
             try:
                 del os.environ[x]
             except:
                 pass
         if len(screens) > 1:
             cmd = [
                 "Xvfb", "+extension", "Composite", "-nolisten", "tcp",
                 "-noreset", "-auth", XAUTHORITY
             ]
             for i, screen in enumerate(screens):
                 (w, h) = screen
                 cmd += ["-screen", "%i" % i, "%ix%ix24+32" % (w, h)]
         else:
             xvfb_cmd = cls.default_config.get("xvfb")
             assert xvfb_cmd, "no 'xvfb' command in default config"
             import shlex
             cmd = shlex.split(osexpand(xvfb_cmd))
             try:
                 i = cmd.index("/etc/xpra/xorg.conf")
             except ValueError:
                 i = -1
             if i > 0 and os.path.exists("./etc/xpra/xorg.conf"):
                 cmd[i] = "./etc/xpra/xorg.conf"
         cmd.append(display)
         os.environ["DISPLAY"] = display
         os.environ["XPRA_LOG_DIR"] = "/tmp"
         cmd_expanded = [osexpand(v) for v in cmd]
         cmdstr = " ".join("'%s'" % x for x in cmd_expanded)
         xvfb = cls.run_command(cmd_expanded,
                                stdout=sys.stdout,
                                stderr=sys.stderr)
         time.sleep(1)
         print("xvfb(%s)=%s" % (cmdstr, xvfb))
         assert pollwait(
             xvfb, XVFB_TIMEOUT
         ) is None, "xvfb command \"%s\" failed and returned %s" % (
             cmdstr, xvfb.poll())
         return xvfb
Beispiel #14
0
 def test_systemd_run(self):
     for s in ("yes", "no", "auto"):
         if not use_systemd_run(s):
             continue
         for user in (True, False):
             for systemd_run_args in ("", "-d"):
                 assert systemd_run_command("mode",
                                            systemd_run_args,
                                            user=user)[0] == "systemd-run"
         with OSEnvContext():
             os.environ["XPRA_LOG_SYSTEMD_WRAP"] = "0"
             assert systemd_run_wrap("unused", ["xpra", "--version"],
                                     stdout=DEVNULL,
                                     stderr=DEVNULL) == 0
Beispiel #15
0
 def test_ival(self):
     with OSEnvContext():
         with silence_warn(log):
             for k in ("XYZ", "WHATEVER"):
                 os.environ.pop("XPRA_BATCH_%s" % k, None)
                 assert ival(k, 20, 0, 100) == 20
                 os.environ["XPRA_BATCH_%s" % k] = "notanumber"
                 assert ival(k, 30, 0, 100) == 30
                 os.environ["XPRA_BATCH_%s" % k] = "50"
                 assert ival(k, 0, 0, 100) == 50
                 os.environ["XPRA_BATCH_%s" % k] = "120"
                 assert ival(k, 0, 0, 100) == 100
                 os.environ["XPRA_BATCH_%s" % k] = "10"
                 assert ival(k, 0, 20, 100) == 20
Beispiel #16
0
    def test_display(self):
        from xpra.x11.gtk3.gdk_display_util import verify_gdk_display
        with OSEnvContext():
            os.environ["GDK_BACKEND"] = "x11"
            os.environ.pop("DISPLAY", None)
            for d in (None, ""):
                try:
                    verify_gdk_display(d)
                except Exception:
                    pass
                else:
                    raise Exception("%s is not a valid display" % d)

            display = self.find_free_display()
            xvfb = self.start_Xvfb(display)
            os.environ["DISPLAY"] = display
            from xpra.x11.bindings.posix_display_source import X11DisplayContext  #@UnresolvedImport
            with X11DisplayContext(display):
                verify_gdk_display(display)
            xvfb.terminate()
Beispiel #17
0
 def init(self, opts):
     self.webcam_option = opts.webcam
     self.webcam_forwarding = self.webcam_option.lower() not in FALSE_OPTIONS
     self.server_webcam = False
     self.server_virtual_video_devices = 0
     if self.webcam_forwarding:
         with OSEnvContext():
             os.environ["LANG"] = "C"
             os.environ["LC_ALL"] = "C"
             try:
                 import cv2
                 from PIL import Image
                 assert cv2 and Image
             except ImportError as e:
                 log("init webcam failure", exc_info=True)
                 if WIN32:
                     log.info("opencv not found:")
                     log.info(" %s", e)
                     log.info(" webcam forwarding is not available")
                 self.webcam_forwarding = False
     log("webcam forwarding: %s", self.webcam_forwarding)
Beispiel #18
0
def load_xdg_menu_data():
    try:
        from xdg.Menu import parse, Menu  #pylint: disable=import-outside-toplevel
    except ImportError:
        log("load_xdg_menu_data()", exc_info=True)
        if first_time("no-python-xdg"):
            log.warn("Warning: cannot use application menu data:")
            log.warn(" no python-xdg module")
        return None
    menu = None
    error = None
    #see ticket #2340,
    #invalid values for XDG_CONFIG_DIRS can cause problems,
    #so try unsetting it if we can't load the menus with it:
    for cd in (False, True):
        with OSEnvContext():
            if cd:
                if not os.environ.pop("XDG_CONFIG_DIRS", ""):
                    #was already unset
                    continue
            #see ticket #2174,
            #things may break if the prefix is not set,
            #and it isn't set when logging in via ssh
            for prefix in (None, "", "gnome-", "kde-"):
                if prefix is not None:
                    os.environ["XDG_MENU_PREFIX"] = prefix
                try:
                    log(
                        "parsing xdg menu data for prefix %r with XDG_CONFIG_DIRS=%s and XDG_MENU_PREFIX=%s",
                        prefix, os.environ.get("XDG_CONFIG_DIRS"),
                        os.environ.get("XDG_MENU_PREFIX"))
                    menu = parse()
                    break
                except Exception as e:
                    log("load_xdg_menu_data()", exc_info=True)
                    error = e
                    menu = None
        if menu:
            break
    if menu is None:
        if error:
            log.error("Error parsing xdg menu data:")
            log.error(" %s", error)
            log.error(" this is either a bug in python-xdg,")
            log.error(" or an invalid system menu configuration")
        return None
    menu_data = {}
    entries = tuple(menu.getEntries())
    log("%s.getEntries()=%s", menu, entries)
    if len(entries) == 1 and entries[0].Submenus:
        entries = entries[0].Submenus
        log("using submenus %s", entries)
    for i, submenu in enumerate(entries):
        if not isinstance(submenu, Menu):
            log("entry '%s' is not a submenu", submenu)
            continue
        name = submenu.getName()
        log("* %-3i %s", i, name)
        if not submenu.Visible:
            log(" submenu '%s' is not visible", name)
            continue
        try:
            md = load_xdg_menu(submenu)
            if md:
                menu_data[name] = md
            else:
                log(" no menu data for %s", name)
        except Exception as e:
            log("load_xdg_menu_data()", exc_info=True)
            log.error("Error loading submenu '%s':", name)
            log.error(" %s", e)
    if LOAD_APPLICATIONS:
        from xdg.Menu import MenuEntry
        entries = {}
        for d in LOAD_APPLICATIONS:
            for f in os.listdir(d):
                if not f.endswith(".desktop"):
                    continue
                try:
                    me = MenuEntry(f, d)
                except Exception:
                    log("failed to load %s from %s", f, d, exc_info=True)
                else:
                    ed = load_xdg_entry(me.DesktopEntry)
                    if not ed:
                        continue
                    name = ed.get("Name")
                    #ensure we don't already have it in another submenu:
                    for menu_category in menu_data.values():
                        if name in menu_category.get("Entries", {}):
                            ed = None
                            break
                    if ed:
                        entries[name] = ed
        log("entries(%s)=%s", LOAD_APPLICATIONS, remove_icons(entries))
        if entries:
            #add an 'Applications' menu if we don't have one:
            md = menu_data.get("Applications")
            if not md:
                md = {
                    "Name": "Applications",
                }
                menu_data["Applications"] = md
            md.setdefault("Entries", {}).update(entries)
    return menu_data
Beispiel #19
0
    def test_networkstate(self):
        with OSEnvContext():
            os.environ["XPRA_PING_TIMEOUT"] = "1"
            from xpra.server.mixins.networkstate_server import NetworkStateServer, MAX_BANDWIDTH_LIMIT, log, bandwidthlog
            from xpra.server.source.networkstate_mixin import NetworkStateMixin
            assert NetworkStateMixin.is_needed(typedict())
            opts = AdHocStruct()
            opts.pings = 1
            opts.bandwidth_limit = "1Gbps"
            #the limit for all clients:
            capped_at = 1 * 1000 * 1000 * 1000  #=="1Gbps"
            with silence_info(log):
                self._test_mixin_class(NetworkStateServer, opts, {},
                                       NetworkStateMixin)
            self.assertEqual(capped_at,
                             self.mixin.get_info().get("bandwidth-limit"))
            self.handle_packet(("ping", 10))
            self.handle_packet(("ping", -1000))
            self.handle_packet(("ping_echo", 10, 500, 500, 600, 10))
            for v in (None, "foo", 1, 2.0, [], (), set()):
                try:
                    self.handle_packet(("connection-data", v))
                except TypeError:
                    pass
                else:
                    raise Exception(
                        "should not allow %s (%s) as connection-data" %
                        (v, type(v)))
            self.handle_packet(("connection-data", {}))
            for v in (None, "foo", 2.0, [], (), set()):
                try:
                    self.handle_packet(("bandwidth-limit", v))
                except TypeError:
                    pass
                else:
                    raise Exception(
                        "should not allow %s (%s) as connection-data" %
                        (v, type(v)))
            with silence_info(bandwidthlog):
                self.handle_packet(("bandwidth-limit", 10 * 1024 * 1024))

            def get_limit():
                return self.source.get_info().get("bandwidth-limit",
                                                  {}).get("setting", 0)

            self.assertEqual(10 * 1024 * 1024, get_limit())
            with silence_info(bandwidthlog):
                self.handle_packet(
                    ("bandwidth-limit", MAX_BANDWIDTH_LIMIT + 1))
            self.assertEqual(min(capped_at, MAX_BANDWIDTH_LIMIT), get_limit())
            #test source:
            timeouts = []

            def timeout(*args):
                timeouts.append(args)

            self.source.disconnect = timeout
            assert self.source.get_caps()
            self.source.ping()
            self.source.check_ping_echo_timeout(0, 0)
            #give time for the timeout to fire:
            self.glib.timeout_add(2000, self.main_loop.quit)
            self.main_loop.run()
Beispiel #20
0
 def test_save_dbus_env(self):
     from xpra.server.dbus import dbus_start
     dbus_start.log = FakeLogger()
     with OSEnvContext():
         #assert get_saved_dbus_env()
         pass
Beispiel #21
0
 def test_misc_env_switches(self):
     with OSEnvContext():
         os.environ["XPRA_NOMD5"] = "1"
         self._test_subcommand("version-info")
Beispiel #22
0
 def test_nox(self):
     with OSEnvContext():
         os.environ["DISPLAY"] = "not-a-display"
         nox()
         assert os.environ.get("DISPLAY") is None
Beispiel #23
0
 def __init__(self):
     OSEnvContext.__init__(self)
     self.xvfb_process = None
Beispiel #24
0
 def test_childreaper(self):
     for polling in (True, False):
         with OSEnvContext():
             os.environ["XPRA_USE_PROCESS_POLLING"] = str(int(polling))
             self.do_test_child_reaper()