~azzar1/unity/add-show-desktop-key

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
#!/usr/bin/python

# usage:
#   python-console <port> <magic> [<working-dir>]

import cjson
import codeop
import md5
import os
import Queue
import signal
import socket
import sys
import traceback
from threading import Thread
from functools import partial

import common.chat

class Interrupt(Exception):
    def __init__(self):
        Exception.__init__(self, "Interrupted!")

class ExpiryTimer(object):
    def __init__(self, idle):
        self.idle = idle
        signal.signal(signal.SIGALRM, partial(self.timeout))

    def ping(self):
        signal.alarm(self.idle)

    def start(self, time):
        signal.alarm(time)

    def stop(self):
        self.ping()

    def timeout(self, signum, frame):
        sys.exit(1)
        
class StdinFromWeb(object):
    def __init__(self, cmdQ, lineQ):
        self.cmdQ = cmdQ
        self.lineQ = lineQ

    def readline(self):
        self.cmdQ.put({"input":None})
        expiry.ping()
        ln = self.lineQ.get()
        if 'chat' in ln:
            return ln['chat']
        if 'interrupt' in ln:
            raise Interrupt()
        if 'terminate' in ln:
            sys.exit(0)
            

class StdoutToWeb(object):
    def __init__(self, cmdQ, lineQ):
        self.cmdQ = cmdQ
        self.lineQ = lineQ
        self.remainder = ''

    def write(self, stuff):
        self.remainder = self.remainder + stuff

        # if there's less than 128 bytes, buffer
        if len(self.remainder) < 128:
            return

        # if there's lots, then send it in 1/2K blocks
        while len(self.remainder) > 512:
            blk = self.remainder[0:512]
            self.cmdQ.put({"output":blk})
            expiry.ping()
            ln = self.lineQ.get()
            self.remainder = self.remainder[512:]

        # Finally, split the remainder up into lines, and ship all the
        # completed lines off to the server.
        lines = self.remainder.split("\n")
        self.remainder = lines[-1]
        del lines[-1]

        if len(lines) > 0:
            lines.append('')
            text = "\n".join(lines)
            self.cmdQ.put({"output":text})
            expiry.ping()
            ln = self.lineQ.get()
            if 'interrupt' in ln:
                raise Interrupt()

    def flush(self):
        if len(self.remainder) > 0:
            self.cmdQ.put({"output":self.remainder})
            expiry.ping()
            ln = self.lineQ.get()
            self.remainder = ''
            if 'interrupt' in ln:
                raise Interrupt()

class WebIO(object):
    """Provides a file like interface to the Web front end of the console.
    You may print text to the console using write(), flush any buffered output 
    using flush(), or request text from the console using readline()"""
    
    def __init__(self, cmdQ, lineQ):
        self.cmdQ = cmdQ
        self.lineQ = lineQ
        self.stdin = StdinFromWeb(self.cmdQ, self.lineQ)
        self.stdout = StdoutToWeb(self.cmdQ, self.lineQ)

    def write(self, stuff):
        self.stdout.write(stuff)

    def flush(self):
        self.stdout.flush()

    def readline(self):
        self.stdout.flush()
        return self.stdin.readline()

class PythonRunner(Thread):
    def __init__(self, cmdQ, lineQ):
        self.cmdQ = cmdQ
        self.lineQ = lineQ
        self.webio = WebIO(self.cmdQ, self.lineQ)
        Thread.__init__(self)

    def execCmd(self, cmd):
        try:
            sys.stdin = self.webio
            sys.stdout = self.webio
            sys.stderr = self.webio
            # We don't expect a return value - 'single' symbol prints it.
            eval(cmd, self.globs)
            self.webio.flush()
            self.cmdQ.put({"okay": None})
            self.curr_cmd = ''
        except:
            tb = format_exc_start(start=1)
            self.webio.flush()
            self.cmdQ.put({"exc": ''.join(tb)})
            self.curr_cmd = ''

    def run(self):
        self.globs = {}
        self.globs['__builtins__'] = globals()['__builtins__']
        self.curr_cmd = ''

        while True:
            ln = self.lineQ.get()
            if 'chat' in ln:
                if self.curr_cmd == '':
                    self.curr_cmd = ln['chat']
                else:
                    self.curr_cmd = self.curr_cmd + '\n' + ln['chat']
                try:
                    cmd = codeop.compile_command(self.curr_cmd, '<web session>')
                    if cmd is None:
                        # The command was incomplete,
                        # so send back a None, so the
                        # client can print a '...'
                        self.cmdQ.put({"more":None})
                    else:
                        self.execCmd(cmd)
                except:
                    tb = format_exc_start(start=3)
                    self.cmdQ.put({"exc": ''.join(tb)})
                    self.webio.flush()
                    self.curr_cmd = ''
            if 'block' in ln:
                # throw away a partial command.
                try:
                    cmd = compile(ln['block'], "<web session>", 'exec');
                    self.execCmd(cmd)
                except:
                    tb = format_exc_start(start=1)
                    self.webio.flush()
                    self.cmdQ.put({"exc": ''.join(tb)})
                    self.curr_cmd = ''

def daemonize():
    if os.fork():   # launch child and...
        os._exit(0) # kill off parent
    os.setsid()
    if os.fork():   # launch child and...
        os._exit(0) # kill off parent again.
    os.umask(077)

# The global 'magic' is the secret that the client and server share
# which is used to create and md5 digest to authenticate requests.
# It is assigned a real value at startup.
magic = ''

cmdQ = Queue.Queue()
lineQ = Queue.Queue()
interpThread = PythonRunner(cmdQ, lineQ)

# Default expiry time of 15 minutes
expiry = ExpiryTimer(15 * 60)

def initializer():
    interpThread.setDaemon(True)
    interpThread.start()
    expiry.ping()

def dispatch_msg(msg):
    expiry.ping()
    lineQ.put({msg['cmd']:msg['text']})
    return cmdQ.get()

def format_exc_start(start=0):
    etype, value, tb = sys.exc_info()
    tbbits = traceback.extract_tb(tb)[start:]
    list = ['Traceback (most recent call last):\n']
    list = list + traceback.format_list(tbbits)
    list = list + traceback.format_exception_only(etype, value)
    return ''.join(list)

if __name__ == "__main__":
    port = int(sys.argv[1])
    magic = sys.argv[2]
    if len(sys.argv) >= 4:
        # working_dir
        os.chdir(sys.argv[3])
        # Make python's search path follow the cwd
        sys.path[0] = ''
        os.environ['HOME'] = sys.argv[3]

    common.chat.start_server(port, magic, True, dispatch_msg, initializer)