/[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 8 by dpavlin, Mon Jul 27 11:46:44 2009 UTC lib/PXElator/dhcpd.pm revision 456 by dpavlin, Sat Jan 2 15:49:09 2010 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  my $debug = shift @ARGV;  warn "server ip $server::ip range: $server::ip_from - $server::ip_to\n";
39    
40  our ( $server_ip, $next_file );  use client;
 require "config.pl";  
41    
42  my $sock = IO::Socket::INET->new(  sub client_mac_ip {
43          LocalPort       => 67,          my ( $mac, $request_ip ) = @_;
44  #       LocalAddr       => 'localhost',  
45  #       LocalAddr       => '10.0.0.100',          if ( ! $mac ) {
46          LocalAddr       => '0.0.0.0',                  warn "W: no mac in requiest\n";
47          Proto           => 'udp',                  return;
48          ReuseAddr       => 1,          }
49  #       PeerPort        => getservbyname('bootpc', 'udp'),  
50          Broadcast       => 1,          my $conf = $server::conf;
51          Type            => SOCK_DGRAM,          mkdir $conf unless -e $conf;
52  ) or die "Failed to bind to socket: $@";  
53            my $ip;
54  my $_ip = 10;  
55  my $_mac2ip;          if ( $ip = client::ip_from_mac( $mac ) ) {
56                    print "RENEW $mac $ip\n";
57  sub client_ip {                  client::save_ip_mac( $ip, $mac );
58          my ( $mac ) = @_;                  return $ip;
59            } elsif ( ip::in_dhcp_range( $request_ip ) || $request_ip eq '0.0.0.0' ) {
60          my $ip = $_mac2ip->{$mac};                  $ip = client::next_ip( $mac );
61          return $ip if $ip;                  print "NEW $mac $ip\n";
62            } else {
63          $ip = $server_ip;                  $ip = $request_ip;
64          $ip =~ s{\.\d+$}{.$_ip};                  client::save_ip_mac( $ip, $mac );
65          $_mac2ip->{$mac} = $ip;                  warn "W: $ip out of server range $server::ip/$server::netmask\n";
   
         $_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          print "waiting for DHCP requests on ",$sock->sockhost,":",$sock->sockport,"\n";  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            warn "recv: ", $dhcp->toString if $debug;
93    
94          if (defined $buf) {          $dhcp->comment( $transaction++ );
95    
96                  my $dhcp;          my $mac = format::mac( substr($dhcp->chaddr(),0,$dhcp->hlen()*2) );
97            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                  eval { $dhcp = Net::DHCP::Packet->new($buf); };  =cut
                 die "can't use request", dump( $buf ) if $@;  
121    
122                  if ( $debug ) {          config::for_ip( $ip );
123                          warn "recv: ", $dhcp->toString, "\n\n";  
124            my $server;
125            map { $server->{ $_ } = eval '$server::' . $_ } ( 'ip', 'netmask', 'bcast', 'domain' );
126    
127            if ( my $force = client::conf( $ip => 'dhcpd.pl' ) ) {
128                    eval $force;
129                    die "$force\n$@" if $@;
130                    warn "force server ", dump $server;
131            }
132    
133            my $packet = {
134                    Op              => BOOTREPLY(),
135                    Hops    => $dhcp->hops(),
136                    Xid             => $dhcp->xid(),
137                    Flags   => $dhcp->flags(),
138                    Ciaddr  => $dhcp->ciaddr(),
139                    Yiaddr  => $ip,
140                    Siaddr  => $server->{ip},
141                    Giaddr  => $dhcp->giaddr(),
142                    Chaddr  => $dhcp->chaddr(),
143                    File    => $file,
144                    DHO_DHCP_SERVER_IDENTIFIER()    => $server->{ip},       # busybox/udhcpc needs it but doesn't request
145            };
146    
147            my $options = {
148                    DHO_SUBNET_MASK()       => $server->{netmask},
149                    DHO_ROUTERS()           => $server->{ip},
150                    DHO_DOMAIN_NAME()       => $server->{domain},
151                    DHO_NAME_SERVERS()      => $server->{ip},
152                    DHO_DOMAIN_NAME_SERVERS() => $server->{ip},
153                    DHO_HOST_NAME()         => client::conf( $ip, 'hostname' ),
154                    DHO_BROADCAST_ADDRESS() => $server->{bcast},
155    #               DHO_NTP_SERVERS() => '',
156            };
157    
158            my @requested = split(/\s/, $dhcp->getOptionValue(DHO_DHCP_PARAMETER_REQUEST_LIST));
159            warn "options ",dump( $options ), ' requested: ',dump( @requested ) if $debug;
160    
161            my @missing;
162            foreach ( @requested ) {
163                    if ( defined $options->{$_} ) {
164                            $packet->{$_} = $options->{$_};
165                    } else {
166                            push @missing, $_;
167                  }                  }
168            }
169    
170            warn "W: options requested but missing: ",dump( @missing ),$/;
171            $audit->{requested} = [ @requested ];
172            $audit->{missing}   = [ @missing   ];
173    
174            foreach my $opt ( 'magic', 'config_file', 'path_prefix', 'reboot_time' ) {
175                    my $DH0 = eval 'DHO_PXELINUX_' . uc $opt;
176                    warn "DH0: $@" if $@;
177                    my $v = eval "\$pxelinux::$opt";
178                    warn "v: $@" if $@;
179                    next unless defined $v;
180                    warn "pxelinux dhcp option $opt = $DH0 = $v\n" if $debug;
181                    $packet->{ $DH0 } = $v;
182            }
183    
184            my $messagetype = $dhcp->getOptionValue(DHO_DHCP_MESSAGE_TYPE());
185    
186            my @type;
187    
188            if ($messagetype eq DHCPDISCOVER()) {
189                    $packet->{Comment} = $dhcp->comment();
190                    $packet->{DHO_DHCP_MESSAGE_TYPE()} = DHCPOFFER();
191                    @type = qw( discover offer );
192            } elsif ($messagetype eq DHCPREQUEST()) {
193                    @type = qw( request );
194                    my $requested_ip = $dhcp->getOptionValue(DHO_DHCP_REQUESTED_ADDRESS()) || $dhcp->ciaddr();
195                    if ( $ip eq $requested_ip ) {
196                            $packet->{DHO_DHCP_MESSAGE_TYPE()}      = DHCPACK();
197                            $packet->{DHO_DHCP_LEASE_TIME()}        = 5 * 60; # 5 min
198    #                       $packet->{DHO_ROOT_PATH()}              = '/exports/foobar';
199                            $type[1] = 'ack';
200                    } else {
201                            $packet->{DHO_DHCP_MESSAGE_TYPE()} = DHCPNAK();
202                            $packet->{DHO_DHCP_MESSAGE()} = "Bad request, expected $ip got $requested_ip";
203                            $type[1] = 'nak';
204                    }
205            } elsif ($messagetype eq DHCPINFORM()) {
206                    @type = qw( inform ignored );
207            } else {
208                    @type = ( $messagetype, 'ignored' );
209            }
210    
211                  my $mac = substr($dhcp->chaddr(),0,$dhcp->hlen()*2);          warn "# type ",dump @type;
212                  my $ip = client_ip($mac);          $audit->{type} = [ @type ];
213    
214                  my $file =  $next_file;          $audit->{response} = $packet;
                 $file = 'undionly.kpxe' if ! $file || $dhcp->getOptionValue(DHO_USER_CLASS()) ne 'gPXE';  
215    
216                  my $packet = new Net::DHCP::Packet(          $packet = new Net::DHCP::Packet( %$packet );
217                          Op              => BOOTREPLY(),          warn "send ",$packet->toString() if $debug;
218                          Hops    => $dhcp->hops(),  
219                          Xid             => $dhcp->xid(),          if ( ip::in_dhcp_range( $ip ) ) {
220                          Flags   => $dhcp->flags(),                  my $buff = $packet->serialize();
                         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;  
221    
222                  my $reply = IO::Socket::INET->new(                  my $reply = IO::Socket::INET->new(
223                          LocalAddr => $server_ip,                          LocalAddr => $server->{ip},
224                          LocalPort => 67,                          LocalPort => 67,
225                          Proto => "udp",                          Proto => "udp",
226                          Broadcast => 1,                          Broadcast => 1,
227                          PeerAddr => '255.255.255.255',  #                       PeerAddr => '255.255.255.255',
228                            PeerAddr => $server->{bcast},
229                          PeerPort => 68,                          PeerPort => 68,
230                          Reuse => 1,                          Reuse => 1,
231                  ) or die "socket: $@";                  ) or die "socket: $@";
232    
                 my $buff = $packet->serialize();  
233                  $reply->send( $buff, 0 ) or die "Error sending: $!\n";                  $reply->send( $buff, 0 ) or die "Error sending: $!\n";
234                    warn ">> $mac == $ip server: $server->{ip}", $file ? " file: $file\n" : "\n";
 #               system("arp -s $ip $mac"),  
   
235          } else {          } else {
236                  print "No bootp request.\n";                  $audit->{error} = "$ip not in server range $server::ip $server::netmask - no packet sent";
237                    warn $audit->{error};
238          }          }
239    
240            CouchDB::audit( @type, $audit );
241    
242    #       system("arp -s $ip $mac"),
243    
244  }  }
245    
246    sub start {
247    
248            my $sock = IO::Socket::INET->new(
249                    LocalPort       => 67,
250    #               LocalAddr       => 'localhost',
251    #               LocalAddr       => '10.0.0.100',
252                    LocalAddr       => '0.0.0.0',
253                    Proto           => 'udp',
254                    ReuseAddr       => 1,
255    #               PeerPort        => getservbyname('bootpc', 'udp'),
256                    Broadcast       => 1,
257                    Type            => SOCK_DGRAM,
258            ) or die "Failed to bind to socket: $@";
259    
260            print "DHCP listen on ",$sock->sockhost,":",$sock->sockport,"\n";
261    
262            CouchDB::audit( 'start', { addr => $sock->sockhost, port => $sock->sockport } );
263    
264            while (1) {
265                    server->refresh;
266                    process_packet $sock;
267            }
268    }
269    
270    warn "loaded";
271    
272    1;

Legend:
Removed from v.8  
changed lines
  Added in v.456

  ViewVC Help
Powered by ViewVC 1.1.26