/[pxelator]/lib/PXElator/dhcpd.pm
This is repository of my old source code which isn't updated any more. Go to git.rot13.org for current projects!
ViewVC logotype

Diff of /lib/PXElator/dhcpd.pm

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

bin/dhcpd.pl revision 17 by dpavlin, Tue Jul 28 10:29:33 2009 UTC lib/PXElator/dhcpd.pm revision 260 by dpavlin, Wed Aug 19 10:56:04 2009 UTC
# Line 1  Line 1 
1  #!/usr/bin/perl  package dhcpd;
2    
3  # based on http://www.perlmonks.org/index.pl?node_id=325248  =head1 dhcpd
4    
5    start with:
6    
7     perl -Ilib/PXElator -Ilib -Mdhcpd -e start
8    
9    based on L<http://www.perlmonks.org/index.pl?node_id=325248>
10    
11    =cut
12    
13  use strict;  use strict;
14  use warnings;  use warnings;
15    
16    use autodie;
17    
18  use IO::Socket::INET;  use IO::Socket::INET;
 use Net::DHCP::Packet;  
 use Net::DHCP::Constants;  
19  use File::Slurp;  use File::Slurp;
20  use Data::Dump qw/dump/;  use Data::Dump qw/dump/;
21    
22  die "need to run $0 as root like this\nsudo $0\n" unless $< == 0;  use lib '..';
23    use Net::DHCP::Packet;
24  my $debug = shift @ARGV;  use Net::DHCP::Constants 0.67;
25    
26  our ( $file, $next_file );  use CouchDB;
27  our ( $ip_from, $ip_to ) = ( 10, 100 );  use format;
28    
29  our $server_ip = readlink 'conf/server.ip';  use server;
30    my $debug = server::debug;
31    
32  my $sock = IO::Socket::INET->new(  if ( ! $server::ip ) {
33          LocalPort       => 67,          my $server_ip = `/sbin/ifconfig`;
34  #       LocalAddr       => 'localhost',          $server_ip =~ s/^.+?addr:([\d\.]+).*$/$1/gs;
35  #       LocalAddr       => '10.0.0.100',          $server::ip = $server_ip;
36          LocalAddr       => '0.0.0.0',  }
         Proto           => 'udp',  
         ReuseAddr       => 1,  
 #       PeerPort        => getservbyname('bootpc', 'udp'),  
         Broadcast       => 1,  
         Type            => SOCK_DGRAM,  
 ) or die "Failed to bind to socket: $@";  
37    
38    warn "server ip $server::ip range: $server::ip_from - $server::ip_to\n";
39    
40  my $addr = $ip_from;  use client;
41    
42  sub client_ip {  sub client_mac_ip {
43          my ( $mac ) = @_;          my ( $mac, $request_ip ) = @_;
44    
45          my $conf = "conf/$server_ip";          my $conf = $server::conf;
46          mkdir $conf unless -e $conf;          mkdir $conf unless -e $conf;
47    
48          if ( -e "$conf/$mac" ) {          my $ip;
                 my $ip = read_file "conf/mac/$mac";  
                 print "$mac old $ip\n";  
                 return $ip;  
         }  
   
         mkdir $_ foreach grep { ! -e $_ } map { "$conf/$_" } ( 'ip', 'mac' );  
49    
50          my $prefix = $server_ip;          if ( $ip = client::ip_from_mac( $mac ) ) {
51          $prefix =~ s{\.\d+$}{.};                  print "RENEW $mac $ip\n";
52          my $ip = $prefix . $addr;                  return $ip;
53          while ( -e "conf/ip/$ip" ) {          } elsif ( in_our_range( $request_ip ) ) {
54                  $ip = $prefix . $addr++;                  $ip = client::next_ip( $mac );
55                  die "all addresses allocated!" if $addr == $ip_to;                  print "NEW $mac $ip\n";
56            } else {
57                    $ip = $request_ip;
58                    client::save_ip_mac( $ip, $mac );
59                    warn "W: $ip our of server range $server::ip $server::netmask\n";
60          }          }
61    
         write_file "$conf/mac/$mac", $ip;  
         symlink    "$conf/mac/$mac", "conf/ip/$ip";  
   
         print "$mac NEW $ip\n";  
   
62          return $ip;          return $ip;
63  }  }
64    
65  while (1) {  use log;
66    use config;
67    use pxelinux;
68    use client;
69    
70    our $file;
71    our $transaction = 0; # FIXME predictible transaction numbers
72    
73    sub ip2bin { pack('C*', split(/\./, $_[0])) };
74    sub in_our_range {
75            my $ip = shift;
76            return 1 if $ip eq '0.0.0.0';
77            return 1 if (
78                    ( ip2bin($ip)         & ip2bin($server::netmask) )
79                    eq
80                    ( ip2bin($server::ip) & ip2bin($server::netmask) )
81            );
82    }
83    
84          require "config.pl"; # refresh config  sub process_packet {
85            my $sock = shift;
86    
87          print "waiting for DHCP requests on ",$sock->sockhost,":",$sock->sockport,"\n";          server->refresh;
88    
89          my $buf;          my $buf;
90          $sock->recv($buf, 1024);          $sock->recv($buf, 1024);
91          print "<< ",$sock->peerhost,":",$sock->peerport,"\n";          my $size = 'empty';
92            $size = length($buf) . ' bytes' if defined $buf;
93    
94            print "packet from ",$sock->peerhost,":",$sock->peerport," $size\n" if $debug;
95            return unless $buf;
96    
97            my $dhcp = Net::DHCP::Packet->new($buf);
98    
99          if (defined $buf) {          warn "recv: ", $dhcp->toString if $debug;
100    
101                  my $dhcp;          $dhcp->comment( $transaction++ );
102    
103                  eval { $dhcp = Net::DHCP::Packet->new($buf); };          my $mac = substr($dhcp->chaddr(),0,$dhcp->hlen()*2);
104                  die "can't use request", dump( $buf ) if $@;          my $ip = client_mac_ip($mac, $dhcp->ciaddr);
105    
106            my $hostname = $dhcp->getOptionValue(DHO_HOST_NAME);
107            print "$ip ", client::conf( $ip => 'hostname', default => $hostname ), " >> /etc/hosts\n";
108    
109            my $audit = { mac => format::mac($mac), ip => $ip, hostname => $hostname,
110                    options => {
111                            map {
112                                    ( $_ => $dhcp->getOptionValue( $_ ) )
113                            } @{ $dhcp->{options_order} }
114                    },
115            };
116    
117    =for later
118    
119            my $user_class = $dhcp->getOptionValue(DHO_USER_CLASS());
120    
121            if ( $user_class eq 'gPXE' ) {
122                    $file = $gpxe_file;
123            } elsif ( ! $file ) {
124                    $file = 'undionly.kpxe';
125            }
126    
127                  if ( $debug ) {  =cut
128                          warn "recv: ", $dhcp->toString, "\n\n";  
129            config::for_ip( $ip );
130    
131            my $packet = {
132                    Op              => BOOTREPLY(),
133                    Hops    => $dhcp->hops(),
134                    Xid             => $dhcp->xid(),
135                    Flags   => $dhcp->flags(),
136                    Ciaddr  => $dhcp->ciaddr(),
137                    Yiaddr  => $ip,
138                    Siaddr  => $server::ip,
139                    Giaddr  => $dhcp->giaddr(),
140                    Chaddr  => $dhcp->chaddr(),
141                    File    => $file,
142                    DHO_DHCP_SERVER_IDENTIFIER()    => $server::ip, # busybox/udhcpc needs it but doesn't request
143            };
144    
145            my $options = {
146                    DHO_SUBNET_MASK()       => $server::netmask,
147                    DHO_ROUTERS()           => $server::ip,
148                    DHO_DOMAIN_NAME()       => $server::domain_name,
149                    DHO_NAME_SERVERS()      => $server::ip,
150                    DHO_DOMAIN_NAME_SERVERS() => $server::ip,
151                    DHO_HOST_NAME()         => client::conf( $ip, 'hostname' ),
152                    DHO_BROADCAST_ADDRESS() => $server::bcast,
153    #               DHO_NTP_SERVERS() => '',
154            };
155    
156            my @requested = split(/\s/, $dhcp->getOptionValue(DHO_DHCP_PARAMETER_REQUEST_LIST));
157            warn "options ",dump( $options ), ' requested: ',dump( @requested ) if $debug;
158    
159            my @missing;
160            foreach ( @requested ) {
161                    if ( defined $options->{$_} ) {
162                            $packet->{$_} = $options->{$_};
163                    } else {
164                            push @missing, $_;
165                  }                  }
166            }
167    
168                  my $mac = substr($dhcp->chaddr(),0,$dhcp->hlen()*2);          warn "W: options requested but missing: ",dump( @missing ),$/;
169                  my $ip = client_ip($mac);          $audit->{requested} = [ @requested ];
170            $audit->{missing}   = [ @missing   ];
171    
172            foreach my $opt ( 'magic', 'config_file', 'path_prefix', 'reboot_time' ) {
173                    my $DH0 = eval 'DHO_PXELINUX_' . uc $opt;
174                    warn "DH0: $@" if $@;
175                    my $v = eval "\$pxelinux::$opt";
176                    warn "v: $@" if $@;
177                    next unless defined $v;
178                    warn "pxelinux dhcp option $opt = $DH0 = $v\n" if $debug;
179                    $packet->{ $DH0 } = $v;
180            }
181    
182            my $messagetype = $dhcp->getOptionValue(DHO_DHCP_MESSAGE_TYPE());
183    
184                  if ( ! $file ) {          if ($messagetype eq DHCPDISCOVER()) {
185                          if ( $dhcp->getOptionValue(DHO_USER_CLASS()) ne 'gPXE' ) {                  $audit->{type} = 'discover';
186                                  $file = 'undionly.kpxe';                  $packet->{Comment} = $dhcp->comment();
187                          } else {                  $packet->{DHO_DHCP_MESSAGE_TYPE()} = DHCPOFFER();
188                                  $file = $next_file;          } elsif ($messagetype eq DHCPREQUEST()) {
189                          }                  my $requested_ip = $dhcp->getOptionValue(DHO_DHCP_REQUESTED_ADDRESS());
190                    $audit->{type} = 'request';
191                    if ( $ip eq $requested_ip ) {
192                            $packet->{DHO_DHCP_MESSAGE_TYPE()}      = DHCPACK();
193                            $packet->{DHO_DHCP_LEASE_TIME()}        = 5 * 60; # 5 min
194    #                       $packet->{DHO_ROOT_PATH()}              = '/exports/foobar';
195                    } else {
196                            $packet->{DHO_DHCP_MESSAGE_TYPE()} = DHCPNAK();
197                            $packet->{DHO_DHCP_MESSAGE()} = "Bad request, expected $ip";
198                  }                  }
199            } elsif ($messagetype eq DHCPINFORM()) {
200                    $audit->{type} = 'inform';
201            } else {
202                    $audit->{type} = sprintf('ignored %x', $messagetype);
203            }
204    
205            warn ">> $mac == $ip server: $server::ip", $file ? " file: $file\n" : "\n" if $debug;
206            $audit->{response} = $packet;
207    
208            $packet = new Net::DHCP::Packet( %$packet );
209            warn "send ",$packet->toString() if $debug;
210    
211                  my $packet = new Net::DHCP::Packet(          if ( in_our_range( $ip ) ) {
212                          Op              => BOOTREPLY(),                  my $buff = $packet->serialize();
                         Hops    => $dhcp->hops(),  
                         Xid             => $dhcp->xid(),  
                         Flags   => $dhcp->flags(),  
                         Ciaddr  => $dhcp->ciaddr(),  
                         Yiaddr  => $ip,  
                         Siaddr  => $server_ip,  
                         Giaddr  => $dhcp->giaddr(),  
                         Chaddr  => $dhcp->chaddr(),  
                         File    => $file,  
 #                       DHO_DHCP_MESSAGE_TYPE() => DHCPACK(),  
                 DHO_SUBNET_MASK() => '255.0.0.0',  
                 );  
   
                 warn ">> $mac == $ip server $server_ip\n";  
                   
                 warn "## ",$packet->toString(),"\n" if $debug;  
213    
214                  my $reply = IO::Socket::INET->new(                  my $reply = IO::Socket::INET->new(
215                          LocalAddr => $server_ip,                          LocalAddr => $server::ip,
216                          LocalPort => 67,                          LocalPort => 67,
217                          Proto => "udp",                          Proto => "udp",
218                          Broadcast => 1,                          Broadcast => 1,
# Line 126  while (1) { Line 221  while (1) {
221                          Reuse => 1,                          Reuse => 1,
222                  ) or die "socket: $@";                  ) or die "socket: $@";
223    
                 my $buff = $packet->serialize();  
224                  $reply->send( $buff, 0 ) or die "Error sending: $!\n";                  $reply->send( $buff, 0 ) or die "Error sending: $!\n";
   
 #               system("arp -s $ip $mac"),  
   
225          } else {          } else {
226                  print "No bootp request.\n";                  $audit->{error} = "$ip our of our range $server::ip $server::netmask";
227          }          }
228    
229            CouchDB::audit( $audit->{type}, $audit );
230    
231    #       system("arp -s $ip $mac"),
232    
233    }
234    
235    sub start {
236    
237            my $sock = IO::Socket::INET->new(
238                    LocalPort       => 67,
239    #               LocalAddr       => 'localhost',
240    #               LocalAddr       => '10.0.0.100',
241                    LocalAddr       => '0.0.0.0',
242                    Proto           => 'udp',
243                    ReuseAddr       => 1,
244    #               PeerPort        => getservbyname('bootpc', 'udp'),
245                    Broadcast       => 1,
246                    Type            => SOCK_DGRAM,
247            ) or die "Failed to bind to socket: $@";
248    
249            print "DHCP listen on ",$sock->sockhost,":",$sock->sockport,"\n";
250    
251            CouchDB::audit( 'start', { addr => $sock->sockhost, port => $sock->sockport } );
252    
253            while (1) {
254                    process_packet $sock;
255            }
256  }  }
257    
258    warn "loaded";
259    
260    1;

Legend:
Removed from v.17  
changed lines
  Added in v.260

  ViewVC Help
Powered by ViewVC 1.1.26