Index: /package_tags/invirt-dhcp/0.0.3/debian/changelog
===================================================================
--- /package_tags/invirt-dhcp/0.0.3/debian/changelog	(revision 2494)
+++ /package_tags/invirt-dhcp/0.0.3/debian/changelog	(revision 2494)
@@ -0,0 +1,76 @@
+invirt-dhcp (0.0.3) unstable; urgency=low
+
+  * Detect local IP address and pass it as the DHCP server-identifier
+    option, as required by several DHCP clients.
+  * Reuse the existing DHCP socket for replies by binding it to the
+    client VM interface and then restoring its global binding after
+    sendto(); this keeps replies coming from port 67, as is standard.
+
+ -- Joshua Oreman <oremanj@mit.edu>  Mon, 28 Sep 2009 22:46:41 -0400
+
+invirt-dhcp (0.0.2) unstable; urgency=low
+
+  * Don't throw a sqlalchemy.exceptions.InvalidRequestError exception if
+    we get a DHCPREQUEST for a MAC address that's not in our database.
+
+ -- Evan Broder <broder@mit.edu>  Mon, 04 May 2009 21:14:26 -0400
+
+invirt-dhcp (0.0.1) unstable; urgency=low
+
+  * sipb-xen-dhcp -> invirt-dhcp
+  * Remove pointless files/ tree
+  * Use library init script
+
+ -- Evan Broder <broder@mit.edu>  Wed, 29 Oct 2008 12:41:31 -0400
+
+sipb-xen-dhcp (3.4) unstable; urgency=low
+
+  * sipb-xen-base -> invirt-base
+
+ -- Evan Broder <broder@mit.edu>  Tue, 28 Oct 2008 04:23:40 -0400
+
+sipb-xen-dhcp (3.3) unstable; urgency=low
+
+  * sipb-xen-database-common -> invirt-database
+
+ -- Evan Broder <broder@mit.edu>  Sat, 25 Oct 2008 21:02:44 -0400
+
+sipb-xen-dhcp (3.2) unstable; urgency=low
+
+  * Update dependencies to reflect new package name for python-pydhcplib
+
+ -- Evan Broder <broder@mit.edu>  Fri, 24 Oct 2008 03:24:28 -0400
+
+sipb-xen-dhcp (3.1) unstable; urgency=low
+
+  * Take out the hack to reconnect to the database if it goes away
+
+ -- Evan Broder <broder@mit.edu>  Sat, 04 Oct 2008 23:22:19 -0400
+
+sipb-xen-dhcp (3) unstable; urgency=low
+
+  * invirt-configurize dhcp
+  * Use the syslog instead of the event_logger module
+  * Install the server in a more standard location
+
+ -- Evan Broder <broder@mit.edu>  Sat, 04 Oct 2008 20:10:17 -0400
+
+sipb-xen-dhcp (2) unstable; urgency=low
+
+  * DHCP server should send information to set correct information
+    (fixes #44)
+
+ -- SIPB Xen Projet <sipb-xen@mit.edu>  Mon, 31 Mar 2008 19:43:00 -0400
+
+sipb-xen-dhcp (1.1) unstable; urgency=low
+
+  * Split off pydhcplib into its own package and add that as a dependency
+
+ -- SIPB Xen Project <sipb-xen@mit.edu>  Sun, 30 Mar 2008 16:59:46 -0400
+
+sipb-xen-dhcp (1) unstable; urgency=low
+
+  * Initial Release.
+
+ -- SIPB Xen Project <sipb-xen@mit.edu>  Sun, 25 Feb 2008 00:05:12 -0500
+
Index: /package_tags/invirt-dhcp/0.0.3/debian/compat
===================================================================
--- /package_tags/invirt-dhcp/0.0.3/debian/compat	(revision 2494)
+++ /package_tags/invirt-dhcp/0.0.3/debian/compat	(revision 2494)
@@ -0,0 +1,1 @@
+4
Index: /package_tags/invirt-dhcp/0.0.3/debian/control
===================================================================
--- /package_tags/invirt-dhcp/0.0.3/debian/control	(revision 2494)
+++ /package_tags/invirt-dhcp/0.0.3/debian/control	(revision 2494)
@@ -0,0 +1,11 @@
+Source: invirt-dhcp
+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.8.0
+
+Package: invirt-dhcp
+Architecture: all
+Depends: ${misc:Depends}, daemon, invirt-database, python-pydhcplib (>= 0.3.2-1), invirt-base
+Description: Install and enable the DHCP server
Index: /package_tags/invirt-dhcp/0.0.3/debian/copyright
===================================================================
--- /package_tags/invirt-dhcp/0.0.3/debian/copyright	(revision 2494)
+++ /package_tags/invirt-dhcp/0.0.3/debian/copyright	(revision 2494)
@@ -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-dhcp/0.0.3/debian/invirt-dhcp.init
===================================================================
--- /package_tags/invirt-dhcp/0.0.3/debian/invirt-dhcp.init	(revision 2494)
+++ /package_tags/invirt-dhcp/0.0.3/debian/invirt-dhcp.init	(revision 2494)
@@ -0,0 +1,61 @@
+#! /bin/sh
+### BEGIN INIT INFO
+# Provides:          invirt-dhcp
+# 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 DHCP 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 DHCP server"
+NAME=invirt-dhcp
+DAEMON=/usr/sbin/invirt-dhcpserver
+DAEMON_ARGS=""
+PIDFILE=/var/run/$NAME.pid
+SCRIPTNAME=/etc/init.d/$NAME
+
+# Exit if the package is not installed
+[ -x "$DAEMON" ] || exit 0
+
+. /lib/init/std-init.sh
+
+#
+# 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"
+}
+
+std_init "$1"
Index: /package_tags/invirt-dhcp/0.0.3/debian/invirt-dhcp.install
===================================================================
--- /package_tags/invirt-dhcp/0.0.3/debian/invirt-dhcp.install	(revision 2494)
+++ /package_tags/invirt-dhcp/0.0.3/debian/invirt-dhcp.install	(revision 2494)
@@ -0,0 +1,1 @@
+invirt-dhcpserver usr/sbin
Index: /package_tags/invirt-dhcp/0.0.3/debian/rules
===================================================================
--- /package_tags/invirt-dhcp/0.0.3/debian/rules	(revision 2494)
+++ /package_tags/invirt-dhcp/0.0.3/debian/rules	(revision 2494)
@@ -0,0 +1,3 @@
+#!/usr/bin/make -f
+
+include /usr/share/cdbs/1/rules/debhelper.mk
Index: /package_tags/invirt-dhcp/0.0.3/invirt-dhcpserver
===================================================================
--- /package_tags/invirt-dhcp/0.0.3/invirt-dhcpserver	(revision 2494)
+++ /package_tags/invirt-dhcp/0.0.3/invirt-dhcpserver	(revision 2494)
@@ -0,0 +1,268 @@
+#!/usr/bin/python
+import sys
+import pydhcplib
+import pydhcplib.dhcp_network
+from pydhcplib.dhcp_packet import *
+from pydhcplib.type_hw_addr import hwmac
+from pydhcplib.type_ipv4 import ipv4
+from pydhcplib.type_strlist import strlist
+import socket
+import IN
+
+import syslog as s
+
+import time
+from invirt import database
+from invirt.config import structs as config
+
+dhcp_options = {'subnet_mask': config.dhcp.netmask,
+                'router': config.dhcp.gateway,
+                'domain_name_server': ','.join(config.dhcp.dns),
+                'ip_address_lease_time': 60*60*24}
+
+class DhcpBackend:
+    def __init__(self):
+        database.connect()
+    def findNIC(self, mac):
+        database.clear_cache()
+        return database.NIC.query().filter_by(mac_addr=mac).first()
+    def find_interface(self, packet):
+        chaddr = hwmac(packet.GetHardwareAddress())
+        nic = self.findNIC(str(chaddr))
+        if nic is None or nic.ip is None:
+            return None
+        ipstr = ''.join(reversed(['%02X' % i for i in ipv4(nic.ip).list()]))
+        for line in open('/proc/net/route'):
+            parts = line.split()
+            if parts[1] == ipstr:
+                s.syslog(s.LOG_DEBUG, "find_interface found "+str(nic.ip)+" on "+parts[0])
+                return parts[0]
+        return None
+                            
+    def getParameters(self, **extra):
+        all_options=dict(dhcp_options)
+        all_options.update(extra)
+        options = {}
+        for parameter, value in all_options.iteritems():
+            if value is None:
+                continue
+            option_type = DhcpOptionsTypes[DhcpOptions[parameter]]
+
+            if option_type == "ipv4" :
+                # this is a single ip address
+                options[parameter] = map(int,value.split("."))
+            elif option_type == "ipv4+" :
+                # this is multiple ip address
+                iplist = value.split(",")
+                opt = []
+                for single in iplist :
+                    opt.extend(ipv4(single).list())
+                options[parameter] = opt
+            elif option_type == "32-bits" :
+                # This is probably a number...
+                digit = int(value)
+                options[parameter] = [digit>>24&0xFF,(digit>>16)&0xFF,(digit>>8)&0xFF,digit&0xFF]
+            elif option_type == "16-bits" :
+                digit = int(value)
+                options[parameter] = [(digit>>8)&0xFF,digit&0xFF]
+
+            elif option_type == "char" :
+                digit = int(value)
+                options[parameter] = [digit&0xFF]
+
+            elif option_type == "bool" :
+                if value=="False" or value=="false" or value==0 :
+                    options[parameter] = [0]
+                else : options[parameter] = [1]
+                    
+            elif option_type == "string" :
+                options[parameter] = strlist(value).list()
+            
+            elif option_type == "RFC3397" :
+                parsed_value = ""
+                for item in value:
+                    components = item.split('.')
+                    item_fmt = "".join(chr(len(elt)) + elt for elt in components) + "\x00"
+                    parsed_value += item_fmt
+                
+                options[parameter] = strlist(parsed_value).list()
+            
+            else :
+                options[parameter] = strlist(value).list()
+        return options
+
+    def Discover(self, packet):
+        s.syslog(s.LOG_DEBUG, "dhcp_backend : Discover ")
+        chaddr = hwmac(packet.GetHardwareAddress())
+        nic = self.findNIC(str(chaddr))
+        if nic is None or nic.machine is None:
+            return False
+        ip = nic.ip
+        if ip is None:  #Deactivated?
+            return False
+
+        options = {}
+        if nic.hostname and '.' in nic.hostname:
+            options['host_name'], options['domain_name'] = nic.hostname.split('.', 1)
+        elif nic.machine.name:
+            options['host_name'] = nic.machine.name
+            options['domain_name'] = config.dns.domains[0]
+        else:
+            hostname = None
+        if DhcpOptions['domain_search'] in packet.GetOption('parameter_request_list'):
+            options['host_name'] += '.' + options['domain_name']
+            del options['domain_name']
+            options['domain_search'] = [config.dhcp.search_domain]
+        if ip is not None:
+            ip = ipv4(ip)
+            s.syslog(s.LOG_DEBUG,"dhcp_backend : Discover result = "+str(ip))
+            packet_parameters = self.getParameters(**options)
+
+            # FIXME: Other offer parameters go here
+            packet_parameters["yiaddr"] = ip.list()
+            
+            packet.SetMultipleOptions(packet_parameters)
+            return True
+        return False
+        
+    def Request(self, packet):
+        s.syslog(s.LOG_DEBUG, "dhcp_backend : Request")
+        
+        discover = self.Discover(packet)
+        
+        chaddr = hwmac(packet.GetHardwareAddress())
+        request = packet.GetOption("request_ip_address")
+        if not request:
+            request = packet.GetOption("ciaddr")
+        yiaddr = packet.GetOption("yiaddr")
+
+        if not discover:
+            s.syslog(s.LOG_INFO,"Unknown MAC address: "+str(chaddr))
+            return False
+        
+        if yiaddr!="0.0.0.0" and yiaddr == request :
+            s.syslog(s.LOG_INFO,"Ack ip "+str(yiaddr)+" for "+str(chaddr))
+            return True
+        else:
+            s.syslog(s.LOG_INFO,"Requested ip "+str(request)+" not available for "+str(chaddr))
+        return False
+
+    def Decline(self, packet):
+        pass
+    def Release(self, packet):
+        pass
+    
+
+class DhcpServer(pydhcplib.dhcp_network.DhcpServer):
+    def __init__(self, backend, options = {'client_listenport':68,'server_listenport':67}):
+        pydhcplib.dhcp_network.DhcpServer.__init__(self,"0.0.0.0",options["client_listen_port"],options["server_listen_port"],)
+        self.backend = backend
+        s.syslog(s.LOG_DEBUG, "__init__ DhcpServer")
+
+    def SendDhcpPacketTo(self, To, packet):
+        intf = self.backend.find_interface(packet)
+        if intf:
+            self.dhcp_socket.setsockopt(socket.SOL_SOCKET, IN.SO_BINDTODEVICE, intf)
+            ret = self.dhcp_socket.sendto(packet.EncodePacket(), (To,self.emit_port))
+            self.dhcp_socket.setsockopt(socket.SOL_SOCKET, IN.SO_BINDTODEVICE, '')
+            return ret
+        else:
+            return self.dhcp_socket.sendto(packet.EncodePacket(),(To,self.emit_port))
+
+    def SendPacket(self, packet):
+        """Encode and send the packet."""
+        
+        giaddr = packet.GetOption('giaddr')
+
+        # in all case, if giaddr is set, send packet to relay_agent
+        # network address defines by giaddr
+        if giaddr!=[0,0,0,0] :
+            agent_ip = ".".join(map(str,giaddr))
+            self.SendDhcpPacketTo(agent_ip,packet)
+            s.syslog(s.LOG_DEBUG, "SendPacket to agent : "+agent_ip)
+
+        # FIXME: This shouldn't broadcast if it has an IP address to send
+        # it to instead. See RFC2131 part 4.1 for full details
+        else :
+            s.syslog(s.LOG_DEBUG, "No agent, broadcast packet.")
+            self.SendDhcpPacketTo("255.255.255.255",packet)
+            
+
+    def HandleDhcpDiscover(self, packet):
+        """Build and send DHCPOFFER packet in response to DHCPDISCOVER
+        packet."""
+
+        logmsg = "Get DHCPDISCOVER packet from " + hwmac(packet.GetHardwareAddress()).str()
+
+        s.syslog(s.LOG_INFO, logmsg)
+        offer = DhcpPacket()
+        offer.CreateDhcpOfferPacketFrom(packet)
+        
+        if self.backend.Discover(offer):
+            self.SendPacket(offer)
+        # FIXME : what if false ?
+
+
+    def HandleDhcpRequest(self, packet):
+        """Build and send DHCPACK or DHCPNACK packet in response to
+        DHCPREQUEST packet. 4 types of DHCPREQUEST exists."""
+
+        ip = packet.GetOption("request_ip_address")
+        sid = packet.GetOption("server_identifier")
+        ciaddr = packet.GetOption("ciaddr")
+        #packet.PrintHeaders()
+        #packet.PrintOptions()
+
+        if sid != [0,0,0,0] and ciaddr == [0,0,0,0] :
+            s.syslog(s.LOG_INFO, "Get DHCPREQUEST_SELECTING_STATE packet")
+
+        elif sid == [0,0,0,0] and ciaddr == [0,0,0,0] and ip :
+            s.syslog(s.LOG_INFO, "Get DHCPREQUEST_INITREBOOT_STATE packet")
+
+        elif sid == [0,0,0,0] and ciaddr != [0,0,0,0] and not ip :
+            s.syslog(s.LOG_INFO,"Get DHCPREQUEST_INITREBOOT_STATE packet")
+
+        else : s.syslog(s.LOG_INFO,"Get DHCPREQUEST_UNKNOWN_STATE packet : not implemented")
+
+        if self.backend.Request(packet) : packet.TransformToDhcpAckPacket()
+        else : packet.TransformToDhcpNackPacket()
+
+        self.SendPacket(packet)
+
+
+
+    # FIXME: These are not yet implemented.
+    def HandleDhcpDecline(self, packet):
+        s.syslog(s.LOG_INFO, "Get DHCPDECLINE packet")
+        self.backend.Decline(packet)
+        
+    def HandleDhcpRelease(self, packet):
+        s.syslog(s.LOG_INFO,"Get DHCPRELEASE packet")
+        self.backend.Release(packet)
+        
+    def HandleDhcpInform(self, packet):
+        s.syslog(s.LOG_INFO, "Get DHCPINFORM packet")
+
+        if self.backend.Request(packet) :
+            packet.TransformToDhcpAckPacket()
+            # FIXME : Remove lease_time from options
+            self.SendPacket(packet)
+
+        # FIXME : what if false ?
+
+if '__main__' == __name__:
+    options = { "server_listen_port":67,
+                "client_listen_port":68,
+                "listen_address":"0.0.0.0"}
+
+    myip = socket.gethostbyname(socket.gethostname())
+    if not myip:
+        print "invirt-dhcpserver: cannot determine local IP address by looking up %s" % socket.gethostname()
+        sys.exit(1)
+    
+    dhcp_options['server_identifier'] = myip
+
+    backend = DhcpBackend()
+    server = DhcpServer(backend, options)
+
+    while True : server.GetNextDhcpPacket()
