source: trunk/packages/invirt-dhcp/invirt-dhcpserver @ 2491

Last change on this file since 2491 was 2491, checked in by oremanj, 15 years ago

[invirt-dhcp] Improve standards compliance

Provide a server-identifier option containing our IP address, as
is required by several DHCP clients including gPXE (used for the
Debathena network install CD) and Windows.

Reuse the existing DHCP socket in a bindtodevice - sendto - restore
global binding sequence, instead of creating a new socket for each
reply, in order to keep replies coming from port 67. This is required
by the standard, some client programs, and all DHCP forwarders.

  • Property svn:executable set to *
File size: 9.7 KB
RevLine 
[189]1#!/usr/bin/python
[191]2import sys
[189]3import pydhcplib
[190]4import pydhcplib.dhcp_network
[189]5from pydhcplib.dhcp_packet import *
6from pydhcplib.type_hw_addr import hwmac
7from pydhcplib.type_ipv4 import ipv4
[191]8from pydhcplib.type_strlist import strlist
[202]9import socket
10import IN
[189]11
[1034]12import syslog as s
[189]13
[202]14import time
[1033]15from invirt import database
16from invirt.config import structs as config
[189]17
[1033]18dhcp_options = {'subnet_mask': config.dhcp.netmask,
19                'router': config.dhcp.gateway,
20                'domain_name_server': ','.join(config.dhcp.dns),
[2362]21                'ip_address_lease_time': 60*60*24}
[191]22
[189]23class DhcpBackend:
[1033]24    def __init__(self):
25        database.connect()
[202]26    def findNIC(self, mac):
[1033]27        database.clear_cache()
[2347]28        return database.NIC.query().filter_by(mac_addr=mac).first()
[202]29    def find_interface(self, packet):
30        chaddr = hwmac(packet.GetHardwareAddress())
31        nic = self.findNIC(str(chaddr))
32        if nic is None or nic.ip is None:
[1042]33            return None
[202]34        ipstr = ''.join(reversed(['%02X' % i for i in ipv4(nic.ip).list()]))
35        for line in open('/proc/net/route'):
36            parts = line.split()
37            if parts[1] == ipstr:
[1034]38                s.syslog(s.LOG_DEBUG, "find_interface found "+str(nic.ip)+" on "+parts[0])
[1033]39                return parts[0]
[1042]40        return None
[202]41                           
42    def getParameters(self, **extra):
43        all_options=dict(dhcp_options)
44        all_options.update(extra)
[191]45        options = {}
[202]46        for parameter, value in all_options.iteritems():
47            if value is None:
48                continue
[191]49            option_type = DhcpOptionsTypes[DhcpOptions[parameter]]
[189]50
[191]51            if option_type == "ipv4" :
52                # this is a single ip address
53                options[parameter] = map(int,value.split("."))
54            elif option_type == "ipv4+" :
55                # this is multiple ip address
56                iplist = value.split(",")
57                opt = []
58                for single in iplist :
[202]59                    opt.extend(ipv4(single).list())
[191]60                options[parameter] = opt
61            elif option_type == "32-bits" :
62                # This is probably a number...
63                digit = int(value)
64                options[parameter] = [digit>>24&0xFF,(digit>>16)&0xFF,(digit>>8)&0xFF,digit&0xFF]
65            elif option_type == "16-bits" :
66                digit = int(value)
67                options[parameter] = [(digit>>8)&0xFF,digit&0xFF]
68
69            elif option_type == "char" :
70                digit = int(value)
71                options[parameter] = [digit&0xFF]
72
73            elif option_type == "bool" :
74                if value=="False" or value=="false" or value==0 :
75                    options[parameter] = [0]
76                else : options[parameter] = [1]
77                   
78            elif option_type == "string" :
79                options[parameter] = strlist(value).list()
[377]80           
81            elif option_type == "RFC3397" :
82                parsed_value = ""
83                for item in value:
84                    components = item.split('.')
85                    item_fmt = "".join(chr(len(elt)) + elt for elt in components) + "\x00"
86                    parsed_value += item_fmt
[191]87               
[377]88                options[parameter] = strlist(parsed_value).list()
89           
[191]90            else :
91                options[parameter] = strlist(value).list()
92        return options
93
[189]94    def Discover(self, packet):
[1034]95        s.syslog(s.LOG_DEBUG, "dhcp_backend : Discover ")
[189]96        chaddr = hwmac(packet.GetHardwareAddress())
[202]97        nic = self.findNIC(str(chaddr))
[230]98        if nic is None or nic.machine is None:
[202]99            return False
100        ip = nic.ip
101        if ip is None:  #Deactivated?
102            return False
[377]103
104        options = {}
[252]105        if nic.hostname and '.' in nic.hostname:
[377]106            options['host_name'], options['domain_name'] = nic.hostname.split('.', 1)
[252]107        elif nic.machine.name:
[377]108            options['host_name'] = nic.machine.name
[1033]109            options['domain_name'] = config.dns.domains[0]
[252]110        else:
111            hostname = None
[377]112        if DhcpOptions['domain_search'] in packet.GetOption('parameter_request_list'):
113            options['host_name'] += '.' + options['domain_name']
114            del options['domain_name']
[1033]115            options['domain_search'] = [config.dhcp.search_domain]
[189]116        if ip is not None:
117            ip = ipv4(ip)
[1034]118            s.syslog(s.LOG_DEBUG,"dhcp_backend : Discover result = "+str(ip))
[377]119            packet_parameters = self.getParameters(**options)
[189]120
121            # FIXME: Other offer parameters go here
122            packet_parameters["yiaddr"] = ip.list()
123           
124            packet.SetMultipleOptions(packet_parameters)
125            return True
126        return False
127       
128    def Request(self, packet):
[1034]129        s.syslog(s.LOG_DEBUG, "dhcp_backend : Request")
[189]130       
131        discover = self.Discover(packet)
132       
133        chaddr = hwmac(packet.GetHardwareAddress())
134        request = packet.GetOption("request_ip_address")
[202]135        if not request:
136            request = packet.GetOption("ciaddr")
[189]137        yiaddr = packet.GetOption("yiaddr")
138
139        if not discover:
[1034]140            s.syslog(s.LOG_INFO,"Unknown MAC address: "+str(chaddr))
[189]141            return False
142       
143        if yiaddr!="0.0.0.0" and yiaddr == request :
[1034]144            s.syslog(s.LOG_INFO,"Ack ip "+str(yiaddr)+" for "+str(chaddr))
[189]145            return True
146        else:
[1034]147            s.syslog(s.LOG_INFO,"Requested ip "+str(request)+" not available for "+str(chaddr))
[189]148        return False
149
150    def Decline(self, packet):
151        pass
152    def Release(self, packet):
153        pass
154   
155
156class DhcpServer(pydhcplib.dhcp_network.DhcpServer):
157    def __init__(self, backend, options = {'client_listenport':68,'server_listenport':67}):
158        pydhcplib.dhcp_network.DhcpServer.__init__(self,"0.0.0.0",options["client_listen_port"],options["server_listen_port"],)
159        self.backend = backend
[1034]160        s.syslog(s.LOG_DEBUG, "__init__ DhcpServer")
[189]161
[202]162    def SendDhcpPacketTo(self, To, packet):
[1033]163        intf = self.backend.find_interface(packet)
[202]164        if intf:
[2491]165            self.dhcp_socket.setsockopt(socket.SOL_SOCKET, IN.SO_BINDTODEVICE, intf)
166            ret = self.dhcp_socket.sendto(packet.EncodePacket(), (To,self.emit_port))
167            self.dhcp_socket.setsockopt(socket.SOL_SOCKET, IN.SO_BINDTODEVICE, '')
[202]168            return ret
169        else:
170            return self.dhcp_socket.sendto(packet.EncodePacket(),(To,self.emit_port))
171
[189]172    def SendPacket(self, packet):
[190]173        """Encode and send the packet."""
[189]174       
175        giaddr = packet.GetOption('giaddr')
176
177        # in all case, if giaddr is set, send packet to relay_agent
178        # network address defines by giaddr
179        if giaddr!=[0,0,0,0] :
180            agent_ip = ".".join(map(str,giaddr))
181            self.SendDhcpPacketTo(agent_ip,packet)
[1034]182            s.syslog(s.LOG_DEBUG, "SendPacket to agent : "+agent_ip)
[189]183
184        # FIXME: This shouldn't broadcast if it has an IP address to send
185        # it to instead. See RFC2131 part 4.1 for full details
186        else :
[1034]187            s.syslog(s.LOG_DEBUG, "No agent, broadcast packet.")
[189]188            self.SendDhcpPacketTo("255.255.255.255",packet)
189           
190
191    def HandleDhcpDiscover(self, packet):
192        """Build and send DHCPOFFER packet in response to DHCPDISCOVER
193        packet."""
194
195        logmsg = "Get DHCPDISCOVER packet from " + hwmac(packet.GetHardwareAddress()).str()
196
[1034]197        s.syslog(s.LOG_INFO, logmsg)
[189]198        offer = DhcpPacket()
199        offer.CreateDhcpOfferPacketFrom(packet)
200       
[191]201        if self.backend.Discover(offer):
[189]202            self.SendPacket(offer)
203        # FIXME : what if false ?
204
205
206    def HandleDhcpRequest(self, packet):
207        """Build and send DHCPACK or DHCPNACK packet in response to
208        DHCPREQUEST packet. 4 types of DHCPREQUEST exists."""
209
210        ip = packet.GetOption("request_ip_address")
211        sid = packet.GetOption("server_identifier")
212        ciaddr = packet.GetOption("ciaddr")
[202]213        #packet.PrintHeaders()
214        #packet.PrintOptions()
[189]215
216        if sid != [0,0,0,0] and ciaddr == [0,0,0,0] :
[1034]217            s.syslog(s.LOG_INFO, "Get DHCPREQUEST_SELECTING_STATE packet")
[189]218
219        elif sid == [0,0,0,0] and ciaddr == [0,0,0,0] and ip :
[1034]220            s.syslog(s.LOG_INFO, "Get DHCPREQUEST_INITREBOOT_STATE packet")
[189]221
222        elif sid == [0,0,0,0] and ciaddr != [0,0,0,0] and not ip :
[1034]223            s.syslog(s.LOG_INFO,"Get DHCPREQUEST_INITREBOOT_STATE packet")
[189]224
[1034]225        else : s.syslog(s.LOG_INFO,"Get DHCPREQUEST_UNKNOWN_STATE packet : not implemented")
[189]226
227        if self.backend.Request(packet) : packet.TransformToDhcpAckPacket()
228        else : packet.TransformToDhcpNackPacket()
229
230        self.SendPacket(packet)
231
232
233
234    # FIXME: These are not yet implemented.
235    def HandleDhcpDecline(self, packet):
[1034]236        s.syslog(s.LOG_INFO, "Get DHCPDECLINE packet")
[189]237        self.backend.Decline(packet)
238       
239    def HandleDhcpRelease(self, packet):
[1034]240        s.syslog(s.LOG_INFO,"Get DHCPRELEASE packet")
[189]241        self.backend.Release(packet)
242       
243    def HandleDhcpInform(self, packet):
[1034]244        s.syslog(s.LOG_INFO, "Get DHCPINFORM packet")
[189]245
246        if self.backend.Request(packet) :
247            packet.TransformToDhcpAckPacket()
248            # FIXME : Remove lease_time from options
249            self.SendPacket(packet)
250
251        # FIXME : what if false ?
252
253if '__main__' == __name__:
254    options = { "server_listen_port":67,
255                "client_listen_port":68,
256                "listen_address":"0.0.0.0"}
[2491]257
258    myip = socket.gethostbyname(socket.gethostname())
259    if not myip:
260        print "invirt-dhcpserver: cannot determine local IP address by looking up %s" % socket.gethostname()
261        sys.exit(1)
262   
263    dhcp_options['server_identifier'] = myip
264
[1033]265    backend = DhcpBackend()
[189]266    server = DhcpServer(backend, options)
267
268    while True : server.GetNextDhcpPacket()
Note: See TracBrowser for help on using the repository browser.