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 = strnlen(str, 255);
129 storage = xzalloc(len + extra + OPT_DATA);
130 storage[OPT_CODE] = code;
131 storage[OPT_LEN] = len + extra;
132 memcpy(storage + extra + OPT_DATA, str, len);
137 int udhcpc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
138 int udhcpc_main(int argc UNUSED_PARAM, char **argv)
140 uint8_t *temp, *message;
141 const char *str_c, *str_V, *str_h, *str_F, *str_r;
142 IF_FEATURE_UDHCP_PORT(char *str_P;)
143 llist_t *list_O = NULL;
144 int tryagain_timeout = 20;
145 int discover_timeout = 3;
146 int discover_retries = 3;
147 uint32_t server_addr = server_addr; /* for compiler */
148 uint32_t requested_ip = 0;
150 uint32_t lease_seconds = 0; /* can be given as 32-bit quantity */
152 int timeout; /* must be signed */
153 unsigned already_waited_sec;
158 struct dhcp_packet packet;
162 static const char udhcpc_longopts[] ALIGN1 =
163 "clientid\0" Required_argument "c"
164 "clientid-none\0" No_argument "C"
165 "vendorclass\0" Required_argument "V"
166 "hostname\0" Required_argument "H"
167 "fqdn\0" Required_argument "F"
168 "interface\0" Required_argument "i"
169 "now\0" No_argument "n"
170 "pidfile\0" Required_argument "p"
171 "quit\0" No_argument "q"
172 "release\0" No_argument "R"
173 "request\0" Required_argument "r"
174 "script\0" Required_argument "s"
175 "timeout\0" Required_argument "T"
176 "version\0" No_argument "v"
177 "retries\0" Required_argument "t"
178 "tryagain\0" Required_argument "A"
179 "syslog\0" No_argument "S"
180 "request-option\0" Required_argument "O"
181 "no-default-options\0" No_argument "o"
182 "foreground\0" No_argument "f"
183 "background\0" No_argument "b"
184 IF_FEATURE_UDHCPC_ARPING("arping\0" No_argument "a")
185 IF_FEATURE_UDHCP_PORT("client-port\0" Required_argument "P")
209 /* The rest has variable bit positions, need to be clever */
211 USE_FOR_MMU( OPTBIT_b,)
212 IF_FEATURE_UDHCPC_ARPING(OPTBIT_a,)
213 IF_FEATURE_UDHCP_PORT( OPTBIT_P,)
214 USE_FOR_MMU( OPT_b = 1 << OPTBIT_b,)
215 IF_FEATURE_UDHCPC_ARPING(OPT_a = 1 << OPTBIT_a,)
216 IF_FEATURE_UDHCP_PORT( OPT_P = 1 << OPTBIT_P,)
219 /* Default options. */
220 IF_FEATURE_UDHCP_PORT(SERVER_PORT = 67;)
221 IF_FEATURE_UDHCP_PORT(CLIENT_PORT = 68;)
222 client_config.interface = "eth0";
223 client_config.script = DEFAULT_SCRIPT;
224 str_V = "udhcp "BB_VER;
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
249 if (opt & (OPT_h|OPT_H))
250 client_config.hostname = alloc_dhcp_option(DHCP_HOST_NAME, str_h, 0);
252 /* FQDN option format: [0x51][len][flags][0][0]<fqdn> */
253 client_config.fqdn = alloc_dhcp_option(DHCP_FQDN, str_F, 3);
254 /* Flag bits: 0000NEOS
255 * S: 1 = Client requests server to update A RR in DNS as well as PTR
256 * O: 1 = Server indicates to client that DNS has been updated regardless
257 * E: 1 = Name is in DNS format, i.e. <4>host<6>domain<3>com<0>,
258 * not "host.domain.com". Format 0 is obsolete.
259 * N: 1 = Client requests server to not update DNS (S must be 0 then)
260 * Two [0] bytes which follow are deprecated and must be 0.
262 client_config.fqdn[OPT_DATA + 0] = 0x1;
263 /*client_config.fqdn[OPT_DATA + 1] = 0; - xzalloc did it */
264 /*client_config.fqdn[OPT_DATA + 2] = 0; */
267 requested_ip = inet_addr(str_r);
268 #if ENABLE_FEATURE_UDHCP_PORT
270 CLIENT_PORT = xatou16(str_P);
271 SERVER_PORT = CLIENT_PORT - 1;
275 client_config.no_default_options = 1;
277 char *optstr = llist_pop(&list_O);
278 int n = index_in_strings(dhcp_option_strings, optstr);
280 bb_error_msg_and_die("unknown option '%s'", optstr);
281 n = dhcp_options[n].code;
282 client_config.opt_mask[n >> 3] |= 1 << (n & 7);
285 if (udhcp_read_interface(client_config.interface,
286 &client_config.ifindex,
288 client_config.client_mac)
294 client_config.clientid = alloc_dhcp_option(DHCP_CLIENT_ID, str_c, 0);
295 } else if (!(opt & OPT_C)) {
296 /* not set and not suppressed, set the default client ID */
297 client_config.clientid = alloc_dhcp_option(DHCP_CLIENT_ID, "", 7);
298 client_config.clientid[OPT_DATA] = 1; /* type: ethernet */
299 memcpy(client_config.clientid + OPT_DATA+1, client_config.client_mac, 6);
301 if (str_V[0] != '\0')
302 client_config.vendorclass = alloc_dhcp_option(DHCP_VENDOR, str_V, 0);
304 /* on NOMMU reexec (i.e., background) early */
305 if (!(opt & OPT_f)) {
306 bb_daemonize_or_rexec(0 /* flags */, argv);
307 logmode = LOGMODE_NONE;
311 openlog(applet_name, LOG_PID, LOG_DAEMON);
312 logmode |= LOGMODE_SYSLOG;
315 /* Make sure fd 0,1,2 are open */
317 /* Equivalent of doing a fflush after every \n */
321 write_pidfile(client_config.pidfile);
323 /* Goes to stdout (unless NOMMU) and possibly syslog */
324 bb_info_msg("%s (v"BB_VER") started", applet_name);
326 /* Set up the signal pipe */
329 state = INIT_SELECTING;
330 udhcp_run_script(NULL, "deconfig");
331 change_listen_mode(LISTEN_RAW);
334 already_waited_sec = 0;
336 /* Main event loop. select() waits on signal pipe and possibly
338 * "continue" statements in code below jump to the top of the loop.
341 /* silence "uninitialized!" warning */
342 unsigned timestamp_before_wait = timestamp_before_wait;
344 //bb_error_msg("sockfd:%d, listen_mode:%d", sockfd, listen_mode);
346 /* Was opening raw or udp socket here
347 * if (listen_mode != LISTEN_NONE && sockfd < 0),
348 * but on fast network renew responses return faster
349 * than we open sockets. Thus this code is moved
350 * to change_listen_mode(). Thus we open listen socket
351 * BEFORE we send renew request (see "case BOUND:"). */
353 max_fd = udhcp_sp_fd_set(&rfds, sockfd);
355 tv.tv_sec = timeout - already_waited_sec;
357 retval = 0; /* If we already timed out, fall through, else... */
358 if ((int)tv.tv_sec > 0) {
359 timestamp_before_wait = (unsigned)monotonic_sec();
360 log1("Waiting on select...");
361 retval = select(max_fd + 1, &rfds, NULL, NULL, &tv);
363 /* EINTR? A signal was caught, don't panic */
364 if (errno == EINTR) {
365 already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
368 /* Else: an error occured, panic! */
369 bb_perror_msg_and_die("select");
373 /* If timeout dropped to zero, time to become active:
374 * resend discover/renew/whatever
377 /* We will restart the wait in any case */
378 already_waited_sec = 0;
382 if (packet_num < discover_retries) {
386 send_discover(xid, requested_ip);
387 timeout = discover_timeout;
392 udhcp_run_script(NULL, "leasefail");
393 #if BB_MMU /* -b is not supported on NOMMU */
394 if (opt & OPT_b) { /* background if no lease */
395 bb_info_msg("No lease, forking to background");
397 /* do not background again! */
398 opt = ((opt & ~OPT_b) | OPT_f);
401 if (opt & OPT_n) { /* abort if no lease */
402 bb_info_msg("No lease, failing");
406 /* wait before trying again */
407 timeout = tryagain_timeout;
411 if (packet_num < discover_retries) {
412 /* send broadcast select packet */
413 send_select(xid, server_addr, requested_ip);
414 timeout = discover_timeout;
418 /* Timed out, go back to init state.
419 * "discover...select...discover..." loops
420 * were seen in the wild. Treat them similarly
421 * to "no response to discover" case */
422 change_listen_mode(LISTEN_RAW);
423 state = INIT_SELECTING;
426 /* 1/2 lease passed, enter renewing state */
428 change_listen_mode(LISTEN_KERNEL);
429 log1("Entering renew state");
430 /* fall right through */
431 case RENEW_REQUESTED: /* manual (SIGUSR1) renew */
432 case_RENEW_REQUESTED:
435 /* send an unicast renew request */
436 /* Sometimes observed to fail (EADDRNOTAVAIL) to bind
437 * a new UDP socket for sending inside send_renew.
438 * I hazard to guess existing listening socket
439 * is somehow conflicting with it, but why is it
440 * not deterministic then?! Strange.
441 * Anyway, it does recover by eventually failing through
442 * into INIT_SELECTING state.
444 send_renew(xid, server_addr, requested_ip);
448 /* Timed out, enter rebinding state */
449 log1("Entering rebinding state");
451 /* fall right through */
453 /* Switch to bcast receive */
454 change_listen_mode(LISTEN_RAW);
455 /* Lease is *really* about to run out,
456 * try to find DHCP server using broadcast */
458 /* send a broadcast renew request */
459 send_renew(xid, 0 /*INADDR_ANY*/, requested_ip);
463 /* Timed out, enter init state */
464 bb_info_msg("Lease lost, entering init state");
465 udhcp_run_script(NULL, "deconfig");
466 state = INIT_SELECTING;
467 /*timeout = 0; - already is */
472 /* yah, I know, *you* say it would never happen */
474 continue; /* back to main loop */
475 } /* if select timed out */
477 /* select() didn't timeout, something happened */
479 /* Is it a signal? */
480 /* note: udhcp_sp_read checks FD_ISSET before reading */
481 switch (udhcp_sp_read(&rfds)) {
484 if (state == RENEW_REQUESTED)
485 goto case_RENEW_REQUESTED;
486 /* Start things over */
488 /* Kill any timeouts, user wants this to hurry along */
492 perform_release(requested_ip, server_addr);
496 bb_info_msg("Received SIGTERM");
497 if (opt & OPT_R) /* release on quit */
498 perform_release(requested_ip, server_addr);
502 /* Is it a packet? */
503 if (listen_mode == LISTEN_NONE || !FD_ISSET(sockfd, &rfds))
509 /* A packet is ready, read it */
510 if (listen_mode == LISTEN_KERNEL)
511 len = udhcp_recv_kernel_packet(&packet, sockfd);
513 len = udhcp_recv_raw_packet(&packet, sockfd);
515 /* Error is severe, reopen socket */
516 bb_info_msg("Read error: %s, reopening socket", strerror(errno));
517 sleep(discover_timeout); /* 3 seconds by default */
518 change_listen_mode(listen_mode); /* just close and reopen */
520 /* If this packet will turn out to be unrelated/bogus,
521 * we will go back and wait for next one.
522 * Be sure timeout is properly decreased. */
523 already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
528 if (packet.xid != xid) {
529 log1("xid %x (our is %x), ignoring packet",
530 (unsigned)packet.xid, (unsigned)xid);
534 /* Ignore packets that aren't for us */
536 || memcmp(packet.chaddr, client_config.client_mac, 6)
538 //FIXME: need to also check that last 10 bytes are zero
539 log1("chaddr does not match, ignoring packet"); // log2?
543 message = get_option(&packet, DHCP_MESSAGE_TYPE);
544 if (message == NULL) {
545 bb_error_msg("no message type option, ignoring packet");
551 /* Must be a DHCPOFFER to one of our xid's */
552 if (*message == DHCPOFFER) {
553 /* TODO: why we don't just fetch server's IP from IP header? */
554 temp = get_option(&packet, DHCP_SERVER_ID);
556 bb_error_msg("no server ID in message");
558 /* still selecting - this server looks bad */
560 /* it IS unaligned sometimes, don't "optimize" */
561 move_from_unaligned32(server_addr, temp);
563 requested_ip = packet.yiaddr;
565 /* enter requesting state */
569 already_waited_sec = 0;
574 case RENEW_REQUESTED:
576 if (*message == DHCPACK) {
577 temp = get_option(&packet, DHCP_LEASE_TIME);
579 bb_error_msg("no lease time with ACK, using 1 hour lease");
580 lease_seconds = 60 * 60;
582 /* it IS unaligned sometimes, don't "optimize" */
583 move_from_unaligned32(lease_seconds, temp);
584 lease_seconds = ntohl(lease_seconds);
585 lease_seconds &= 0x0fffffff; /* paranoia: must not be prone to overflows */
586 if (lease_seconds < 10) /* and not too small */
589 #if ENABLE_FEATURE_UDHCPC_ARPING
591 /* RFC 2131 3.1 paragraph 5:
592 * "The client receives the DHCPACK message with configuration
593 * parameters. The client SHOULD perform a final check on the
594 * parameters (e.g., ARP for allocated network address), and notes
595 * the duration of the lease specified in the DHCPACK message. At this
596 * point, the client is configured. If the client detects that the
597 * address is already in use (e.g., through the use of ARP),
598 * the client MUST send a DHCPDECLINE message to the server and restarts
599 * the configuration process..." */
600 if (!arpping(packet.yiaddr,
603 client_config.client_mac,
604 client_config.interface)
606 bb_info_msg("Offered address is in use "
607 "(got ARP reply), declining");
608 send_decline(xid, server_addr, packet.yiaddr);
610 if (state != REQUESTING)
611 udhcp_run_script(NULL, "deconfig");
612 change_listen_mode(LISTEN_RAW);
613 state = INIT_SELECTING;
615 timeout = tryagain_timeout;
617 already_waited_sec = 0;
618 continue; /* back to main loop */
622 /* enter bound state */
623 timeout = lease_seconds / 2;
625 struct in_addr temp_addr;
626 temp_addr.s_addr = packet.yiaddr;
627 bb_info_msg("Lease of %s obtained, lease time %u",
628 inet_ntoa(temp_addr), (unsigned)lease_seconds);
630 requested_ip = packet.yiaddr;
631 udhcp_run_script(&packet, state == REQUESTING ? "bound" : "renew");
634 change_listen_mode(LISTEN_NONE);
635 if (opt & OPT_q) { /* quit after lease */
636 if (opt & OPT_R) /* release on quit */
637 perform_release(requested_ip, server_addr);
640 /* future renew failures should not exit (JM) */
642 #if BB_MMU /* NOMMU case backgrounded earlier */
643 if (!(opt & OPT_f)) {
645 /* do not background again! */
646 opt = ((opt & ~OPT_b) | OPT_f);
649 already_waited_sec = 0;
650 continue; /* back to main loop */
652 if (*message == DHCPNAK) {
653 /* return to init state */
654 bb_info_msg("Received DHCP NAK");
655 udhcp_run_script(&packet, "nak");
656 if (state != REQUESTING)
657 udhcp_run_script(NULL, "deconfig");
658 change_listen_mode(LISTEN_RAW);
659 sleep(3); /* avoid excessive network traffic */
660 state = INIT_SELECTING;
664 already_waited_sec = 0;
667 /* case BOUND: - ignore all packets */
668 /* case RELEASED: - ignore all packets */
670 /* back to main loop */
671 } /* for (;;) - main loop ends */
676 /*if (client_config.pidfile) - remove_pidfile has its own check */
677 remove_pidfile(client_config.pidfile);