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

Legend:
Removed from v.6  
changed lines
  Added in v.393

  ViewVC Help
Powered by ViewVC 1.1.26