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