execute.py 4.72 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
# Copyright (c) 2010, Alexander Cherniuk (ts33kr@gmail.com)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
#   notice, this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
#   notice, this list of conditions and the following disclaimer in the
#   documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""
Provides facilities to safely execute expressions inside a shell process
and capture the resulting output, in an asynchronous fashion, avoiding
deadlocks. If the process execution time reaches the threshold - it is
forced to terminate. Consists of a tiny framework and a couple of
commands as a frontend.
"""

from subprocess import Popen, PIPE
from os.path import expanduser

Yann Leboulanger's avatar
Yann Leboulanger committed
38
from gi.repository import GLib
39

40
from gajim.common import app
41
from gajim.common.i18n import _
42 43 44 45 46 47
from gajim.command_system.framework import CommandContainer
from gajim.command_system.framework import command
from gajim.command_system.framework import doc
from gajim.command_system.implementation.hosts import ChatCommands
from gajim.command_system.implementation.hosts import PrivateChatCommands
from gajim.command_system.implementation.hosts import GroupChatCommands
48 49

class Execute(CommandContainer):
Dicson's avatar
Dicson committed
50
    AUTOMATIC = True
51 52 53 54
    HOSTS = ChatCommands, PrivateChatCommands, GroupChatCommands

    DIRECTORY = "~"

55
    POLL_INTERVAL = 100
56 57 58 59 60 61 62 63 64
    POLL_COUNT = 5

    @command("exec", raw=True)
    @doc(_("Execute expression inside a shell, show output"))
    def execute(self, expression):
        Execute.spawn(self, expression)

    @classmethod
    def spawn(cls, processor, expression):
65 66 67 68 69 70 71 72 73 74 75 76
        command_system_execute = app.config.get('command_system_execute')
        if command_system_execute:
            pipes = dict(stdout=PIPE, stderr=PIPE)
            directory = expanduser(cls.DIRECTORY)
            popen = Popen(expression, shell=True, cwd=directory, **pipes)
            cls.monitor(processor, popen)
        else:
            processor.echo_error(
                _('Command disabled. This command can be enabled by '
                  'setting \'command_system_execute\' to True in ACE '
                  '(Advanced Configuration Editor).'))
            return
77 78 79 80

    @classmethod
    def monitor(cls, processor, popen):
        poller = cls.poller(processor, popen)
Yann Leboulanger's avatar
Yann Leboulanger committed
81
        GLib.timeout_add(cls.POLL_INTERVAL, next, poller)
82 83 84

    @classmethod
    def poller(cls, processor, popen):
85
        for _ in range(cls.POLL_COUNT):
86 87 88 89 90 91 92 93 94 95 96 97 98 99
            yield cls.brush(processor, popen)
        cls.overdue(processor, popen)
        yield False

    @classmethod
    def brush(cls, processor, popen):
        if popen.poll() is not None:
            cls.terminated(processor, popen)
            return False
        return True

    @classmethod
    def terminated(cls, processor, popen):
        stdout, stderr = cls.fetch(popen)
100 101
        success = popen.returncode == 0
        if success and stdout:
102
            processor.echo(stdout)
103 104
        elif not success and stderr:
            processor.echo_error(stderr)
105 106 107 108 109 110 111 112 113 114 115 116 117

    @classmethod
    def overdue(cls, processor, popen):
        popen.terminate()

    @classmethod
    def fetch(cls, popen):
        data = popen.communicate()
        return map(cls.clean, data)

    @staticmethod
    def clean(text):
        strip = chr(10) + chr(32)
118
        return text.decode().strip(strip)
119 120 121 122 123 124 125 126 127 128 129

class Show(Execute):

    @command("sh", raw=True)
    @doc(_("Execute expression inside a shell, send output"))
    def show(self, expression):
        Show.spawn(self, expression)

    @classmethod
    def terminated(cls, processor, popen):
        stdout, stderr = cls.fetch(popen)
130 131
        success = popen.returncode == 0
        if success and stdout:
132
            processor.send(stdout)
133
        elif not success and stderr:
134
            processor.echo_error(stderr)