Index: /package_tags/invirt-dns/0.0.11/debian/changelog
===================================================================
--- /package_tags/invirt-dns/0.0.11/debian/changelog	(revision 2369)
+++ /package_tags/invirt-dns/0.0.11/debian/changelog	(revision 2369)
@@ -0,0 +1,125 @@
+invirt-dns (0.0.11) unstable; urgency=low
+
+  * Refactor DNS logic.
+  * Fix bugs in 0.0.10: shouldn't give answers to A, NS on *.in-addr.arpa.
+
+ -- Greg Price <price@mit.edu>  Fri, 27 Feb 2009 04:51:16 -0500
+
+invirt-dns (0.0.10) unstable; urgency=low
+
+  * Add support for resolving PTR records in the in-addr.arpa zone.
+  * If we're not authoritative for an in-addr.arpa zone, generate a
+    phantom SOA record for the exact request that came in.
+
+ -- Quentin Smith <quentin@mit.edu>  Fri, 27 Feb 2009 02:56:31 -0500
+
+invirt-dns (0.0.9) unstable; urgency=low
+
+  * Don't error if dns.zone_files isn't set in the config.
+
+ -- Evan Broder <broder@mit.edu>  Fri, 30 Jan 2009 20:09:35 -0500
+
+invirt-dns (0.0.8) unstable; urgency=low
+
+  * Check the nics table first and then the machines table so that you can
+    do DNS lookups for machines with multiple IPs.
+
+ -- Evan Broder <broder@mit.edu>  Mon, 12 Jan 2009 20:51:28 -0500
+
+invirt-dns (0.0.7) unstable; urgency=low
+
+  [ Yang Zhang ]
+  * Do a better job of handling quoting
+
+ -- Evan Broder <broder@mit.edu>  Wed, 12 Nov 2008 18:48:50 -0500
+
+invirt-dns (0.0.6) unstable; urgency=low
+
+  * Add support for basic quoting in the zone file
+
+ -- Evan Broder <broder@mit.edu>  Sat, 01 Nov 2008 04:01:09 -0400
+
+invirt-dns (0.0.5) unstable; urgency=low
+
+  * Instead of hacking in support for prod.xvm.mit.edu, support zone files
+    that override the database
+  * Punt passup option as it can be handled by the zone file
+
+ -- Evan Broder <broder@mit.edu>  Sat, 01 Nov 2008 01:05:57 -0400
+
+invirt-dns (0.0.4) unstable; urgency=low
+
+  * Whoops - actually install the invirt-dns script
+  * Fix some stale, unneeded dependencies
+
+ -- Evan Broder <broder@mit.edu>  Fri, 31 Oct 2008 21:05:28 -0400
+
+invirt-dns (0.0.3) unstable; urgency=low
+
+  * Don't hang on NXDOMAINs
+  * Rearrange package structure
+
+ -- Evan Broder <broder@mit.edu>  Fri, 31 Oct 2008 21:00:51 -0400
+
+invirt-dns (0.0.2) unstable; urgency=low
+
+  * Standardize on "Invirt project"
+
+ -- Evan Broder <broder@mit.edu>  Fri, 24 Oct 2008 13:33:10 -0400
+
+invirt-dns (0.0.1) unstable; urgency=low
+
+  * sipb-xen -> invirt
+
+ -- Greg Price <price@mit.edu>  Fri, 24 Oct 2008 00:54:52 -0400
+
+sipb-xen-dns (1.06) unstable; urgency=low
+
+  * Fix the SQLAlchemy calls
+
+ -- Evan Broder <broder@mit.edu>  Fri, 03 Oct 2008 20:44:23 -0400
+
+sipb-xen-dns (1.05.1) unstable; urgency=low
+
+  * Include the requirement on twisted.names
+
+ -- Evan Broder <broder@mit.edu>  Thu, 02 Oct 2008 18:48:58 -0400
+
+sipb-xen-dns (1.05) unstable; urgency=low
+
+  * Convert package to not include a svn checkout in the binary package
+
+ -- Evan Broder <broder@mit.edu>  Thu, 02 Oct 2008 18:41:25 -0400
+
+sipb-xen-dns (1.04) unstable; urgency=low
+
+  * Search for longest-matching domain name instead of first-matching.
+  * ns1.prod.xvm.mit.edu (0.0.0.0) is the primary nameserver for the prod
+    zone.
+
+ -- Yang Zhang <y_z@mit.edu>  Mon, 25 Aug 2008 01:01:17 -0400
+
+sipb-xen-dns (1.03) unstable; urgency=low
+
+  * debian/
+
+ -- Yang Zhang <y_z@mit.edu>  Sun, 24 Aug 2008 16:37:16 -0400
+
+sipb-xen-dns (1.02) unstable; urgency=low
+
+  * sipb_xen_database -> invirt.database
+  * use invirt.config in dnsserver.py
+
+ -- Yang Zhang <y_z@mit.edu>  Sun,  3 Aug 2008 19:18:40 -0400
+
+sipb-xen-dns (1.01) unstable; urgency=low
+
+  * update SOA record for the xvm.mit.edu order of things
+
+ -- Greg Price <price@mit.edu>  Sun,  3 Aug 2008 02:10:03 -0400
+
+sipb-xen-dns (1) unstable; urgency=low
+
+  * Initial Release.
+ -- SIPB Xen Project <sipb-xen@mit.edu>  Sun, 24 Feb 2008 20:45:28 -0500
+
Index: /package_tags/invirt-dns/0.0.11/debian/compat
===================================================================
--- /package_tags/invirt-dns/0.0.11/debian/compat	(revision 2369)
+++ /package_tags/invirt-dns/0.0.11/debian/compat	(revision 2369)
@@ -0,0 +1,1 @@
+4
Index: /package_tags/invirt-dns/0.0.11/debian/control
===================================================================
--- /package_tags/invirt-dns/0.0.11/debian/control	(revision 2369)
+++ /package_tags/invirt-dns/0.0.11/debian/control	(revision 2369)
@@ -0,0 +1,11 @@
+Source: invirt-dns
+Section: base
+Priority: extra
+Maintainer: Invirt project <invirt@mit.edu>
+Build-Depends: cdbs (>= 0.4.23-1.1), debhelper (>= 4.1.0)
+Standards-Version: 3.7.2
+
+Package: invirt-dns
+Architecture: all
+Depends: ${misc:Depends}, daemon, python-twisted-names
+Description: Install and enable the DNS server
Index: /package_tags/invirt-dns/0.0.11/debian/copyright
===================================================================
--- /package_tags/invirt-dns/0.0.11/debian/copyright	(revision 2369)
+++ /package_tags/invirt-dns/0.0.11/debian/copyright	(revision 2369)
@@ -0,0 +1,16 @@
+This software was written as part of the Invirt project <invirt@mit.edu>.
+
+Copyright :
+
+  This program is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; either version 2 of the License, or
+  (at your option) any later version.
+
+  This program is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+On Debian systems, the complete text of the GNU General Public License
+can be found in the file /usr/share/common-licenses/GPL.
Index: /package_tags/invirt-dns/0.0.11/debian/invirt-dns.init
===================================================================
--- /package_tags/invirt-dns/0.0.11/debian/invirt-dns.init	(revision 2369)
+++ /package_tags/invirt-dns/0.0.11/debian/invirt-dns.init	(revision 2369)
@@ -0,0 +1,124 @@
+#! /bin/sh
+### BEGIN INIT INFO
+# Provides:          invirt-dns
+# Required-Start:    $local_fs $remote_fs
+# Required-Stop:     $local_fs $remote_fs
+# Default-Start:     2 3 4 5
+# Default-Stop:      0 1 6
+# Short-Description: Invirt DNS server
+# Description:       
+### END INIT INFO
+
+# Author: Invirt project <invirt@mit.edu>
+
+# Do NOT "set -e"
+
+# PATH should only include /usr/* if it runs after the mountnfs.sh script
+PATH=/sbin:/usr/sbin:/bin:/usr/bin
+DESC="the Invirt DNS server"
+NAME=invirt-dns
+DAEMON=/usr/sbin/invirt-dns
+DAEMON_ARGS=""
+PIDFILE=/var/run/$NAME.pid
+SCRIPTNAME=/etc/init.d/$NAME
+
+# Exit if the package is not installed
+[ -x "$DAEMON" ] || exit 0
+
+# Read configuration variable file if it is present
+[ -r /etc/default/$NAME ] && . /etc/default/$NAME
+
+# Load the VERBOSE setting and other rcS variables
+. /lib/init/vars.sh
+
+# Define LSB log_* functions.
+# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
+. /lib/lsb/init-functions
+
+#
+# Function that starts the daemon/service
+#
+do_start()
+{
+	# Return
+	#   0 if daemon has been started
+	#   1 if daemon was already running
+	#   2 if daemon could not be started
+	daemon --running -n $NAME && return 1
+	daemon -r -O daemon.info -E daemon.err -n $NAME -U $DAEMON $DAEMON_ARGS || return 2
+}
+
+#
+# Function that stops the daemon/service
+#
+do_stop()
+{
+	# Return
+	#   0 if daemon has been stopped
+	#   1 if daemon was already stopped
+	#   2 if daemon could not be stopped
+	#   other if a failure occurred
+	daemon --stop -n $NAME
+	RETVAL="$?"
+	[ "$RETVAL" = 2 ] && return 2
+	# Many daemons don't delete their pidfiles when they exit.
+	rm -f $PIDFILE
+	return "$RETVAL"
+}
+
+case "$1" in
+  start)
+	[ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
+	do_start
+	case "$?" in
+		0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
+		2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
+	esac
+	;;
+  stop)
+	[ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
+	do_stop
+	case "$?" in
+		0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
+		2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
+	esac
+	;;
+  #reload|force-reload)
+	#
+	# If do_reload() is not implemented then leave this commented out
+	# and leave 'force-reload' as an alias for 'restart'.
+	#
+	#log_daemon_msg "Reloading $DESC" "$NAME"
+	#do_reload
+	#log_end_msg $?
+	#;;
+  restart|force-reload)
+	#
+	# If the "reload" option is implemented then remove the
+	# 'force-reload' alias
+	#
+	log_daemon_msg "Restarting $DESC" "$NAME"
+	do_stop
+	case "$?" in
+	  0|1)
+		do_start
+		case "$?" in
+			0) log_end_msg 0 ;;
+			1) log_end_msg 1 ;; # Old process is still running
+			*) log_end_msg 1 ;; # Failed to start
+		esac
+		;;
+	  *)
+	  	# Failed to stop
+		log_end_msg 1
+		;;
+	esac
+	;;
+  *)
+	#echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2
+	echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
+	exit 3
+	;;
+esac
+
+:
Index: /package_tags/invirt-dns/0.0.11/debian/invirt-dns.install
===================================================================
--- /package_tags/invirt-dns/0.0.11/debian/invirt-dns.install	(revision 2369)
+++ /package_tags/invirt-dns/0.0.11/debian/invirt-dns.install	(revision 2369)
@@ -0,0 +1,1 @@
+invirt-dns usr/sbin
Index: /package_tags/invirt-dns/0.0.11/debian/rules
===================================================================
--- /package_tags/invirt-dns/0.0.11/debian/rules	(revision 2369)
+++ /package_tags/invirt-dns/0.0.11/debian/rules	(revision 2369)
@@ -0,0 +1,3 @@
+#!/usr/bin/make -f
+
+include /usr/share/cdbs/1/rules/debhelper.mk
Index: /package_tags/invirt-dns/0.0.11/invirt-dns
===================================================================
--- /package_tags/invirt-dns/0.0.11/invirt-dns	(revision 2369)
+++ /package_tags/invirt-dns/0.0.11/invirt-dns	(revision 2369)
@@ -0,0 +1,223 @@
+#!/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.names import authority
+from twisted.internet import defer
+from twisted.python import failure
+
+from invirt.common import InvirtConfigError
+from invirt.config import structs as config
+import invirt.database
+import psycopg2
+import sqlalchemy
+import time
+import re
+
+class DatabaseAuthority(common.ResolverBase):
+    """An Authority that is loaded from a file."""
+
+    soa = None
+
+    def __init__(self, domains=None, database=None):
+        common.ResolverBase.__init__(self)
+        if database is not None:
+            invirt.database.connect(database)
+        else:
+            invirt.database.connect()
+        if domains is not None:
+            self.domains = domains
+        else:
+            self.domains = config.dns.domains
+        ns = config.dns.nameservers[0]
+        self.soa = dns.Record_SOA(mname=ns.hostname,
+                                  rname=config.dns.contact.replace('@','.',1),
+                                  serial=1, refresh=3600, retry=900,
+                                  expire=3600000, minimum=21600, ttl=3600)
+        self.ns = dns.Record_NS(name=ns.hostname, ttl=3600)
+        record = dns.Record_A(address=ns.ip, ttl=3600)
+        self.ns1 = dns.RRHeader(ns.hostname, dns.A, dns.IN,
+                                3600, record, auth=True)
+
+    
+    def _lookup(self, name, cls, type, timeout = None):
+        for i in range(3):
+            try:
+                value = self._lookup_unsafe(name, cls, type, timeout = None)
+            except (psycopg2.OperationalError, sqlalchemy.exceptions.SQLError):
+                if i == 2:
+                    raise
+                print "Reloading database"
+                time.sleep(0.5)
+                continue
+            else:
+                return value
+
+    def _lookup_unsafe(self, name, cls, type, timeout):
+        invirt.database.clear_cache()
+        
+        ttl = 900
+        name = name.lower()
+
+        if name in self.domains:
+            domain = name
+        else:
+            # Look for the longest-matching domain.
+            best_domain = ''
+            for domain in self.domains:
+                if name.endswith('.'+domain) and len(domain) > len(best_domain):
+                    best_domain = domain
+            if best_domain == '':
+                if name.endswith('.in-addr.arpa'):
+                    # Act authoritative for the IP address for reverse resolution requests
+                    best_domain = name
+                else:
+                    return defer.fail(failure.Failure(dns.DomainError(name)))
+            domain = best_domain
+        results = []
+        authority = []
+        additional = [self.ns1]
+        authority.append(dns.RRHeader(domain, dns.NS, dns.IN,
+                                      3600, self.ns, auth=True))
+
+        # The order of logic:
+        # - What class?
+        # - What domain: in-addr.arpa, domain root, or subdomain?
+        # - What query type: A, PTR, NS, ...?
+
+        if cls != dns.IN:
+            # Hahaha.  No.
+            return defer.fail(failure.Failure(dns.AuthoritativeDomainError(name)))
+
+        if name.endswith(".in-addr.arpa"):
+            if type in (dns.PTR, dns.ALL_RECORDS):
+                ip = '.'.join(reversed(name.split('.')[:-2]))
+                value = invirt.database.NIC.query.filter_by(ip=ip).first()
+                if value and value.hostname:
+                    hostname = value.hostname
+                    if '.' not in hostname:
+                        hostname = hostname + "." + config.dns.domains[0]
+                    record = dns.Record_PTR(hostname, ttl)
+                    results.append(dns.RRHeader(name, dns.PTR, dns.IN,
+                                                ttl, record, auth=True))
+                else: # IP address doesn't point to an active host
+                    return defer.fail(failure.Failure(dns.AuthoritativeDomainError(name)))
+            elif type == dns.SOA:
+                results.append(dns.RRHeader(domain, dns.SOA, dns.IN,
+                                            ttl, self.soa, auth=True))
+            # FIXME: Should only return success with no records if the name actually exists
+
+        elif name == domain or name == '.'+domain:
+            if type in (dns.A, dns.ALL_RECORDS):
+                record = dns.Record_A(config.dns.nameservers[0].ip, ttl)
+                results.append(dns.RRHeader(name, dns.A, dns.IN,
+                                            ttl, record, auth=True))
+            elif type == dns.NS:
+                results.append(dns.RRHeader(domain, dns.NS, dns.IN,
+                                            ttl, self.ns, auth=True))
+                authority = []
+            elif type == dns.SOA:
+                results.append(dns.RRHeader(domain, dns.SOA, dns.IN,
+                                            ttl, self.soa, auth=True))
+
+        else:
+            host = name[:-len(domain)-1]
+            value = invirt.database.NIC.query.filter_by(hostname=host).first()
+            if value:
+                ip = value.ip
+            else:
+                value = invirt.database.Machine.query().filter_by(name=host).first()
+                if value:
+                    ip = value.nics[0].ip
+                else:
+                    return defer.fail(failure.Failure(dns.AuthoritativeDomainError(name)))
+            if ip is None:
+                return defer.fail(failure.Failure(dns.AuthoritativeDomainError(name)))
+            if type in (dns.A, dns.ALL_RECORDS):
+                record = dns.Record_A(ip, ttl)
+                results.append(dns.RRHeader(name, dns.A, dns.IN,
+                                            ttl, record, auth=True))
+            elif type == dns.SOA:
+                results.append(dns.RRHeader(domain, dns.SOA, dns.IN,
+                                            ttl, self.soa, auth=True))
+
+        if len(results) == 0:
+            authority = []
+            additional = []
+        return defer.succeed((results, authority, additional))
+
+class QuotingBindAuthority(authority.BindAuthority):
+    """
+    A BindAuthority that (almost) deals with quoting correctly
+    
+    This will catch double quotes as marking the start or end of a
+    quoted phrase, unless the double quote is escaped by a backslash
+    """
+    # Match either a quoted or unquoted string literal followed by
+    # whitespace or the end of line.  This yields two groups, one of
+    # which has a match, and the other of which is None, depending on
+    # whether the string literal was quoted or unquoted; this is what
+    # necessitates the subsequent filtering out of groups that are
+    # None.
+    string_pat = \
+            re.compile(r'"((?:[^"\\]|\\.)*)"|((?:[^\\\s]|\\.)+)(?:\s+|\s*$)')
+
+    # For interpreting escapes.
+    escape_pat = re.compile(r'\\(.)')
+
+    def collapseContinuations(self, lines):
+        L = []
+        state = 0
+        for line in lines:
+            if state == 0:
+                if line.find('(') == -1:
+                    L.append(line)
+                else:
+                    L.append(line[:line.find('(')])
+                    state = 1
+            else:
+                if line.find(')') != -1:
+                    L[-1] += ' ' + line[:line.find(')')]
+                    state = 0
+                else:
+                    L[-1] += ' ' + line
+        lines = L
+        L = []
+
+        for line in lines:
+            in_quote = False
+            split_line = []
+            for m in self.string_pat.finditer(line):
+                [x] = [x for x in m.groups() if x is not None]
+                split_line.append(self.escape_pat.sub(r'\1', x))
+            L.append(split_line)
+        return filter(None, L)
+
+if '__main__' == __name__:
+    resolvers = []
+    try:
+        for zone in config.dns.zone_files:
+            for origin in config.dns.domains:
+                r = QuotingBindAuthority(zone)
+                # This sucks, but if I want a generic zone file, I have to
+                # reload the information by hand
+                r.origin = origin
+                lines = open(zone).readlines()
+                lines = r.collapseContinuations(r.stripComments(lines))
+                r.parseLines(lines)
+                
+                resolvers.append(r)
+    except InvirtConfigError:
+        # Don't care if zone_files isn't defined
+        pass
+    resolvers.append(DatabaseAuthority())
+
+    verbosity = 0
+    f = server.DNSServerFactory(authorities=resolvers, verbose=verbosity)
+    p = dns.DNSDatagramProtocol(f)
+    f.noisy = p.noisy = verbosity
+    
+    reactor.listenUDP(53, p)
+    reactor.listenTCP(53, f)
+    reactor.run()
