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

Legend:
Removed from v.22  
changed lines
  Added in v.313

  ViewVC Help
Powered by ViewVC 1.1.26