udhcpd: remove redundant code in send_offer()
[oweals/busybox.git] / networking / udhcp / dhcpd.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * udhcp Server
4  * Copyright (C) 1999 Matthew Ramsay <matthewr@moreton.com.au>
5  *                      Chris Trew <ctrew@moreton.com.au>
6  *
7  * Rewrite by Russ Dill <Russ.Dill@asu.edu> July 2001
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22  */
23
24 #include <syslog.h>
25 #include "common.h"
26 #include "dhcpc.h"
27 #include "dhcpd.h"
28 #include "options.h"
29
30
31 /* send a packet to gateway_nip using the kernel ip stack */
32 static int send_packet_to_relay(struct dhcp_packet *dhcp_pkt)
33 {
34         log1("Forwarding packet to relay");
35
36         return udhcp_send_kernel_packet(dhcp_pkt,
37                         server_config.server_nip, SERVER_PORT,
38                         dhcp_pkt->gateway_nip, SERVER_PORT);
39 }
40
41 /* send a packet to a specific mac address and ip address by creating our own ip packet */
42 static int send_packet_to_client(struct dhcp_packet *dhcp_pkt, int force_broadcast)
43 {
44         const uint8_t *chaddr;
45         uint32_t ciaddr;
46
47         // Was:
48         //if (force_broadcast) { /* broadcast */ }
49         //else if (dhcp_pkt->ciaddr) { /* unicast to dhcp_pkt->ciaddr */ }
50         //else if (dhcp_pkt->flags & htons(BROADCAST_FLAG)) { /* broadcast */ }
51         //else { /* unicast to dhcp_pkt->yiaddr */ }
52         // But this is wrong: yiaddr is _our_ idea what client's IP is
53         // (for example, from lease file). Client may not know that,
54         // and may not have UDP socket listening on that IP!
55         // We should never unicast to dhcp_pkt->yiaddr!
56         // dhcp_pkt->ciaddr, OTOH, comes from client's request packet,
57         // and can be used.
58
59         if (force_broadcast
60          || (dhcp_pkt->flags & htons(BROADCAST_FLAG))
61          || !dhcp_pkt->ciaddr
62         ) {
63                 log1("Broadcasting packet to client");
64                 ciaddr = INADDR_BROADCAST;
65                 chaddr = MAC_BCAST_ADDR;
66         } else {
67                 log1("Unicasting packet to client ciaddr");
68                 ciaddr = dhcp_pkt->ciaddr;
69                 chaddr = dhcp_pkt->chaddr;
70         }
71
72         return udhcp_send_raw_packet(dhcp_pkt,
73                 /*src*/ server_config.server_nip, SERVER_PORT,
74                 /*dst*/ ciaddr, CLIENT_PORT, chaddr,
75                 server_config.ifindex);
76 }
77
78 /* send a dhcp packet, if force broadcast is set, the packet will be broadcast to the client */
79 static int send_packet(struct dhcp_packet *dhcp_pkt, int force_broadcast)
80 {
81         if (dhcp_pkt->gateway_nip)
82                 return send_packet_to_relay(dhcp_pkt);
83         return send_packet_to_client(dhcp_pkt, force_broadcast);
84 }
85
86 static void init_packet(struct dhcp_packet *packet, struct dhcp_packet *oldpacket, char type)
87 {
88         udhcp_init_header(packet, type);
89         packet->xid = oldpacket->xid;
90         memcpy(packet->chaddr, oldpacket->chaddr, sizeof(oldpacket->chaddr));
91         packet->flags = oldpacket->flags;
92         packet->gateway_nip = oldpacket->gateway_nip;
93         packet->ciaddr = oldpacket->ciaddr;
94         add_simple_option(packet->options, DHCP_SERVER_ID, server_config.server_nip);
95 }
96
97 /* add in the bootp options */
98 static void add_bootp_options(struct dhcp_packet *packet)
99 {
100         packet->siaddr_nip = server_config.siaddr_nip;
101         if (server_config.sname)
102                 strncpy((char*)packet->sname, server_config.sname, sizeof(packet->sname) - 1);
103         if (server_config.boot_file)
104                 strncpy((char*)packet->file, server_config.boot_file, sizeof(packet->file) - 1);
105 }
106
107 static uint32_t select_lease_time(struct dhcp_packet *packet)
108 {
109         uint32_t lease_time_sec = server_config.max_lease_sec;
110         uint8_t *lease_time_opt = get_option(packet, DHCP_LEASE_TIME);
111         if (lease_time_opt) {
112                 move_from_unaligned32(lease_time_sec, lease_time_opt);
113                 lease_time_sec = ntohl(lease_time_sec);
114                 if (lease_time_sec > server_config.max_lease_sec)
115                         lease_time_sec = server_config.max_lease_sec;
116                 if (lease_time_sec < server_config.min_lease_sec)
117                         lease_time_sec = server_config.min_lease_sec;
118         }
119         return lease_time_sec;
120 }
121
122 /* send a DHCP OFFER to a DHCP DISCOVER */
123 static int send_offer(struct dhcp_packet *oldpacket, uint32_t static_lease_nip, struct dyn_lease *lease)
124 {
125         struct dhcp_packet packet;
126         uint32_t req_nip;
127         uint32_t lease_time_sec = server_config.max_lease_sec;
128         uint8_t *req_ip_opt;
129         const char *p_host_name;
130         struct option_set *curr;
131         struct in_addr addr;
132
133         init_packet(&packet, oldpacket, DHCPOFFER);
134
135         /* ADDME: if static, short circuit */
136         if (!static_lease_nip) {
137                 /* The client is in our lease/offered table */
138                 if (lease) {
139                         packet.yiaddr = lease->lease_nip;
140                 }
141                 /* Or the client has requested an IP */
142                 else if ((req_ip_opt = get_option(oldpacket, DHCP_REQUESTED_IP)) != NULL
143                  /* (read IP) */
144                  && (move_from_unaligned32(req_nip, req_ip_opt), 1)
145                  /* and the IP is in the lease range */
146                  && ntohl(req_nip) >= server_config.start_ip
147                  && ntohl(req_nip) <= server_config.end_ip
148                  /* and is not already taken/offered */
149                  && (!(lease = find_lease_by_nip(req_nip))
150                         /* or its taken, but expired */
151                         || is_expired_lease(lease))
152                 ) {
153                         packet.yiaddr = req_nip;
154                 }
155                 /* Otherwise, find a free IP */
156                 else {
157                         packet.yiaddr = find_free_or_expired_nip(oldpacket->chaddr);
158                 }
159
160                 if (!packet.yiaddr) {
161                         bb_error_msg("no IP addresses to give - OFFER abandoned");
162                         return -1;
163                 }
164                 p_host_name = (const char*) get_option(oldpacket, DHCP_HOST_NAME);
165                 if (add_lease(packet.chaddr, packet.yiaddr,
166                                 server_config.offer_time,
167                                 p_host_name,
168                                 p_host_name ? (unsigned char)p_host_name[OPT_LEN - OPT_DATA] : 0
169                         ) == 0
170                 ) {
171                         bb_error_msg("lease pool is full - OFFER abandoned");
172                         return -1;
173                 }
174                 lease_time_sec = select_lease_time(oldpacket);
175         } else {
176                 /* It is a static lease... use it */
177                 packet.yiaddr = static_lease_nip;
178         }
179
180         add_simple_option(packet.options, DHCP_LEASE_TIME, htonl(lease_time_sec));
181
182         curr = server_config.options;
183         while (curr) {
184                 if (curr->data[OPT_CODE] != DHCP_LEASE_TIME)
185                         add_option_string(packet.options, curr->data);
186                 curr = curr->next;
187         }
188
189         add_bootp_options(&packet);
190
191         addr.s_addr = packet.yiaddr;
192         bb_info_msg("Sending OFFER of %s", inet_ntoa(addr));
193         return send_packet(&packet, 0);
194 }
195
196 static int send_NAK(struct dhcp_packet *oldpacket)
197 {
198         struct dhcp_packet packet;
199
200         init_packet(&packet, oldpacket, DHCPNAK);
201
202         log1("Sending NAK");
203         return send_packet(&packet, 1);
204 }
205
206 static int send_ACK(struct dhcp_packet *oldpacket, uint32_t yiaddr)
207 {
208         struct dhcp_packet packet;
209         struct option_set *curr;
210         uint32_t lease_time_sec;
211         struct in_addr addr;
212         const char *p_host_name;
213
214         init_packet(&packet, oldpacket, DHCPACK);
215         packet.yiaddr = yiaddr;
216
217         lease_time_sec = select_lease_time(oldpacket);
218
219         add_simple_option(packet.options, DHCP_LEASE_TIME, htonl(lease_time_sec));
220
221         curr = server_config.options;
222         while (curr) {
223                 if (curr->data[OPT_CODE] != DHCP_LEASE_TIME)
224                         add_option_string(packet.options, curr->data);
225                 curr = curr->next;
226         }
227
228         add_bootp_options(&packet);
229
230         addr.s_addr = packet.yiaddr;
231         bb_info_msg("Sending ACK to %s", inet_ntoa(addr));
232
233         if (send_packet(&packet, 0) < 0)
234                 return -1;
235
236         p_host_name = (const char*) get_option(oldpacket, DHCP_HOST_NAME);
237         add_lease(packet.chaddr, packet.yiaddr,
238                 lease_time_sec,
239                 p_host_name,
240                 p_host_name ? (unsigned char)p_host_name[OPT_LEN - OPT_DATA] : 0
241         );
242         if (ENABLE_FEATURE_UDHCPD_WRITE_LEASES_EARLY) {
243                 /* rewrite the file with leases at every new acceptance */
244                 write_leases();
245         }
246
247         return 0;
248 }
249
250 static int send_inform(struct dhcp_packet *oldpacket)
251 {
252         struct dhcp_packet packet;
253         struct option_set *curr;
254
255         init_packet(&packet, oldpacket, DHCPACK);
256
257         curr = server_config.options;
258         while (curr) {
259                 if (curr->data[OPT_CODE] != DHCP_LEASE_TIME)
260                         add_option_string(packet.options, curr->data);
261                 curr = curr->next;
262         }
263
264         add_bootp_options(&packet);
265
266         return send_packet(&packet, 0);
267 }
268
269
270 /* globals */
271 struct dyn_lease *g_leases;
272 /* struct server_config_t server_config is in bb_common_bufsiz1 */
273
274
275 int udhcpd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
276 int udhcpd_main(int argc UNUSED_PARAM, char **argv)
277 {
278         fd_set rfds;
279         int server_socket = -1, retval, max_sock;
280         struct dhcp_packet packet;
281         uint8_t *state;
282         uint32_t static_lease_nip;
283         unsigned timeout_end;
284         unsigned num_ips;
285         unsigned opt;
286         struct option_set *option;
287         struct dyn_lease *lease, fake_lease;
288         IF_FEATURE_UDHCP_PORT(char *str_P;)
289
290 #if ENABLE_FEATURE_UDHCP_PORT
291         SERVER_PORT = 67;
292         CLIENT_PORT = 68;
293 #endif
294
295 #if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
296         opt_complementary = "vv";
297 #endif
298         opt = getopt32(argv, "fSv"
299                 IF_FEATURE_UDHCP_PORT("P:", &str_P)
300 #if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
301                 , &dhcp_verbose
302 #endif
303                 );
304         argv += optind;
305         if (!(opt & 1)) { /* no -f */
306                 bb_daemonize_or_rexec(0, argv);
307                 logmode = LOGMODE_NONE;
308         }
309         if (opt & 2) { /* -S */
310                 openlog(applet_name, LOG_PID, LOG_DAEMON);
311                 logmode |= LOGMODE_SYSLOG;
312         }
313 #if ENABLE_FEATURE_UDHCP_PORT
314         if (opt & 4) { /* -P */
315                 SERVER_PORT = xatou16(str_P);
316                 CLIENT_PORT = SERVER_PORT + 1;
317         }
318 #endif
319         /* Would rather not do read_config before daemonization -
320          * otherwise NOMMU machines will parse config twice */
321         read_config(argv[0] ? argv[0] : DHCPD_CONF_FILE);
322
323         /* Make sure fd 0,1,2 are open */
324         bb_sanitize_stdio();
325         /* Equivalent of doing a fflush after every \n */
326         setlinebuf(stdout);
327
328         /* Create pidfile */
329         write_pidfile(server_config.pidfile);
330         /* if (!..) bb_perror_msg("can't create pidfile %s", pidfile); */
331
332         bb_info_msg("%s (v"BB_VER") started", applet_name);
333
334         option = find_option(server_config.options, DHCP_LEASE_TIME);
335         server_config.max_lease_sec = LEASE_TIME;
336         if (option) {
337                 move_from_unaligned32(server_config.max_lease_sec, option->data + OPT_DATA);
338                 server_config.max_lease_sec = ntohl(server_config.max_lease_sec);
339         }
340
341         /* Sanity check */
342         num_ips = server_config.end_ip - server_config.start_ip + 1;
343         if (server_config.max_leases > num_ips) {
344                 bb_error_msg("max_leases=%u is too big, setting to %u",
345                         (unsigned)server_config.max_leases, num_ips);
346                 server_config.max_leases = num_ips;
347         }
348
349         g_leases = xzalloc(server_config.max_leases * sizeof(g_leases[0]));
350         read_leases(server_config.lease_file);
351
352         if (udhcp_read_interface(server_config.interface,
353                         &server_config.ifindex,
354                         &server_config.server_nip,
355                         server_config.server_mac)
356         ) {
357                 retval = 1;
358                 goto ret;
359         }
360
361         /* Setup the signal pipe */
362         udhcp_sp_setup();
363
364         timeout_end = monotonic_sec() + server_config.auto_time;
365         while (1) { /* loop until universe collapses */
366                 int bytes;
367                 struct timeval tv;
368
369                 if (server_socket < 0) {
370                         server_socket = udhcp_listen_socket(/*INADDR_ANY,*/ SERVER_PORT,
371                                         server_config.interface);
372                 }
373
374                 max_sock = udhcp_sp_fd_set(&rfds, server_socket);
375                 if (server_config.auto_time) {
376                         tv.tv_sec = timeout_end - monotonic_sec();
377                         tv.tv_usec = 0;
378                 }
379                 retval = 0;
380                 if (!server_config.auto_time || tv.tv_sec > 0) {
381                         retval = select(max_sock + 1, &rfds, NULL, NULL,
382                                         server_config.auto_time ? &tv : NULL);
383                 }
384                 if (retval == 0) {
385                         write_leases();
386                         timeout_end = monotonic_sec() + server_config.auto_time;
387                         continue;
388                 }
389                 if (retval < 0 && errno != EINTR) {
390                         log1("Error on select");
391                         continue;
392                 }
393
394                 switch (udhcp_sp_read(&rfds)) {
395                 case SIGUSR1:
396                         bb_info_msg("Received a SIGUSR1");
397                         write_leases();
398                         /* why not just reset the timeout, eh */
399                         timeout_end = monotonic_sec() + server_config.auto_time;
400                         continue;
401                 case SIGTERM:
402                         bb_info_msg("Received a SIGTERM");
403                         goto ret0;
404                 case 0: /* no signal: read a packet */
405                         break;
406                 default: /* signal or error (probably EINTR): back to select */
407                         continue;
408                 }
409
410                 bytes = udhcp_recv_kernel_packet(&packet, server_socket);
411                 if (bytes < 0) {
412                         /* bytes can also be -2 ("bad packet data") */
413                         if (bytes == -1 && errno != EINTR) {
414                                 log1("Read error: %s, reopening socket", strerror(errno));
415                                 close(server_socket);
416                                 server_socket = -1;
417                         }
418                         continue;
419                 }
420
421                 if (packet.hlen != 6) {
422                         bb_error_msg("MAC length != 6, ignoring packet");
423                         continue;
424                 }
425
426                 state = get_option(&packet, DHCP_MESSAGE_TYPE);
427                 if (state == NULL) {
428                         bb_error_msg("no message type option, ignoring packet");
429                         continue;
430                 }
431
432                 /* Look for a static lease */
433                 static_lease_nip = get_static_nip_by_mac(server_config.static_leases, &packet.chaddr);
434                 if (static_lease_nip) {
435                         bb_info_msg("Found static lease: %x", static_lease_nip);
436
437                         memcpy(&fake_lease.lease_mac, &packet.chaddr, 6);
438                         fake_lease.lease_nip = static_lease_nip;
439                         fake_lease.expires = 0;
440
441                         lease = &fake_lease;
442                 } else {
443                         lease = find_lease_by_mac(packet.chaddr);
444                 }
445
446                 switch (state[0]) {
447                 case DHCPDISCOVER:
448                         log1("Received DISCOVER");
449
450                         if (send_offer(&packet, static_lease_nip, lease) < 0) {
451                                 bb_error_msg("send OFFER failed");
452                         }
453                         break;
454                 case DHCPREQUEST: {
455                         uint8_t *server_id_opt, *requested_opt;
456                         uint32_t server_id_net = server_id_net; /* for compiler */
457                         uint32_t requested_nip = requested_nip; /* for compiler */
458
459                         log1("Received REQUEST");
460
461                         requested_opt = get_option(&packet, DHCP_REQUESTED_IP);
462                         server_id_opt = get_option(&packet, DHCP_SERVER_ID);
463                         if (requested_opt)
464                                 move_from_unaligned32(requested_nip, requested_opt);
465                         if (server_id_opt)
466                                 move_from_unaligned32(server_id_net, server_id_opt);
467
468                         if (lease) {
469                                 if (server_id_opt) {
470                                         /* SELECTING State */
471                                         if (server_id_net == server_config.server_nip
472                                          && requested_opt
473                                          && requested_nip == lease->lease_nip
474                                         ) {
475                                                 send_ACK(&packet, lease->lease_nip);
476                                         }
477                                 } else if (requested_opt) {
478                                         /* INIT-REBOOT State */
479                                         if (lease->lease_nip == requested_nip)
480                                                 send_ACK(&packet, lease->lease_nip);
481                                         else
482                                                 send_NAK(&packet);
483                                 } else if (lease->lease_nip == packet.ciaddr) {
484                                         /* RENEWING or REBINDING State */
485                                         send_ACK(&packet, lease->lease_nip);
486                                 } else { /* don't know what to do!!!! */
487                                         send_NAK(&packet);
488                                 }
489
490                         /* what to do if we have no record of the client */
491                         } else if (server_id_opt) {
492                                 /* SELECTING State */
493
494                         } else if (requested_opt) {
495                                 /* INIT-REBOOT State */
496                                 lease = find_lease_by_nip(requested_nip);
497                                 if (lease) {
498                                         if (is_expired_lease(lease)) {
499                                                 /* probably best if we drop this lease */
500                                                 memset(lease->lease_mac, 0, sizeof(lease->lease_mac));
501                                         } else {
502                                                 /* make some contention for this address */
503                                                 send_NAK(&packet);
504                                         }
505                                 } else {
506                                         uint32_t r = ntohl(requested_nip);
507                                         if (r < server_config.start_ip
508                                          || r > server_config.end_ip
509                                         ) {
510                                                 send_NAK(&packet);
511                                         }
512                                         /* else remain silent */
513                                 }
514
515                         } else {
516                                 /* RENEWING or REBINDING State */
517                         }
518                         break;
519                 }
520                 case DHCPDECLINE:
521                         log1("Received DECLINE");
522                         if (lease) {
523                                 memset(lease->lease_mac, 0, sizeof(lease->lease_mac));
524                                 lease->expires = time(NULL) + server_config.decline_time;
525                         }
526                         break;
527                 case DHCPRELEASE:
528                         log1("Received RELEASE");
529                         if (lease)
530                                 lease->expires = time(NULL);
531                         break;
532                 case DHCPINFORM:
533                         log1("Received INFORM");
534                         send_inform(&packet);
535                         break;
536                 default:
537                         bb_info_msg("Unsupported DHCP message (%02x) - ignoring", state[0]);
538                 }
539         }
540  ret0:
541         retval = 0;
542  ret:
543         /*if (server_config.pidfile) - server_config.pidfile is never NULL */
544                 remove_pidfile(server_config.pidfile);
545         return retval;
546 }