dbus service : removing the method cloudeebus.Service.add
[contrib/cloudeebus.git] / cloudeebus / cloudeebus.py
index 4024da9..4e046d7 100755 (executable)
@@ -18,6 +18,7 @@
 #
 # Luc Yriarte <luc.yriarte@intel.com>
 # Christophe Guiraud <christophe.guiraud@intel.com>
+# Frederic Paut <frederic.paut@intel.com>
 #
 
 
@@ -48,15 +49,39 @@ from twisted.python import log
 # XML parser module
 from xml.etree.ElementTree import XMLParser
 
-# For debug only
-import os
-
 ###############################################################################
 
-VERSION = "0.3.0"
+VERSION = "0.5.1"
 OPENDOOR = False
 CREDENTIALS = {}
 WHITELIST = []
+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:
@@ -253,6 +278,10 @@ class XmlCbParser: # The target object of the parser
 
 
        
+###############################################################################
+def createClassName(objectPath):
+    return re.sub('/', '_', objectPath[1:])
+
 ################################################################################       
 class DynDBusClass():
     def __init__(self, className, globalCtx, localCtx):
@@ -403,7 +432,9 @@ 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.proxyObjects = {}
         self.proxyMethods = {}
         self.pendingCalls = []
@@ -423,7 +454,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]
@@ -450,7 +481,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)
@@ -544,7 +575,13 @@ class CloudeebusService:
                'errorCB': async_error_cb}
         if methodId not in self.servicePendingCalls:
             self.servicePendingCalls[methodId] = {'count': 0, 'calls': []}
-        pendingCallStr = json.dumps({'callIndex': len(self.servicePendingCalls[methodId]['calls']), 'args': args})
+            
+        try:
+            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)
@@ -555,7 +592,7 @@ 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):            
             self.services[self.srvName] = dbus.service.BusName(name = self.srvName, bus = self.bus)
@@ -580,22 +617,10 @@ class CloudeebusService:
         '''
         self.agentObjectPath = list[0]
         xmlTemplate = list[1]
-        self.className = re.sub('/', '_', self.agentObjectPath[1:])
+        self.className = createClassName(self.agentObjectPath)
         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)
-
-            # For Debug only
-            if (1):
-                if (1): ## Force deletion
-                    if os.access('./MyDbusClass.py', os.R_OK) == True:
-                        os.remove('./MyDbusClass.py')
-                    
-                    if os.access('./MyDbusClass.py', os.R_OK) == False:
-                        f = open('./MyDbusClass.py', 'w')
-                        f.write(self.dynDBusClasses[self.className].class_code.exec_string)
-                        f.close()
-                        
             self.dynDBusClasses[self.className].declare()
 
         ## Class already exist, instanciate it if not already instanciated
@@ -611,7 +636,7 @@ class CloudeebusService:
         arguments: objectPath, xmlTemplate
         '''
         agentObjectPath = list[0]
-        className = re.sub('/', '_', agentObjectPath[1:])
+        className = createClassName(agentObjectPath)
 
         if (self.serviceAgents.has_key(className)):
             self.serviceAgents[self.className].remove_from_connection()
@@ -645,25 +670,35 @@ 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)}   
     
     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)
+            for req in permissions['permissions']:
+                    WHITELIST.index(req);
         # create cloudeebus service instance
         self.cloudeebusService = CloudeebusService(permissions)
         # register it for RPC
@@ -698,6 +733,8 @@ if __name__ == '__main__':
         help='path to credentials file')
     parser.add_argument('-w', '--whitelist',
         help='path to whitelist file')
+    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:])
 
@@ -719,6 +756,18 @@ if __name__ == '__main__':
         jfile = open(args.whitelist)
         WHITELIST = 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