Esempio n. 1
0
def _handleConnection(conn):
    conn.setblocking(True)
    f = conn.makefile()

    binstruct.write(f, (appinfo.appid, "SocketControl", 0.1))
    f.flush()
    try:
        clientappid, clientname, clientver, clientstatus = binstruct.read(f)
    except binstruct.FormatError:
        print "socketcontrol.handleConnection: wrong signature"
        return
    if clientstatus != "ok":
        print "socketcontrol.handleConnection: status returned %s" % status
        return

    from State import state
    from queue import queue
    shellGlobals = {
        "state": state,
        "queue": queue,
    }
    globals = locals = shellGlobals
    COMPILE_STRING_FN = "<socketcontrol input>"

    while True:
        try:
            idx, s = binstruct.varDecode(f)
        except Exception:
            # probably closed
            return
        assert isinstance(s, (str, unicode))

        try:
            c = utils.interactive_py_compile(s, COMPILE_STRING_FN)
        except Exception as e:
            answer = (idx, "compile-exception", (e.__class__.__name__, str(e)))
        else:
            try:
                ret = eval(c, globals, locals)
            except Exception as e:
                answer = (idx, "eval-exception", (e.__class__.__name__,
                                                  str(e)))
            else:
                if ret is not None:
                    try:
                        ret = repr(ret)
                    except Exception as e:
                        ret = "<repr exception: %s: %s>" % (
                            e.__class__.__name__, str(e))
                answer = (idx, "return", ret)

        f.write(binstruct.varEncode(answer).tostring())
        f.flush()
Esempio n. 2
0
def _handleConnection(conn):
	conn.setblocking(True)
	f = conn.makefile()

	binstruct.write(f, (appinfo.appid, "SocketControl", 0.1))
	f.flush()
	try:
		clientappid,clientname,clientver,clientstatus = binstruct.read(f)
	except binstruct.FormatError:
		print "socketcontrol.handleConnection: wrong signature"
		return	
	if clientstatus != "ok":
		print "socketcontrol.handleConnection: status returned %s" % status
		return
	
	from State import state
	from queue import queue
	shellGlobals = {
		"state": state,
		"queue": queue,
		}
	globals = locals = shellGlobals
	COMPILE_STRING_FN = "<socketcontrol input>"
		
	while True:
		try:
			idx,s = binstruct.varDecode(f)
		except Exception:
			# probably closed
			return
		assert isinstance(s, (str,unicode))
		
		try:
			c = utils.interactive_py_compile(s, COMPILE_STRING_FN)
		except Exception as e:
			answer = (idx, "compile-exception", (e.__class__.__name__, str(e)))
		else:
			try:
				ret = eval(c, globals, locals)
			except Exception as e:
				answer = (idx, "eval-exception", (e.__class__.__name__, str(e)))
			else:
				if ret is not None:
					try:
						ret = repr(ret)
					except Exception as e:
						ret = "<repr exception: %s: %s>" % (e.__class__.__name__, str(e))
				answer = (idx, "return", ret)
		
		f.write(binstruct.varEncode(answer).tostring())
		f.flush()
Esempio n. 3
0
def registerDev(dev):
	"""returns existing matching Dev, if there is any
	otherwise, it creates a new Dev"""
	assert "privateKeys" in dev
	assert "publicKeys" in dev
	assert "appInfo" in dev
	assert "type" in dev
	global localDev
	
	from sha import sha
	longDevId = LList("dev-" + sha(dev["publicKeys"]["sign"]).hexdigest()) + "-" + LRndSeq()
	longestCommonDevId = 9
	takenDevIds = set()
	for d in devices():
		if d.publicKeys == dev["publicKeys"]:
			# update if needed
			for key,value in dev.items():
				if isinstance(value, dict): value = binstruct.Dict(value)
				setattr(d, key, value)
			if localDev.publicKeys["sign"] == d.publicKeys["sign"]:
				localDev = d
			return d
		takenDevIds.add(d.devId)
		longestCommonDevId = max(longestCommonDevId, commonStrLen(longDevId, d.devId))
	devId = longDevId[:longestCommonDevId+1]
	
	# create new
	devdir = devId
	fs.makedirs(devdir)
	binstruct.write(fs.openW(devdir + "/publicKeys"), dev["publicKeys"]).close()
	for key in ("appInfo","type"):
		binstruct.writeEncrypt(
			fs.openW(devdir + "/" + key), dev[key],
			sign_rsaprivkey = dev["privateKeys"]["sign"])
	newdev = Dev(devId, binstruct.Dict(dev["publicKeys"]))
	for key,value in dev.items():
		if isinstance(value, dict): value = binstruct.Dict(value)
		setattr(newdev, key, value)
	binstruct.writeEncrypt(
		fs.openW(devdir + "/name"), localDevName(),
		sign_rsaprivkey = dev["privateKeys"]["sign"])
	if localDev.publicKeys["sign"] == newdev.publicKeys["sign"]:
		localDev = newdev
	return newdev
Esempio n. 4
0
def connect(verbose=False):
	global f, s
	if f: return
	s = socket.socket(socket.AF_UNIX)

	sockfile = None
	if __name__ == "__main__":
		if len(sys.argv) > 1:
			sockfile = sys.argv[1]
			assert os.path.exists(sockfile)

			s.connect(sockfile)

	if not sockfile:
		tmpdir = tempfile.gettempdir()
		files = glob("%s/%s-*-socketcontrol" % (tmpdir, appinfo.appid))
		assert files, "no socket files found"

		for fn in files:
			sockfile = fn
			try:
				s.connect(sockfile)
			except socket.error:
				pass
			else:
				if verbose: print "socket:", sockfile
				break
		assert s

	s.setblocking(True)
	f = s.makefile()

	serverappid,servername,serverver = binstruct.read(f)
	if verbose: print "connected to", serverappid, servername, serverver
	assert serverappid == appinfo.appid
	assert serverver == 0.1

	binstruct.write(f, (appinfo.appid, "SocketControl-InteractiveClient", 0.1, "ok"))
	f.flush()
Esempio n. 5
0
def connect(verbose=False):
	global f
	if f: return
	socket.setdefaulttimeout(1.0)

	sockfiles = []
	if __name__ == "__main__":
		if len(sys.argv) > 1:
			sockfile = sys.argv[1]
			assert os.path.exists(sockfile)
			sockfiles = [sockfile]

	if not sockfiles:
		tmpdir = tempfile.gettempdir()
		sockfiles = glob("%s/%s-*-socketcontrol" % (tmpdir, appinfo.appid))
		if not sockfiles:
			print "No socket files found. MusicPlayer is probably not running."
			sys.exit(1)

	import threading
	class ConnectThread(threading.Thread):
		def __init__(self, sockfile):
			threading.Thread.__init__(self)
			self.daemon = True
			self.sockfile = sockfile
			self.res = None
			self.file = None
			self.start()

		def run(self):
			try:
				s = socket.socket(socket.AF_UNIX)
				s.connect(self.sockfile)
				f = s.makefile()
				res = binstruct.read(f)
			except socket.error as e:
				self.res = e
				if e.errno == 61: # Connection refused
					# Cleanup
					os.remove(self.sockfile)
			else:
				s.setblocking(True) # No timeout from now on.
				self.file = f
				self.res = res

	connects = list(map(ConnectThread, sockfiles))
	while not f:
		anyoneAlive = False
		for t in connects:
			if t.isAlive():
				anyoneAlive = True
			elif t.file:
				sockfile = t.sockfile
				f = t.file
				res = t.res
				break
		if f: break
		if not anyoneAlive:
			print "Cannot connect to any socket:"
			for t in connects:
				print t.res
			print "MusicPlayer is probably not running."
			sys.exit(1)

	if verbose: print "socket:", sockfile

	serverappid,servername,serverver = res
	if verbose: print "connected to", serverappid, servername, serverver
	assert serverappid == appinfo.appid
	assert serverver == 0.1

	binstruct.write(f, (appinfo.appid, "SocketControl-InteractiveClient", 0.1, "ok"))
	f.flush()
		except socket.error:
			pass
		else:
			print "socket:", sockfile
			break
	assert s
	
s.setblocking(True)
f = s.makefile()

serverappid,servername,serverver = binstruct.read(f)
print "connected to", serverappid, servername, serverver
assert serverappid == appinfo.appid
assert serverver == 0.1

binstruct.write(f, (appinfo.appid, "SocketControl-InteractiveClient", 0.1, "ok"))
f.flush()

try: import readline
except ImportError: pass # ignore

idx = 0
while True:
	idx += 1
	try: s = raw_input("> ")
	except (KeyboardInterrupt,EOFError):
		print("")
		sys.exit(0)
	
	if s.strip() == "": continue
	f.write(binstruct.varEncode((idx, s)).tostring())
Esempio n. 7
0
def connect(verbose=False):
    global f
    if f: return
    socket.setdefaulttimeout(1.0)

    sockfiles = []
    if __name__ == "__main__":
        if len(sys.argv) > 1:
            sockfile = sys.argv[1]
            assert os.path.exists(sockfile)
            sockfiles = [sockfile]

    if not sockfiles:
        tmpdir = tempfile.gettempdir()
        sockfiles = glob("%s/%s-*-socketcontrol" % (tmpdir, appinfo.appid))
        if not sockfiles:
            print "No socket files found. MusicPlayer is probably not running."
            sys.exit(1)

    import threading

    class ConnectThread(threading.Thread):
        def __init__(self, sockfile):
            threading.Thread.__init__(self)
            self.daemon = True
            self.sockfile = sockfile
            self.res = None
            self.file = None
            self.start()

        def run(self):
            try:
                s = socket.socket(socket.AF_UNIX)
                s.connect(self.sockfile)
                f = s.makefile()
                res = binstruct.read(f)
            except socket.error as e:
                self.res = e
                if e.errno == 61:  # Connection refused
                    # Cleanup
                    os.remove(self.sockfile)
            else:
                s.setblocking(True)  # No timeout from now on.
                self.file = f
                self.res = res

    connects = list(map(ConnectThread, sockfiles))
    while not f:
        anyoneAlive = False
        for t in connects:
            if t.isAlive():
                anyoneAlive = True
            elif t.file:
                sockfile = t.sockfile
                f = t.file
                res = t.res
                break
        if f: break
        if not anyoneAlive:
            print "Cannot connect to any socket:"
            for t in connects:
                print t.res
            print "MusicPlayer is probably not running."
            sys.exit(1)

    if verbose: print "socket:", sockfile

    serverappid, servername, serverver = res
    if verbose: print "connected to", serverappid, servername, serverver
    assert serverappid == appinfo.appid
    assert serverver == 0.1

    binstruct.write(
        f, (appinfo.appid, "SocketControl-InteractiveClient", 0.1, "ok"))
    f.flush()
Esempio n. 8
0
        except socket.error:
            pass
        else:
            print "socket:", sockfile
            break
    assert s

s.setblocking(True)
f = s.makefile()

serverappid, servername, serverver = binstruct.read(f)
print "connected to", serverappid, servername, serverver
assert serverappid == appinfo.appid
assert serverver == 0.1

binstruct.write(f,
                (appinfo.appid, "SocketControl-InteractiveClient", 0.1, "ok"))
f.flush()

try:
    import readline
except ImportError:
    pass  # ignore

idx = 0
while True:
    try:
        s = raw_input("> ")
    except (KeyboardInterrupt, EOFError):
        print("")
        sys.exit(0)