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

Legend:
Removed from v.3  
changed lines
  Added in v.449

  ViewVC Help
Powered by ViewVC 1.1.26