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