1#!/usr/bin/env python
2
3import socket
4import subprocess
5import sys
6
7
8address = '0.0.0.0'
9port = 4242
10
11
12def receiveExactly(connection, size):
13	data = '';
14	while size > 0:
15		dataReceived = connection.recv(size)
16		if not dataReceived:
17			raise EOFError()
18		data += dataReceived
19		size -= len(dataReceived)
20	return data
21
22
23def handleConnection(listenerSocket):
24	(controlConnection, controlAddress) = listenerSocket.accept()
25	(stdioConnection, stdioAddress) = listenerSocket.accept()
26	(stderrConnection, stderrAddress) = listenerSocket.accept()
27
28	print 'accepted client connections'
29
30	try:
31		commandLength = receiveExactly(controlConnection, 8)
32		commandToRun = receiveExactly(controlConnection, int(commandLength))
33
34		print 'received command: ' + commandToRun
35
36		exitCode = subprocess.call(commandToRun, stdin=stdioConnection,
37			stdout=stdioConnection, stderr=stderrConnection, shell=True)
38
39		controlConnection.send(str(exitCode))
40	finally:
41		controlConnection.close()
42		stdioConnection.close()
43		stderrConnection.close()
44
45	print 'client connections closed'
46
47
48listenerSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
49listenerSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
50
51try:
52	listenerSocket.bind((address, port))
53except socket.error, msg:
54	sys.exit('Failed to bind to %s port %d: %s' % (address, port, msg[1]))
55
56listenerSocket.listen(3)
57
58print 'started listening on adddress %s port %s' % (address, port)
59
60while True:
61	handleConnection(listenerSocket)
62