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 timeout; /* = 0. Must be signed */
22 static uint32_t requested_ip; /* = 0 */
23 static uint32_t server_addr;
24 static int sockfd = -1;
27 #define LISTEN_KERNEL 1
29 static smallint listen_mode;
31 static smallint state;
33 /* struct client_config_t client_config is in bb_common_bufsiz1 */
36 /* just a little helper */
37 static void change_listen_mode(int new_mode)
39 DEBUG("entering %s listen mode",
40 new_mode ? (new_mode == 1 ? "kernel" : "raw") : "none");
45 listen_mode = new_mode;
50 static void perform_renew(void)
52 bb_info_msg("Performing a DHCP renew");
55 change_listen_mode(LISTEN_KERNEL);
58 state = RENEW_REQUESTED;
60 case RENEW_REQUESTED: /* impatient are we? fine, square 1 */
61 udhcp_run_script(NULL, "deconfig");
64 change_listen_mode(LISTEN_RAW);
65 state = INIT_SELECTING;
73 /* perform a release */
74 static void perform_release(void)
76 char buffer[sizeof("255.255.255.255")];
77 struct in_addr temp_addr;
79 /* send release packet */
80 if (state == BOUND || state == RENEWING || state == REBINDING) {
81 temp_addr.s_addr = server_addr;
82 strcpy(buffer, inet_ntoa(temp_addr));
83 temp_addr.s_addr = requested_ip;
84 bb_info_msg("Unicasting a release of %s to %s",
85 inet_ntoa(temp_addr), buffer);
86 send_release(server_addr, requested_ip); /* unicast */
87 udhcp_run_script(NULL, "deconfig");
89 bb_info_msg("Entering released state");
91 change_listen_mode(LISTEN_NONE);
97 static void client_background(void)
100 bb_error_msg("cannot background in uclinux (yet)");
101 /* ... mainly because udhcpc calls client_background()
102 * in _the _middle _of _udhcpc _run_, not at the start!
103 * If that will be properly disabled for NOMMU, client_background()
104 * will work on NOMMU too */
107 logmode &= ~LOGMODE_STDIO;
108 /* rewrite pidfile, as our pid is different now */
109 write_pidfile(client_config.pidfile);
111 /* Do not fork again. */
112 client_config.foreground = 1;
113 client_config.background_if_no_lease = 0;
117 static uint8_t* alloc_dhcp_option(int code, const char *str, int extra)
120 int len = strlen(str);
121 if (len > 255) len = 255;
122 storage = xzalloc(len + extra + OPT_DATA);
123 storage[OPT_CODE] = code;
124 storage[OPT_LEN] = len + extra;
125 memcpy(storage + extra + OPT_DATA, str, len);
130 int udhcpc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
131 int udhcpc_main(int argc ATTRIBUTE_UNUSED, char **argv)
133 uint8_t *temp, *message;
134 char *str_c, *str_V, *str_h, *str_F, *str_r;
135 USE_FEATURE_UDHCP_PORT(char *str_P;)
136 llist_t *list_O = NULL;
137 #if ENABLE_FEATURE_UDHCPC_ARPING
140 int tryagain_timeout = 20;
141 int discover_timeout = 3;
142 int discover_retries = 3;
144 uint32_t lease_seconds = 0; /* can be given as 32-bit quantity */
146 /* t1, t2... what a wonderful names... */
147 unsigned t1 = t1; /* for gcc */
149 unsigned timestamp_got_lease = timestamp_got_lease;
155 struct in_addr temp_addr;
156 struct dhcpMessage packet;
180 #if ENABLE_FEATURE_UDHCPC_ARPING
187 #if ENABLE_GETOPT_LONG
188 static const char udhcpc_longopts[] ALIGN1 =
189 "clientid\0" Required_argument "c"
190 "clientid-none\0" No_argument "C"
191 "vendorclass\0" Required_argument "V"
192 "foreground\0" No_argument "f"
193 "background\0" No_argument "b"
194 "hostname\0" Required_argument "H"
195 "fqdn\0" Required_argument "F"
196 "interface\0" Required_argument "i"
197 "now\0" No_argument "n"
198 "pidfile\0" Required_argument "p"
199 "quit\0" No_argument "q"
200 "release\0" No_argument "R"
201 "request\0" Required_argument "r"
202 "script\0" Required_argument "s"
203 "timeout\0" Required_argument "T"
204 "version\0" No_argument "v"
205 "retries\0" Required_argument "t"
206 "tryagain\0" Required_argument "A"
207 "syslog\0" No_argument "S"
208 #if ENABLE_FEATURE_UDHCPC_ARPING
209 "arping\0" No_argument "a"
211 "request-option\0" Required_argument "O"
212 #if ENABLE_FEATURE_UDHCP_PORT
213 "client-port\0" Required_argument "P"
215 "no-default-options\0" No_argument "o"
218 /* Default options. */
219 #if ENABLE_FEATURE_UDHCP_PORT
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 ENABLE_GETOPT_LONG
230 applet_long_options = udhcpc_longopts;
232 opt = getopt32(argv, "c:CV:fbH:h:F:i:np:qRr:s:T:t:vSA:"
233 USE_FEATURE_UDHCPC_ARPING("aW:")
234 USE_FEATURE_UDHCP_PORT("P:")
236 , &str_c, &str_V, &str_h, &str_h, &str_F
237 , &client_config.interface, &client_config.pidfile, &str_r
238 , &client_config.script
239 , &discover_timeout, &discover_retries, &tryagain_timeout
240 USE_FEATURE_UDHCPC_ARPING(, &str_W)
241 USE_FEATURE_UDHCP_PORT(, &str_P)
246 client_config.clientid = alloc_dhcp_option(DHCP_CLIENT_ID, str_c, 0);
249 client_config.vendorclass = alloc_dhcp_option(DHCP_VENDOR, str_V, 0);
251 client_config.foreground = 1;
253 client_config.background_if_no_lease = 1;
254 if (opt & (OPT_h|OPT_H))
255 client_config.hostname = alloc_dhcp_option(DHCP_HOST_NAME, str_h, 0);
257 client_config.fqdn = alloc_dhcp_option(DHCP_FQDN, str_F, 3);
259 S: 1 => Client requests Server to update A RR in DNS as well as PTR
260 O: 1 => Server indicates to client that DNS has been updated regardless
261 E: 1 => Name data is DNS format, i.e. <4>host<6>domain<4>com<0> not "host.domain.com"
262 N: 1 => Client requests Server to not update DNS
264 client_config.fqdn[OPT_DATA + 0] = 0x1;
265 /* client_config.fqdn[OPT_DATA + 1] = 0; - redundant */
266 /* client_config.fqdn[OPT_DATA + 2] = 0; - redundant */
268 // if (opt & OPT_i) client_config.interface = ...
270 client_config.abort_if_no_lease = 1;
271 // if (opt & OPT_p) client_config.pidfile = ...
273 client_config.quit_after_lease = 1;
275 client_config.release_on_quit = 1;
277 requested_ip = inet_addr(str_r);
278 // if (opt & OPT_s) client_config.script = ...
279 // if (opt & OPT_T) discover_timeout = xatoi_u(str_T);
280 // if (opt & OPT_t) discover_retries = xatoi_u(str_t);
281 // if (opt & OPT_A) tryagain_timeout = xatoi_u(str_A);
283 puts("version "BB_VER);
287 openlog(applet_name, LOG_PID, LOG_LOCAL0);
288 logmode |= LOGMODE_SYSLOG;
290 #if ENABLE_FEATURE_UDHCP_PORT
292 CLIENT_PORT = xatou16(str_P);
293 SERVER_PORT = CLIENT_PORT - 1;
297 client_config.no_default_options = 1;
299 int n = index_in_strings(dhcp_option_strings, list_O->data);
301 bb_error_msg_and_die("unknown option '%s'", list_O->data);
302 n = dhcp_options[n].code;
303 client_config.opt_mask[n >> 3] |= 1 << (n & 7);
304 list_O = list_O->link;
307 if (read_interface(client_config.interface, &client_config.ifindex,
308 NULL, client_config.arp))
311 /* Make sure fd 0,1,2 are open */
313 /* Equivalent of doing a fflush after every \n */
317 write_pidfile(client_config.pidfile);
318 /* if (!..) bb_perror_msg("cannot create pidfile %s", pidfile); */
320 /* Goes to stdout and possibly syslog */
321 bb_info_msg("%s (v"BB_VER") started", applet_name);
323 /* if not set, and not suppressed, setup the default client ID */
324 if (!client_config.clientid && !(opt & OPT_C)) {
325 client_config.clientid = alloc_dhcp_option(DHCP_CLIENT_ID, "", 7);
326 client_config.clientid[OPT_DATA] = 1;
327 memcpy(client_config.clientid + OPT_DATA+1, client_config.arp, 6);
330 if (!client_config.vendorclass)
331 client_config.vendorclass = alloc_dhcp_option(DHCP_VENDOR, "udhcp "BB_VER, 0);
333 /* setup the signal pipe */
336 state = INIT_SELECTING;
337 udhcp_run_script(NULL, "deconfig");
338 change_listen_mode(LISTEN_RAW);
341 /* Main event loop. select() waits on signal pipe and possibly
343 * "continue" statements in code below jump to the top of the loop.
346 unsigned timestamp_before_wait;
348 if (listen_mode != LISTEN_NONE && sockfd < 0) {
349 if (listen_mode == LISTEN_KERNEL)
350 sockfd = listen_socket(/*INADDR_ANY,*/ CLIENT_PORT, client_config.interface);
352 sockfd = raw_socket(client_config.ifindex);
354 max_fd = udhcp_sp_fd_set(&rfds, sockfd);
358 retval = 0; /* If we already timed out, fall through, else... */
360 timestamp_before_wait = (unsigned)monotonic_sec();
361 DEBUG("Waiting on select...");
362 retval = select(max_fd + 1, &rfds, NULL, NULL, &tv);
364 /* EINTR? A signal was caught, don't panic */
367 /* Else: an error occured, panic! */
368 bb_perror_msg_and_die("select");
372 /* If timeout dropped to zero, time to become active:
373 * resend discover/renew/whatever
378 if (packet_num < discover_retries) {
382 /* send discover packet */
383 send_discover(xid, requested_ip); /* broadcast */
385 timeout = discover_timeout;
389 udhcp_run_script(NULL, "leasefail");
390 if (client_config.background_if_no_lease) {
391 bb_info_msg("No lease, forking to background");
393 } else if (client_config.abort_if_no_lease) {
394 bb_info_msg("No lease, failing");
398 /* wait to try again */
399 timeout = tryagain_timeout;
402 case RENEW_REQUESTED:
404 if (packet_num < discover_retries) {
405 /* send request packet */
406 if (state == RENEW_REQUESTED)
407 send_renew(xid, server_addr, requested_ip); /* unicast */
408 else send_selecting(xid, server_addr, requested_ip); /* broadcast */
410 timeout = ((packet_num == 2) ? 10 : 2);
414 /* timed out, go back to init state */
415 if (state == RENEW_REQUESTED)
416 udhcp_run_script(NULL, "deconfig");
417 change_listen_mode(LISTEN_RAW);
418 state = INIT_SELECTING;
423 /* Lease is starting to run out, time to enter renewing state */
424 change_listen_mode(LISTEN_KERNEL);
425 DEBUG("Entering renew state");
427 /* fall right through */
429 /* Either set a new T1, or enter REBINDING state */
430 if ((t2 - t1) > (lease_seconds / (4*60*60) + 1)) {
431 /* send a request packet */
432 send_renew(xid, server_addr, requested_ip); /* unicast */
434 timeout = t1 - ((unsigned)monotonic_sec() - timestamp_got_lease);
437 /* Timed out, enter rebinding state */
438 DEBUG("Entering rebinding state");
443 /* Lease is *really* about to run out,
444 * try to find DHCP server using broadcast */
445 if ((lease_seconds - t2) > (lease_seconds / (4*60*60) + 1)) {
446 /* send a request packet */
447 send_renew(xid, 0, requested_ip); /* broadcast */
448 t2 += (lease_seconds - t2) / 2;
449 timeout = t2 - ((unsigned)monotonic_sec() - timestamp_got_lease);
452 /* Timed out, enter init state */
453 bb_info_msg("Lease lost, entering init state");
454 udhcp_run_script(NULL, "deconfig");
455 change_listen_mode(LISTEN_RAW);
456 state = INIT_SELECTING;
462 /* yah, I know, *you* say it would never happen */
464 continue; /* back to main loop */
467 /* select() didn't timeout, something did happen. */
468 /* Is is a packet? */
469 if (listen_mode != LISTEN_NONE && FD_ISSET(sockfd, &rfds)) {
470 /* A packet is ready, read it */
472 if (listen_mode == LISTEN_KERNEL)
473 len = udhcp_recv_packet(&packet, sockfd);
475 len = get_raw_packet(&packet, sockfd);
477 /* If this packet will turn out to be unrelated/bogus,
478 * we will go back and wait for next one.
479 * Be sure timeout is properly decreased. */
480 timeout -= (unsigned)monotonic_sec() - timestamp_before_wait;
482 if (len == -1) { /* error is severe, reopen socket */
483 DEBUG("error on read, %s, reopening socket", strerror(errno));
484 change_listen_mode(listen_mode); /* just close and reopen */
486 if (len < 0) continue;
488 if (packet.xid != xid) {
489 DEBUG("Ignoring XID %x (our xid is %x)",
490 (unsigned)packet.xid, (unsigned)xid);
494 /* Ignore packets that aren't for us */
495 if (memcmp(packet.chaddr, client_config.arp, 6)) {
496 DEBUG("Packet does not have our chaddr - ignoring");
500 message = get_option(&packet, DHCP_MESSAGE_TYPE);
501 if (message == NULL) {
502 bb_error_msg("cannot get message type from packet - ignoring");
508 /* Must be a DHCPOFFER to one of our xid's */
509 if (*message == DHCPOFFER) {
510 /* TODO: why we don't just fetch server's IP from IP header? */
511 temp = get_option(&packet, DHCP_SERVER_ID);
513 bb_error_msg("no server ID in message");
515 /* still selecting - this server looks bad */
517 /* can be misaligned, thus memcpy */
518 memcpy(&server_addr, temp, 4);
520 requested_ip = packet.yiaddr;
522 /* enter requesting state */
528 case RENEW_REQUESTED:
532 if (*message == DHCPACK) {
533 temp = get_option(&packet, DHCP_LEASE_TIME);
535 bb_error_msg("no lease time with ACK, using 1 hour lease");
536 lease_seconds = 60 * 60;
538 /* can be misaligned, thus memcpy */
539 memcpy(&lease_seconds, temp, 4);
540 lease_seconds = ntohl(lease_seconds);
542 #if ENABLE_FEATURE_UDHCPC_ARPING
544 if (!arpping(packet.yiaddr,
547 client_config.interface)
549 bb_info_msg("offered address is in use "
550 "(got ARP reply), declining");
551 send_decline(xid, server_addr, packet.yiaddr);
553 if (state != REQUESTING)
554 udhcp_run_script(NULL, "deconfig");
555 change_listen_mode(LISTEN_RAW);
556 state = INIT_SELECTING;
558 timeout = tryagain_timeout;
560 continue; /* back to main loop */
564 /* enter bound state */
565 t1 = lease_seconds / 2;
567 /* little fixed point for n * .875 */
568 t2 = (lease_seconds * 7) >> 3;
569 temp_addr.s_addr = packet.yiaddr;
570 bb_info_msg("Lease of %s obtained, lease time %u",
571 inet_ntoa(temp_addr), (unsigned)lease_seconds);
572 timestamp_got_lease = monotonic_sec();
574 requested_ip = packet.yiaddr;
575 udhcp_run_script(&packet,
576 ((state == RENEWING || state == REBINDING) ? "renew" : "bound"));
579 change_listen_mode(LISTEN_NONE);
580 if (client_config.quit_after_lease) {
581 if (client_config.release_on_quit)
585 if (!client_config.foreground)
588 continue; /* back to main loop */
590 if (*message == DHCPNAK) {
591 /* return to init state */
592 bb_info_msg("Received DHCP NAK");
593 udhcp_run_script(&packet, "nak");
594 if (state != REQUESTING)
595 udhcp_run_script(NULL, "deconfig");
596 change_listen_mode(LISTEN_RAW);
597 sleep(3); /* avoid excessive network traffic */
598 state = INIT_SELECTING;
604 /* case BOUND, RELEASED: - ignore all packets */
606 continue; /* back to main loop */
609 /* select() didn't timeout, something did happen.
610 * But it wasn't a packet. It's a signal pipe then. */
612 int signo = udhcp_sp_read(&rfds);
616 /* start things over */
618 /* Kill any timeouts because the user wants this to hurry along */
625 bb_info_msg("Received SIGTERM");
626 if (client_config.release_on_quit)
631 } /* for (;;) - main loop ends */
636 /*if (client_config.pidfile) - remove_pidfile has its own check */
637 remove_pidfile(client_config.pidfile);