Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

NMControl 0.8

Split plugins between plugins and services
New service "DNS"
plugin NamespaceDomain now use the DNS service
  • Loading branch information...
commit 0abd8a32de6b48ac665cc2c2347f7ddf10e6d0b1 1 parent fe6fe21
@khalahan khalahan authored
View
3  doc/TODO.md
@@ -2,6 +2,8 @@ TODO
====
Remarks/TODO :
+- need to clean old code + dns server code (remove endswith from lib/dnsServer/namecoindns.py, etc)
+- finish the split between the DNS service and namespaces plugins
* plugins
- DATA: allow to start and stop namecoin to do full updates
- DATA: fetch data only for used namespaces
@@ -12,3 +14,4 @@ Remarks/TODO :
- tested only on linux => need to be adapted for windows & mac too
- need a gui
+
View
6 lib/backendDataFile.py
@@ -1,15 +1,15 @@
+from common import *
import os, json
class backendData():
- def __init__(self, app, filename):
- self.app = app
+ def __init__(self, filename):
self.datafile = filename
def getAllNames(self):
if not os.path.exists(self.datafile):
return True, 'Config file "' + self.datafile + '" doesn\'t exist.'
- data = open(self.app['path']['app'] + self.datafile).read()
+ data = open(app['path']['app'] + self.datafile).read()
try:
data = json.loads(data)
except:
View
8 lib/backendDataNamecoin.py
@@ -1,9 +1,9 @@
+from common import *
import rpcClient
import ConfigParser, StringIO
class backendData():
- def __init__(self, app, conf):
- self.app = app
+ def __init__(self, conf):
self.conf = conf
rpc = None
@@ -32,7 +32,7 @@ def _loadRPCConfig(self):
def getAllNames(self):
datas = {}
- error, data = self._rpcSend(["name_filter", self.app['plugins']['data'].conf['name_filter']])
+ error, data = self._rpcSend(["name_filter", app['plugins']['data'].conf['name_filter']])
for name in data:
datas[name['name']] = name
return error, datas
@@ -41,7 +41,7 @@ def getName(self, name):
return self._rpcSend(["name_show", name])
def _rpcSend(self, rpcCmd):
- if self.app['debug']: print "BackendDataNamecoin:", rpcCmd
+ if app['debug']: print "BackendDataNamecoin:", rpcCmd
if self.rpc is None:
self._loadRPCConfig()
return self.rpc.sendJson(rpcCmd)
View
3  lib/common.py
@@ -0,0 +1,3 @@
+
+app = {}
+
View
20 lib/dnsServer/__init__.py
@@ -23,7 +23,7 @@
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
-# Modified by Khalahan in order ti include it in nmcontrol
+# Modified by Khalahan in order to include it in nmcontrol
# Modified by sonicrules1234 (Westly Ward) in order to have it work as a dns server for all domains rather than just one
# File originally named pymds
import sys
@@ -36,6 +36,7 @@
import threading
from utils import *
+from common import *
class DnsError(Exception):
pass
@@ -43,12 +44,7 @@ class DnsError(Exception):
class DnsServer(threading.Thread):
daemon = True;
running = True
- app = None
udps = None
-
- def __init__(self, app):
- self.app = app
- threading.Thread.__init__(self)
def run(self):
self.serve()
@@ -57,8 +53,8 @@ def serve(self):
self.udps = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.udps.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
udps = self.udps
- listen_host = self.app['plugins']['dns'].conf['host']
- listen_port = int(self.app['plugins']['dns'].conf['port'])
+ listen_host = app['services']['dns'].conf['host']
+ listen_port = int(app['services']['dns'].conf['port'])
try:
udps.bind((listen_host, listen_port))
except socket.error as e:
@@ -83,7 +79,7 @@ def serve(self):
question = map(lambda x: x.lower(), question)
found = False
source_module = __import__("namecoindns", globals(), locals(), [])
- source_instance = source_module.Source(self.app)
+ source_instance = source_module.Source()
for config in [True]:
#if question[1:] == config['domain']:
#query = question[0]
@@ -106,7 +102,7 @@ def serve(self):
exception_rcode = 3
raise Exception("query is not for our domain: %s" % ".".join(question))
except:
- if self.app['debug']: traceback.print_exc()
+ if app['debug']: traceback.print_exc()
if not self.running:
continue
if qid:
@@ -253,8 +249,8 @@ def format_resource(resource, question):
# die("Usage: %s\n" % (cmd))
#config_files = {}
-listen_port = 1053
-listen_host = ''
+#listen_port = 1053
+#listen_host = ''
#try:
# options, filenames = getopt.getopt(sys.argv[1:], "p:h:")
View
3  lib/dnsServer/listdns.py
@@ -1,5 +1,6 @@
import DNS
import json, base64, types, traceback
+from common import *
def lookup(sp, qdict) :
domain = qdict["domain"]
@@ -15,7 +16,7 @@ def lookup(sp, qdict) :
try:
item = json.loads(item)
except:
- if self.app['debug']: traceback.print_exc()
+ if app['debug']: traceback.print_exc()
return
if str(item[u"name"]) == "d/" + host :
View
21 lib/dnsServer/namecoindns.py
@@ -6,11 +6,12 @@
import struct, listdns, base64, types, json, random
#from jsonrpc import ServiceProxy
from utils import *
+from common import *
class Source(object):
- def __init__(self, app):
- self.servers = app['plugins']['dns'].conf['resolver'].split(',')
- self.reqobj = DNS.Request()
+ #def __init__(self):
+ #self.servers = app['services']['dns'].conf['resolver'].split(',')
+ #self.reqobj = DNS.Request()
#jsonfile = open("config.json", "r")
#data = json.loads(jsonfile.read())
#jsonfile.close()
@@ -19,7 +20,7 @@ def __init__(self, app):
#password = str(data[u"password"])
#self.sp = ServiceProxy("http://%(user)s:%(passwd)s@127.0.0.1:%(port)d" % dict(user=username, passwd=password, port=port))
#elf.sp = rpcClient.rpcClientNamecoin('127.0.0.1', port, username, password)
- self.sp = app['plugins']['domain']
+ #self.sp = app['plugins']['domain']
# def _parse_file(self):
# f = open(self._filename, "r")
@@ -93,9 +94,13 @@ def get_response(self, query, domain, qtype, qclass, src_addr):
#answer = struct.pack("!I", ipstr2int(value))
reqtype = "AAAA"
else : reqtype = None
- if domain.endswith(".bit") :
+ answers = app['services']['dns'].lookup({"query":query, "domain":domain, "qtype":qtype, "qclass":qclass, "src_addr":src_addr})
+ #print 'domain:', domain
+ #print 'answers:', answers
+ if domain.endswith(".bit") or domain.endswith(".tor") :
#response = listdns.lookup(self.sp, {"query":query, "domain":domain, "qtype":qtype, "qclass":qclass, "src_addr":src_addr})
- response = self.sp.lookup({"query":query, "domain":domain, "qtype":qtype, "qclass":qclass, "src_addr":src_addr})
+ #response = self.sp.lookup({"query":query, "domain":domain, "qtype":qtype, "qclass":qclass, "src_addr":src_addr})
+ response = answers
results = []
if type(response) == types.DictType :
tempresults = {"qtype":response["type"], "qclass":response["class"], "ttl":response["ttl"]}
@@ -130,8 +135,8 @@ def get_response(self, query, domain, qtype, qclass, src_addr):
# if they asked for an A record and we didn't find one, check for a CNAME
#return self.get_response(query, domain, 5, qclass, src_addr)
else:
- server = self.servers[random.randrange(0, len(self.servers)-1)]
- answers = self.reqobj.req(name=domain, qtype=qtype, server=server).answers
+ #server = self.servers[random.randrange(0, len(self.servers)-1)]
+ #answers = self.reqobj.req(name=domain, qtype=qtype, server=server).answers
results = []
for response in answers :
tempresults = {"qtype":response["type"], "qclass":response["class"], "ttl":response["ttl"]}
View
67 lib/plugin.py
@@ -1,3 +1,4 @@
+from common import *
import threading
import time
import os
@@ -10,52 +11,60 @@
class PluginThread(threading.Thread):
daemon = True
- app = None
name = None
+ mode = None
desc = None
running = False
options = {}
helps = {}
- depends = []
+ depends = {}
+ services = {}
#version = None
- def __init__(self, app):
+ def __init__(self, mode = 'plugin'):
if self.name is None:
raise Exception(str(self.__class__) + " : name not defined")
- self.app = app
- self.nameconf = 'plugin-' + self.name + '.conf'
- self.nameclass = 'plugin' + self.name.capitalize()
+ self.mode = mode
+ self.nameconf = self.mode + '-' + self.name + '.conf'
+ self.nameclass = self.mode + self.name.capitalize()
self.parser = app['parser']
self.conf = {}
self._loadconfig()
threading.Thread.__init__(self)
+ def start(self):
+ threading.Thread.start(self)
+
def run(self):
if self.running: return
self.start2()
def start2(self, arg = []):
- if self.app['debug']: print "Plugin %s parent starting" %(self.name)
+ if app['debug']: print "Plugin %s parent starting" %(self.name)
self.running = True
# start depends
if len(self.depends) > 0:
- for dep in self.depends:
- self.app['plugins'][dep].start()
+ if 'plugins' in self.depends:
+ for dep in self.depends['plugins']:
+ app['plugins'][dep].start()
+ if 'services' in self.depends:
+ for dep in self.depends['services']:
+ app['services'][dep].start()
return self.pStart()
def pStart(self, arg = []):
- if self.app['debug']: print "Plugin %s parent start" %(self.name)
+ if app['debug']: print "Plugin %s parent start" %(self.name)
#time.sleep(1)
return True
def stop(self, arg = []):
if not self.running: return
- if self.app['debug']: print "Plugin %s parent stopping" %(self.name)
+ if app['debug']: print "Plugin %s parent stopping" %(self.name)
self.running = False
return self.pStop()
def pStop(self, arg = []):
- if self.app['debug']: print "Plugin %s parent stop" %(self.name)
+ if app['debug']: print "Plugin %s parent stop" %(self.name)
print "Plugin %s stopped" %(self.name)
return True
@@ -67,20 +76,20 @@ def pStatus(self, arg = []):
return "Plugin " + self.name + " running"
def reload(self, arg = []):
- if self.app['debug']: print "Plugin %s parent reloading" %(self.name)
+ if app['debug']: print "Plugin %s parent reloading" %(self.name)
return self.pReload()
def pReload(self, arg = []):
- if self.app['debug']: print "Plugin %s parent reload" %(self.name)
+ if app['debug']: print "Plugin %s parent reload" %(self.name)
self.loadconfig()
return True
def restart(self, arg = []):
- if self.app['debug']: print "Plugin %s parent restarting" %(self.name)
+ if app['debug']: print "Plugin %s parent restarting" %(self.name)
return self.pRestart()
def pRestart(self, arg = []):
- if self.app['debug']: print "Plugin %s parent restart" %(self.name)
+ if app['debug']: print "Plugin %s parent restart" %(self.name)
self.stop()
self.start2()
return True
@@ -91,15 +100,15 @@ def help(self, arg = []):
def pHelp(self, arg = []):
#if arg[0] == 'help':
# help = '* Available plugins :\n'
- # for plugin in self.app['plugins']:
- # if self.app['plugins'][plugin].running == True:
+ # for plugin in app['plugins']:
+ # if app['plugins'][plugin].running == True:
# help += '\n' + plugin + ' help'
# return help
if len(arg[1]) > 1:
- if arg[1][1] in self.app['plugins'][arg[0]].helps:
- help = self.app['plugins'][arg[0]].helps[arg[1][1]][3]
- help += '\n' + arg[1][1] + ' ' + self.app['plugins'][arg[0]].helps[arg[1][1]][2]
+ if arg[1][1] in app['plugins'][arg[0]].helps:
+ help = app['plugins'][arg[0]].helps[arg[1][1]][3]
+ help += '\n' + arg[1][1] + ' ' + app['plugins'][arg[0]].helps[arg[1][1]][2]
return help
methods = self._getPluginMethods()
@@ -133,9 +142,15 @@ def _getPluginMethods(self):
return methods
def _loadconfig(self, arg = []):
+ # manage services
+ for service, value in self.services.iteritems():
+ if self.name not in app['services'][service].services:
+ app['services'][service].services = {}
+ app['services'][service].services[self.name] = value
+
# add command line args to the program options + build default configuration data
defaultConf = '[' + self.name + ']\n'
- group = OptionGroup(self.app['parser'], self.name.capitalize() + " Options", self.desc)
+ group = OptionGroup(app['parser'], self.name.capitalize() + " Options", self.desc)
if self.options.__class__ is dict:
tmp = []
for option, value in self.options.items():
@@ -157,13 +172,13 @@ def _loadconfig(self, arg = []):
else:
group.add_option('--' + self.name + '.' + option, type='str', help=help, metavar=str(value[1]))
self.conf[option] = value[1]
- self.app['parser'].add_option_group(group)
+ app['parser'].add_option_group(group)
# create default config if none
- userConfFile = self.app['path']['conf'] + self.nameconf
+ userConfFile = app['path']['conf'] + self.nameconf
if not os.path.exists(userConfFile):
- if not os.path.exists(self.app['path']['conf']):
- os.mkdir(self.app['path']['conf'])
+ if not os.path.exists(app['path']['conf']):
+ os.mkdir(app['path']['conf'])
fp = open(userConfFile, 'w')
fp.write(defaultConf)
fp.close()
View
77 nmcontrol
@@ -1,6 +1,6 @@
#!/usr/bin/python
-__version__ = '0.7'
+__version__ = '0.8'
import os
import sys
@@ -20,6 +20,10 @@ def main():
# add import path
sys.path.append(app['path']['app'] + 'lib')
sys.path.append(app['path']['app'] + 'plugin')
+ sys.path.append(app['path']['app'] + 'service')
+
+ import common
+ common.app = app
import console
(cWidth, cHeight) = console.getTerminalSize()
@@ -32,39 +36,66 @@ def main():
if argv in ['--debug=1','--main.debug=1']:
app['debug'] = True
- # load plugins
+ # init modules
import re
import dircache
+
+ # init vars and main plugin
+ app['services'] = {}
app['plugins'] = {}
- plugins = dircache.listdir('plugin')
- # set main plugin in first pos
- plugins.remove('pluginMain.py')
- plugins.insert(0, 'pluginMain.py')
- for plugin in dircache.listdir('plugin'):
- if re.match("^plugin.*.py$", plugin):
- plugin = re.sub(r'\.py$', '', plugin)
- pluginname = re.sub(r'^plugin', '', plugin).lower()
- exec("import " + plugin)
+ import pluginMain
+ app['plugins']['main'] = pluginMain.pluginMain('plugin')
+
+ # init service
+ modules = dircache.listdir('service')
+ for module in modules:
+ if re.match("^service.*.py$", module):
+ module = re.sub(r'\.py$', '', module)
+ modulename = re.sub(r'^service', '', module).lower()
+ exec("import " + module)
try:
- exec("p = " + plugin + "." + plugin + "(app)")
- exec("app['plugins'][p.name] = p")
+ #exec("p = " + module + "." + module + "(app, 'service')")
+ #exec("app['services'][p.name] = p")
+ exec("p = " + module + "." + module)
+ app['services'][p.name] = p('service')
+ module.app = app
except AttributeError as e:
- if app['debug']: print 'Plugin "' + plugin + '" has no', plugin + '() class'
-
+ if app['debug']: print 'Service "' + module + '" has no', module + '() class'
+
+ # init plugins
+ modules = dircache.listdir('plugin')
+ modules.remove('pluginMain.py')
+ #modules.insert(0, 'pluginMain.py')
+ for module in modules: #dircache.listdir('module'):
+ if re.match("^plugin.*.py$", module):
+ module = re.sub(r'\.py$', '', module)
+ modulename = re.sub(r'^plugin', '', module).lower()
+ exec("import " + module)
+ try:
+ #exec("p = " + module + "." + module + "(app)")
+ #exec("app['plugins'][p.name] = p")
+ exec("p = " + module + "." + module)
+ app['plugins'][p.name] = p('plugin')
+ module.app = app
+ except AttributeError as e:
+ if app['debug']: print 'Plugin "' + module + '" has no', module + '() class'
# parse command line options
(options, app['args']) = app['parser'].parse_args()
- if app['debug']: print "Cmdline options:", options
if app['debug']: print "Cmdline args:", app['args']
+ if app['debug']: print "Cmdline options:", options
for option, value in vars(options).items():
if value is not None:
tmp = option.split('.')
if len(tmp) == 1:
app['plugins']['main'].conf[tmp[0]] = value
else:
- plugin = tmp[0]
- tmp.remove(plugin)
- app['plugins'][plugin].conf['.'.join(tmp)] = value
+ module = tmp[0]
+ tmp.remove(module)
+ if module in app['plugins']:
+ app['plugins'][module].conf['.'.join(tmp)] = value
+ elif module in app['services']:
+ app['services'][module].conf['.'.join(tmp)] = value
###### Act as client : send rpc request ######
if len(app['args']) > 0 and app['args'][0] != 'start':
@@ -95,7 +126,13 @@ def main():
if app['plugins'][plugin].running is False:
app['plugins'][plugin].start()
plugins_started.append(app['plugins'][plugin].name)
- print "Plugin started :", ', '.join(plugins_started)
+ print "Plugins started :", ', '.join(plugins_started)
+
+ #services_started = []
+ #for service in app['services']:
+ # if app['services'][service].running:
+ # services_started.append(app['services'][service].name)
+ #print "Services started :", ', '.join(services_started)
# stay there to catch CTRL + C and not exit when in daemon mode
try:
View
19 plugin/pluginData.py
@@ -1,3 +1,4 @@
+from common import *
import json, StringIO, os, sys, time
import plugin
import rpcClient
@@ -55,19 +56,19 @@ def pStart(self):
# build filter for namespaces
namespaces = []
self.conf['name_filter'] = ''
- for plugin in self.app['plugins']:
- if self.app['plugins'][plugin].conf['start'] == 1:
- if hasattr(self.app['plugins'][plugin], 'namespaces'):
- namespaces.extend(self.app['plugins'][plugin].namespaces)
+ for plugin in app['plugins']:
+ if app['plugins'][plugin].conf['start'] == 1:
+ if hasattr(app['plugins'][plugin], 'namespaces'):
+ namespaces.extend(app['plugins'][plugin].namespaces)
if len(namespaces) > 0:
self.conf['name_filter'] = '^' + '|'.join(namespaces) + '/'
# load import backend
if self.conf['import.mode'] == 'all':
- if self.app['debug']: print "Plugin Data : loading...",
+ if app['debug']: print "Plugin Data : loading...",
sys.stdout.flush()
exec('backend = backendData' + self.conf['import.from'].capitalize() + '.backendData');
- backend = backend(self.app, self.conf['import.' + self.conf['import.from']])
+ backend = backend(self.conf['import.' + self.conf['import.from']])
error, data = backend.getAllNames()
if error is None:
self.data = data
@@ -75,17 +76,17 @@ def pStart(self):
for name in self.data:
if 'expires_at' not in self.data[name]:
self.data[name]['expires_at'] = int(time.time() + self.conf['update.freq'])
- if self.app['debug']: print len(self.data), "names loaded"
+ if app['debug']: print len(self.data), "names loaded"
# load update backend
if self.conf['update.mode'] != 'none':
exec('backend = backendData' + self.conf['update.from'].capitalize() + '.backendData');
- self.update = backend(self.app, self.conf['update.' + self.conf['update.from']])
+ self.update = backend(self.conf['update.' + self.conf['update.from']])
# load export backend
if self.conf['export.mode'] != 'none':
exec('backend = backendData' + self.conf['export.to'].capitalize() + '.backendData');
- self.export = backend(self.app, self.conf['export.' + self.conf['export.to']])
+ self.export = backend(self.conf['export.' + self.conf['export.to']])
def getData(self, cmd):
if cmd[1][1] not in self.data or self.data[cmd[1][1]]['expires_at'] < time.time():
View
27 plugin/pluginMain.py
@@ -1,3 +1,4 @@
+from common import *
import plugin
import platform
@@ -11,25 +12,25 @@ class pluginMain(plugin.PluginThread):
}
def pStart(self):
- self.app['plugins']['rpc'].start2()
+ app['plugins']['rpc'].start2()
def pStatus(self):
ret = ''
if self.running:
ret = "Plugin " + self.name + " running"
- for plugin in self.app['plugins']:
- if plugin != 'main' and self.app['plugins'][plugin].running:
- ret += '\n' + self.app['plugins'][plugin].pStatus()
+ for plugin in app['plugins']:
+ if plugin != 'main' and app['plugins'][plugin].running:
+ ret += '\n' + app['plugins'][plugin].pStatus()
return ret
def pStop(self):
self.running = False
- self.app['plugins']['rpc'].stop()
- if self.app['debug']: print "Plugin %s stopping" %(self.name)
- #for plugin in self.app['plugins']:
- # if self.app['plugins'][plugin].running == True:
- # self.app['plugins'][plugin].stop()
+ app['plugins']['rpc'].stop()
+ if app['debug']: print "Plugin %s stopping" %(self.name)
+ #for plugin in app['plugins']:
+ # if app['plugins'][plugin].running == True:
+ # app['plugins'][plugin].stop()
print "Plugin %s stopped" %(self.name)
def pRestart(self):
@@ -38,13 +39,13 @@ def pRestart(self):
def pLoadconfig(self):
self.conf['start'] = 1
- if 'debug' in self.app:
- self.conf['debug'] = self.app['debug']
+ if 'debug' in app:
+ self.conf['debug'] = app['debug']
def pHelp(self, args = []):
help = '* Available plugins :'
- for plug in self.app['plugins']:
- if self.app['plugins'][plug].running == True:
+ for plug in app['plugins']:
+ if app['plugins'][plug].running == True:
help += '\n' + plug + ' help'
return help + '\n\n' + plugin.PluginThread.pHelp(self, args)
View
55 plugin/pluginNamespaceDomain.py
@@ -1,7 +1,7 @@
+from common import *
import plugin
-import dnsServer
import DNS
-import json, base64, types, traceback
+import json, base64, types, random, traceback
class pluginNamespaceDomain(plugin.PluginThread):
name = 'domain'
@@ -11,25 +11,32 @@ class pluginNamespaceDomain(plugin.PluginThread):
#'port': ['Listen on port', 53],
#'resolver': ['Forward standard requests to', '8.8.8.8,8.8.4.4'],
}
+ depends = {'services': ['dns']}
+ services = {'dns':{'filter':'.bit$','cache':True}}
namespaces = ['d']
- def pStart(self):
- self.servers = self.app['plugins']['dns'].conf['resolver'].split(',')
-
- def lookup(self, qdict) :
- domain = qdict["domain"]
+ def domainToNamespace(self, domain):
if domain.count(".") >= 2 :
host = ".".join(domain.split(".")[-2:-1])
subdomain = ".".join(domain.split(".")[:-2])
else :
host = domain.split(".")[0]
subdomain = ""
+ return 'd/'+host, host, subdomain
+
+ def namespaceToDomain(self, name):
+ pass
+
+ def lookup(self, qdict) :
+ #dns = app['services']['dns'].lookup()
+ #
+ name, host, subdomain = self.domainToNamespace(qdict["domain"])
+ item = app['plugins']['data'].getData(['data', ['getData', name]])
#rawlist = json.dumps(rawjson)
- item = self.app['plugins']['data'].getData(['data', ['getData', 'd/'+host]])
try:
item = json.loads(item)
except:
- if self.app['debug']: traceback.print_exc()
+ if app['debug']: traceback.print_exc()
return
if str(item[u"name"]) == "d/" + host :
@@ -43,7 +50,13 @@ def lookup(self, qdict) :
hasdefault = True
if str(key) == subdomain :
if type(value[u"map"][key]) == types.DictType :
- return dnslookup(value, key, qdict)
+ #return dnslookup(value, key, qdict)
+ if value[u"map"][key].has_key(u"ns") :
+ server = value[u"map"][key][u"ns"][random.randrange(0, len(value[u"map"][key][u"ns"])-1)]
+ #return app['services']['dns']._lookup(qdict, server)
+ return app['services']['dns']._lookup(qdict, server)[0]['data']
+ #return [{"qtype":1, "qclass":qclass, "ttl":300, "rdata":struct.pack("!I", ipstr2int(response))}]
+ #return [{'name': 'ssl.bit', 'data': '178.32.31.42', 'typename': 'A', 'classstr': 'IN', 'ttl': 86400, 'type': 1, 'class': 1, 'rdlength': 4}]
return str(value[u"map"][u""])
#else :
#if type(value[u"map"][key]) == types.DictType :
@@ -54,9 +67,13 @@ def lookup(self, qdict) :
return self.dnslookup(value, u"", qdict)
return str(value[u"map"][u""])
except :
- if self.app['debug']: traceback.print_exc()
+ if app['debug']: traceback.print_exc()
return
+
+ #app['services']['dns'].lookup()
+
def dnslookup(self, value, key, qdict) :
+ print 'dnslookup:', value, key, qdict
if value[u"map"][key].has_key(u"ns") :
server = self.servers[random.randrange(0, len(self.servers)-1)]
self.reqobj = DNS.Request(server=server)
@@ -69,19 +86,3 @@ def dnslookup(self, value, key, qdict) :
ns = DNS.Request(server=y)
return ns.req(name=qdict["domain"], qtype=qdict["qtype"]).answers[0]
-
- #srv = None
- #
- #def pStart(self):
- # if self.srv is None:
- # self.srv = dnsServer.DnsServer()
- # self.srv.start(self.app)
- # return True
- #
- #def pStop(self):
- # if self.srv is not None:
- # self.srv.stop()
- # print "Plugin %s stopped" %(self.name)
- # return True
-
-
View
40 plugin/pluginRpc.py
@@ -1,3 +1,4 @@
+from common import *
import plugin
import rpcClient
import socket, json, threading, StringIO, sys, time, traceback
@@ -23,30 +24,30 @@ def pStart(self):
self.s.listen(1)
while self.running:
try:
- c = rpcClientThread(self.s.accept(), self.app)
+ c = rpcClientThread(self.s.accept(), app)
c.start()
self.threads.append(c)
except Exception as e:
- if self.app['debug']: print "except:", e
+ if app['debug']: print "except:", e
except KeyboardInterrupt:
pass
except:
print "nmc-manager: unable to listen on port"
- if self.app['debug']: traceback.print_exc()
+ if app['debug']: traceback.print_exc()
# close all threads
- if self.app['debug']: print "RPC stop listening"
+ if app['debug']: print "RPC stop listening"
self.s.close()
for c in self.threads:
c.join()
def pStop(self):
- if self.app['debug']: print "Plugin stop :", self.name
+ if app['debug']: print "Plugin stop :", self.name
self.pSend(['exit'])
print "Plugin %s stopped" %(self.name)
def pSend(self, args):
- if self.app['debug']: print "RPC - sending cmd :", args
+ if app['debug']: print "RPC - sending cmd :", args
r = rpcClient.rpcClient(self.conf['host'], int(self.conf['port']))
error, data = r.sendJson(args)
return error, data
@@ -59,9 +60,9 @@ def pSend(self, args):
s.sendall(json.dumps(args))
data = s.recv(4096)
s.close()
- if self.app['debug']: print 'RPC - received data : ', repr(data)
+ if app['debug']: print 'RPC - received data : ', repr(data)
data = json.loads(data)
- if self.app['debug'] and 'result' in data and 'prints' in data['result']:
+ if app['debug'] and 'result' in data and 'prints' in data['result']:
print data['result']['prints']
if data['error'] is None:
@@ -82,7 +83,6 @@ def __init__(self, (client, address), app):
self.client.settimeout(10)
self.address = address
self.size = 4096
- self.app = app
threading.Thread.__init__(self)
def run(self):
@@ -115,7 +115,7 @@ def computeJsonData(self, data):
return self.computeData([data['method'], data['params']])
def computeData(self, args):
- #if self.app['debug']: print "Received data :", data
+ #if app['debug']: print "Received data :", data
# check for default plugin
if len(args[1]) == 0: args = ['main', [args[0]]]
@@ -125,16 +125,16 @@ def computeData(self, args):
#print "Plugin:", plugin
#print "Params:", params
- if plugin not in self.app['plugins']:
+ if plugin not in app['plugins']:
return (True, 'Plugin "' + plugin + '" not allowed')
- if not self.app['plugins'][plugin].running and params[0] != 'start':
+ if not app['plugins'][plugin].running and params[0] != 'start':
return (True, 'Plugin "' + plugin + '" not started')
if params[0] == 'start': params[0] = 'start2'
# reply before being blocked by non threaded start
# TODO : recreate thread for the start command and delete when stop
- if not self.app['plugins'][plugin].running and params[0] == 'start2':
+ if not app['plugins'][plugin].running and params[0] == 'start2':
self.client.send('{"result":'+json.dumps({'reply':True, 'prints':'Restarting '+plugin+''})+',"error":'+json.dumps(None)+',"id":1}');
# reply before closing connection
@@ -142,17 +142,17 @@ def computeData(self, args):
self.client.send('{"result":'+json.dumps({'reply':True, 'prints':'Restarting rpc'})+',"error":'+json.dumps(None)+',"id":1}');
if params[0][0] == '_':
- if self.app['debug']: print "RPC - forbidden cmd :", args
+ if app['debug']: print "RPC - forbidden cmd :", args
return (True, 'Method "' + params[0] + '" not allowed')
if 'help' in params \
- or params[0] in self.app['plugins'][plugin].helps \
- and len(params)-1 not in range(self.app['plugins'][plugin].helps[params[0]][0], self.app['plugins'][plugin].helps[params[0]][1]+1):
+ or params[0] in app['plugins'][plugin].helps \
+ and len(params)-1 not in range(app['plugins'][plugin].helps[params[0]][0], app['plugins'][plugin].helps[params[0]][1]+1):
params.insert(0, 'help')
args[1] = params
- if self.app['debug']: print "RPC - executing cmd :", args
- exec("Cmd = self.app['plugins'][plugin]." + params[0])
+ if app['debug']: print "RPC - executing cmd :", args
+ exec("Cmd = app['plugins'][plugin]." + params[0])
# capture stdout
capture = StringIO.StringIO()
@@ -161,10 +161,10 @@ def computeData(self, args):
try:
result = Cmd(args)
except AttributeError, e:
- if self.app['debug']: traceback.print_exc()
+ if app['debug']: traceback.print_exc()
return (True, 'Method "' + params[0] + '" not supported by plugin "' + plugin + '"')
except Exception, e:
- if self.app['debug']: traceback.print_exc()
+ if app['debug']: traceback.print_exc()
return (True, 'Exception : ' + str(e))
# restore stdout
View
27 plugin/pluginServiceDNS.py
@@ -1,27 +0,0 @@
-import plugin
-import dnsServer
-
-class pluginServiceDNS(plugin.PluginThread):
- name = 'dns'
- options = {
- 'start': ['Launch at startup', 1],
- 'host': ['Listen on ip', '127.0.0.1'],
- 'port': ['Listen on port', 53],
- 'resolver': ['Forward standard requests to', '8.8.8.8,8.8.4.4'],
- }
- srv = None
-
- def pStart(self):
- if self.srv is None:
- self.srv = dnsServer.DnsServer(self.app)
- self.srv.start()
- if self.app['debug']: print "Plugin %s started" %(self.name)
- return True
-
- def pStop(self):
- if self.srv is not None:
- self.srv.stop()
- self.srv = None
- if self.app['debug']: print "Plugin %s stopped" %(self.name)
- return True
-
View
46 service/serviceDNS.py
@@ -0,0 +1,46 @@
+from common import *
+import plugin
+import DNS
+import dnsServer
+import random, re
+
+class serviceDNS(plugin.PluginThread):
+ name = 'dns'
+ options = {
+ 'start': ['Launch at startup', 1],
+ 'host': ['Listen on ip', '127.0.0.1'],
+ 'port': ['Listen on port', 53],
+ 'resolver': ['Forward standard requests to', '8.8.8.8,8.8.4.4'],
+ }
+ srv = None
+
+ def pStart(self):
+ self.servers = self.conf['resolver'].split(',')
+ if self.srv is None:
+ self.srv = dnsServer.DnsServer()
+ self.srv.start()
+ if app['debug']: print "Service %s started" %(self.name)
+ return True
+
+ def pStop(self):
+ if self.srv is not None:
+ self.srv.stop()
+ self.srv = None
+ if app['debug']: print "Service %s stopped" %(self.name)
+ return True
+
+ def lookup(self, qdict) :
+ if app['debug']: print 'Lookup:', qdict
+ for service, value in self.services.iteritems():
+ if re.search(value['filter'], qdict["domain"]):
+ return app['plugins'][service].lookup(qdict)
+
+ return self._lookup(qdict)
+
+ def _lookup(self, qdict, server = ''):
+ if server == '':
+ server = self.servers[random.randrange(0, len(self.servers)-1)]
+
+ x = DNS.Request(server=server)
+ return x.req(name=qdict["domain"], qtype=qdict["qtype"]).answers
+
View
0  plugin/pluginServiceProxy.py → service/serviceProxy.py
File renamed without changes
Please sign in to comment.
Something went wrong with that request. Please try again.