[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 |
---|
| 10 | import IN |
---|
[189] | 11 | |
---|
[190] | 12 | import event_logger |
---|
| 13 | if '__main__' == __name__: |
---|
[191] | 14 | event_logger.init("stdout", 'DEBUG', {}) |
---|
[189] | 15 | from event_logger import Log |
---|
| 16 | |
---|
[202] | 17 | import psycopg2 |
---|
| 18 | import time |
---|
[1033] | 19 | from invirt import database |
---|
| 20 | from invirt.config import structs as config |
---|
[189] | 21 | |
---|
[1033] | 22 | dhcp_options = {'subnet_mask': config.dhcp.netmask, |
---|
| 23 | 'router': config.dhcp.gateway, |
---|
| 24 | 'domain_name_server': ','.join(config.dhcp.dns), |
---|
[202] | 25 | 'ip_address_lease_time': 60*60*24} |
---|
[191] | 26 | |
---|
[189] | 27 | class DhcpBackend: |
---|
[1033] | 28 | def __init__(self): |
---|
| 29 | database.connect() |
---|
[202] | 30 | def findNIC(self, mac): |
---|
[1033] | 31 | database.clear_cache() |
---|
[202] | 32 | for i in range(3): |
---|
| 33 | try: |
---|
[1033] | 34 | value = database.NIC.query().filter_by(mac_addr=mac).one() |
---|
[202] | 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. |
---|
[1033] | 40 | database.connect() |
---|
[202] | 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: |
---|
[1033] | 48 | return |
---|
[202] | 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]) |
---|
[1033] | 54 | return parts[0] |
---|
| 55 | return |
---|
[202] | 56 | |
---|
| 57 | def getParameters(self, **extra): |
---|
| 58 | all_options=dict(dhcp_options) |
---|
| 59 | all_options.update(extra) |
---|
[191] | 60 | options = {} |
---|
[202] | 61 | for parameter, value in all_options.iteritems(): |
---|
| 62 | if value is None: |
---|
| 63 | continue |
---|
[191] | 64 | option_type = DhcpOptionsTypes[DhcpOptions[parameter]] |
---|
[189] | 65 | |
---|
[191] | 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 : |
---|
[202] | 74 | opt.extend(ipv4(single).list()) |
---|
[191] | 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() |
---|
[377] | 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 |
---|
[191] | 102 | |
---|
[377] | 103 | options[parameter] = strlist(parsed_value).list() |
---|
| 104 | |
---|
[191] | 105 | else : |
---|
| 106 | options[parameter] = strlist(value).list() |
---|
| 107 | return options |
---|
| 108 | |
---|
[189] | 109 | def Discover(self, packet): |
---|
| 110 | Log.Output(Log.debug,"dhcp_backend : Discover ") |
---|
| 111 | chaddr = hwmac(packet.GetHardwareAddress()) |
---|
[202] | 112 | nic = self.findNIC(str(chaddr)) |
---|
[230] | 113 | if nic is None or nic.machine is None: |
---|
[202] | 114 | return False |
---|
| 115 | ip = nic.ip |
---|
| 116 | if ip is None: #Deactivated? |
---|
| 117 | return False |
---|
[377] | 118 | |
---|
| 119 | options = {} |
---|
[252] | 120 | if nic.hostname and '.' in nic.hostname: |
---|
[377] | 121 | options['host_name'], options['domain_name'] = nic.hostname.split('.', 1) |
---|
[252] | 122 | elif nic.machine.name: |
---|
[377] | 123 | options['host_name'] = nic.machine.name |
---|
[1033] | 124 | options['domain_name'] = config.dns.domains[0] |
---|
[252] | 125 | else: |
---|
| 126 | hostname = None |
---|
[377] | 127 | if DhcpOptions['domain_search'] in packet.GetOption('parameter_request_list'): |
---|
| 128 | options['host_name'] += '.' + options['domain_name'] |
---|
| 129 | del options['domain_name'] |
---|
[1033] | 130 | options['domain_search'] = [config.dhcp.search_domain] |
---|
[189] | 131 | if ip is not None: |
---|
| 132 | ip = ipv4(ip) |
---|
| 133 | Log.Output(Log.debug,"dhcp_backend : Discover result = "+str(ip)) |
---|
[377] | 134 | packet_parameters = self.getParameters(**options) |
---|
[189] | 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") |
---|
[202] | 150 | if not request: |
---|
| 151 | request = packet.GetOption("ciaddr") |
---|
[189] | 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 | |
---|
[202] | 177 | def SendDhcpPacketTo(self, To, packet): |
---|
[1033] | 178 | intf = self.backend.find_interface(packet) |
---|
[202] | 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 | |
---|
[189] | 190 | def SendPacket(self, packet): |
---|
[190] | 191 | """Encode and send the packet.""" |
---|
[189] | 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 | |
---|
[191] | 219 | if self.backend.Discover(offer): |
---|
[189] | 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") |
---|
[202] | 231 | #packet.PrintHeaders() |
---|
| 232 | #packet.PrintOptions() |
---|
[189] | 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"} |
---|
[1033] | 275 | backend = DhcpBackend() |
---|
[189] | 276 | server = DhcpServer(backend, options) |
---|
| 277 | |
---|
| 278 | while True : server.GetNextDhcpPacket() |
---|