#!/usr/bin/python
from twisted.internet import reactor
from twisted.names import server
from twisted.names import dns
from twisted.names import common
from twisted.internet import defer
from twisted.python import failure

import sipb_xen_database

class DatabaseAuthority(common.ResolverBase):
    """An Authority that is loaded from a file."""

    soa = None

    def __init__(self, domain, database=None):
        common.ResolverBase.__init__(self)
        if database is not None:
            sipb_xen_database.connect(database)
        self.domain = domain
        self.soa = dns.Record_SOA(mname='sipb-xen-dev.mit.edu', 
                                  rname='sipb-xen.mit.edu',
                                  serial=1, refresh=3600, retry=900,
                                  expire=3600000, minimum=21600, ttl=3600)
    def _lookup(self, name, cls, type, timeout = None):
        if not (name.lower() == self.domain or 
                name.lower().endswith('.'+self.domain)):
            #Not us
            return defer.fail(failure.Failure(dns.DomainError(name)))
        results = []
        if cls == dns.IN and type in (dns.A, dns.ALL_RECORDS):
            host = name[:-len(self.domain)-1]
            value = sipb_xen_database.NIC.get_by(hostname=host)
            if value is None:
                return defer.fail(failure.Failure(dns.AuthoritativeDomainError(name)))
            ip = value.ip
            if ip is None:  #Deactivated?
                return defer.fail(failure.Failure(dns.AuthoritativeDomainError(name)))
            ttl = 900
            record = dns.Record_A(ip, ttl)
            results.append(dns.RRHeader(name, dns.A, dns.IN, 
                                        ttl, record, auth=True))
        authority = []
        authority.append(dns.RRHeader(self.domain, dns.SOA, dns.IN, 3600,
                                      self.soa, auth=True))
        return defer.succeed((results, authority, []))
        #Doesn't exist
        return defer.fail(failure.Failure(dns.AuthoritativeDomainError(name)))

if '__main__' == __name__:
    resolver = DatabaseAuthority('servers.csail.mit.edu',
                                 'postgres://sipb-xen@sipb-xen-dev/sipb_xen')

    verbosity = 0
    f = server.DNSServerFactory(authorities=[resolver], verbose=verbosity)
    p = dns.DNSDatagramProtocol(f)
    f.noisy = p.noisy = verbosity
    
    reactor.listenUDP(53, p)
    reactor.listenTCP(53, f)
    reactor.run()
