From dbcb963e3cc1cd4450e8aa5d4fa187f45d956950 Mon Sep 17 00:00:00 2001 From: Sebastian Lohff Date: Wed, 29 Mar 2017 03:14:18 +0200 Subject: [PATCH] Whoisd --- bin/whoisd | 96 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100755 bin/whoisd diff --git a/bin/whoisd b/bin/whoisd new file mode 100755 index 0000000..c5d8974 --- /dev/null +++ b/bin/whoisd @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +import argparse +import socketserver +import os +import sys +import django +import logging +import select + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dnmgmt.settings") +sys.path.append("..") +django.setup() + +from whoisdb.helpers import findInDatabase, getWhoisObjectFields + +log = logging.getLogger("whoisd") + +__VERSION__ = '0.1' + +class WhoisHandler(socketserver.BaseRequestHandler): + def handle(self): + self.request.sendall(b"Welcome!\n\n") + line = self.request.recv(1024) + line = line.split(b"\n", 2)[0].strip() + print("Request object is %s" % line) + log.info("Request by %s for %s" % (self.request.getpeername()[0], line)) + self.request.send(b"\n") + + objs = findInDatabase(line.decode()) + if len(objs) > 0: + self.request.sendall(("%d result%s\n" % (len(objs), "" if len(objs)==1 else "s")).encode()) + for obj in objs: + self.sendObject(obj) + else: + self.request.sendall(b"NOT FOUND\n\n") + + def sendObject(self, obj): + result = [ + "", + "Object %s (%s)" % (obj, obj.getClassName()), + "" + ] + + for field, value in getWhoisObjectFields(obj, False): + fieldName = field.lower().replace(" ", "_") + ":" + if not value: + value = "" + + if hasattr(value, "through"): + for v in value.all(): + result.append("%-16s %s" % (fieldName, v)) + else: + result.append("%-16s %s" % (fieldName, value)) + result.extend(["", ""]) + + self.request.sendall("\n".join(result).encode()) + +class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): + allow_reuse_address = True + + +def _parser(): + parser = argparse.ArgumentParser( + #prog='foo', + #description='do some awesome foo', + ) + + parser.add_argument("-p", "--port", default=43, type=int, help="whoisd port") + #parser.add_argument("-v", "--verbose", default=False, action="store_true", help="Be more verbose") + + parser.add_argument("--version", action="version", version="%(prog)s " + __VERSION__) + + return parser + +def main(): + parser = _parser() + args = parser.parse_args() + + server = ThreadedTCPServer(('', args.port), WhoisHandler) + + while True: + try: + server.serve_forever() + except select.error as e: + log.exception(e) + except KeyboardInterrupt: + log.info("^c hit, quitting.") + break + + server.server_close() + + +if __name__ == '__main__': + main()