--- bin/dhcpd.pl 2009/07/27 11:46:44 8 +++ bin/dhcpd.pl 2009/07/28 10:29:33 17 @@ -8,14 +8,17 @@ use IO::Socket::INET; use Net::DHCP::Packet; use Net::DHCP::Constants; +use File::Slurp; use Data::Dump qw/dump/; die "need to run $0 as root like this\nsudo $0\n" unless $< == 0; my $debug = shift @ARGV; -our ( $server_ip, $next_file ); -require "config.pl"; +our ( $file, $next_file ); +our ( $ip_from, $ip_to ) = ( 10, 100 ); + +our $server_ip = readlink 'conf/server.ip'; my $sock = IO::Socket::INET->new( LocalPort => 67, @@ -29,35 +32,48 @@ Type => SOCK_DGRAM, ) or die "Failed to bind to socket: $@"; -my $_ip = 10; -my $_mac2ip; + +my $addr = $ip_from; sub client_ip { my ( $mac ) = @_; - my $ip = $_mac2ip->{$mac}; - return $ip if $ip; + my $conf = "conf/$server_ip"; + mkdir $conf unless -e $conf; + + if ( -e "$conf/$mac" ) { + my $ip = read_file "conf/mac/$mac"; + print "$mac old $ip\n"; + return $ip; + } + + mkdir $_ foreach grep { ! -e $_ } map { "$conf/$_" } ( 'ip', 'mac' ); - $ip = $server_ip; - $ip =~ s{\.\d+$}{.$_ip}; - $_mac2ip->{$mac} = $ip; - - $_ip++; - if ( $_ip == 100 ) { - warn "IP roll-over to 10\n"; - $_ip = 10; + my $prefix = $server_ip; + $prefix =~ s{\.\d+$}{.}; + my $ip = $prefix . $addr; + while ( -e "conf/ip/$ip" ) { + $ip = $prefix . $addr++; + die "all addresses allocated!" if $addr == $ip_to; } + write_file "$conf/mac/$mac", $ip; + symlink "$conf/mac/$mac", "conf/ip/$ip"; + + print "$mac NEW $ip\n"; + return $ip; } while (1) { + require "config.pl"; # refresh config + print "waiting for DHCP requests on ",$sock->sockhost,":",$sock->sockport,"\n"; my $buf; $sock->recv($buf, 1024); - print "<< peer:",$sock->peerhost,":",$sock->peerport,"\n"; + print "<< ",$sock->peerhost,":",$sock->peerport,"\n"; if (defined $buf) { @@ -73,8 +89,13 @@ my $mac = substr($dhcp->chaddr(),0,$dhcp->hlen()*2); my $ip = client_ip($mac); - my $file = $next_file; - $file = 'undionly.kpxe' if ! $file || $dhcp->getOptionValue(DHO_USER_CLASS()) ne 'gPXE'; + if ( ! $file ) { + if ( $dhcp->getOptionValue(DHO_USER_CLASS()) ne 'gPXE' ) { + $file = 'undionly.kpxe'; + } else { + $file = $next_file; + } + } my $packet = new Net::DHCP::Packet( Op => BOOTREPLY(),