Commit 98c0b06f authored by nextime's avatar nextime

Better managing for plugin and daemons web redirection

parent a99f376f
#!/usr/bin/python
import sys, os
import time
import libopenzwave
from libopenzwave import PyManager
"""
{'homeId': 23191651L, 'event': 0, 'valueId': {'index': 0, 'units': '', 'type': 'Bool', 'nodeId': 2, 'value': None, 'commandClass': 'COMMAND_CLASS_NO_OPERATION', 'instance': 1, 'readOnly': False, 'homeId': 23191651L, 'label': '', 'genre': 'Basic', 'id': 72057594071482368L}, 'notificationType': 'NodeEvent', 'nodeId': 2}
"""
def callback(res):
print '------------------------------'
print res
print '=============================='
if 'valueId' in res.keys():
if 'nodeId' in res['valueId'].keys():
#nid=res['valueId']['nodeId']
nid=res['nodeId']
hid=res['homeId']
ntype=res['notificationType']
print 'NOTIFICATION', ntype
print 'NODEID:', nid, 'NodeLocation:', manager.getNodeLocation(hid, nid)
print 'NODETYPE:', manager.getNodeType(hid, nid)
print 'NODENAME:', manager.getNodeName(hid, nid)
print 'NODEBASIC:', manager.getNodeBasic(hid, nid)
print 'NODEGENERIC:', manager.getNodeGeneric(hid, nid)
print 'NODESPECIFIC:', manager.getNodeSpecific(hid, nid)
print 'NODEMANUFACTURERNAME:', manager.getNodeManufacturerName(hid, nid)
print 'NODEPRODUCTNAME:', manager.getNodeProductName(hid, nid)
print '******************************'
options = libopenzwave.PyOptions()
#options.create("openzwave/","","--logging false")
options.create("openzwave/","","")
options.lock()
manager = libopenzwave.PyManager()
manager.create()
manager.addWatcher(callback)
manager.addDriver("/dev/ttyUSB0")
time.sleep(360000)
#!/usr/bin/python
import sys, os
import time
import libopenzwave
from libopenzwave import PyManager
from twisted.internet import epollreactor
epollreactor.install()
from twisted.internet import reactor
from dmlib.daemonizer import Daemonizer
import logging, time, sys, os
from logging import handlers as loghandlers
try:
import setproctitle
setproctitle.setproctitle('domotika_zwaved')
print 'Setting process title to', sys.argv[0]
except:
pass
log = logging.getLogger( 'ZWaved' )
#sys.path.append(os.path.abspath(os.path.dirname(sys.argv[0])+"/../../"))
"""
{'homeId': 23191651L, 'event': 0, 'valueId': {'index': 0, 'units': '', 'type': 'Bool', 'nodeId': 2, 'value': None, 'commandClass': 'COMMAND_CLASS_NO_OPERATION', 'instance': 1, 'readOnly': False, 'homeId': 23191651L, 'label': '', 'genre': 'Basic', 'id': 72057594071482368L}, 'notificationType': 'NodeEvent', 'nodeId': 2}
"""
class DMZWave(object):
def __init__(self):
self.options = libopenzwave.PyOptions()
#self.options.create("openzwave/","","--logging false")
self.options.create("openzwave/","","")
self.options.lock()
self.manager = libopenzwave.PyManager()
self.manager.create()
self.manager.addWatcher(self.callback)
self.manager.addDriver("/dev/ttyUSB0")
def callback(self, res):
print '------------------------------'
print res
print '=============================='
if 'valueId' in res.keys():
if 'nodeId' in res['valueId'].keys():
#nid=res['valueId']['nodeId']
nid=res['nodeId']
hid=res['homeId']
ntype=res['notificationType']
print 'NOTIFICATION', ntype
print 'NODEID:', nid, 'NodeLocation:', self.manager.getNodeLocation(hid, nid)
print 'NODETYPE:', self.manager.getNodeType(hid, nid)
print 'NODENAME:', self.manager.getNodeName(hid, nid)
print 'NODEBASIC:', self.manager.getNodeBasic(hid, nid)
print 'NODEGENERIC:', self.manager.getNodeGeneric(hid, nid)
print 'NODESPECIFIC:', self.manager.getNodeSpecific(hid, nid)
print 'NODEMANUFACTURERNAME:', self.manager.getNodeManufacturerName(hid, nid)
print 'NODEPRODUCTNAME:', self.manager.getNodeProductName(hid, nid)
print '******************************'
class ZWaved(Daemonizer):
def main_loop(self):
DMZWave()
reactor.run()
if __name__ == '__main__':
if len(sys.argv) > 1:
log.debug("Starting daemon with option "+sys.argv[1])
ZWaved().process_command_line(sys.argv)
else:
print 'Please specify start, stop or debug option'
...@@ -2201,9 +2201,6 @@ class domotikaService(service.Service): ...@@ -2201,9 +2201,6 @@ class domotikaService(service.Service):
def web_on_getAuth(self, usr, pwd): def web_on_getAuth(self, usr, pwd):
return dmdb.Users.find(where=["username='%s' AND passwd='%s' AND active=1" % ( usr, pwd)]) return dmdb.Users.find(where=["username='%s' AND passwd='%s' AND active=1" % ( usr, pwd)])
def web_on_pluginRequest(self, pname, ppath, pargs, pheaders):
return self.plugins.webRequest(pname, ppath, pargs, pheaders)
def web_on_getPermissionForPath(self, user, path): def web_on_getPermissionForPath(self, user, path):
return dmdb.getPermissionForPath(user, path) return dmdb.getPermissionForPath(user, path)
......
...@@ -321,10 +321,6 @@ class Loader(object): ...@@ -321,10 +321,6 @@ class Loader(object):
else: else:
log.debug("Plugin "+str(plugin)+" doesn't exists or not loaded") log.debug("Plugin "+str(plugin)+" doesn't exists or not loaded")
def webRequest(self, pname, ppath, pargs, pheaders):
self.push_request(pname, ['WEB', ppath, base64.b64encode(pargs), base64.b64encode(pheaders)])
return 'OK' # XXX vediamo di ritornare qualcosa di utile?
def loadPlugin(self, name): def loadPlugin(self, name):
if name in PLUGINREGISTRY.plugins.keys(): if name in PLUGINREGISTRY.plugins.keys():
log.debug("stopping plugin "+str(name)) log.debug("stopping plugin "+str(name))
......
...@@ -39,7 +39,7 @@ import logging ...@@ -39,7 +39,7 @@ import logging
log = logging.getLogger( 'Proxy' ) log = logging.getLogger( 'Proxy' )
class ApacheProxyClient(ProxyClient): class WebProxyClient(ProxyClient):
def handleHeader(self, key, value): def handleHeader(self, key, value):
if key.lower() == 'location': if key.lower() == 'location':
log.debug("Manage location header") log.debug("Manage location header")
...@@ -92,7 +92,7 @@ class ApacheProxyClient(ProxyClient): ...@@ -92,7 +92,7 @@ class ApacheProxyClient(ProxyClient):
resource.reactor.disconnect() resource.reactor.disconnect()
class ApacheProxyClientFactory(ProxyClientFactory): class WebProxyClientFactory(ProxyClientFactory):
def __init__(self, command, rest, version, headers, data, father, resource): def __init__(self, command, rest, version, headers, data, father, resource):
self.resource = resource self.resource = resource
ProxyClientFactory.__init__(self, ProxyClientFactory.__init__(self,
...@@ -104,7 +104,7 @@ class ApacheProxyClientFactory(ProxyClientFactory): ...@@ -104,7 +104,7 @@ class ApacheProxyClientFactory(ProxyClientFactory):
father=father) father=father)
def buildProtocol(self, addr): def buildProtocol(self, addr):
return ApacheProxyClient(command=self.command, return WebProxyClient(command=self.command,
rest=self.rest, rest=self.rest,
version=self.version, version=self.version,
headers=self.headers, headers=self.headers,
...@@ -119,19 +119,27 @@ def hostport(host, port, headerhost, defaultport=80): ...@@ -119,19 +119,27 @@ def hostport(host, port, headerhost, defaultport=80):
return '%s:%d' % (host, port) return '%s:%d' % (host, port)
class ApacheProxyResource(ReverseProxyResource): class WebProxyResource(ReverseProxyResource):
""" Just to permit future modifications """ """ Just to permit future modifications """
clientFactory = ApacheProxyClientFactory clientFactory = WebProxyClientFactory
remove = False
def __init__(self, *arg, **kwarg): def __init__(self, *arg, **kwarg):
log.debug("ApacheProxy called") log.debug("WebProxy called")
#try:
if True:
if 'remove' in kwarg.keys():
self.remove=int(kwarg['remove'])
del kwarg['remove']
#except:
# log.debug("error in remove")
return ReverseProxyResource.__init__(self, *arg, **kwarg) return ReverseProxyResource.__init__(self, *arg, **kwarg)
def getChild(self, path, request): def getChild(self, path, request):
log.debug("APACHE PROXY SEND HEADERS "+str(request.requestHeaders)) log.debug("APACHE PROXY SEND HEADERS "+str(request.requestHeaders))
#return ReverseProxyResource.getChild(self, path, request) #return ReverseProxyResource.getChild(self, path, request)
return ApacheProxyResource(self.host, self.port, self.path+'/'+urlquote(path, safe="")) return WebProxyResource(self.host, self.port, self.path+'/'+urlquote(path, safe=""), remove=self.remove)
def render(self, request): def render(self, request):
...@@ -159,6 +167,17 @@ class ApacheProxyResource(ReverseProxyResource): ...@@ -159,6 +167,17 @@ class ApacheProxyResource(ReverseProxyResource):
rest = self.path + '?' + qs rest = self.path + '?' + qs
else: else:
rest = self.path rest = self.path
if rest.startswith("//"):
rest=rest[1:]
if self.remove:
tmprest="/".join([x for x in rest.split("/") if x != ''][self.remove:])
if rest.endswith('/'):
tmprest+="/"
rest="/"+tmprest
log.debug("Proxying requesto to "+str(rest))
clientFactory = self.clientFactory(command=request.method, clientFactory = self.clientFactory(command=request.method,
rest=rest, rest=rest,
version=request.clientproto, version=request.clientproto,
......
...@@ -59,7 +59,7 @@ from twisted.internet import defer ...@@ -59,7 +59,7 @@ from twisted.internet import defer
from nevow import appserver from nevow import appserver
import time import time
import auth import auth
from dmlib.utils.genutils import configFile
import phpserialize import phpserialize
log = logging.getLogger( 'Webgui' ) log = logging.getLogger( 'Webgui' )
...@@ -129,24 +129,58 @@ class RootPage(rend.Page): ...@@ -129,24 +129,58 @@ class RootPage(rend.Page):
return session.sse return session.sse
return self.childFactory(ctx, 'sse') return self.childFactory(ctx, 'sse')
def child_plugin(self, ctx): def child_rawplugin(self, ctx):
request = inevow.IRequest(ctx) request = inevow.IRequest(ctx)
pl=request.path.split("/") pl=request.path.split("/")
if len(pl)>=2: if len(pl)>2:
pname=pl[2] pname=pl[2]
ppath="/".join(pl[3:]) pconf=os.path.normpath("/".join([curdir, 'plugins', pname, 'conf', pname+".conf" ]))
pargs=urllib.urlencode(request.args) log.debug("trying to read "+str(dconf))
pheaders="" if os.path.isfile(dconf):
for hk, hv in request.requestHeaders.getAllRawHeaders(): try:
for hvv in hv: pcfg=configFile(pconf)
pheaders=hk+"="+hvv+"\r\n" pcfg.readConfig()
if pheaders.endswith("\r\n"): port=int(pcfg.get('web','port'))
pheaders=pheaders[:-2] except:
ret = self.core.pluginRequest(pname, ppath, pargs, pheaders) port=False
r=codeOk() log.debug("Cannot read config file for plugin "+pname)
r.setContent(ret) if port:
return r self._sendProxySession(request, ctx)
return self.childFactory(ctx, 'plugin') log.debug("Proxying to plugin path "+str(request.path))
return proxy.WebProxyResource('localhost', port, path='/', remove=1)
else:
log.debug("Plugin hasn't a conf file to read")
else:
log.debug("no plugin name in request")
return self.childFactory(ctx, 'rawplugin')
def child_rawdaemon(self, ctx):
request = inevow.IRequest(ctx)
log.debug("Raw Daemon request for "+str(request.path))
pl=request.path.split("/")
if len(pl)>2:
dname=pl[2]
dconf=os.path.normpath("/".join([curdir, 'daemons', dname, 'conf', dname+".conf" ]))
log.debug("trying to read "+str(dconf))
if os.path.isfile(dconf):
try:
dcfg=configFile(dconf)
dcfg.readConfig()
port=int(dcfg.get('web','port'))
except:
port=False
log.debug("Cannot read config file for daemon "+dname)
if port:
self._sendProxySession(request, ctx)
log.debug("Proxying to daemon path "+str(request.path))
return proxy.WebProxyResource('localhost', port, path='/', remove=1)
else:
log.debug("Daemon hasn't a conf file to read")
else:
log.debug("no daemon name in request")
return self.childFactory(ctx, 'rawdaemon')
def child_mediaproxy(self, ctx): def child_mediaproxy(self, ctx):
if str(self.core.configGet('web', 'enablemediagui')).lower() in ['yes', '1', 'y','true']: if str(self.core.configGet('web', 'enablemediagui')).lower() in ['yes', '1', 'y','true']:
...@@ -248,7 +282,7 @@ class RootPage(rend.Page): ...@@ -248,7 +282,7 @@ class RootPage(rend.Page):
#log.info("Request: "+str(request)) #log.info("Request: "+str(request))
if host and host in self.core.configGet('proxy', 'localproxyhosts').split(','): if host and host in self.core.configGet('proxy', 'localproxyhosts').split(','):
self._sendProxySession(request, ctx) self._sendProxySession(request, ctx)
return proxy.ApacheProxyResource('localhost', int(self.core.configGet('proxy', 'localproxyport')), path='/') return proxy.WebProxyResource('localhost', int(self.core.configGet('proxy', 'localproxyport')), path='/')
else: else:
if self.logged: if self.logged:
if(len(self.perms.homepath)) > 0: if(len(self.perms.homepath)) > 0:
...@@ -266,12 +300,12 @@ class RootPage(rend.Page): ...@@ -266,12 +300,12 @@ class RootPage(rend.Page):
#log.info("childFactory2 "+str(request)) #log.info("childFactory2 "+str(request))
if name in self.core.configGet('proxy', 'localproxypaths').split(','): if name in self.core.configGet('proxy', 'localproxypaths').split(','):
self._sendProxySession(request, ctx) self._sendProxySession(request, ctx)
return proxy.ApacheProxyResource('localhost', 80, path='/'+name) return proxy.WebProxyResource('localhost', 80, path='/'+name)
host=request.getHeader('host') host=request.getHeader('host')
log.debug("HOST CALLED: "+str(host)) log.debug("HOST CALLED: "+str(host))
if host and host in self.core.configGet('proxy', 'localproxyhosts').split(','): if host and host in self.core.configGet('proxy', 'localproxyhosts').split(','):
self._sendProxySession(request, ctx) self._sendProxySession(request, ctx)
return proxy.ApacheProxyResource('localhost', 80, path='/'+name) return proxy.WebProxyResource('localhost', 80, path='/'+name)
log.debug("No child found (%s)" % name) log.debug("No child found (%s)" % name)
return permissionDenied() return permissionDenied()
...@@ -288,7 +322,7 @@ class SessionWrapper(guard.SessionWrapper): ...@@ -288,7 +322,7 @@ class SessionWrapper(guard.SessionWrapper):
log.debug("SessionWrapper HOST CALLED: "+str(host)) log.debug("SessionWrapper HOST CALLED: "+str(host))
if host and host in self.core.configGet('proxy', 'localproxyhostsnologin').split(','): if host and host in self.core.configGet('proxy', 'localproxyhostsnologin').split(','):
log.debug("Proxy Bypass Host in SessionWrapper renderHTTP "+host) log.debug("Proxy Bypass Host in SessionWrapper renderHTTP "+host)
return proxy.ApacheProxyResource('localhost', int(self.core.configGet('proxy', 'localproxyport')), path='/') return proxy.WebProxyResource('localhost', int(self.core.configGet('proxy', 'localproxyport')), path='/')
return guard.SessionWrapper.renderHTTP(self, ctx) return guard.SessionWrapper.renderHTTP(self, ctx)
...@@ -306,7 +340,7 @@ class SessionWrapper(guard.SessionWrapper): ...@@ -306,7 +340,7 @@ class SessionWrapper(guard.SessionWrapper):
for n in self.core.configGet('proxy', 'localproxypathsnologin').split(','): for n in self.core.configGet('proxy', 'localproxypathsnologin').split(','):
if n and name.startswith(n): if n and name.startswith(n):
log.info("Proxy Bypass localproxypathsnologin locateChild "+name) log.info("Proxy Bypass localproxypathsnologin locateChild "+name)
return (proxy.ApacheProxyResource('localhost', 80, path='/'+name), '') return (proxy.WebProxyResource('localhost', 80, path='/'+name), '')
for n in self.core.configGet('web', 'nologinpaths').split(','): for n in self.core.configGet('web', 'nologinpaths').split(','):
if n and name.startswith(n): if n and name.startswith(n):
if not ((name==n and n.endswith("/")) or (name[:-1]==n and name.endswith("/"))): if not ((name==n and n.endswith("/")) or (name[:-1]==n and name.endswith("/"))):
...@@ -317,7 +351,7 @@ class SessionWrapper(guard.SessionWrapper): ...@@ -317,7 +351,7 @@ class SessionWrapper(guard.SessionWrapper):
for n in self.core.configGet('proxy', 'localproxyhostsnologin').split(','): for n in self.core.configGet('proxy', 'localproxyhostsnologin').split(','):
if n and host==n: if n and host==n:
log.info("Proxy Bypass Host in SessionWrapper locateChild "+host) log.info("Proxy Bypass Host in SessionWrapper locateChild "+host)
return (proxy.ApacheProxyResource('localhost', 80, path='/'+name), '') return (proxy.WebProxyResource('localhost', 80, path='/'+name), '')
u = self.core.configGet('web', 'nologindefaultuser') u = self.core.configGet('web', 'nologindefaultuser')
p = self.core.configGet('web', 'nologindefaultpass') p = self.core.configGet('web', 'nologindefaultpass')
for n in self.core.configGet('web', 'nologinips').split(','): for n in self.core.configGet('web', 'nologinips').split(','):
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment