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