Index: package_tags/sipb-xen-dhcp/2/code/dhcpserver.py
===================================================================
--- package_tags/sipb-xen-dhcp/2/code/dhcpserver.py	(revision 378)
+++ package_tags/sipb-xen-dhcp/2/code/dhcpserver.py	(revision 378)
@@ -0,0 +1,280 @@
+#!/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 event_logger
+if '__main__' == __name__:
+    event_logger.init("stdout", 'DEBUG', {})
+from event_logger import Log
+
+import psycopg2
+import time
+import sipb_xen_database
+from sqlalchemy import create_engine
+
+dhcp_options = {'subnet_mask': '255.255.0.0',
+                'router': '18.181.0.1',
+                'domain_name_server': '18.70.0.160,18.71.0.151,18.72.0.3',
+                'ip_address_lease_time': 60*60*24}
+
+class DhcpBackend:
+    def __init__(self, database=None):
+        if database is not None:
+            self.database = database
+            sipb_xen_database.connect(create_engine(database))
+    def findNIC(self, mac):
+        sipb_xen_database.clear_cache()
+        for i in range(3):
+            try:
+                value = sipb_xen_database.NIC.get_by(mac_addr=mac)
+            except psycopg2.OperationalError:
+                time.sleep(0.5)
+                if i == 2:  #Try twice to reconnect.
+                    raise
+                #Sigh.  SQLAlchemy should do this itself.
+                sipb_xen_database.connect(create_engine(self.database))
+            else:
+                break
+        return value
+    def find_interface(self, packet):
+        chaddr = hwmac(packet.GetHardwareAddress())
+        nic = self.findNIC(str(chaddr))
+        if nic is None or nic.ip is None:
+            return ("18.181.0.60", 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:
+                Log.Output(Log.debug, "find_interface found "+str(nic.ip)+" on "+parts[0])
+                return ("18.181.0.60", parts[0])
+        return ("18.181.0.60", 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):
+        Log.Output(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'] = 'servers.csail.mit.edu'
+        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'] = ['mit.edu']
+        if ip is not None:
+            ip = ipv4(ip)
+            Log.Output(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):
+        Log.Output(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:
+            Log.Output(Log.info,"Unknown MAC address: "+str(chaddr))
+            return False
+        
+        if yiaddr!="0.0.0.0" and yiaddr == request :
+            Log.Output(Log.info,"Ack ip "+str(yiaddr)+" for "+str(chaddr))
+            return True
+        else:
+            Log.Output(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
+        Log.Output(Log.debug, "__init__ DhcpServer")
+
+    def SendDhcpPacketTo(self, To, packet):
+        (ip, intf) = self.backend.find_interface(packet)
+        if intf:
+            out_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+            out_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST,1)
+            out_socket.setsockopt(socket.SOL_SOCKET, IN.SO_BINDTODEVICE, intf)
+            #out_socket.bind((ip, self.listen_port))
+            ret = out_socket.sendto(packet.EncodePacket(), (To,self.emit_port))
+            out_socket.close()
+            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)
+            Log.Output(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 :
+            Log.Output(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()
+
+        Log.Output(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] :
+            Log.Output(Log.info, "Get DHCPREQUEST_SELECTING_STATE packet")
+
+        elif sid == [0,0,0,0] and ciaddr == [0,0,0,0] and ip :
+            Log.Output(Log.info, "Get DHCPREQUEST_INITREBOOT_STATE packet")
+
+        elif sid == [0,0,0,0] and ciaddr != [0,0,0,0] and not ip :
+            Log.Output(Log.info,"Get DHCPREQUEST_INITREBOOT_STATE packet")
+
+        else : Log.Output(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):
+        Log.Output(Log.info, "Get DHCPDECLINE packet")
+        self.backend.Decline(packet)
+        
+    def HandleDhcpRelease(self, packet):
+        Log.Output(Log.info,"Get DHCPRELEASE packet")
+        self.backend.Release(packet)
+        
+    def HandleDhcpInform(self, packet):
+        Log.Output(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"}
+    backend = DhcpBackend('postgres://sipb-xen@sipb-xen-dev/sipb_xen')
+    server = DhcpServer(backend, options)
+
+    while True : server.GetNextDhcpPacket()
Index: package_tags/sipb-xen-dhcp/2/code/event_logger.py
===================================================================
--- package_tags/sipb-xen-dhcp/2/code/event_logger.py	(revision 378)
+++ package_tags/sipb-xen-dhcp/2/code/event_logger.py	(revision 378)
@@ -0,0 +1,63 @@
+# Anemon Dhcp
+# Copyright (C) 2005 Mathieu Ignacio -- mignacio@april.org
+#
+# 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.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301, USA
+
+import sys
+from logging import *
+
+
+
+class EventLogger:
+    def __init__(self,logtype="stdout",loglevel=WARNING,option={}):
+        self.loglevel = loglevel
+        self.logtype = logtype
+
+        self.info = INFO
+        self.debug = DEBUG
+        self.warn = WARN
+        self.error = ERROR
+        self.critical = CRITICAL
+
+
+        self.logger = getLogger('SipbXenDhcpServer')
+
+        if logtype == "file" :
+            # into file logger
+            handler = FileHandler(option["log_file"])
+            
+        elif logtype == "syslog" :
+            handler = SysLogHandler((option["log_host"],option["log_port"]))
+
+        elif logtype == "http" :
+            handler = HTTPHandler(option["log_host"],option["log_url"],option["log_method"])
+
+        else : # logtype == "stdout" :
+            handler = StreamHandler()
+
+
+
+        handler.setFormatter(Formatter('%(asctime)s %(levelname)s %(message)s'))
+        self.logger.addHandler(handler) 
+        self.logger.setLevel(loglevel)
+
+    def Output(self,level,infostring) :
+        self.logger.log(level,infostring)
+
+def init(logtype,level,path):
+    global Log
+    
+    Log = EventLogger(logtype,eval(level),path)
+    Log.Output(INFO,"EventLogger : Started.")
Index: package_tags/sipb-xen-dhcp/2/debian/changelog
===================================================================
--- package_tags/sipb-xen-dhcp/2/debian/changelog	(revision 378)
+++ package_tags/sipb-xen-dhcp/2/debian/changelog	(revision 378)
@@ -0,0 +1,19 @@
+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/sipb-xen-dhcp/2/debian/compat
===================================================================
--- package_tags/sipb-xen-dhcp/2/debian/compat	(revision 378)
+++ package_tags/sipb-xen-dhcp/2/debian/compat	(revision 378)
@@ -0,0 +1,1 @@
+4
Index: package_tags/sipb-xen-dhcp/2/debian/control
===================================================================
--- package_tags/sipb-xen-dhcp/2/debian/control	(revision 378)
+++ package_tags/sipb-xen-dhcp/2/debian/control	(revision 378)
@@ -0,0 +1,11 @@
+Source: sipb-xen-dhcp
+Section: base
+Priority: extra
+Maintainer: SIPB Xen Project <sipb-xen@mit.edu>
+Build-Depends: cdbs (>= 0.4.23-1.1), debhelper (>= 4.1.0), subversion
+Standards-Version: 3.7.2
+
+Package: sipb-xen-dhcp
+Architecture: all
+Depends: ${misc:Depends}, daemon, sipb-xen-database-common, sipb-xen-python-pydhcplib (>= 0.3.2-2)
+Description: Install and enable the DHCP server
Index: package_tags/sipb-xen-dhcp/2/debian/copyright
===================================================================
--- package_tags/sipb-xen-dhcp/2/debian/copyright	(revision 378)
+++ package_tags/sipb-xen-dhcp/2/debian/copyright	(revision 378)
@@ -0,0 +1,3 @@
+This package was created for internal use of the SIPB Xen Project of
+the MIT Student Information Processing Board.  Ask sipb-xen@mit.edu if
+you have questions about redistribution.
Index: package_tags/sipb-xen-dhcp/2/debian/rules
===================================================================
--- package_tags/sipb-xen-dhcp/2/debian/rules	(revision 378)
+++ package_tags/sipb-xen-dhcp/2/debian/rules	(revision 378)
@@ -0,0 +1,6 @@
+#!/usr/bin/make -f
+
+include /usr/share/cdbs/1/rules/debhelper.mk
+
+binary-fixup/sipb-xen-dhcp::
+	svn co https://sipb-xen-dev.mit.edu:1111/trunk/packages/sipb-xen-dhcp/code/ $(DEB_DESTDIR)/usr/local/lib/sipb-xen-dhcp
Index: package_tags/sipb-xen-dhcp/2/debian/sipb-xen-dhcp.init
===================================================================
--- package_tags/sipb-xen-dhcp/2/debian/sipb-xen-dhcp.init	(revision 378)
+++ package_tags/sipb-xen-dhcp/2/debian/sipb-xen-dhcp.init	(revision 378)
@@ -0,0 +1,124 @@
+#! /bin/sh
+### BEGIN INIT INFO
+# Provides:          sipb-xen-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: sipb-xen DHCP server
+# Description:       
+### END INIT INFO
+
+# Author: SIPB Xen Project <sipb-xen@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 sipb-xen DHCP server"
+NAME=sipb-xen-dhcp
+DAEMON=/usr/local/lib/sipb-xen-dhcp/dhcpserver.py
+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 -D "$(dirname $DAEMON)" -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/sipb-xen-dhcp/2/debian/sipb-xen-dhcp.install
===================================================================
--- package_tags/sipb-xen-dhcp/2/debian/sipb-xen-dhcp.install	(revision 378)
+++ package_tags/sipb-xen-dhcp/2/debian/sipb-xen-dhcp.install	(revision 378)
@@ -0,0 +1,1 @@
+files/* .
