a3b47e7442f35077bac4b907a062f65905256204
[contrib/cloudeebus.git] / cloudeebus / cloudeebus.py
1 #!/usr/bin/env python
2
3 # Cloudeebus
4 #
5 # Copyright 2012 Intel Corporation.
6 #
7 # Licensed under the Apache License, Version 2.0 (the "License");
8 # you may not use this file except in compliance with the License.
9 # You may obtain a copy of the License at
10 #
11 # http://www.apache.org/licenses/LICENSE-2.0
12 #
13 # Unless required by applicable law or agreed to in writing, software
14 # distributed under the License is distributed on an "AS IS" BASIS,
15 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 # See the License for the specific language governing permissions and
17 # limitations under the License.
18 #
19 # Luc Yriarte <luc.yriarte@intel.com>
20 # Christophe Guiraud <christophe.guiraud@intel.com>
21 # Frederic Paut <frederic.paut@intel.com>
22 #
23
24
25 import argparse, dbus, json, sys
26
27 from twisted.internet import glib2reactor
28 # Configure the twisted mainloop to be run inside the glib mainloop.
29 # This must be done before importing the other twisted modules
30 glib2reactor.install()
31 from twisted.internet import reactor, defer
32
33 from autobahn.websocket import listenWS
34 from autobahn.wamp import exportRpc, WampServerFactory, WampCraServerProtocol
35
36 from dbus.mainloop.glib import DBusGMainLoop
37
38 import gobject
39 import re
40 import dbus.service
41 gobject.threads_init()
42
43 from dbus import glib
44 glib.init_threads()
45
46 # enable debug log
47 from twisted.python import log
48
49 # XML parser module
50 from xml.etree.ElementTree import XMLParser
51
52 ###############################################################################
53
54 VERSION = "0.5.99"
55 OPENDOOR = False
56 CREDENTIALS = {}
57 WHITELIST = []
58 SERVICELIST = []
59 NETMASK =  []
60
61 ###############################################################################
62 def ipV4ToHex(mask):
63     ## Convert an ip or an IP mask (such as ip/24 or ip/255.255.255.0) in hex value (32bits)
64     maskHex = 0
65     byte = 0
66     if mask.rfind(".") == -1:
67         if (int(mask) < 32):
68             maskHex = (2**(int(mask))-1)
69             maskHex = maskHex << (32-int(mask))
70         else:
71             raise Exception("Illegal mask (larger than 32 bits) " + mask)
72     else:
73         maskField = mask.split(".")
74         # Check if mask has four fields (byte)
75         if len(maskField) != 4:
76             raise Exception("Illegal ip address / mask (should be 4 bytes) " + mask)
77         for maskQuartet in maskField:
78             byte = int(maskQuartet)
79             # Check if each field is really a byte
80             if byte > 255:
81                 raise Exception("Illegal ip address / mask (digit larger than a byte) " + mask)              
82             maskHex += byte
83             maskHex = maskHex << 8
84         maskHex = maskHex >> 8
85     return maskHex
86
87 ###############################################################################
88 class DbusCache:
89     '''
90     Global cache of DBus connexions and signal handlers
91     '''
92     def __init__(self):
93         self.dbusConnexions = {}
94         self.signalHandlers = {}
95
96
97     def reset(self):
98         '''
99         Disconnect signal handlers before resetting cache.
100         '''
101         self.dbusConnexions = {}
102         # disconnect signal handlers
103         for key in self.signalHandlers:
104             self.signalHandlers[key].disconnect()
105         self.signalHandlers = {}
106
107
108     def dbusConnexion(self, busName):
109         if not self.dbusConnexions.has_key(busName):
110             if busName == "session":
111                 self.dbusConnexions[busName] = dbus.SessionBus()
112             elif busName == "system":
113                 self.dbusConnexions[busName] = dbus.SystemBus()
114             else:
115                 raise Exception("Error: invalid bus: %s" % busName)
116         return self.dbusConnexions[busName]
117
118
119
120 ###############################################################################
121 class DbusSignalHandler:
122     '''
123     signal hash id as busName#senderName#objectName#interfaceName#signalName
124     '''
125     def __init__(self, busName, senderName, objectName, interfaceName, signalName):
126         self.id = "#".join([busName, senderName, objectName, interfaceName, signalName])
127         # connect handler to signal
128         self.bus = cache.dbusConnexion(busName)
129         self.bus.add_signal_receiver(self.handleSignal, signalName, interfaceName, senderName, objectName)
130         
131     
132     def disconnect(self):
133         names = self.id.split("#")
134         self.bus.remove_signal_receiver(self.handleSignal, names[4], names[3], names[1], names[2])
135
136
137     def handleSignal(self, *args):
138         '''
139         publish dbus args under topic hash id
140         '''
141         factory.dispatch(self.id, json.dumps(args))
142
143
144
145 ###############################################################################
146 class DbusCallHandler:
147     '''
148     deferred reply to return dbus results
149     '''
150     def __init__(self, method, args):
151         self.pending = False
152         self.request = defer.Deferred()
153         self.method = method
154         self.args = args
155
156
157     def callMethod(self):
158         '''
159         dbus method async call
160         '''
161         self.pending = True
162         self.method(*self.args, reply_handler=self.dbusSuccess, error_handler=self.dbusError)
163         return self.request
164
165
166     def dbusSuccess(self, *result):
167         '''
168         return JSON string result array
169         '''
170         self.request.callback(json.dumps(result))
171         self.pending = False
172
173
174     def dbusError(self, error):
175         '''
176         return dbus error message
177         '''
178         self.request.errback(Exception(error.get_dbus_message()))
179         self.pending = False
180
181
182
183 ################################################################################       
184 class ExecCode:
185     '''
186     Execute DynDBusClass generated code
187     '''
188     def __init__(self, globalCtx, localCtx) :
189         self.exec_string = ""
190         self.exec_code = None
191         self.exec_code_valid = 1
192         self.indent_level = 0
193         self.indent_increment = 1
194         self.line = 0
195         self.localCtx = localCtx
196         self.globalCtx = globalCtx
197         
198
199     def append_stmt(self, stmt) :
200         self.exec_code_valid = 0
201         self.line += 1
202         for x in range(0,self.indent_level):
203             self.exec_string = self.exec_string + ' '            
204         self.exec_string = self.exec_string + stmt + '\n'
205
206     def indent(self) :
207         self.indent_level = self.indent_level + self.indent_increment
208
209     def dedent(self) :
210         self.indent_level = self.indent_level - self.indent_increment
211     
212     # compile : Compile exec_string into exec_code using the builtin
213     # compile function. Skip if already in sync.
214     def compile(self) :
215         if not self.exec_code_valid :
216             self.exec_code = compile(self.exec_string, "<string>", "exec")
217         self.exec_code_valid = True
218
219     def execute(self) :
220         if not self.exec_code_valid :
221             self.compile()
222         exec(self.exec_code, self.globalCtx, self.localCtx)
223
224
225
226 ################################################################################       
227 class XmlCbParser: # The target object of the parser
228     maxDepth = 0
229     depth = 0
230     def __init__(self, dynDBusClass):
231         self.dynDBusClass = dynDBusClass
232         
233     def start(self, tag, attrib):   # Called for each opening tag.
234         if (tag == 'node'):
235             return
236         # Set interface name
237         if (tag == 'interface'):
238             self.dynDBusClass.set_interface(attrib['name'])
239             return
240         # Set method name
241         if (tag == 'method'):
242             self.current = tag
243             self.dynDBusClass.def_method(attrib['name'])
244             return
245         if (tag == 'signal'):
246             self.current = tag
247             self.dynDBusClass.def_signal(attrib['name'])
248             return
249
250         # Set signature (in/out & name) for method
251         if (tag == 'arg'):
252             if (self.current == 'method'):
253                 if (attrib.has_key('direction') == False):
254                     attrib['direction'] = "in"
255                 self.dynDBusClass.add_signature(attrib['name'],
256                                                 attrib['direction'],
257                                                 attrib['type'])
258                 return
259             if (self.current == 'signal'):
260                 if (attrib.has_key('name') == False):
261                     attrib['name'] = 'value'
262                 self.dynDBusClass.add_signature(attrib['name'], 'in',
263                                                 attrib['type'])
264                 return
265     def end(self, tag):             # Called for each closing tag.
266         if (tag == 'method'):
267             self.dynDBusClass.add_dbus_method()
268             self.dynDBusClass.add_body_method()
269             self.dynDBusClass.end_method()
270         if (tag == 'signal'):
271             self.dynDBusClass.add_dbus_signal()
272             self.dynDBusClass.add_body_signal()
273             self.dynDBusClass.end_method()
274            
275     def data(self, data):
276         pass            # We do not need to do anything with data.
277     def close(self):    # Called when all data has been parsed.
278         return self.maxDepth
279
280
281        
282 ###############################################################################
283 def createClassName(objectPath):
284     return re.sub('/', '_', objectPath[1:])
285
286 ################################################################################       
287 class DynDBusClass():
288     def __init__(self, className, globalCtx, localCtx):
289         self.className = className
290         self.xmlCB = XmlCbParser(self)
291         self.signature = {}
292         self.class_code = ExecCode(globalCtx, localCtx)  
293         self.class_code.indent_increment = 4
294         self.class_code.append_stmt("import dbus")
295         self.class_code.append_stmt("\n")
296         self.class_code.append_stmt("class " + self.className + "(dbus.service.Object):")
297         self.class_code.indent()
298         
299         ## Overload of __init__ method 
300         self.def_method("__init__")
301         self.add_method("bus, callback=None, objPath='/sample', busName='org.cloudeebus'")
302         self.add_stmt("self.bus = bus")
303         self.add_stmt("self.objPath = objPath")
304         self.add_stmt("self.callback = callback")        
305         self.add_stmt("dbus.service.Object.__init__(self, conn=bus, bus_name=busName)")
306         self.end_method()
307                
308         ## Create 'add_to_connection' method 
309         self.def_method("add_to_connection")
310         self.add_method("connection=None, path=None")
311         self.add_stmt("dbus.service.Object.add_to_connection(self, connection=self.bus, path=self.objPath)")
312         self.end_method()
313                
314         ## Create 'remove_from_connection' method 
315         self.def_method("remove_from_connection")
316         self.add_method("connection=None, path=None")
317         self.add_stmt("dbus.service.Object.remove_from_connection(self, connection=None, path=self.objPath)")
318         self.end_method()
319                
320     def createDBusServiceFromXML(self, xml):
321         self.parser = XMLParser(target=self.xmlCB)
322         self.parser.feed(xml)
323         self.parser.close()
324     
325     def set_interface(self, ifName):
326         self.ifName = ifName
327         
328     def def_method(self, methodName):
329         self.methodToAdd = methodName
330         self.signalToAdd = None
331         self.args_str = str()
332         self.signature = {}
333         self.signature['name'] = str()
334         self.signature['in'] = str()                
335         self.signature['out'] = str()                        
336
337     def def_signal(self, signalName):
338         self.methodToAdd = None
339         self.signalToAdd = signalName
340         self.args_str = str()
341         self.signature = {}
342         self.signature['name'] = str()
343         self.signature['in'] = str()                
344         self.signature['out'] = str()                        
345
346     def add_signature(self, name, direction, signature):
347         if (direction == 'in'):
348             self.signature['in'] += signature
349             if (self.signature['name'] != str()):
350                 self.signature['name'] += ", "
351             self.signature['name'] += name
352         if (direction == 'out'):
353             self.signature['out'] = signature                        
354         
355     def add_method(self, args = None, async_success_cb = None, async_err_cb = None):
356         async_cb_str = str()
357         if (self.methodToAdd != None):
358             name = self.methodToAdd
359         else:
360             name = self.signalToAdd
361         if (args != None):
362             self.args_str = args
363         if (async_success_cb != None):
364             async_cb_str = async_success_cb
365         if (async_err_cb != None):
366             if (async_cb_str != str()):
367                 async_cb_str += ", "
368             async_cb_str += async_err_cb
369                         
370         parameters = self.args_str
371         if (async_cb_str != str()):
372             if (parameters != str()):
373                 parameters += ", "
374             parameters +=async_cb_str       
375         
376         if (parameters != str()):
377             self.class_code.append_stmt("def " + name + "(self, %s):" % parameters)               
378         else:
379             self.class_code.append_stmt("def " + name + "(self):")
380         self.class_code.indent()
381         
382     def end_method(self):
383         self.class_code.append_stmt("\n")
384         self.class_code.dedent()
385         
386     def add_dbus_method(self):
387         decorator = '@dbus.service.method("' + self.ifName + '"'
388         if (self.signature.has_key('in') and self.signature['in'] != str()):
389                 decorator += ", in_signature='" + self.signature['in'] + "'"
390         if (self.signature.has_key('out') and self.signature['out'] != str()):
391                 decorator += ", out_signature='" + self.signature['out'] + "'"
392         decorator += ", async_callbacks=('dbus_async_cb', 'dbus_async_err_cb')"            
393         decorator += ")"
394         self.class_code.append_stmt(decorator)
395         if (self.signature.has_key('name') and self.signature['name'] != str()):
396             self.add_method(self.signature['name'], async_success_cb='dbus_async_cb', async_err_cb='dbus_async_err_cb')
397         else:
398             self.add_method(async_success_cb='dbus_async_cb', async_err_cb='dbus_async_err_cb')
399
400     def add_dbus_signal(self):
401         decorator = '@dbus.service.signal("' + self.ifName + '"'
402         if (self.signature.has_key('in') and self.signature['in'] != str()):
403                 decorator += ", signature='" + self.signature['in'] + "'"
404         decorator += ")"            
405         self.class_code.append_stmt(decorator)
406         if (self.signature.has_key('name') and self.signature['name'] != str()):
407             self.add_method(self.signature['name'])
408         else:
409             self.add_method()
410
411     def add_body_method(self):
412         if (self.methodToAdd != None):
413             if (self.args_str != str()):
414                 self.class_code.append_stmt("self.callback('" + self.methodToAdd + "', self.objPath, '"  + self.ifName + "', " + "dbus_async_cb, dbus_async_err_cb, %s)" % self.args_str)
415             else:        
416                 self.class_code.append_stmt("self.callback('" + self.methodToAdd + "', self.objPath, '"  + self.ifName + "', " + "dbus_async_cb, dbus_async_err_cb)")
417
418     def add_body_signal(self):
419         self.class_code.append_stmt("return") ## TODO: Remove and fix with code ad hoc
420         self.class_code.append_stmt("\n")
421
422     def add_stmt(self, stmt) :
423         self.class_code.append_stmt(stmt)
424         
425     def declare(self) :
426         self.class_code.execute()
427
428
429
430 ###############################################################################
431 class CloudeebusService:
432     '''
433     support for sending DBus messages and registering for DBus signals
434     '''
435     def __init__(self, permissions):
436         self.permissions = {};
437         self.permissions['permissions'] = permissions['permissions']
438         self.permissions['authextra'] = permissions['authextra']
439         self.permissions['services'] = permissions['services']
440         self.proxyObjects = {}
441         self.proxyMethods = {}
442         self.pendingCalls = []
443         self.dynDBusClasses = {} # DBus class source code generated dynamically (a list because one by classname)
444         self.services = {}  # DBus service created
445         self.serviceAgents = {} # Instantiated DBus class previously generated dynamically, for now, one by classname
446         self.servicePendingCalls = {} # JS methods called (and waiting for a Success/error response), containing 'methodId', (successCB, errorCB)
447         self.localCtx = locals()
448         self.globalCtx = globals()
449
450
451     def proxyObject(self, busName, serviceName, objectName):
452         '''
453         object hash id as busName#serviceName#objectName
454         '''
455         id = "#".join([busName, serviceName, objectName])
456         if not self.proxyObjects.has_key(id):
457             if not OPENDOOR:
458                 # check permissions, array.index throws exception
459                 self.permissions['permissions'].index(serviceName)
460             bus = cache.dbusConnexion(busName)
461             self.proxyObjects[id] = bus.get_object(serviceName, objectName)
462         return self.proxyObjects[id]
463
464
465     def proxyMethod(self, busName, serviceName, objectName, interfaceName, methodName):
466         '''
467         method hash id as busName#serviceName#objectName#interfaceName#methodName
468         '''
469         id = "#".join([busName, serviceName, objectName, interfaceName, methodName])
470         if not self.proxyMethods.has_key(id):
471             obj = self.proxyObject(busName, serviceName, objectName)
472             self.proxyMethods[id] = obj.get_dbus_method(methodName, interfaceName)
473         return self.proxyMethods[id]
474
475
476     @exportRpc
477     def dbusRegister(self, list):
478         '''
479         arguments: bus, sender, object, interface, signal
480         '''
481         if len(list) < 5:
482             raise Exception("Error: expected arguments: bus, sender, object, interface, signal)")
483         
484         if not OPENDOOR:
485             # check permissions, array.index throws exception
486             self.permissions['permissions'].index(list[1])
487         
488         # check if a handler exists
489         sigId = "#".join(list)
490         if cache.signalHandlers.has_key(sigId):
491             return sigId
492         
493         # create a handler that will publish the signal
494         dbusSignalHandler = DbusSignalHandler(*list)
495         cache.signalHandlers[sigId] = dbusSignalHandler
496         
497         return dbusSignalHandler.id
498
499
500     @exportRpc
501     def dbusSend(self, list):
502         '''
503         arguments: bus, destination, object, interface, message, [args]
504         '''
505         # clear pending calls
506         for call in self.pendingCalls:
507             if not call.pending:
508                 self.pendingCalls.remove(call)
509         
510         if len(list) < 5:
511             raise Exception("Error: expected arguments: bus, destination, object, interface, message, [args])")
512         
513         # parse JSON arg list
514         args = []
515         if len(list) == 6:
516             args = json.loads(list[5])
517         
518         # get dbus proxy method
519         method = self.proxyMethod(*list[0:5])
520         
521         # use a deferred call handler to manage dbus results
522         dbusCallHandler = DbusCallHandler(method, args)
523         self.pendingCalls.append(dbusCallHandler)
524         return dbusCallHandler.callMethod()
525
526
527     @exportRpc
528     def emitSignal(self, list):
529         '''
530         arguments: agentObjectPath, signalName, result (to emit)
531         '''
532         objectPath = list[0]
533         className = re.sub('/', '_', objectPath[1:])
534         signalName = list[1]
535         result = list[2]
536         if (self.serviceAgents.has_key(className) == True):
537             exe_str = "self.serviceAgents['"+ className +"']."+ signalName + "(" + str(result) + ")"
538             eval(exe_str, self.globalCtx, self.localCtx)
539         else:
540             raise Exception("No object path " + objectPath)
541
542     @exportRpc
543     def returnMethod(self, list):
544         '''
545         arguments: methodId, callIndex, success (=true, error otherwise), result (to return)
546         '''
547         methodId = list[0]
548         callIndex = list[1]
549         success = list[2]
550         result = list[3]
551         if (self.servicePendingCalls.has_key(methodId)):
552             cb = self.servicePendingCalls[methodId]['calls'][callIndex]
553             if cb is None:
554                 raise Exception("No pending call " + str(callIndex) + " for methodID " + methodId)
555             if (success):                
556                 successCB = cb["successCB"]
557                 if (result != None):
558                     successCB(result)
559                 else:
560                     successCB()                    
561             else:     
562                 errorCB = cb["errorCB"]        
563                 if (result != None):
564                     errorCB(result)
565                 else:
566                     errorCB()
567             self.servicePendingCalls[methodId]['calls'][callIndex] = None
568             self.servicePendingCalls[methodId]['count'] = self.servicePendingCalls[methodId]['count'] - 1
569             if self.servicePendingCalls[methodId]['count'] == 0:
570                 del self.servicePendingCalls[methodId]
571         else:
572             raise Exception("No methodID " + methodId)
573
574     def srvCB(self, name, objPath, ifName, async_succes_cb, async_error_cb, *args):
575         methodId = self.srvName + "#" + objPath + "#" + ifName + "#" + name
576         cb = { 'successCB': async_succes_cb, 
577                'errorCB': async_error_cb}
578         if methodId not in self.servicePendingCalls:
579             self.servicePendingCalls[methodId] = {'count': 0, 'calls': []}
580             
581         try:
582             pendingCallStr = json.dumps({'callIndex': len(self.servicePendingCalls[methodId]['calls']), 'args': args})
583         except Exception, e:                
584             args = eval( str(args).replace("dbus.Byte", "dbus.Int16") )
585             pendingCallStr = json.dumps({'callIndex': len(self.servicePendingCalls[methodId]['calls']), 'args': args})
586                
587         self.servicePendingCalls[methodId]['calls'].append(cb)
588         self.servicePendingCalls[methodId]['count'] = self.servicePendingCalls[methodId]['count'] + 1
589         factory.dispatch(methodId, pendingCallStr)
590                     
591     @exportRpc
592     def serviceAdd(self, list):
593         '''
594         arguments: busName, srvName
595         '''
596         busName = list[0]
597         self.bus =  cache.dbusConnexion( busName )
598         self.srvName = list[1]
599         if not OPENDOOR and (SERVICELIST == [] or SERVICELIST != [] and self.permissions['services'] == None):
600             SERVICELIST.index(self.srvName)
601             
602         if (self.services.has_key(self.srvName) == False):
603             self.services[self.srvName] = dbus.service.BusName(name = self.srvName, bus = self.bus)
604         return self.srvName
605
606     @exportRpc
607     def serviceRelease(self, list):
608         '''
609         arguments: busName, srvName
610         '''
611         self.srvName = list[0]
612         if (self.services.has_key(self.srvName) == True):
613             self.services.pop(self.srvName)
614             return self.srvName
615         else:
616             raise Exception(self.srvName + " does not exist")
617                    
618     @exportRpc
619     def serviceAddAgent(self, list):
620         '''
621         arguments: objectPath, xmlTemplate
622         '''
623         self.agentObjectPath = list[0]
624         xmlTemplate = list[1]
625         self.className = createClassName(self.agentObjectPath)
626         if (self.dynDBusClasses.has_key(self.className) == False):
627             self.dynDBusClasses[self.className] = DynDBusClass(self.className, self.globalCtx, self.localCtx)
628             self.dynDBusClasses[self.className].createDBusServiceFromXML(xmlTemplate)
629             self.dynDBusClasses[self.className].declare()
630
631         ## Class already exist, instanciate it if not already instanciated
632         if (self.serviceAgents.has_key(self.className) == False):
633             self.serviceAgents[self.className] = eval(self.className + "(self.bus, callback=self.srvCB, objPath=self.agentObjectPath, busName=self.srvName)", self.globalCtx, self.localCtx)
634             
635         self.serviceAgents[self.className].add_to_connection()
636         return (self.agentObjectPath)
637                     
638     @exportRpc
639     def serviceDelAgent(self, list):
640         '''
641         arguments: objectPath, xmlTemplate
642         '''
643         agentObjectPath = list[0]
644         className = createClassName(agentObjectPath)
645
646         if (self.serviceAgents.has_key(className)):
647             self.serviceAgents[self.className].remove_from_connection()
648             self.serviceAgents.pop(self.className)
649         else:
650             raise Exception(agentObjectPath + " doesn't exist!")
651         
652         return (agentObjectPath)
653                     
654     @exportRpc
655     def getVersion(self):
656         '''
657         return current version string
658         '''
659         return VERSION
660
661
662
663 ###############################################################################
664 class CloudeebusServerProtocol(WampCraServerProtocol):
665     '''
666     connexion and session authentication management
667     '''
668     
669     def onSessionOpen(self):
670         # CRA authentication options
671         self.clientAuthTimeout = 0
672         self.clientAuthAllowAnonymous = OPENDOOR
673         # CRA authentication init
674         WampCraServerProtocol.onSessionOpen(self)
675     
676     
677     def getAuthPermissions(self, key, extra):
678          return {'permissions': extra.get("permissions", None),
679                  'authextra': extra.get("authextra", None),
680                  'services': extra.get("services", None)}   
681     
682     def getAuthSecret(self, key):
683         secret = CREDENTIALS.get(key, None)
684         if secret is None:
685             return None
686         # secret must be of str type to be hashed
687         return str(secret)
688     
689
690     def onAuthenticated(self, key, permissions):
691         if not OPENDOOR:
692             # check net filter
693             if NETMASK != []:
694                 ipAllowed = False
695                 for netfilter in NETMASK:
696                     ipHex=ipV4ToHex(self.peer.host)
697                     ipAllowed = (ipHex & netfilter['mask']) == netfilter['ipAllowed'] & netfilter['mask']
698                     if ipAllowed:
699                         break
700                 if not ipAllowed:
701                     raise Exception("host " + self.peer.host + " is not allowed!")
702             # check authentication key
703             if key is None:
704                 raise Exception("Authentication failed")
705             # check permissions, array.index throws exception
706             if (permissions['permissions'] != None):
707                 for req in permissions['permissions']:
708                     WHITELIST.index(req);
709             # check allowed service creation, array.index throws exception
710             if (permissions['services'] != None):
711                 for req in permissions['services']:
712                     SERVICELIST.index(req);
713         # create cloudeebus service instance
714         self.cloudeebusService = CloudeebusService(permissions)
715         # register it for RPC
716         self.registerForRpc(self.cloudeebusService)
717         # register for Publish / Subscribe
718         self.registerForPubSub("", True)
719     
720     
721     def connectionLost(self, reason):
722         WampCraServerProtocol.connectionLost(self, reason)
723         if factory.getConnectionCount() == 0:
724             cache.reset()
725
726
727
728 ###############################################################################
729
730 if __name__ == '__main__':
731     
732     cache = DbusCache()
733
734     parser = argparse.ArgumentParser(description='Javascript DBus bridge.')
735     parser.add_argument('-v', '--version', action='store_true', 
736         help='print version and exit')
737     parser.add_argument('-d', '--debug', action='store_true', 
738         help='log debug info on standard output')
739     parser.add_argument('-o', '--opendoor', action='store_true',
740         help='allow anonymous access to all services')
741     parser.add_argument('-p', '--port', default='9000',
742         help='port number')
743     parser.add_argument('-c', '--credentials',
744         help='path to credentials file')
745     parser.add_argument('-w', '--whitelist',
746         help='path to whitelist file (DBus services to use)')
747     parser.add_argument('-s', '--servicelist',
748         help='path to servicelist file (DBus services to export)')
749     parser.add_argument('-n', '--netmask',
750         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')
751     
752     args = parser.parse_args(sys.argv[1:])
753
754     if args.version:
755         print("Cloudeebus version " + VERSION)
756         exit(0)
757     
758     if args.debug:
759         log.startLogging(sys.stdout)
760     
761     OPENDOOR = args.opendoor
762     
763     if args.credentials:
764         jfile = open(args.credentials)
765         CREDENTIALS = json.load(jfile)
766         jfile.close()
767     
768     if args.whitelist:
769         jfile = open(args.whitelist)
770         WHITELIST = json.load(jfile)
771         jfile.close()
772         
773     if args.servicelist:
774         jfile = open(args.servicelist)
775         SERVICELIST = json.load(jfile)
776         jfile.close()
777         
778     if args.netmask:
779         iplist = args.netmask.split(",")
780         for ip in iplist:
781             if ip.rfind("/") != -1:
782                 ip=ip.split("/")
783                 ipAllowed = ip[0]
784                 mask = ip[1]
785             else:
786                 ipAllowed = ip
787                 mask = "255.255.255.255" 
788             NETMASK.append( {'ipAllowed': ipV4ToHex(ipAllowed), 'mask' : ipV4ToHex(mask)} )
789     
790     if args.debug:
791         print "OPENDOOR='" + str(OPENDOOR) + "'" 
792         print "CREDENTIALS='" + str(args.credentials) + "'" 
793         print "WHITELIST='" + str(args.whitelist) + "'"
794         print "SERVICELIST='" + str(args.servicelist) + "'" 
795         print "NETMASK='" + str(args.netmask) + "'"
796         print 
797         
798     uri = "ws://localhost:" + args.port
799     
800     factory = WampServerFactory(uri, debugWamp = args.debug)
801     factory.protocol = CloudeebusServerProtocol
802     factory.setProtocolOptions(allowHixie76 = True)
803     
804     listenWS(factory)
805     
806     DBusGMainLoop(set_as_default=True)
807     
808     reactor.run()