udhcp: code shrink; disable time and log server options
[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 the dhcp packet.
79  * If force broadcast is set, the packet will be broadcast.
80  */
81 static int send_packet(struct dhcp_packet *dhcp_pkt, int force_broadcast)
82 {
83         if (dhcp_pkt->gateway_nip)
84                 return send_packet_to_relay(dhcp_pkt);
85         return send_packet_to_client(dhcp_pkt, force_broadcast);
86 }
87
88 static void init_packet(struct dhcp_packet *packet, struct dhcp_packet *oldpacket, char type)
89 {
90         udhcp_init_header(packet, type);
91         packet->xid = oldpacket->xid;
92         memcpy(packet->chaddr, oldpacket->chaddr, sizeof(oldpacket->chaddr));
93         packet->flags = oldpacket->flags;
94         packet->gateway_nip = oldpacket->gateway_nip;
95         packet->ciaddr = oldpacket->ciaddr;
96         add_simple_option(packet->options, DHCP_SERVER_ID, server_config.server_nip);
97 }
98
99 /* Fill options field, siaddr_nip, and sname and boot_file fields.
100  * TODO: teach this code to use overload option.
101  */
102 static void add_server_options(struct dhcp_packet *packet)
103 {
104         struct option_set *curr = server_config.options;
105
106         while (curr) {
107                 if (curr->data[OPT_CODE] != DHCP_LEASE_TIME)
108                         add_option_string(packet->options, curr->data);
109                 curr = curr->next;
110         }
111
112         packet->siaddr_nip = server_config.siaddr_nip;
113
114         if (server_config.sname)
115                 strncpy((char*)packet->sname, server_config.sname, sizeof(packet->sname) - 1);
116         if (server_config.boot_file)
117                 strncpy((char*)packet->file, server_config.boot_file, sizeof(packet->file) - 1);
118 }
119
120 static uint32_t select_lease_time(struct dhcp_packet *packet)
121 {
122         uint32_t lease_time_sec = server_config.max_lease_sec;
123         uint8_t *lease_time_opt = get_option(packet, DHCP_LEASE_TIME);
124         if (lease_time_opt) {
125                 move_from_unaligned32(lease_time_sec, lease_time_opt);
126                 lease_time_sec = ntohl(lease_time_sec);
127                 if (lease_time_sec > server_config.max_lease_sec)
128                         lease_time_sec = server_config.max_lease_sec;
129                 if (lease_time_sec < server_config.min_lease_sec)
130                         lease_time_sec = server_config.min_lease_sec;
131         }
132         return lease_time_sec;
133 }
134
135 /* send a DHCP OFFER to a DHCP DISCOVER */
136 static int send_offer(struct dhcp_packet *oldpacket, uint32_t static_lease_nip, struct dyn_lease *lease)
137 {
138         struct dhcp_packet packet;
139         uint32_t lease_time_sec = server_config.max_lease_sec;
140         const char *p_host_name;
141         struct in_addr addr;
142
143         init_packet(&packet, oldpacket, DHCPOFFER);
144
145         /* ADDME: if static, short circuit */
146         if (!static_lease_nip) {
147                 uint32_t req_nip;
148                 uint8_t *req_ip_opt;
149
150                 /* The client is in our lease/offered table */
151                 if (lease) {
152                         packet.yiaddr = lease->lease_nip;
153                 }
154                 /* Or the client has requested an IP */
155                 else if ((req_ip_opt = get_option(oldpacket, DHCP_REQUESTED_IP)) != NULL
156                  /* (read IP) */
157                  && (move_from_unaligned32(req_nip, req_ip_opt), 1)
158                  /* and the IP is in the lease range */
159                  && ntohl(req_nip) >= server_config.start_ip
160                  && ntohl(req_nip) <= server_config.end_ip
161                  /* and */
162                  && (  !(lease = find_lease_by_nip(req_nip)) /* is not already taken */
163                     || is_expired_lease(lease) /* or is taken, but expired */
164                     )
165                 ) {
166                         packet.yiaddr = req_nip;
167                 }
168                 /* Otherwise, find a free IP */
169                 else {
170                         packet.yiaddr = find_free_or_expired_nip(oldpacket->chaddr);
171                 }
172
173                 if (!packet.yiaddr) {
174                         bb_error_msg("no IP addresses to give - OFFER abandoned");
175                         return -1;
176                 }
177                 p_host_name = (const char*) get_option(oldpacket, DHCP_HOST_NAME);
178                 if (add_lease(packet.chaddr, packet.yiaddr,
179                                 server_config.offer_time,
180                                 p_host_name,
181                                 p_host_name ? (unsigned char)p_host_name[OPT_LEN - OPT_DATA] : 0
182                         ) == 0
183                 ) {
184                         bb_error_msg("lease pool is full - OFFER abandoned");
185                         return -1;
186                 }
187                 lease_time_sec = select_lease_time(oldpacket);
188         } else {
189                 /* It is a static lease... use it */
190                 packet.yiaddr = static_lease_nip;
191         }
192
193         add_simple_option(packet.options, DHCP_LEASE_TIME, htonl(lease_time_sec));
194         add_server_options(&packet);
195
196         addr.s_addr = packet.yiaddr;
197         bb_info_msg("Sending OFFER of %s", inet_ntoa(addr));
198         return send_packet(&packet, /*force_bcast:*/ 0);
199 }
200
201 static int send_NAK(struct dhcp_packet *oldpacket)
202 {
203         struct dhcp_packet packet;
204
205         init_packet(&packet, oldpacket, DHCPNAK);
206
207         log1("Sending NAK");
208         return send_packet(&packet, /*force_bcast:*/ 1);
209 }
210
211 static int send_ACK(struct dhcp_packet *oldpacket, uint32_t yiaddr)
212 {
213         struct dhcp_packet packet;
214         uint32_t lease_time_sec;
215         struct in_addr addr;
216         const char *p_host_name;
217
218         init_packet(&packet, oldpacket, DHCPACK);
219         packet.yiaddr = yiaddr;
220
221         lease_time_sec = select_lease_time(oldpacket);
222
223         add_simple_option(packet.options, DHCP_LEASE_TIME, htonl(lease_time_sec));
224         add_server_options(&packet);
225
226         addr.s_addr = packet.yiaddr;
227         bb_info_msg("Sending ACK to %s", inet_ntoa(addr));
228
229         if (send_packet(&packet, /*force_bcast:*/ 0) < 0)
230                 return -1;
231
232         p_host_name = (const char*) get_option(oldpacket, DHCP_HOST_NAME);
233         add_lease(packet.chaddr, packet.yiaddr,
234                 lease_time_sec,
235                 p_host_name,
236                 p_host_name ? (unsigned char)p_host_name[OPT_LEN - OPT_DATA] : 0
237         );
238         if (ENABLE_FEATURE_UDHCPD_WRITE_LEASES_EARLY) {
239                 /* rewrite the file with leases at every new acceptance */
240                 write_leases();
241         }
242
243         return 0;
244 }
245
246 static int send_inform(struct dhcp_packet *oldpacket)
247 {
248         struct dhcp_packet packet;
249
250         init_packet(&packet, oldpacket, DHCPACK);
251         add_server_options(&packet);
252
253         return send_packet(&packet, /*force_bcast:*/ 0);
254 }
255
256
257 /* globals */
258 struct dyn_lease *g_leases;
259 /* struct server_config_t server_config is in bb_common_bufsiz1 */
260
261
262 int udhcpd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
263 int udhcpd_main(int argc UNUSED_PARAM, char **argv)
264 {
265         fd_set rfds;
266         int server_socket = -1, retval, max_sock;
267         struct dhcp_packet packet;
268         uint8_t *state;
269         uint32_t static_lease_nip;
270         unsigned timeout_end;
271         unsigned num_ips;
272         unsigned opt;
273         struct option_set *option;
274         struct dyn_lease *lease, fake_lease;
275         IF_FEATURE_UDHCP_PORT(char *str_P;)
276
277 #if ENABLE_FEATURE_UDHCP_PORT
278         SERVER_PORT = 67;
279         CLIENT_PORT = 68;
280 #endif
281
282 #if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
283         opt_complementary = "vv";
284 #endif
285         opt = getopt32(argv, "fSv"
286                 IF_FEATURE_UDHCP_PORT("P:", &str_P)
287 #if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
288                 , &dhcp_verbose
289 #endif
290                 );
291         argv += optind;
292         if (!(opt & 1)) { /* no -f */
293                 bb_daemonize_or_rexec(0, argv);
294                 logmode = LOGMODE_NONE;
295         }
296         if (opt & 2) { /* -S */
297                 openlog(applet_name, LOG_PID, LOG_DAEMON);
298                 logmode |= LOGMODE_SYSLOG;
299         }
300 #if ENABLE_FEATURE_UDHCP_PORT
301         if (opt & 4) { /* -P */
302                 SERVER_PORT = xatou16(str_P);
303                 CLIENT_PORT = SERVER_PORT + 1;
304         }
305 #endif
306         /* Would rather not do read_config before daemonization -
307          * otherwise NOMMU machines will parse config twice */
308         read_config(argv[0] ? argv[0] : DHCPD_CONF_FILE);
309
310         /* Make sure fd 0,1,2 are open */
311         bb_sanitize_stdio();
312         /* Equivalent of doing a fflush after every \n */
313         setlinebuf(stdout);
314
315         /* Create pidfile */
316         write_pidfile(server_config.pidfile);
317         /* if (!..) bb_perror_msg("can't create pidfile %s", pidfile); */
318
319         bb_info_msg("%s (v"BB_VER") started", applet_name);
320
321         option = find_option(server_config.options, DHCP_LEASE_TIME);
322         server_config.max_lease_sec = LEASE_TIME;
323         if (option) {
324                 move_from_unaligned32(server_config.max_lease_sec, option->data + OPT_DATA);
325                 server_config.max_lease_sec = ntohl(server_config.max_lease_sec);
326         }
327
328         /* Sanity check */
329         num_ips = server_config.end_ip - server_config.start_ip + 1;
330         if (server_config.max_leases > num_ips) {
331                 bb_error_msg("max_leases=%u is too big, setting to %u",
332                         (unsigned)server_config.max_leases, num_ips);
333                 server_config.max_leases = num_ips;
334         }
335
336         g_leases = xzalloc(server_config.max_leases * sizeof(g_leases[0]));
337         read_leases(server_config.lease_file);
338
339         if (udhcp_read_interface(server_config.interface,
340                         &server_config.ifindex,
341                         &server_config.server_nip,
342                         server_config.server_mac)
343         ) {
344                 retval = 1;
345                 goto ret;
346         }
347
348         /* Setup the signal pipe */
349         udhcp_sp_setup();
350
351         timeout_end = monotonic_sec() + server_config.auto_time;
352         while (1) { /* loop until universe collapses */
353                 int bytes;
354                 struct timeval tv;
355
356                 if (server_socket < 0) {
357                         server_socket = udhcp_listen_socket(/*INADDR_ANY,*/ SERVER_PORT,
358                                         server_config.interface);
359                 }
360
361                 max_sock = udhcp_sp_fd_set(&rfds, server_socket);
362                 if (server_config.auto_time) {
363                         tv.tv_sec = timeout_end - monotonic_sec();
364                         tv.tv_usec = 0;
365                 }
366                 retval = 0;
367                 if (!server_config.auto_time || tv.tv_sec > 0) {
368                         retval = select(max_sock + 1, &rfds, NULL, NULL,
369                                         server_config.auto_time ? &tv : NULL);
370                 }
371                 if (retval == 0) {
372                         write_leases();
373                         timeout_end = monotonic_sec() + server_config.auto_time;
374                         continue;
375                 }
376                 if (retval < 0 && errno != EINTR) {
377                         log1("Error on select");
378                         continue;
379                 }
380
381                 switch (udhcp_sp_read(&rfds)) {
382                 case SIGUSR1:
383                         bb_info_msg("Received a SIGUSR1");
384                         write_leases();
385                         /* why not just reset the timeout, eh */
386                         timeout_end = monotonic_sec() + server_config.auto_time;
387                         continue;
388                 case SIGTERM:
389                         bb_info_msg("Received a SIGTERM");
390                         goto ret0;
391                 case 0: /* no signal: read a packet */
392                         break;
393                 default: /* signal or error (probably EINTR): back to select */
394                         continue;
395                 }
396
397                 bytes = udhcp_recv_kernel_packet(&packet, server_socket);
398                 if (bytes < 0) {
399                         /* bytes can also be -2 ("bad packet data") */
400                         if (bytes == -1 && errno != EINTR) {
401                                 log1("Read error: %s, reopening socket", strerror(errno));
402                                 close(server_socket);
403                                 server_socket = -1;
404                         }
405                         continue;
406                 }
407
408                 if (packet.hlen != 6) {
409                         bb_error_msg("MAC length != 6, ignoring packet");
410                         continue;
411                 }
412
413                 state = get_option(&packet, DHCP_MESSAGE_TYPE);
414                 if (state == NULL) {
415                         bb_error_msg("no message type option, ignoring packet");
416                         continue;
417                 }
418
419                 /* Look for a static lease */
420                 static_lease_nip = get_static_nip_by_mac(server_config.static_leases, &packet.chaddr);
421                 if (static_lease_nip) {
422                         bb_info_msg("Found static lease: %x", static_lease_nip);
423
424                         memcpy(&fake_lease.lease_mac, &packet.chaddr, 6);
425                         fake_lease.lease_nip = static_lease_nip;
426                         fake_lease.expires = 0;
427
428                         lease = &fake_lease;
429                 } else {
430                         lease = find_lease_by_mac(packet.chaddr);
431                 }
432
433                 switch (state[0]) {
434                 case DHCPDISCOVER:
435                         log1("Received DISCOVER");
436
437                         if (send_offer(&packet, static_lease_nip, lease) < 0) {
438                                 bb_error_msg("send OFFER failed");
439                         }
440                         break;
441                 case DHCPREQUEST: {
442                         uint8_t *server_id_opt, *requested_opt;
443                         uint32_t server_id_net = server_id_net; /* for compiler */
444                         uint32_t requested_nip = requested_nip; /* for compiler */
445
446                         log1("Received REQUEST");
447
448                         requested_opt = get_option(&packet, DHCP_REQUESTED_IP);
449                         server_id_opt = get_option(&packet, DHCP_SERVER_ID);
450                         if (requested_opt)
451                                 move_from_unaligned32(requested_nip, requested_opt);
452                         if (server_id_opt)
453                                 move_from_unaligned32(server_id_net, server_id_opt);
454
455                         if (lease) {
456                                 if (server_id_opt) {
457                                         /* SELECTING State */
458                                         if (server_id_net == server_config.server_nip
459                                          && requested_opt
460                                          && requested_nip == lease->lease_nip
461                                         ) {
462                                                 send_ACK(&packet, lease->lease_nip);
463                                         }
464                                 } else if (requested_opt) {
465                                         /* INIT-REBOOT State */
466                                         if (lease->lease_nip == requested_nip)
467                                                 send_ACK(&packet, lease->lease_nip);
468                                         else
469                                                 send_NAK(&packet);
470                                 } else if (lease->lease_nip == packet.ciaddr) {
471                                         /* RENEWING or REBINDING State */
472                                         send_ACK(&packet, lease->lease_nip);
473                                 } else { /* don't know what to do!!!! */
474                                         send_NAK(&packet);
475                                 }
476
477                         /* what to do if we have no record of the client */
478                         } else if (server_id_opt) {
479                                 /* SELECTING State */
480
481                         } else if (requested_opt) {
482                                 /* INIT-REBOOT State */
483                                 lease = find_lease_by_nip(requested_nip);
484                                 if (lease) {
485                                         if (is_expired_lease(lease)) {
486                                                 /* probably best if we drop this lease */
487                                                 memset(lease->lease_mac, 0, sizeof(lease->lease_mac));
488                                         } else {
489                                                 /* make some contention for this address */
490                                                 send_NAK(&packet);
491                                         }
492                                 } else {
493                                         uint32_t r = ntohl(requested_nip);
494                                         if (r < server_config.start_ip
495                                          || r > server_config.end_ip
496                                         ) {
497                                                 send_NAK(&packet);
498                                         }
499                                         /* else remain silent */
500                                 }
501
502                         } else {
503                                 /* RENEWING or REBINDING State */
504                         }
505                         break;
506                 }
507                 case DHCPDECLINE:
508                         log1("Received DECLINE");
509                         if (lease) {
510                                 memset(lease->lease_mac, 0, sizeof(lease->lease_mac));
511                                 lease->expires = time(NULL) + server_config.decline_time;
512                         }
513                         break;
514                 case DHCPRELEASE:
515                         log1("Received RELEASE");
516                         if (lease)
517                                 lease->expires = time(NULL);
518                         break;
519                 case DHCPINFORM:
520                         log1("Received INFORM");
521                         send_inform(&packet);
522                         break;
523                 default:
524                         bb_info_msg("Unsupported DHCP message (%02x) - ignoring", state[0]);
525                 }
526         }
527  ret0:
528         retval = 0;
529  ret:
530         /*if (server_config.pidfile) - server_config.pidfile is never NULL */
531                 remove_pidfile(server_config.pidfile);
532         return retval;
533 }