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

« back to all changes in this revision

Viewing changes to console/python-console

  • Committer: mattgiuca
  • Date: 2008-02-01 02:25:59 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:363
setup.py: Added new config option - "database name"

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/python
 
2
 
 
3
# usage:
 
4
#   python-console <port> <magic>
 
5
 
 
6
import cjson
 
7
import codeop
 
8
import cStringIO
 
9
import md5
 
10
import os
 
11
import Queue
 
12
import signal
 
13
import socket
 
14
import sys
 
15
from threading import Thread
 
16
 
 
17
class StdinFromWeb(object):
 
18
    def __init__(self, cmdQ, lineQ):
 
19
        self.cmdQ = cmdQ
 
20
        self.lineQ = lineQ
 
21
 
 
22
    def readline(self):
 
23
        # stop the clock!
 
24
        signal.alarm(0)
 
25
        self.cmdQ.put({"input":None})
 
26
        ln = self.lineQ.get()
 
27
        if 'chat' in ln:
 
28
            # restart the clock:
 
29
            # Some of our 5 seconds may have elapsed, but never mind.
 
30
            signal.alarm(5)
 
31
            return ln['chat']
 
32
 
 
33
class PythonRunner(Thread):
 
34
    def __init__(self, cmdQ, lineQ):
 
35
        self.cmdQ = cmdQ
 
36
        self.lineQ = lineQ
 
37
        self.out = cStringIO.StringIO()
 
38
        Thread.__init__(self)
 
39
 
 
40
    def run(self):
 
41
        self.init_state()
 
42
        compiler = codeop.CommandCompiler()
 
43
 
 
44
        while True:
 
45
            ln = self.lineQ.get()
 
46
            if 'chat' in ln:
 
47
                if self.curr_cmd == '':
 
48
                    self.curr_cmd = ln['chat']
 
49
                else:
 
50
                    self.curr_cmd = self.curr_cmd + '\n' + ln['chat']
 
51
                try:
 
52
                    cmd = compiler(self.curr_cmd)
 
53
                    if cmd is None:
 
54
                        # The command was incomplete,
 
55
                        # so send back a None, so the
 
56
                        # client can print a '...'
 
57
                        self.cmdQ.put({"more":None})
 
58
                    else:
 
59
                        # The command was complete,
 
60
                        # so evaluate it!
 
61
                        sys.stdin = StdinFromWeb(self.cmdQ, self.lineQ)
 
62
                        sys.stdout = self.out
 
63
                        sys.stderr = self.out
 
64
                        signal.alarm(5)
 
65
                        res = eval(cmd, self.globs, self.locls)
 
66
                        signal.alarm(0)
 
67
                        self.cmdQ.put({"okay":(self.out.getvalue(),res)})
 
68
                        self.curr_cmd = ''
 
69
                        self.out = cStringIO.StringIO()
 
70
                except Exception, exc:
 
71
                    signal.alarm(0)
 
72
                    self.cmdQ.put({"exc":(self.out.getvalue(),str(exc))})
 
73
                    self.curr_cmd = ''
 
74
                    self.out = cStringIO.StringIO()
 
75
            if 'block' in ln:
 
76
                # throw away a partial command.
 
77
                try:
 
78
                    cmd = compile(ln['block'], "<web session>", 'exec');
 
79
                    
 
80
                    sys.stdin = StdinFromWeb(self.cmdQ, self.lineQ)
 
81
                    self.out = cStringIO.StringIO()
 
82
                    sys.stdout = self.out
 
83
                    sys.stderr = self.out
 
84
                    signal.alarm(5)
 
85
                    res = eval(cmd, self.globs, self.locls)
 
86
                    signal.alarm(0)
 
87
                    self.cmdQ.put({"okay":(self.out.getvalue(),res)})
 
88
                    self.curr_cmd = ''
 
89
                    self.out = cStringIO.StringIO()
 
90
                except Exception, exc:
 
91
                    signal.alarm(0)
 
92
                    self.cmdQ.put({"exc":(self.out.getvalue(),str(exc))})
 
93
                    self.curr_cmd = ''
 
94
                    self.out = cStringIO.StringIO()
 
95
 
 
96
    def init_state(self):
 
97
        self.globs = {}
 
98
        self.globs['__builtins__'] = globals()['__builtins__']
 
99
        self.locls = {}
 
100
        self.curr_cmd = ''
 
101
 
 
102
def daemonize():
 
103
    if os.fork():   # launch child and...
 
104
        os._exit(0) # kill off parent
 
105
    os.setsid()
 
106
    if os.fork():   # launch child and...
 
107
        os._exit(0) # kill off parent again.
 
108
    os.umask(077)
 
109
 
 
110
# The global 'magic' is the secret that the client and server share
 
111
# which is used to create and md5 digest to authenticate requests.
 
112
# It is assigned a real value at startup.
 
113
magic = ''
 
114
 
 
115
cmdQ = Queue.Queue()
 
116
lineQ = Queue.Queue()
 
117
interpThread = PythonRunner(cmdQ, lineQ)
 
118
 
 
119
if __name__ == "__main__":
 
120
    port = int(sys.argv[1])
 
121
    magic = sys.argv[2]
 
122
 
 
123
    # Attempt to open the socket.
 
124
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 
125
    s.bind(('', port))
 
126
    s.listen(1)
 
127
 
 
128
    # Excellent! It worked. Let's turn ourself into a daemon,
 
129
    # then get on with the job of being a python interpreter.
 
130
    daemonize()
 
131
 
 
132
    interpThread.setDaemon(True)
 
133
    interpThread.start()
 
134
 
 
135
    while True:
 
136
        (conn, addr) = s.accept()
 
137
        try:
 
138
            # Grab the input
 
139
            buf = cStringIO.StringIO()
 
140
            blk = conn.recv(1024)
 
141
            while blk:
 
142
                buf.write(blk)
 
143
                try:
 
144
                    blk = conn.recv(1024, socket.MSG_DONTWAIT)
 
145
                except:
 
146
                    # Exception thrown if it WOULD block (but we
 
147
                    # told it not to wait) - ie. we are done
 
148
                    blk = None
 
149
            inp = buf.getvalue()
 
150
            msg = cjson.decode(inp)
 
151
            
 
152
            # Check that the message is 
 
153
            digest = md5.new(msg['text'] + magic).digest().encode('hex')
 
154
            if msg['digest'] != digest:
 
155
                conn.close()
 
156
                continue
 
157
 
 
158
            lineQ.put({msg['cmd']:msg['text']})
 
159
            r = cmdQ.get()
 
160
            conn.sendall(cjson.encode(r))
 
161
            conn.close()
 
162
        except Exception, e:
 
163
            conn.close()