X-Git-Url: http://review.tizen.org/git/?a=blobdiff_plain;f=cloudeebus%2Fcloudeebus.py;h=fade6fe57f38b0a3747518273f1ec8c1b4e6f864;hb=50f9107a8bf3455e9d3e8797ffa2b8d3c1dc4c06;hp=faf520419b8a176bd571cce98402adf34c073846;hpb=2648d7cfd933ffb906ed660a889b1f6fd14fb151;p=contrib%2Fcloudeebus.git diff --git a/cloudeebus/cloudeebus.py b/cloudeebus/cloudeebus.py index faf5204..fade6fe 100755 --- a/cloudeebus/cloudeebus.py +++ b/cloudeebus/cloudeebus.py @@ -18,6 +18,7 @@ # # Luc Yriarte # Christophe Guiraud +# Frederic Paut # @@ -48,13 +49,40 @@ from twisted.python import log # XML parser module from xml.etree.ElementTree import XMLParser - ############################################################################### -VERSION = "0.3.0" +VERSION = "0.5.99" OPENDOOR = False CREDENTIALS = {} WHITELIST = [] +SERVICELIST = [] +NETMASK = [] + +############################################################################### +def ipV4ToHex(mask): + ## Convert an ip or an IP mask (such as ip/24 or ip/255.255.255.0) in hex value (32bits) + maskHex = 0 + byte = 0 + if mask.rfind(".") == -1: + if (int(mask) < 32): + maskHex = (2**(int(mask))-1) + maskHex = maskHex << (32-int(mask)) + else: + raise Exception("Illegal mask (larger than 32 bits) " + mask) + else: + maskField = mask.split(".") + # Check if mask has four fields (byte) + if len(maskField) != 4: + raise Exception("Illegal ip address / mask (should be 4 bytes) " + mask) + for maskQuartet in maskField: + byte = int(maskQuartet) + # Check if each field is really a byte + if byte > 255: + raise Exception("Illegal ip address / mask (digit larger than a byte) " + mask) + maskHex += byte + maskHex = maskHex << 8 + maskHex = maskHex >> 8 + return maskHex ############################################################################### class DbusCache: @@ -153,7 +181,10 @@ class DbusCallHandler: ################################################################################ -class exec_code: +class ExecCode: + ''' + Execute DynDBusClass generated code + ''' def __init__(self, globalCtx, localCtx) : self.exec_string = "" self.exec_code = None @@ -165,26 +196,12 @@ class exec_code: self.globalCtx = globalCtx - # __str__ : Return a string representation of the object, for - # nice printing. - def __str__(self) : - return self.exec_string - - def p(self) : - print str(self) - def append_stmt(self, stmt) : self.exec_code_valid = 0 self.line += 1 - if (stmt != "\n"): - for x in range(0,self.indent_level): - self.exec_string = self.exec_string + ' ' - self.exec_string = self.exec_string + stmt + "\t\t# l:" + str(self.line) + '\n' - else: - if (stmt == "\n"): - self.exec_string = self.exec_string + "# l:" + str(self.line) + '\n' - else: - self.exec_string = self.exec_string + stmt + "\t\t# l:" + str(self.line) + '\n' + for x in range(0,self.indent_level): + self.exec_string = self.exec_string + ' ' + self.exec_string = self.exec_string + stmt + '\n' def indent(self) : self.indent_level = self.indent_level + self.indent_increment @@ -207,7 +224,7 @@ class exec_code: ################################################################################ -class XmlCb_Parser: # The target object of the parser +class XmlCbParser: # The target object of the parser maxDepth = 0 depth = 0 def __init__(self, dynDBusClass): @@ -240,6 +257,8 @@ class XmlCb_Parser: # The target object of the parser attrib['type']) return if (self.current == 'signal'): + if (attrib.has_key('name') == False): + attrib['name'] = 'value' self.dynDBusClass.add_signature(attrib['name'], 'in', attrib['type']) return @@ -260,40 +279,41 @@ class XmlCb_Parser: # The target object of the parser +############################################################################### +def createClassName(objectPath): + return re.sub('/', '_', objectPath[1:]) + ################################################################################ -class dynDBusClass(): +class DynDBusClass(): def __init__(self, className, globalCtx, localCtx): - self.className = className - self.xmlCB = XmlCb_Parser(self) + self.xmlCB = XmlCbParser(self) self.signature = {} - self.class_code = exec_code(globalCtx, localCtx) + self.class_code = ExecCode(globalCtx, localCtx) self.class_code.indent_increment = 4 self.class_code.append_stmt("import dbus") self.class_code.append_stmt("\n") - self.class_code.append_stmt("\n") - self.class_code.append_stmt("class " + self.className + "(dbus.service.Object):") + self.class_code.append_stmt("class " + className + "(dbus.service.Object):") self.class_code.indent() ## Overload of __init__ method self.def_method("__init__") - self.add_method("bus, callback=None, objName='/sample', busName='org.cloudeebus'") + self.add_method("bus, callback=None, objPath='/sample', busName='org.cloudeebus'") self.add_stmt("self.bus = bus") - self.add_stmt("self.objName = objName") + self.add_stmt("self.objPath = objPath") self.add_stmt("self.callback = callback") -# self.add_stmt("dbus.service.Object.__init__(self, conn=bus, object_path=objName, bus_name=busName)") self.add_stmt("dbus.service.Object.__init__(self, conn=bus, bus_name=busName)") self.end_method() ## Create 'add_to_connection' method self.def_method("add_to_connection") self.add_method("connection=None, path=None") - self.add_stmt("dbus.service.Object.add_to_connection(self, connection=self.bus, path=self.objName)") + self.add_stmt("dbus.service.Object.add_to_connection(self, connection=self.bus, path=self.objPath)") self.end_method() ## Create 'remove_from_connection' method self.def_method("remove_from_connection") self.add_method("connection=None, path=None") - self.add_stmt("dbus.service.Object.remove_from_connection(self, connection=None, path=self.objName)") + self.add_stmt("dbus.service.Object.remove_from_connection(self, connection=None, path=self.objPath)") self.end_method() def createDBusServiceFromXML(self, xml): @@ -360,7 +380,6 @@ class dynDBusClass(): def end_method(self): self.class_code.append_stmt("\n") - self.class_code.append_stmt("\n") self.class_code.dedent() def add_dbus_method(self): @@ -390,11 +409,10 @@ class dynDBusClass(): def add_body_method(self): if (self.methodToAdd != None): - self.class_code.append_stmt("print 'In " + self.methodToAdd + "()'") if (self.args_str != str()): - self.class_code.append_stmt("self.callback('" + self.methodToAdd + "', dbus_async_cb, dbus_async_err_cb, %s)" % self.args_str) + self.class_code.append_stmt("self.callback('" + self.methodToAdd + "', self.objPath, '" + self.ifName + "', " + "dbus_async_cb, dbus_async_err_cb, %s)" % self.args_str) else: - self.class_code.append_stmt("self.callback('" + self.methodToAdd + "', dbus_async_cb, dbus_async_err_cb)") + self.class_code.append_stmt("self.callback('" + self.methodToAdd + "', self.objPath, '" + self.ifName + "', " + "dbus_async_cb, dbus_async_err_cb)") def add_body_signal(self): self.class_code.append_stmt("return") ## TODO: Remove and fix with code ad hoc @@ -405,17 +423,6 @@ class dynDBusClass(): def declare(self) : self.class_code.execute() - - def __str__(self) : - return self.class_code.exec_string - - # p : Since it is often useful to be able to look at the code - # that is generated interactively, this function provides - # a shorthand for "print str(some_exec_code_instance)", which - # gives a reasonable nice look at the contents of the - # exec_code object. - def p(self) : - print str(self) @@ -425,7 +432,10 @@ class CloudeebusService: support for sending DBus messages and registering for DBus signals ''' def __init__(self, permissions): - self.permissions = permissions; + self.permissions = {}; + self.permissions['permissions'] = permissions['permissions'] + self.permissions['authextra'] = permissions['authextra'] + self.permissions['services'] = permissions['services'] self.proxyObjects = {} self.proxyMethods = {} self.pendingCalls = [] @@ -445,7 +455,7 @@ class CloudeebusService: if not self.proxyObjects.has_key(id): if not OPENDOOR: # check permissions, array.index throws exception - self.permissions.index(serviceName) + self.permissions['permissions'].index(serviceName) bus = cache.dbusConnexion(busName) self.proxyObjects[id] = bus.get_object(serviceName, objectName) return self.proxyObjects[id] @@ -472,7 +482,7 @@ class CloudeebusService: if not OPENDOOR: # check permissions, array.index throws exception - self.permissions.index(list[1]) + self.permissions['permissions'].index(list[1]) # check if a handler exists sigId = "#".join(list) @@ -514,15 +524,33 @@ class CloudeebusService: @exportRpc + def emitSignal(self, list): + ''' + arguments: agentObjectPath, signalName, result (to emit) + ''' + objectPath = list[0] + className = re.sub('/', '_', objectPath[1:]) + signalName = list[1] + result = list[2] + if (self.serviceAgents.has_key(className) == True): + exe_str = "self.serviceAgents['"+ className +"']."+ signalName + "(" + str(result) + ")" + eval(exe_str, self.globalCtx, self.localCtx) + else: + raise Exception("No object path " + objectPath) + + @exportRpc def returnMethod(self, list): ''' - arguments: methodId, success (=true, error otherwise), result (to return) + arguments: methodId, callIndex, success (=true, error otherwise), result (to return) ''' methodId = list[0] - success = list[1] - result = list[2] + callIndex = list[1] + success = list[2] + result = list[3] if (self.servicePendingCalls.has_key(methodId)): - cb = self.servicePendingCalls[methodId] + cb = self.servicePendingCalls[methodId]['calls'][callIndex] + if cb is None: + raise Exception("No pending call " + str(callIndex) + " for methodID " + methodId) if (success): successCB = cb["successCB"] if (result != None): @@ -535,74 +563,29 @@ class CloudeebusService: errorCB(result) else: errorCB() - self.servicePendingCalls[methodId] = None + self.servicePendingCalls[methodId]['calls'][callIndex] = None + self.servicePendingCalls[methodId]['count'] = self.servicePendingCalls[methodId]['count'] - 1 + if self.servicePendingCalls[methodId]['count'] == 0: + del self.servicePendingCalls[methodId] else: - print "No methodID %s !!" % (methodId) - - def jsonEncodeTupleKeyDict(self, data): - ndict = dict() - # creates new dictionary with the original tuple converted to json string - dataLen = len(data) - string = "" - for index in range(dataLen): - for key in data[index]: - value = data[index][key] - print "key=" + key - print "value=" + str(value) - nkey = str(key) - nvalue = "" - print "JSON key=" + nkey - if (isinstance(value, dbus.Array)): - # Searching dbus byte in array... - ValueLen = len(value) - nvalue = [] - for indexValue in range(ValueLen): - a = value[indexValue] - if (isinstance(a, dbus.Byte)): - a = int(value[indexValue]) - nvalue.append(a) - else: - nvalue = str(value[indexValue]) - - print "JSON value=" + str(nvalue) - ndict[nkey] = nvalue - - return ndict - - def srvCB(self, name, async_succes_cb, async_error_cb, *args): - methodId = self.srvName + "#" + self.agentObjectPath + "#" + name + raise Exception("No methodID " + methodId) + + def srvCB(self, name, objPath, ifName, async_succes_cb, async_error_cb, *args): + methodId = self.srvName + "#" + objPath + "#" + ifName + "#" + name cb = { 'successCB': async_succes_cb, 'errorCB': async_error_cb} - self.servicePendingCalls[methodId] = cb - - if (len(args) > 0): - print "Received args=%s" % (str(args)) - else: - print "No args received" - - try: - print "factory.dispatch(methodId=%s, args=%s)" % (methodId, json.dumps(args)) - factory.dispatch(methodId, json.dumps(args)) - return - except Exception, e : - print "Error=%s" % (str(e)) + if methodId not in self.servicePendingCalls: + self.servicePendingCalls[methodId] = {'count': 0, 'calls': []} - print "Trying to decode dbus.Dictionnary..." try: - params = self.jsonEncodeTupleKeyDict(args) - print "factory.dispatch(methodId=%s, args=%s)" % (methodId, params) - factory.dispatch(methodId, params) - return - except Exception, e : - print "Error=%s" % (str(e)) - - print "Trying to pass args as string..." - try: - print "factory.dispatch(methodId=%s, args=%s)" % (methodId, str(args)) - factory.dispatch(methodId, str(args)) - return - except Exception, e : - print "Error=%s" % (str(e)) + pendingCallStr = json.dumps({'callIndex': len(self.servicePendingCalls[methodId]['calls']), 'args': args}) + except Exception, e: + args = eval( str(args).replace("dbus.Byte", "dbus.Int16") ) + pendingCallStr = json.dumps({'callIndex': len(self.servicePendingCalls[methodId]['calls']), 'args': args}) + + self.servicePendingCalls[methodId]['calls'].append(cb) + self.servicePendingCalls[methodId]['count'] = self.servicePendingCalls[methodId]['count'] + 1 + factory.dispatch(methodId, pendingCallStr) @exportRpc def serviceAdd(self, list): @@ -610,9 +593,12 @@ class CloudeebusService: arguments: busName, srvName ''' busName = list[0] - self.bus = cache.dbusConnexion( busName['name'] ) + self.bus = cache.dbusConnexion( busName ) self.srvName = list[1] - if (self.services.has_key(self.srvName) == False): + if not OPENDOOR and (SERVICELIST == [] or SERVICELIST != [] and self.permissions['services'] == None): + SERVICELIST.index(self.srvName) + + if (self.services.has_key(self.srvName) == False): self.services[self.srvName] = dbus.service.BusName(name = self.srvName, bus = self.bus) return self.srvName @@ -626,7 +612,7 @@ class CloudeebusService: self.services.pop(self.srvName) return self.srvName else: - raise Exception(self.srvName + " do not exist") + raise Exception(self.srvName + " does not exist") @exportRpc def serviceAddAgent(self, list): @@ -635,17 +621,17 @@ class CloudeebusService: ''' self.agentObjectPath = list[0] xmlTemplate = list[1] - self.className = re.sub('/', '_', self.agentObjectPath[1:]) - if (self.dynDBusClasses.has_key(self.className) == False): - self.dynDBusClasses[self.className] = dynDBusClass(self.className, self.globalCtx, self.localCtx) - self.dynDBusClasses[self.className].createDBusServiceFromXML(xmlTemplate) - self.dynDBusClasses[self.className].declare() + className = createClassName(self.agentObjectPath) + if (self.dynDBusClasses.has_key(className) == False): + self.dynDBusClasses[className] = DynDBusClass(className, self.globalCtx, self.localCtx) + self.dynDBusClasses[className].createDBusServiceFromXML(xmlTemplate) + self.dynDBusClasses[className].declare() ## Class already exist, instanciate it if not already instanciated - if (self.serviceAgents.has_key(self.className) == False): - self.serviceAgents[self.className] = eval(self.className + "(self.bus, callback=self.srvCB, objName=self.agentObjectPath, busName=self.srvName)", self.globalCtx, self.localCtx) + if (self.serviceAgents.has_key(className) == False): + self.serviceAgents[className] = eval(className + "(self.bus, callback=self.srvCB, objPath=self.agentObjectPath, busName=self.srvName)", self.globalCtx, self.localCtx) - self.serviceAgents[self.className].add_to_connection() + self.serviceAgents[className].add_to_connection() return (self.agentObjectPath) @exportRpc @@ -654,11 +640,13 @@ class CloudeebusService: arguments: objectPath, xmlTemplate ''' agentObjectPath = list[0] - className = re.sub('/', '_', agentObjectPath[1:]) + className = createClassName(agentObjectPath) + + print 'PY Try to remove ' + className if (self.serviceAgents.has_key(className)): - self.serviceAgents[self.className].remove_from_connection() - self.serviceAgents.pop(self.className) + self.serviceAgents[className].remove_from_connection() + self.serviceAgents.pop(className) else: raise Exception(agentObjectPath + " doesn't exist!") @@ -688,25 +676,41 @@ class CloudeebusServerProtocol(WampCraServerProtocol): def getAuthPermissions(self, key, extra): - return json.loads(extra.get("permissions", "[]")) - + return {'permissions': extra.get("permissions", None), + 'authextra': extra.get("authextra", None), + 'services': extra.get("services", None)} def getAuthSecret(self, key): secret = CREDENTIALS.get(key, None) if secret is None: return None # secret must be of str type to be hashed - return secret.encode('utf-8') + return str(secret) def onAuthenticated(self, key, permissions): if not OPENDOOR: + # check net filter + if NETMASK != []: + ipAllowed = False + for netfilter in NETMASK: + ipHex=ipV4ToHex(self.peer.host) + ipAllowed = (ipHex & netfilter['mask']) == netfilter['ipAllowed'] & netfilter['mask'] + if ipAllowed: + break + if not ipAllowed: + raise Exception("host " + self.peer.host + " is not allowed!") # check authentication key if key is None: raise Exception("Authentication failed") # check permissions, array.index throws exception - for req in permissions: - WHITELIST.index(req) + if (permissions['permissions'] != None): + for req in permissions['permissions']: + WHITELIST.index(req); + # check allowed service creation, array.index throws exception + if (permissions['services'] != None): + for req in permissions['services']: + SERVICELIST.index(req); # create cloudeebus service instance self.cloudeebusService = CloudeebusService(permissions) # register it for RPC @@ -740,7 +744,11 @@ if __name__ == '__main__': parser.add_argument('-c', '--credentials', help='path to credentials file') parser.add_argument('-w', '--whitelist', - help='path to whitelist file') + help='path to whitelist file (DBus services to use)') + parser.add_argument('-s', '--servicelist', + help='path to servicelist file (DBus services to export)') + parser.add_argument('-n', '--netmask', + help='netmask,IP filter (comma separated.) eg. : -n 127.0.0.1,192.168.2.0/24,10.12.16.0/255.255.255.0') args = parser.parse_args(sys.argv[1:]) @@ -762,7 +770,24 @@ if __name__ == '__main__': jfile = open(args.whitelist) WHITELIST = json.load(jfile) jfile.close() - + + if args.servicelist: + jfile = open(args.servicelist) + SERVICELIST = json.load(jfile) + jfile.close() + + if args.netmask: + iplist = args.netmask.split(",") + for ip in iplist: + if ip.rfind("/") != -1: + ip=ip.split("/") + ipAllowed = ip[0] + mask = ip[1] + else: + ipAllowed = ip + mask = "255.255.255.255" + NETMASK.append( {'ipAllowed': ipV4ToHex(ipAllowed), 'mask' : ipV4ToHex(mask)} ) + uri = "ws://localhost:" + args.port factory = WampServerFactory(uri, debugWamp = args.debug)