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.
13 /* Override ENABLE_FEATURE_PIDFILE - ifupdown needs our pidfile to always exist */
14 #define WANT_PIDFILE 1
21 static int sockfd = -1;
24 #define LISTEN_KERNEL 1
26 static smallint listen_mode;
28 #define INIT_SELECTING 0
34 #define RENEW_REQUESTED 6
36 static smallint state;
38 /* struct client_config_t client_config is in bb_common_bufsiz1 */
41 /* just a little helper */
42 static void change_listen_mode(int new_mode)
44 log1("entering %s listen mode",
45 new_mode ? (new_mode == 1 ? "kernel" : "raw") : "none");
47 listen_mode = new_mode;
52 if (new_mode == LISTEN_KERNEL)
53 sockfd = udhcp_listen_socket(/*INADDR_ANY,*/ CLIENT_PORT, client_config.interface);
54 else if (new_mode != LISTEN_NONE)
55 sockfd = udhcp_raw_socket(client_config.ifindex);
56 /* else LISTEN_NONE: sockfd stay closed */
61 static void perform_renew(void)
63 bb_info_msg("Performing a DHCP renew");
66 change_listen_mode(LISTEN_KERNEL);
69 state = RENEW_REQUESTED;
71 case RENEW_REQUESTED: /* impatient are we? fine, square 1 */
72 udhcp_run_script(NULL, "deconfig");
75 change_listen_mode(LISTEN_RAW);
76 state = INIT_SELECTING;
84 /* perform a release */
85 static void perform_release(uint32_t requested_ip, uint32_t server_addr)
87 char buffer[sizeof("255.255.255.255")];
88 struct in_addr temp_addr;
90 /* send release packet */
91 if (state == BOUND || state == RENEWING || state == REBINDING) {
92 temp_addr.s_addr = server_addr;
93 strcpy(buffer, inet_ntoa(temp_addr));
94 temp_addr.s_addr = requested_ip;
95 bb_info_msg("Unicasting a release of %s to %s",
96 inet_ntoa(temp_addr), buffer);
97 send_release(server_addr, requested_ip); /* unicast */
98 udhcp_run_script(NULL, "deconfig");
100 bb_info_msg("Entering released state");
102 change_listen_mode(LISTEN_NONE);
108 static void client_background(void)
111 logmode &= ~LOGMODE_STDIO;
112 /* rewrite pidfile, as our pid is different now */
113 write_pidfile(client_config.pidfile);
118 static uint8_t* alloc_dhcp_option(int code, const char *str, int extra)
121 int len = strlen(str);
122 if (len > 255) len = 255;
123 storage = xzalloc(len + extra + OPT_DATA);
124 storage[OPT_CODE] = code;
125 storage[OPT_LEN] = len + extra;
126 memcpy(storage + extra + OPT_DATA, str, len);
131 int udhcpc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
132 int udhcpc_main(int argc UNUSED_PARAM, char **argv)
134 uint8_t *temp, *message;
135 char *str_c, *str_V, *str_h, *str_F, *str_r;
136 IF_FEATURE_UDHCP_PORT(char *str_P;)
137 llist_t *list_O = NULL;
138 int tryagain_timeout = 20;
139 int discover_timeout = 3;
140 int discover_retries = 3;
141 uint32_t server_addr = server_addr; /* for compiler */
142 uint32_t requested_ip = 0;
144 uint32_t lease_seconds = 0; /* can be given as 32-bit quantity */
146 int timeout; /* must be signed */
147 unsigned already_waited_sec;
152 struct dhcpMessage packet;
155 #if ENABLE_GETOPT_LONG
156 static const char udhcpc_longopts[] ALIGN1 =
157 "clientid\0" Required_argument "c"
158 "clientid-none\0" No_argument "C"
159 "vendorclass\0" Required_argument "V"
160 "hostname\0" Required_argument "H"
161 "fqdn\0" Required_argument "F"
162 "interface\0" Required_argument "i"
163 "now\0" No_argument "n"
164 "pidfile\0" Required_argument "p"
165 "quit\0" No_argument "q"
166 "release\0" No_argument "R"
167 "request\0" Required_argument "r"
168 "script\0" Required_argument "s"
169 "timeout\0" Required_argument "T"
170 "version\0" No_argument "v"
171 "retries\0" Required_argument "t"
172 "tryagain\0" Required_argument "A"
173 "syslog\0" No_argument "S"
174 "request-option\0" Required_argument "O"
175 "no-default-options\0" No_argument "o"
176 "foreground\0" No_argument "f"
177 "background\0" No_argument "b"
178 IF_FEATURE_UDHCPC_ARPING("arping\0" No_argument "a")
179 IF_FEATURE_UDHCP_PORT("client-port\0" Required_argument "P")
203 /* The rest has variable bit positions, need to be clever */
205 USE_FOR_MMU( OPTBIT_b,)
206 IF_FEATURE_UDHCPC_ARPING(OPTBIT_a,)
207 IF_FEATURE_UDHCP_PORT( OPTBIT_P,)
208 USE_FOR_MMU( OPT_b = 1 << OPTBIT_b,)
209 IF_FEATURE_UDHCPC_ARPING(OPT_a = 1 << OPTBIT_a,)
210 IF_FEATURE_UDHCP_PORT( OPT_P = 1 << OPTBIT_P,)
213 /* Default options. */
214 IF_FEATURE_UDHCP_PORT(SERVER_PORT = 67;)
215 IF_FEATURE_UDHCP_PORT(CLIENT_PORT = 68;)
216 client_config.interface = "eth0";
217 client_config.script = DEFAULT_SCRIPT;
219 /* Parse command line */
220 /* Cc: mutually exclusive; O: list; -T,-t,-A take numeric param */
221 opt_complementary = "c--C:C--c:O::T+:t+:A+"
222 #if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
226 IF_GETOPT_LONG(applet_long_options = udhcpc_longopts;)
227 opt = getopt32(argv, "c:CV:H:h:F:i:np:qRr:s:T:t:SA:O:of"
229 IF_FEATURE_UDHCPC_ARPING("a")
230 IF_FEATURE_UDHCP_PORT("P:")
232 , &str_c, &str_V, &str_h, &str_h, &str_F
233 , &client_config.interface, &client_config.pidfile, &str_r /* i,p */
234 , &client_config.script /* s */
235 , &discover_timeout, &discover_retries, &tryagain_timeout /* T,t,A */
237 IF_FEATURE_UDHCP_PORT(, &str_P)
238 #if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
243 client_config.clientid = alloc_dhcp_option(DHCP_CLIENT_ID, str_c, 0);
245 client_config.vendorclass = alloc_dhcp_option(DHCP_VENDOR, str_V, 0);
246 if (opt & (OPT_h|OPT_H))
247 client_config.hostname = alloc_dhcp_option(DHCP_HOST_NAME, str_h, 0);
249 client_config.fqdn = alloc_dhcp_option(DHCP_FQDN, str_F, 3);
251 S: 1 => Client requests Server to update A RR in DNS as well as PTR
252 O: 1 => Server indicates to client that DNS has been updated regardless
253 E: 1 => Name data is DNS format, i.e. <4>host<6>domain<3>com<0> not "host.domain.com"
254 N: 1 => Client requests Server to not update DNS
256 client_config.fqdn[OPT_DATA + 0] = 0x1;
257 /* client_config.fqdn[OPT_DATA + 1] = 0; - redundant */
258 /* client_config.fqdn[OPT_DATA + 2] = 0; - redundant */
261 requested_ip = inet_addr(str_r);
262 #if ENABLE_FEATURE_UDHCP_PORT
264 CLIENT_PORT = xatou16(str_P);
265 SERVER_PORT = CLIENT_PORT - 1;
269 client_config.no_default_options = 1;
271 char *optstr = llist_pop(&list_O);
272 int n = index_in_strings(dhcp_option_strings, optstr);
274 bb_error_msg_and_die("unknown option '%s'", optstr);
275 n = dhcp_options[n].code;
276 client_config.opt_mask[n >> 3] |= 1 << (n & 7);
279 if (udhcp_read_interface(client_config.interface,
280 &client_config.ifindex,
282 client_config.client_mac)
288 /* on NOMMU reexec (i.e., background) early */
289 if (!(opt & OPT_f)) {
290 bb_daemonize_or_rexec(0 /* flags */, argv);
291 logmode = LOGMODE_NONE;
295 openlog(applet_name, LOG_PID, LOG_DAEMON);
296 logmode |= LOGMODE_SYSLOG;
299 /* Make sure fd 0,1,2 are open */
301 /* Equivalent of doing a fflush after every \n */
305 write_pidfile(client_config.pidfile);
307 /* Goes to stdout (unless NOMMU) and possibly syslog */
308 bb_info_msg("%s (v"BB_VER") started", applet_name);
310 /* if not set, and not suppressed, setup the default client ID */
311 if (!client_config.clientid && !(opt & OPT_C)) {
312 client_config.clientid = alloc_dhcp_option(DHCP_CLIENT_ID, "", 7);
313 client_config.clientid[OPT_DATA] = 1;
314 memcpy(client_config.clientid + OPT_DATA+1, client_config.client_mac, 6);
317 if (!client_config.vendorclass)
318 client_config.vendorclass = alloc_dhcp_option(DHCP_VENDOR, "udhcp "BB_VER, 0);
320 /* setup the signal pipe */
323 state = INIT_SELECTING;
324 udhcp_run_script(NULL, "deconfig");
325 change_listen_mode(LISTEN_RAW);
328 already_waited_sec = 0;
330 /* Main event loop. select() waits on signal pipe and possibly
332 * "continue" statements in code below jump to the top of the loop.
335 /* silence "uninitialized!" warning */
336 unsigned timestamp_before_wait = timestamp_before_wait;
338 //bb_error_msg("sockfd:%d, listen_mode:%d", sockfd, listen_mode);
340 /* Was opening raw or udp socket here
341 * if (listen_mode != LISTEN_NONE && sockfd < 0),
342 * but on fast network renew responses return faster
343 * than we open sockets. Thus this code is moved
344 * to change_listen_mode(). Thus we open listen socket
345 * BEFORE we send renew request (see "case BOUND:"). */
347 max_fd = udhcp_sp_fd_set(&rfds, sockfd);
349 tv.tv_sec = timeout - already_waited_sec;
351 retval = 0; /* If we already timed out, fall through, else... */
353 timestamp_before_wait = (unsigned)monotonic_sec();
354 log1("Waiting on select...");
355 retval = select(max_fd + 1, &rfds, NULL, NULL, &tv);
357 /* EINTR? A signal was caught, don't panic */
360 /* Else: an error occured, panic! */
361 bb_perror_msg_and_die("select");
365 /* If timeout dropped to zero, time to become active:
366 * resend discover/renew/whatever
369 /* We will restart the wait in any case */
370 already_waited_sec = 0;
374 if (packet_num < discover_retries) {
378 send_discover(xid, requested_ip); /* broadcast */
380 timeout = discover_timeout;
385 udhcp_run_script(NULL, "leasefail");
386 #if BB_MMU /* -b is not supported on NOMMU */
387 if (opt & OPT_b) { /* background if no lease */
388 bb_info_msg("No lease, forking to background");
390 /* do not background again! */
391 opt = ((opt & ~OPT_b) | OPT_f);
394 if (opt & OPT_n) { /* abort if no lease */
395 bb_info_msg("No lease, failing");
399 /* wait before trying again */
400 timeout = tryagain_timeout;
403 case RENEW_REQUESTED:
405 if (packet_num < discover_retries) {
406 /* send request packet */
407 if (state == RENEW_REQUESTED) /* unicast */
408 send_renew(xid, server_addr, requested_ip);
410 send_select(xid, server_addr, requested_ip);
412 timeout = discover_timeout;
416 /* timed out, go back to init state */
417 if (state == RENEW_REQUESTED)
418 udhcp_run_script(NULL, "deconfig");
419 change_listen_mode(LISTEN_RAW);
420 /* "discover...select...discover..." loops
421 * were seen in the wild. Treat them similarly
422 * to "no response to discover" case */
423 if (state == REQUESTING) {
424 state = INIT_SELECTING;
427 state = INIT_SELECTING;
432 /* Half of the lease passed, time to enter renewing state */
433 change_listen_mode(LISTEN_KERNEL);
434 log1("Entering renew state");
436 /* fall right through */
439 /* send a request packet */
440 send_renew(xid, server_addr, requested_ip); /* unicast */
444 /* Timed out, enter rebinding state */
445 log1("Entering rebinding state");
447 /* fall right through */
449 /* Lease is *really* about to run out,
450 * try to find DHCP server using broadcast */
452 /* send a request packet */
453 send_renew(xid, 0 /*INADDR_ANY*/, requested_ip); /* broadcast */
457 /* Timed out, enter init state */
458 bb_info_msg("Lease lost, entering init state");
459 udhcp_run_script(NULL, "deconfig");
460 change_listen_mode(LISTEN_RAW);
461 state = INIT_SELECTING;
462 /*timeout = 0; - already is */
467 /* yah, I know, *you* say it would never happen */
469 continue; /* back to main loop */
472 /* select() didn't timeout, something did happen. */
473 /* Is it a packet? */
474 if (listen_mode != LISTEN_NONE && FD_ISSET(sockfd, &rfds)) {
476 /* A packet is ready, read it */
478 if (listen_mode == LISTEN_KERNEL)
479 len = udhcp_recv_kernel_packet(&packet, sockfd);
481 len = udhcp_recv_raw_packet(&packet, sockfd);
482 if (len == -1) { /* error is severe, reopen socket */
483 bb_info_msg("Read error: %s, reopening socket", strerror(errno));
484 sleep(discover_timeout); /* 3 seconds by default */
485 change_listen_mode(listen_mode); /* just close and reopen */
487 /* If this packet will turn out to be unrelated/bogus,
488 * we will go back and wait for next one.
489 * Be sure timeout is properly decreased. */
490 already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
494 if (packet.xid != xid) {
495 log1("xid %x (our is %x), ignoring packet",
496 (unsigned)packet.xid, (unsigned)xid);
500 /* Ignore packets that aren't for us */
501 if (memcmp(packet.chaddr, client_config.client_mac, 6)) {
502 //FIXME: need to also check that last 10 bytes are zero
503 log1("chaddr does not match, ignoring packet"); // log2?
507 message = get_option(&packet, DHCP_MESSAGE_TYPE);
508 if (message == NULL) {
509 bb_error_msg("no message type option, ignoring packet");
515 /* Must be a DHCPOFFER to one of our xid's */
516 if (*message == DHCPOFFER) {
517 /* TODO: why we don't just fetch server's IP from IP header? */
518 temp = get_option(&packet, DHCP_SERVER_ID);
520 bb_error_msg("no server ID in message");
522 /* still selecting - this server looks bad */
524 /* it IS unaligned sometimes, don't "optimize" */
525 move_from_unaligned32(server_addr, temp);
527 requested_ip = packet.yiaddr;
529 /* enter requesting state */
533 already_waited_sec = 0;
536 case RENEW_REQUESTED:
540 if (*message == DHCPACK) {
541 temp = get_option(&packet, DHCP_LEASE_TIME);
543 bb_error_msg("no lease time with ACK, using 1 hour lease");
544 lease_seconds = 60 * 60;
546 /* it IS unaligned sometimes, don't "optimize" */
547 move_from_unaligned32(lease_seconds, temp);
548 lease_seconds = ntohl(lease_seconds);
549 lease_seconds &= 0x0fffffff; /* paranoia: must not be prone to overflows */
550 if (lease_seconds < 10) /* and not too small */
553 #if ENABLE_FEATURE_UDHCPC_ARPING
555 /* RFC 2131 3.1 paragraph 5:
556 * "The client receives the DHCPACK message with configuration
557 * parameters. The client SHOULD perform a final check on the
558 * parameters (e.g., ARP for allocated network address), and notes
559 * the duration of the lease specified in the DHCPACK message. At this
560 * point, the client is configured. If the client detects that the
561 * address is already in use (e.g., through the use of ARP),
562 * the client MUST send a DHCPDECLINE message to the server and restarts
563 * the configuration process..." */
564 if (!arpping(packet.yiaddr,
567 client_config.client_mac,
568 client_config.interface)
570 bb_info_msg("Offered address is in use "
571 "(got ARP reply), declining");
572 send_decline(xid, server_addr, packet.yiaddr);
574 if (state != REQUESTING)
575 udhcp_run_script(NULL, "deconfig");
576 change_listen_mode(LISTEN_RAW);
577 state = INIT_SELECTING;
579 timeout = tryagain_timeout;
581 already_waited_sec = 0;
582 continue; /* back to main loop */
586 /* enter bound state */
587 timeout = lease_seconds / 2;
589 struct in_addr temp_addr;
590 temp_addr.s_addr = packet.yiaddr;
591 bb_info_msg("Lease of %s obtained, lease time %u",
592 inet_ntoa(temp_addr), (unsigned)lease_seconds);
594 requested_ip = packet.yiaddr;
595 udhcp_run_script(&packet,
596 ((state == RENEWING || state == REBINDING) ? "renew" : "bound"));
599 change_listen_mode(LISTEN_NONE);
600 if (opt & OPT_q) { /* quit after lease */
601 if (opt & OPT_R) /* release on quit */
602 perform_release(requested_ip, server_addr);
605 #if BB_MMU /* NOMMU case backgrounded earlier */
606 if (!(opt & OPT_f)) {
608 /* do not background again! */
609 opt = ((opt & ~OPT_b) | OPT_f);
612 already_waited_sec = 0;
613 continue; /* back to main loop */
615 if (*message == DHCPNAK) {
616 /* return to init state */
617 bb_info_msg("Received DHCP NAK");
618 udhcp_run_script(&packet, "nak");
619 if (state != REQUESTING)
620 udhcp_run_script(NULL, "deconfig");
621 change_listen_mode(LISTEN_RAW);
622 sleep(3); /* avoid excessive network traffic */
623 state = INIT_SELECTING;
627 already_waited_sec = 0;
630 /* case BOUND, RELEASED: - ignore all packets */
632 continue; /* back to main loop */
635 /* select() didn't timeout, something did happen.
636 * But it wasn't a packet. It's a signal pipe then. */
638 int signo = udhcp_sp_read(&rfds);
642 /* start things over */
644 /* Kill any timeouts because the user wants this to hurry along */
648 perform_release(requested_ip, server_addr);
652 bb_info_msg("Received SIGTERM");
653 if (opt & OPT_R) /* release on quit */
654 perform_release(requested_ip, server_addr);
658 } /* for (;;) - main loop ends */
663 /*if (client_config.pidfile) - remove_pidfile has its own check */
664 remove_pidfile(client_config.pidfile);