/[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 208 by dpavlin, Wed Aug 12 23:59:01 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_ip {
43          my ( $mac ) = @_;          my ( $mac ) = @_;
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" ) {          } else {
54                  $ip = $prefix . $addr++;                  $ip = client::next_ip( $mac );
55                  die "all addresses allocated!" if $addr == $ip_to;                  print "NEW $mac $ip\n";
56          }          }
57    
         write_file "$conf/mac/$mac", $ip;  
         symlink    "$conf/mac/$mac", "conf/ip/$ip";  
   
         print "$mac NEW $ip\n";  
   
58          return $ip;          return $ip;
59  }  }
60    
61  while (1) {  use log;
62    use config;
63    use pxelinux;
64    use client;
65    
66    our $file;
67    our $transaction = 0; # FIXME predictible transaction numbers
68    
69          require "config.pl"; # refresh config  sub process_packet {
70            my $sock = shift;
71    
72          print "waiting for DHCP requests on ",$sock->sockhost,":",$sock->sockport,"\n";          server->refresh;
73    
74          my $buf;          my $buf;
75          $sock->recv($buf, 1024);          $sock->recv($buf, 1024);
76          print "<< ",$sock->peerhost,":",$sock->peerport,"\n";          my $size = 'empty';
77            $size = length($buf) . ' bytes' if defined $buf;
78    
79          if (defined $buf) {          print "packet from ",$sock->peerhost,":",$sock->peerport," $size\n" if $debug;
80            return unless $buf;
81    
82                  my $dhcp;          my $dhcp = Net::DHCP::Packet->new($buf);
83            $dhcp->comment( $transaction++ );
84    
85                  eval { $dhcp = Net::DHCP::Packet->new($buf); };          warn "recv: ", $dhcp->toString if $debug;
                 die "can't use request", dump( $buf ) if $@;  
86    
87                  if ( $debug ) {          my $mac = substr($dhcp->chaddr(),0,$dhcp->hlen()*2);
88                          warn "recv: ", $dhcp->toString, "\n\n";          my $ip = client_ip($mac);
                 }  
89    
90                  my $mac = substr($dhcp->chaddr(),0,$dhcp->hlen()*2);          my $hostname = $dhcp->getOptionValue(DHO_HOST_NAME);
91                  my $ip = client_ip($mac);          print "$ip ", client::conf( $ip => 'hostname', default => $hostname ), " >> /etc/hosts\n";
92    
93                  if ( ! $file ) {          my $audit = { mac => format::mac($mac), ip => $ip, hostname => $hostname };
94                          if ( $dhcp->getOptionValue(DHO_USER_CLASS()) ne 'gPXE' ) {  
95                                  $file = 'undionly.kpxe';  =for later
96                          } else {  
97                                  $file = $next_file;          my $user_class = $dhcp->getOptionValue(DHO_USER_CLASS());
98                          }  
99                  }          if ( $user_class eq 'gPXE' ) {
100                    $file = $gpxe_file;
101            } elsif ( ! $file ) {
102                    $file = 'undionly.kpxe';
103            }
104    
105    =cut
106    
107            config::for_ip( $ip );
108    
109                  my $packet = new Net::DHCP::Packet(          my $packet = {
110                          Op              => BOOTREPLY(),                  Op              => BOOTREPLY(),
111                          Hops    => $dhcp->hops(),                  Hops    => $dhcp->hops(),
112                          Xid             => $dhcp->xid(),                  Xid             => $dhcp->xid(),
113                          Flags   => $dhcp->flags(),                  Flags   => $dhcp->flags(),
114                          Ciaddr  => $dhcp->ciaddr(),                  Ciaddr  => $dhcp->ciaddr(),
115                          Yiaddr  => $ip,                  Yiaddr  => $ip,
116                          Siaddr  => $server_ip,                  Siaddr  => $server::ip,
117                          Giaddr  => $dhcp->giaddr(),                  Giaddr  => $dhcp->giaddr(),
118                          Chaddr  => $dhcp->chaddr(),                  Chaddr  => $dhcp->chaddr(),
119                          File    => $file,                  File    => $file,
120  #                       DHO_DHCP_MESSAGE_TYPE() => DHCPACK(),                  DHO_DHCP_SERVER_IDENTIFIER()    => $server::ip, # busybox/udhcpc needs it but doesn't request
121                  DHO_SUBNET_MASK() => '255.0.0.0',          };
122                  );  
123            my $options = {
124                  warn ">> $mac == $ip server $server_ip\n";                  DHO_SUBNET_MASK()       => $server::netmask,
125                                    DHO_ROUTERS()           => $server::ip,
126                  warn "## ",$packet->toString(),"\n" if $debug;                  DHO_DOMAIN_NAME()       => $server::domain_name,
127                    DHO_NAME_SERVERS()      => $server::ip,
128                  my $reply = IO::Socket::INET->new(                  DHO_DOMAIN_NAME_SERVERS() => $server::ip,
129                          LocalAddr => $server_ip,                  DHO_HOST_NAME()         => client::conf( $ip, 'hostname' ),
130                          LocalPort => 67,                  DHO_BROADCAST_ADDRESS() => $server::bcast,
131                          Proto => "udp",  #               DHO_NTP_SERVERS() => '',
132                          Broadcast => 1,          };
133                          PeerAddr => '255.255.255.255',  
134                          PeerPort => 68,          my @requested = split(/\s/, $dhcp->getOptionValue(DHO_DHCP_PARAMETER_REQUEST_LIST));
135                          Reuse => 1,          warn "options ",dump( $options ), ' requested: ',dump( @requested ) if $debug;
136                  ) or die "socket: $@";  
137            my @missing;
138            foreach ( @requested ) {
139                    if ( defined $options->{$_} ) {
140                            $packet->{$_} = $options->{$_};
141                    } else {
142                            push @missing, $_;
143                    }
144            }
145    
146                  my $buff = $packet->serialize();          warn "W: options requested but missing: ",dump( @missing ),$/;
147                  $reply->send( $buff, 0 ) or die "Error sending: $!\n";          $audit->{requested} = [ @requested ];
148            $audit->{missing}   = [ @missing   ];
149    
150            foreach my $opt ( 'magic', 'config_file', 'path_prefix', 'reboot_time' ) {
151                    my $DH0 = eval 'DHO_PXELINUX_' . uc $opt;
152                    warn "DH0: $@" if $@;
153                    my $v = eval "\$pxelinux::$opt";
154                    warn "v: $@" if $@;
155                    next unless defined $v;
156                    warn "pxelinux dhcp option $opt = $DH0 = $v\n" if $debug;
157                    $packet->{ $DH0 } = $v;
158            }
159    
160  #               system("arp -s $ip $mac"),          my $messagetype = $dhcp->getOptionValue(DHO_DHCP_MESSAGE_TYPE());
161    
162            if ($messagetype eq DHCPDISCOVER()) {
163                    $audit->{type} = 'discover';
164                    $packet->{Comment} = $dhcp->comment();
165                    $packet->{DHO_DHCP_MESSAGE_TYPE()} = DHCPOFFER();
166            } elsif ($messagetype eq DHCPREQUEST()) {
167                    my $requested_ip = $dhcp->getOptionValue(DHO_DHCP_REQUESTED_ADDRESS());
168                    $audit->{type} = 'request';
169                    if ( $ip eq $requested_ip ) {
170                            $packet->{DHO_DHCP_MESSAGE_TYPE()}      = DHCPACK();
171                            $packet->{DHO_DHCP_LEASE_TIME()}        = 5 * 60; # 5 min
172    #                       $packet->{DHO_ROOT_PATH()}              = '/exports/foobar';
173                    } else {
174                            $packet->{DHO_DHCP_MESSAGE_TYPE()} = DHCPNAK();
175                            $packet->{DHO_DHCP_MESSAGE()} = "Bad request, expected $ip";
176                    }
177            } elsif ($messagetype eq DHCPINFORM()) {
178                    $audit->{type} = 'inform';
179          } else {          } else {
180                  print "No bootp request.\n";                  $audit->{type} = sprintf('ignored %x', $messagetype);
181          }          }
182    
183            warn ">> $mac == $ip server: $server::ip", $file ? " file: $file\n" : "\n" if $debug;
184            $audit->{response} = $packet;
185    
186            $packet = new Net::DHCP::Packet( %$packet );
187            warn "send ",$packet->toString() if $debug;
188    
189            CouchDB::audit( $audit->{type}, $audit );
190    
191            my $reply = IO::Socket::INET->new(
192                    LocalAddr => $server::ip,
193                    LocalPort => 67,
194                    Proto => "udp",
195                    Broadcast => 1,
196                    PeerAddr => '255.255.255.255',
197                    PeerPort => 68,
198                    Reuse => 1,
199            ) or die "socket: $@";
200    
201            my $buff = $packet->serialize();
202            $reply->send( $buff, 0 ) or die "Error sending: $!\n";
203    
204    #       system("arp -s $ip $mac"),
205    
206  }  }
207    
208    sub start {
209    
210            my $sock = IO::Socket::INET->new(
211                    LocalPort       => 67,
212    #               LocalAddr       => 'localhost',
213    #               LocalAddr       => '10.0.0.100',
214                    LocalAddr       => '0.0.0.0',
215                    Proto           => 'udp',
216                    ReuseAddr       => 1,
217    #               PeerPort        => getservbyname('bootpc', 'udp'),
218                    Broadcast       => 1,
219                    Type            => SOCK_DGRAM,
220            ) or die "Failed to bind to socket: $@";
221    
222            print "DHCP listen on ",$sock->sockhost,":",$sock->sockport,"\n";
223    
224            CouchDB::audit( 'start', { 'listen' => { addr => $sock->sockhost, port => $sock->sockport } } );
225    
226            while (1) {
227                    process_packet $sock;
228            }
229    }
230    
231    warn "loaded";
232    
233    1;

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

  ViewVC Help
Powered by ViewVC 1.1.26