1 /* vi: set sw=4 ts=4: */
6 * Russ Dill <Russ.Dill@asu.edu> July 2001
8 * Licensed under the GPL v2 or later, see the file LICENSE in this tarball.
11 /* Override ENABLE_FEATURE_PIDFILE - ifupdown needs our pidfile to always exist */
12 #define WANT_PIDFILE 1
19 static int sockfd = -1;
22 #define LISTEN_KERNEL 1
24 static smallint listen_mode;
26 /* initial state: (re)start DHCP negotiation */
27 #define INIT_SELECTING 0
28 /* discover was sent, DHCPOFFER reply received */
30 /* select/renew was sent, DHCPACK reply received */
32 /* half of lease passed, want to renew it by sending unicast renew requests */
34 /* renew requests were not answered, lease is almost over, send broadcast renew */
36 /* manually requested renew (SIGUSR1) */
37 #define RENEW_REQUESTED 5
38 /* release, possibly manually requested (SIGUSR2) */
40 static smallint state;
42 /* struct client_config_t client_config is in bb_common_bufsiz1 */
45 /* just a little helper */
46 static void change_listen_mode(int new_mode)
48 log1("Entering listen mode: %s",
49 new_mode != LISTEN_NONE
50 ? (new_mode == LISTEN_KERNEL ? "kernel" : "raw")
54 listen_mode = new_mode;
59 if (new_mode == LISTEN_KERNEL)
60 sockfd = udhcp_listen_socket(/*INADDR_ANY,*/ CLIENT_PORT, client_config.interface);
61 else if (new_mode != LISTEN_NONE)
62 sockfd = udhcp_raw_socket(client_config.ifindex);
63 /* else LISTEN_NONE: sockfd stay closed */
68 static void perform_renew(void)
70 bb_info_msg("Performing a DHCP renew");
73 change_listen_mode(LISTEN_KERNEL);
76 state = RENEW_REQUESTED;
78 case RENEW_REQUESTED: /* impatient are we? fine, square 1 */
79 udhcp_run_script(NULL, "deconfig");
82 change_listen_mode(LISTEN_RAW);
83 state = INIT_SELECTING;
91 /* perform a release */
92 static void perform_release(uint32_t requested_ip, uint32_t server_addr)
94 char buffer[sizeof("255.255.255.255")];
95 struct in_addr temp_addr;
97 /* send release packet */
98 if (state == BOUND || state == RENEWING || state == REBINDING) {
99 temp_addr.s_addr = server_addr;
100 strcpy(buffer, inet_ntoa(temp_addr));
101 temp_addr.s_addr = requested_ip;
102 bb_info_msg("Unicasting a release of %s to %s",
103 inet_ntoa(temp_addr), buffer);
104 send_release(server_addr, requested_ip); /* unicast */
105 udhcp_run_script(NULL, "deconfig");
107 bb_info_msg("Entering released state");
109 change_listen_mode(LISTEN_NONE);
115 static void client_background(void)
118 logmode &= ~LOGMODE_STDIO;
119 /* rewrite pidfile, as our pid is different now */
120 write_pidfile(client_config.pidfile);
125 static uint8_t* alloc_dhcp_option(int code, const char *str, int extra)
128 int len = strlen(str);
129 if (len > 255) len = 255;
130 storage = xzalloc(len + extra + OPT_DATA);
131 storage[OPT_CODE] = code;
132 storage[OPT_LEN] = len + extra;
133 memcpy(storage + extra + OPT_DATA, str, len);
138 int udhcpc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
139 int udhcpc_main(int argc UNUSED_PARAM, char **argv)
141 uint8_t *temp, *message;
142 char *str_c, *str_V, *str_h, *str_F, *str_r;
143 IF_FEATURE_UDHCP_PORT(char *str_P;)
144 llist_t *list_O = NULL;
145 int tryagain_timeout = 20;
146 int discover_timeout = 3;
147 int discover_retries = 3;
148 uint32_t server_addr = server_addr; /* for compiler */
149 uint32_t requested_ip = 0;
151 uint32_t lease_seconds = 0; /* can be given as 32-bit quantity */
153 int timeout; /* must be signed */
154 unsigned already_waited_sec;
159 struct dhcp_packet packet;
163 static const char udhcpc_longopts[] ALIGN1 =
164 "clientid\0" Required_argument "c"
165 "clientid-none\0" No_argument "C"
166 "vendorclass\0" Required_argument "V"
167 "hostname\0" Required_argument "H"
168 "fqdn\0" Required_argument "F"
169 "interface\0" Required_argument "i"
170 "now\0" No_argument "n"
171 "pidfile\0" Required_argument "p"
172 "quit\0" No_argument "q"
173 "release\0" No_argument "R"
174 "request\0" Required_argument "r"
175 "script\0" Required_argument "s"
176 "timeout\0" Required_argument "T"
177 "version\0" No_argument "v"
178 "retries\0" Required_argument "t"
179 "tryagain\0" Required_argument "A"
180 "syslog\0" No_argument "S"
181 "request-option\0" Required_argument "O"
182 "no-default-options\0" No_argument "o"
183 "foreground\0" No_argument "f"
184 "background\0" No_argument "b"
185 IF_FEATURE_UDHCPC_ARPING("arping\0" No_argument "a")
186 IF_FEATURE_UDHCP_PORT("client-port\0" Required_argument "P")
210 /* The rest has variable bit positions, need to be clever */
212 USE_FOR_MMU( OPTBIT_b,)
213 IF_FEATURE_UDHCPC_ARPING(OPTBIT_a,)
214 IF_FEATURE_UDHCP_PORT( OPTBIT_P,)
215 USE_FOR_MMU( OPT_b = 1 << OPTBIT_b,)
216 IF_FEATURE_UDHCPC_ARPING(OPT_a = 1 << OPTBIT_a,)
217 IF_FEATURE_UDHCP_PORT( OPT_P = 1 << OPTBIT_P,)
220 /* Default options. */
221 IF_FEATURE_UDHCP_PORT(SERVER_PORT = 67;)
222 IF_FEATURE_UDHCP_PORT(CLIENT_PORT = 68;)
223 client_config.interface = "eth0";
224 client_config.script = DEFAULT_SCRIPT;
226 /* Parse command line */
227 /* Cc: mutually exclusive; O: list; -T,-t,-A take numeric param */
228 opt_complementary = "c--C:C--c:O::T+:t+:A+"
229 #if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
233 IF_LONG_OPTS(applet_long_options = udhcpc_longopts;)
234 opt = getopt32(argv, "c:CV:H:h:F:i:np:qRr:s:T:t:SA:O:of"
236 IF_FEATURE_UDHCPC_ARPING("a")
237 IF_FEATURE_UDHCP_PORT("P:")
239 , &str_c, &str_V, &str_h, &str_h, &str_F
240 , &client_config.interface, &client_config.pidfile, &str_r /* i,p */
241 , &client_config.script /* s */
242 , &discover_timeout, &discover_retries, &tryagain_timeout /* T,t,A */
244 IF_FEATURE_UDHCP_PORT(, &str_P)
245 #if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
250 client_config.clientid = alloc_dhcp_option(DHCP_CLIENT_ID, str_c, 0);
252 client_config.vendorclass = alloc_dhcp_option(DHCP_VENDOR, str_V, 0);
253 if (opt & (OPT_h|OPT_H))
254 client_config.hostname = alloc_dhcp_option(DHCP_HOST_NAME, str_h, 0);
256 client_config.fqdn = alloc_dhcp_option(DHCP_FQDN, str_F, 3);
258 S: 1 => Client requests Server to update A RR in DNS as well as PTR
259 O: 1 => Server indicates to client that DNS has been updated regardless
260 E: 1 => Name data is DNS format, i.e. <4>host<6>domain<3>com<0> not "host.domain.com"
261 N: 1 => Client requests Server to not update DNS
263 client_config.fqdn[OPT_DATA + 0] = 0x1;
264 /* client_config.fqdn[OPT_DATA + 1] = 0; - redundant */
265 /* client_config.fqdn[OPT_DATA + 2] = 0; - redundant */
268 requested_ip = inet_addr(str_r);
269 #if ENABLE_FEATURE_UDHCP_PORT
271 CLIENT_PORT = xatou16(str_P);
272 SERVER_PORT = CLIENT_PORT - 1;
276 client_config.no_default_options = 1;
278 char *optstr = llist_pop(&list_O);
279 int n = index_in_strings(dhcp_option_strings, optstr);
281 bb_error_msg_and_die("unknown option '%s'", optstr);
282 n = dhcp_options[n].code;
283 client_config.opt_mask[n >> 3] |= 1 << (n & 7);
286 if (udhcp_read_interface(client_config.interface,
287 &client_config.ifindex,
289 client_config.client_mac)
295 /* on NOMMU reexec (i.e., background) early */
296 if (!(opt & OPT_f)) {
297 bb_daemonize_or_rexec(0 /* flags */, argv);
298 logmode = LOGMODE_NONE;
302 openlog(applet_name, LOG_PID, LOG_DAEMON);
303 logmode |= LOGMODE_SYSLOG;
306 /* Make sure fd 0,1,2 are open */
308 /* Equivalent of doing a fflush after every \n */
312 write_pidfile(client_config.pidfile);
314 /* Goes to stdout (unless NOMMU) and possibly syslog */
315 bb_info_msg("%s (v"BB_VER") started", applet_name);
317 /* If not set, and not suppressed, set up the default client ID */
318 if (!client_config.clientid && !(opt & OPT_C)) {
319 client_config.clientid = alloc_dhcp_option(DHCP_CLIENT_ID, "", 7);
320 client_config.clientid[OPT_DATA] = 1;
321 memcpy(client_config.clientid + OPT_DATA+1, client_config.client_mac, 6);
324 if (!client_config.vendorclass)
325 client_config.vendorclass = alloc_dhcp_option(DHCP_VENDOR, "udhcp "BB_VER, 0);
327 /* Set up the signal pipe */
330 state = INIT_SELECTING;
331 udhcp_run_script(NULL, "deconfig");
332 change_listen_mode(LISTEN_RAW);
335 already_waited_sec = 0;
337 /* Main event loop. select() waits on signal pipe and possibly
339 * "continue" statements in code below jump to the top of the loop.
342 /* silence "uninitialized!" warning */
343 unsigned timestamp_before_wait = timestamp_before_wait;
345 //bb_error_msg("sockfd:%d, listen_mode:%d", sockfd, listen_mode);
347 /* Was opening raw or udp socket here
348 * if (listen_mode != LISTEN_NONE && sockfd < 0),
349 * but on fast network renew responses return faster
350 * than we open sockets. Thus this code is moved
351 * to change_listen_mode(). Thus we open listen socket
352 * BEFORE we send renew request (see "case BOUND:"). */
354 max_fd = udhcp_sp_fd_set(&rfds, sockfd);
356 tv.tv_sec = timeout - already_waited_sec;
358 retval = 0; /* If we already timed out, fall through, else... */
359 if ((int)tv.tv_sec > 0) {
360 timestamp_before_wait = (unsigned)monotonic_sec();
361 log1("Waiting on select...");
362 retval = select(max_fd + 1, &rfds, NULL, NULL, &tv);
364 /* EINTR? A signal was caught, don't panic */
365 if (errno == EINTR) {
366 already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
369 /* Else: an error occured, panic! */
370 bb_perror_msg_and_die("select");
374 /* If timeout dropped to zero, time to become active:
375 * resend discover/renew/whatever
378 /* We will restart the wait in any case */
379 already_waited_sec = 0;
383 if (packet_num < discover_retries) {
387 send_discover(xid, requested_ip);
388 timeout = discover_timeout;
393 udhcp_run_script(NULL, "leasefail");
394 #if BB_MMU /* -b is not supported on NOMMU */
395 if (opt & OPT_b) { /* background if no lease */
396 bb_info_msg("No lease, forking to background");
398 /* do not background again! */
399 opt = ((opt & ~OPT_b) | OPT_f);
402 if (opt & OPT_n) { /* abort if no lease */
403 bb_info_msg("No lease, failing");
407 /* wait before trying again */
408 timeout = tryagain_timeout;
412 if (packet_num < discover_retries) {
413 /* send broadcast select packet */
414 send_select(xid, server_addr, requested_ip);
415 timeout = discover_timeout;
419 /* Timed out, go back to init state.
420 * "discover...select...discover..." loops
421 * were seen in the wild. Treat them similarly
422 * to "no response to discover" case */
423 change_listen_mode(LISTEN_RAW);
424 state = INIT_SELECTING;
427 /* 1/2 lease passed, enter renewing state */
429 change_listen_mode(LISTEN_KERNEL);
430 log1("Entering renew state");
431 /* fall right through */
432 case RENEW_REQUESTED: /* manual (SIGUSR1) renew */
433 case_RENEW_REQUESTED:
436 /* send an unicast renew request */
437 /* Sometimes observed to fail (EADDRNOTAVAIL) to bind
438 * a new UDP socket for sending inside send_renew.
439 * I hazard to guess existing listening socket
440 * is somehow conflicting with it, but why is it
441 * not deterministic then?! Strange.
442 * Anyway, it does recover by eventually failing through
443 * into INIT_SELECTING state.
445 send_renew(xid, server_addr, requested_ip);
449 /* Timed out, enter rebinding state */
450 log1("Entering rebinding state");
452 /* fall right through */
454 /* Switch to bcast receive */
455 change_listen_mode(LISTEN_RAW);
456 /* Lease is *really* about to run out,
457 * try to find DHCP server using broadcast */
459 /* send a broadcast renew request */
460 send_renew(xid, 0 /*INADDR_ANY*/, requested_ip);
464 /* Timed out, enter init state */
465 bb_info_msg("Lease lost, entering init state");
466 udhcp_run_script(NULL, "deconfig");
467 state = INIT_SELECTING;
468 /*timeout = 0; - already is */
473 /* yah, I know, *you* say it would never happen */
475 continue; /* back to main loop */
476 } /* if select timed out */
478 /* select() didn't timeout, something happened */
480 /* Is it a signal? */
481 /* note: udhcp_sp_read checks FD_ISSET before reading */
482 switch (udhcp_sp_read(&rfds)) {
485 if (state == RENEW_REQUESTED)
486 goto case_RENEW_REQUESTED;
487 /* Start things over */
489 /* Kill any timeouts, user wants this to hurry along */
493 perform_release(requested_ip, server_addr);
497 bb_info_msg("Received SIGTERM");
498 if (opt & OPT_R) /* release on quit */
499 perform_release(requested_ip, server_addr);
503 /* Is it a packet? */
504 if (listen_mode == LISTEN_NONE || !FD_ISSET(sockfd, &rfds))
510 /* A packet is ready, read it */
511 if (listen_mode == LISTEN_KERNEL)
512 len = udhcp_recv_kernel_packet(&packet, sockfd);
514 len = udhcp_recv_raw_packet(&packet, sockfd);
516 /* Error is severe, reopen socket */
517 bb_info_msg("Read error: %s, reopening socket", strerror(errno));
518 sleep(discover_timeout); /* 3 seconds by default */
519 change_listen_mode(listen_mode); /* just close and reopen */
521 /* If this packet will turn out to be unrelated/bogus,
522 * we will go back and wait for next one.
523 * Be sure timeout is properly decreased. */
524 already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
529 if (packet.xid != xid) {
530 log1("xid %x (our is %x), ignoring packet",
531 (unsigned)packet.xid, (unsigned)xid);
535 /* Ignore packets that aren't for us */
537 || memcmp(packet.chaddr, client_config.client_mac, 6)
539 //FIXME: need to also check that last 10 bytes are zero
540 log1("chaddr does not match, ignoring packet"); // log2?
544 message = get_option(&packet, DHCP_MESSAGE_TYPE);
545 if (message == NULL) {
546 bb_error_msg("no message type option, ignoring packet");
552 /* Must be a DHCPOFFER to one of our xid's */
553 if (*message == DHCPOFFER) {
554 /* TODO: why we don't just fetch server's IP from IP header? */
555 temp = get_option(&packet, DHCP_SERVER_ID);
557 bb_error_msg("no server ID in message");
559 /* still selecting - this server looks bad */
561 /* it IS unaligned sometimes, don't "optimize" */
562 move_from_unaligned32(server_addr, temp);
564 requested_ip = packet.yiaddr;
566 /* enter requesting state */
570 already_waited_sec = 0;
575 case RENEW_REQUESTED:
577 if (*message == DHCPACK) {
578 temp = get_option(&packet, DHCP_LEASE_TIME);
580 bb_error_msg("no lease time with ACK, using 1 hour lease");
581 lease_seconds = 60 * 60;
583 /* it IS unaligned sometimes, don't "optimize" */
584 move_from_unaligned32(lease_seconds, temp);
585 lease_seconds = ntohl(lease_seconds);
586 lease_seconds &= 0x0fffffff; /* paranoia: must not be prone to overflows */
587 if (lease_seconds < 10) /* and not too small */
590 #if ENABLE_FEATURE_UDHCPC_ARPING
592 /* RFC 2131 3.1 paragraph 5:
593 * "The client receives the DHCPACK message with configuration
594 * parameters. The client SHOULD perform a final check on the
595 * parameters (e.g., ARP for allocated network address), and notes
596 * the duration of the lease specified in the DHCPACK message. At this
597 * point, the client is configured. If the client detects that the
598 * address is already in use (e.g., through the use of ARP),
599 * the client MUST send a DHCPDECLINE message to the server and restarts
600 * the configuration process..." */
601 if (!arpping(packet.yiaddr,
604 client_config.client_mac,
605 client_config.interface)
607 bb_info_msg("Offered address is in use "
608 "(got ARP reply), declining");
609 send_decline(xid, server_addr, packet.yiaddr);
611 if (state != REQUESTING)
612 udhcp_run_script(NULL, "deconfig");
613 change_listen_mode(LISTEN_RAW);
614 state = INIT_SELECTING;
616 timeout = tryagain_timeout;
618 already_waited_sec = 0;
619 continue; /* back to main loop */
623 /* enter bound state */
624 timeout = lease_seconds / 2;
626 struct in_addr temp_addr;
627 temp_addr.s_addr = packet.yiaddr;
628 bb_info_msg("Lease of %s obtained, lease time %u",
629 inet_ntoa(temp_addr), (unsigned)lease_seconds);
631 requested_ip = packet.yiaddr;
632 udhcp_run_script(&packet, state == REQUESTING ? "bound" : "renew");
635 change_listen_mode(LISTEN_NONE);
636 if (opt & OPT_q) { /* quit after lease */
637 if (opt & OPT_R) /* release on quit */
638 perform_release(requested_ip, server_addr);
641 /* future renew failures should not exit (JM) */
643 #if BB_MMU /* NOMMU case backgrounded earlier */
644 if (!(opt & OPT_f)) {
646 /* do not background again! */
647 opt = ((opt & ~OPT_b) | OPT_f);
650 already_waited_sec = 0;
651 continue; /* back to main loop */
653 if (*message == DHCPNAK) {
654 /* return to init state */
655 bb_info_msg("Received DHCP NAK");
656 udhcp_run_script(&packet, "nak");
657 if (state != REQUESTING)
658 udhcp_run_script(NULL, "deconfig");
659 change_listen_mode(LISTEN_RAW);
660 sleep(3); /* avoid excessive network traffic */
661 state = INIT_SELECTING;
665 already_waited_sec = 0;
668 /* case BOUND: - ignore all packets */
669 /* case RELEASED: - ignore all packets */
671 /* back to main loop */
672 } /* for (;;) - main loop ends */
677 /*if (client_config.pidfile) - remove_pidfile has its own check */
678 remove_pidfile(client_config.pidfile);