extracted client::next_ip
[pxelator] / lib / PXElator / dhcpd.pm
1 package dhcpd;
2
3 =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;
14 use warnings;
15
16 use autodie;
17
18 use IO::Socket::INET;
19 use File::Slurp;
20 use Data::Dump qw/dump/;
21
22 use lib '..';
23 use Net::DHCP::Packet;
24 use Net::DHCP::Constants 0.67;
25
26 use server;
27 my $debug = server::debug;
28
29 if ( ! $server::ip ) {
30         my $server_ip = `/sbin/ifconfig`;
31         $server_ip =~ s/^.+?addr:([\d\.]+).*$/$1/gs;
32         $server::ip = $server_ip;
33 }
34
35 warn "server ip $server::ip range: $server::ip_from - $server::ip_to\n";
36
37 use client;
38
39 sub client_ip {
40         my ( $mac ) = @_;
41
42         my $conf = $server::conf;
43         mkdir $conf unless -e $conf;
44
45         if ( -e "$conf/mac/$mac" ) {
46                 my $ip = read_file "$conf/mac/$mac";
47                 print "RENEW $mac $ip\n";
48                 return $ip;
49         }
50
51         my $ip = client::next_ip;
52
53         write_file "$conf/mac/$mac", $ip;
54
55         my $ip_path = "$conf/ip/$ip";
56         mkdir $ip_path unless -e $ip_path;
57
58         if ( -l "$ip_path/mac" && readlink "$ip_path/mac" ne "$conf/mac/$mac" ) {
59                 warn "$mac IP changed from ", readlink "$ip_path/mac", " to $ip";
60                 unlink "$ip_path/mac";
61         };
62         symlink "$conf/mac/$mac", "$ip_path/mac";
63
64         print "$mac NEW $ip\n";
65
66         return $ip;
67 }
68
69 use log;
70 use config;
71 use pxelinux;
72 use client;
73
74 our $file;
75 our $transaction = 0; # FIXME predictible transaction numbers
76
77 sub process_packet {
78         my $sock = shift;
79
80         server->refresh;
81
82         my $buf;
83         $sock->recv($buf, 1024);
84         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         $dhcp->comment( $transaction++ );
92
93         warn "recv: ", $dhcp->toString if $debug;
94
95         my $mac = substr($dhcp->chaddr(),0,$dhcp->hlen()*2);
96         my $ip = client_ip($mac);
97
98 =for later
99
100         my $user_class = $dhcp->getOptionValue(DHO_USER_CLASS());
101
102         if ( $user_class eq 'gPXE' ) {
103                 $file = $gpxe_file;
104         } elsif ( ! $file ) {
105                 $file = 'undionly.kpxe';
106         }
107
108 =cut
109
110         config::for_ip( $ip );
111
112         my $packet = {
113                 Op              => BOOTREPLY(),
114                 Hops    => $dhcp->hops(),
115                 Xid             => $dhcp->xid(),
116                 Flags   => $dhcp->flags(),
117                 Ciaddr  => $dhcp->ciaddr(),
118                 Yiaddr  => $ip,
119                 Siaddr  => $server::ip,
120                 Giaddr  => $dhcp->giaddr(),
121                 Chaddr  => $dhcp->chaddr(),
122                 File    => $file,
123                 DHO_DHCP_SERVER_IDENTIFIER()    => $server::ip, # busybox/udhcpc needs it but doesn't request
124         };
125
126         my $options = {
127                 DHO_SUBNET_MASK()       => $server::netmask,
128                 DHO_ROUTERS()           => $server::ip,
129                 DHO_DOMAIN_NAME()       => $server::domain_name,
130                 DHO_NAME_SERVERS()      => $server::ip,
131                 DHO_DOMAIN_NAME_SERVERS() => $server::ip,
132                 DHO_HOST_NAME()         => client::conf( $ip, 'hostname' ),
133                 DHO_BROADCAST_ADDRESS() => $server::bcast,
134 #               DHO_NTP_SERVERS() => '',
135         };
136
137         my @requested = split(/\s/, $dhcp->getOptionValue(DHO_DHCP_PARAMETER_REQUEST_LIST));
138         warn "options ",dump( $options ), ' requested: ',dump( @requested ) if $debug;
139
140         my @missing;
141         foreach ( @requested ) {
142                 if ( defined $options->{$_} ) {
143                         $packet->{$_} = $options->{$_};
144                 } else {
145                         push @missing, $_;
146                 }
147         }
148
149         warn "W: options requested but missing: ",dump( @missing ),$/;
150
151         foreach my $opt ( 'magic', 'config_file', 'path_prefix', 'reboot_time' ) {
152                 my $DH0 = eval 'DHO_PXELINUX_' . uc $opt;
153                 warn "DH0: $@" if $@;
154                 my $v = eval "\$pxelinux::$opt";
155                 warn "v: $@" if $@;
156                 next unless defined $v;
157                 warn "pxelinux dhcp option $opt = $DH0 = $v\n" if $debug;
158                 $packet->{ $DH0 } = $v;
159         }
160
161         my $messagetype = $dhcp->getOptionValue(DHO_DHCP_MESSAGE_TYPE());
162
163         if ($messagetype eq DHCPDISCOVER()) {
164                 log::mac $mac, "DHCP DISCOVER";
165                 $packet->{Comment} = $dhcp->comment();
166                 $packet->{DHO_DHCP_MESSAGE_TYPE()} = DHCPOFFER();
167         } elsif ($messagetype eq DHCPREQUEST()) {
168                 my $requested_ip = $dhcp->getOptionValue(DHO_DHCP_REQUESTED_ADDRESS());
169                 log::mac $mac, "DHCP REQUEST $requested_ip $ip $file";
170                 if ( $ip eq $requested_ip ) {
171                         $packet->{DHO_DHCP_MESSAGE_TYPE()}      = DHCPACK();
172                         $packet->{DHO_DHCP_LEASE_TIME()}        = 5 * 60; # 5 min
173 #                       $packet->{DHO_ROOT_PATH()}              = '/exports/foobar';
174                 } else {
175                         $packet->{DHO_DHCP_MESSAGE_TYPE()} = DHCPNAK();
176                         $packet->{DHO_DHCP_MESSAGE()} = "Bad request, expected $ip";
177                 }
178         } elsif ($messagetype eq DHCPINFORM()) {
179                 log::mac $mac, "DHCP INFORM ignored";
180         } else {
181                 log::mac $mac, "$messagetype igored (bootp?)";
182         }
183
184         warn ">> $mac == $ip server: $server::ip", $file ? " file: $file\n" : "\n" if $debug;
185
186         $packet = new Net::DHCP::Packet( %$packet );
187         warn "send ",$packet->toString() if $debug;
188
189         my $reply = IO::Socket::INET->new(
190                 LocalAddr => $server::ip,
191                 LocalPort => 67,
192                 Proto => "udp",
193                 Broadcast => 1,
194                 PeerAddr => '255.255.255.255',
195                 PeerPort => 68,
196                 Reuse => 1,
197         ) or die "socket: $@";
198
199         my $buff = $packet->serialize();
200         $reply->send( $buff, 0 ) or die "Error sending: $!\n";
201
202 #       system("arp -s $ip $mac"),
203
204 }
205
206 sub start {
207
208         my $sock = IO::Socket::INET->new(
209                 LocalPort       => 67,
210 #               LocalAddr       => 'localhost',
211 #               LocalAddr       => '10.0.0.100',
212                 LocalAddr       => '0.0.0.0',
213                 Proto           => 'udp',
214                 ReuseAddr       => 1,
215 #               PeerPort        => getservbyname('bootpc', 'udp'),
216                 Broadcast       => 1,
217                 Type            => SOCK_DGRAM,
218         ) or die "Failed to bind to socket: $@";
219
220         print "DHCP listen on ",$sock->sockhost,":",$sock->sockport,"\n";
221
222         while (1) {
223                 process_packet $sock;
224         }
225 }
226
227 warn "loaded";
228
229 1;