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 DEBUG("entering %s listen mode",
45 new_mode ? (new_mode == 1 ? "kernel" : "raw") : "none");
50 listen_mode = new_mode;
55 static void perform_renew(void)
57 bb_info_msg("Performing a DHCP renew");
60 change_listen_mode(LISTEN_KERNEL);
63 state = RENEW_REQUESTED;
65 case RENEW_REQUESTED: /* impatient are we? fine, square 1 */
66 udhcp_run_script(NULL, "deconfig");
69 change_listen_mode(LISTEN_RAW);
70 state = INIT_SELECTING;
78 /* perform a release */
79 static void perform_release(uint32_t requested_ip, uint32_t server_addr)
81 char buffer[sizeof("255.255.255.255")];
82 struct in_addr temp_addr;
84 /* send release packet */
85 if (state == BOUND || state == RENEWING || state == REBINDING) {
86 temp_addr.s_addr = server_addr;
87 strcpy(buffer, inet_ntoa(temp_addr));
88 temp_addr.s_addr = requested_ip;
89 bb_info_msg("Unicasting a release of %s to %s",
90 inet_ntoa(temp_addr), buffer);
91 send_release(server_addr, requested_ip); /* unicast */
92 udhcp_run_script(NULL, "deconfig");
94 bb_info_msg("Entering released state");
96 change_listen_mode(LISTEN_NONE);
101 static void client_background(void)
104 bb_error_msg("cannot background in uclinux (yet)");
105 /* ... mainly because udhcpc calls client_background()
106 * in _the _middle _of _udhcpc _run_, not at the start!
107 * If that will be properly disabled for NOMMU, client_background()
108 * will work on NOMMU too */
111 logmode &= ~LOGMODE_STDIO;
112 /* rewrite pidfile, as our pid is different now */
113 write_pidfile(client_config.pidfile);
115 /* Do not fork again. */
116 client_config.foreground = 1;
117 client_config.background_if_no_lease = 0;
121 static uint8_t* alloc_dhcp_option(int code, const char *str, int extra)
124 int len = strlen(str);
125 if (len > 255) len = 255;
126 storage = xzalloc(len + extra + OPT_DATA);
127 storage[OPT_CODE] = code;
128 storage[OPT_LEN] = len + extra;
129 memcpy(storage + extra + OPT_DATA, str, len);
134 int udhcpc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
135 int udhcpc_main(int argc ATTRIBUTE_UNUSED, char **argv)
137 uint8_t *temp, *message;
138 char *str_c, *str_V, *str_h, *str_F, *str_r;
139 USE_FEATURE_UDHCP_PORT(char *str_P;)
140 llist_t *list_O = NULL;
141 #if ENABLE_FEATURE_UDHCPC_ARPING
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 dhcpMessage packet;
182 #if ENABLE_FEATURE_UDHCPC_ARPING
189 #if ENABLE_GETOPT_LONG
190 static const char udhcpc_longopts[] ALIGN1 =
191 "clientid\0" Required_argument "c"
192 "clientid-none\0" No_argument "C"
193 "vendorclass\0" Required_argument "V"
194 "foreground\0" No_argument "f"
195 "background\0" No_argument "b"
196 "hostname\0" Required_argument "H"
197 "fqdn\0" Required_argument "F"
198 "interface\0" Required_argument "i"
199 "now\0" No_argument "n"
200 "pidfile\0" Required_argument "p"
201 "quit\0" No_argument "q"
202 "release\0" No_argument "R"
203 "request\0" Required_argument "r"
204 "script\0" Required_argument "s"
205 "timeout\0" Required_argument "T"
206 "version\0" No_argument "v"
207 "retries\0" Required_argument "t"
208 "tryagain\0" Required_argument "A"
209 "syslog\0" No_argument "S"
210 #if ENABLE_FEATURE_UDHCPC_ARPING
211 "arping\0" No_argument "a"
213 "request-option\0" Required_argument "O"
214 #if ENABLE_FEATURE_UDHCP_PORT
215 "client-port\0" Required_argument "P"
217 "no-default-options\0" No_argument "o"
220 /* Default options. */
221 #if ENABLE_FEATURE_UDHCP_PORT
225 client_config.interface = "eth0";
226 client_config.script = DEFAULT_SCRIPT;
228 /* Parse command line */
229 /* Cc: mutually exclusive; O: list; -T,-t,-A take numeric param */
230 opt_complementary = "c--C:C--c:O::T+:t+:A+";
231 #if ENABLE_GETOPT_LONG
232 applet_long_options = udhcpc_longopts;
234 opt = getopt32(argv, "c:CV:fbH:h:F:i:np:qRr:s:T:t:vSA:"
235 USE_FEATURE_UDHCPC_ARPING("aW:")
236 USE_FEATURE_UDHCP_PORT("P:")
238 , &str_c, &str_V, &str_h, &str_h, &str_F
239 , &client_config.interface, &client_config.pidfile, &str_r
240 , &client_config.script
241 , &discover_timeout, &discover_retries, &tryagain_timeout
242 USE_FEATURE_UDHCPC_ARPING(, &str_W)
243 USE_FEATURE_UDHCP_PORT(, &str_P)
248 client_config.clientid = alloc_dhcp_option(DHCP_CLIENT_ID, str_c, 0);
251 client_config.vendorclass = alloc_dhcp_option(DHCP_VENDOR, str_V, 0);
253 client_config.foreground = 1;
255 client_config.background_if_no_lease = 1;
256 if (opt & (OPT_h|OPT_H))
257 client_config.hostname = alloc_dhcp_option(DHCP_HOST_NAME, str_h, 0);
259 client_config.fqdn = alloc_dhcp_option(DHCP_FQDN, str_F, 3);
261 S: 1 => Client requests Server to update A RR in DNS as well as PTR
262 O: 1 => Server indicates to client that DNS has been updated regardless
263 E: 1 => Name data is DNS format, i.e. <4>host<6>domain<4>com<0> not "host.domain.com"
264 N: 1 => Client requests Server to not update DNS
266 client_config.fqdn[OPT_DATA + 0] = 0x1;
267 /* client_config.fqdn[OPT_DATA + 1] = 0; - redundant */
268 /* client_config.fqdn[OPT_DATA + 2] = 0; - redundant */
270 // if (opt & OPT_i) client_config.interface = ...
272 client_config.abort_if_no_lease = 1;
273 // if (opt & OPT_p) client_config.pidfile = ...
275 client_config.quit_after_lease = 1;
277 client_config.release_on_quit = 1;
279 requested_ip = inet_addr(str_r);
280 // if (opt & OPT_s) client_config.script = ...
281 // if (opt & OPT_T) discover_timeout = xatoi_u(str_T);
282 // if (opt & OPT_t) discover_retries = xatoi_u(str_t);
283 // if (opt & OPT_A) tryagain_timeout = xatoi_u(str_A);
285 puts("version "BB_VER);
289 openlog(applet_name, LOG_PID, LOG_LOCAL0);
290 logmode |= LOGMODE_SYSLOG;
292 #if ENABLE_FEATURE_UDHCP_PORT
294 CLIENT_PORT = xatou16(str_P);
295 SERVER_PORT = CLIENT_PORT - 1;
299 client_config.no_default_options = 1;
301 int n = index_in_strings(dhcp_option_strings, list_O->data);
303 bb_error_msg_and_die("unknown option '%s'", list_O->data);
304 n = dhcp_options[n].code;
305 client_config.opt_mask[n >> 3] |= 1 << (n & 7);
306 list_O = list_O->link;
309 if (read_interface(client_config.interface, &client_config.ifindex,
310 NULL, client_config.arp))
313 /* Make sure fd 0,1,2 are open */
315 /* Equivalent of doing a fflush after every \n */
319 write_pidfile(client_config.pidfile);
320 /* if (!..) bb_perror_msg("cannot create pidfile %s", pidfile); */
322 /* Goes to stdout and possibly syslog */
323 bb_info_msg("%s (v"BB_VER") started", applet_name);
325 /* if not set, and not suppressed, setup the default client ID */
326 if (!client_config.clientid && !(opt & OPT_C)) {
327 client_config.clientid = alloc_dhcp_option(DHCP_CLIENT_ID, "", 7);
328 client_config.clientid[OPT_DATA] = 1;
329 memcpy(client_config.clientid + OPT_DATA+1, client_config.arp, 6);
332 if (!client_config.vendorclass)
333 client_config.vendorclass = alloc_dhcp_option(DHCP_VENDOR, "udhcp "BB_VER, 0);
335 /* setup the signal pipe */
338 state = INIT_SELECTING;
339 udhcp_run_script(NULL, "deconfig");
340 change_listen_mode(LISTEN_RAW);
343 already_waited_sec = 0;
345 /* Main event loop. select() waits on signal pipe and possibly
347 * "continue" statements in code below jump to the top of the loop.
350 unsigned timestamp_before_wait;
352 if (listen_mode != LISTEN_NONE && sockfd < 0) {
353 if (listen_mode == LISTEN_KERNEL)
354 sockfd = listen_socket(/*INADDR_ANY,*/ CLIENT_PORT, client_config.interface);
356 sockfd = raw_socket(client_config.ifindex);
358 max_fd = udhcp_sp_fd_set(&rfds, sockfd);
360 tv.tv_sec = timeout - already_waited_sec;
362 retval = 0; /* If we already timed out, fall through, else... */
364 timestamp_before_wait = (unsigned)monotonic_sec();
365 DEBUG("Waiting on select...");
366 retval = select(max_fd + 1, &rfds, NULL, NULL, &tv);
368 /* EINTR? A signal was caught, don't panic */
371 /* Else: an error occured, panic! */
372 bb_perror_msg_and_die("select");
376 /* If timeout dropped to zero, time to become active:
377 * resend discover/renew/whatever
380 /* We will restart wait afresh in any case */
381 already_waited_sec = 0;
385 if (packet_num < discover_retries) {
389 send_discover(xid, requested_ip); /* broadcast */
391 timeout = discover_timeout;
395 udhcp_run_script(NULL, "leasefail");
396 if (client_config.background_if_no_lease) {
397 bb_info_msg("No lease, forking to background");
399 } else if (client_config.abort_if_no_lease) {
400 bb_info_msg("No lease, failing");
404 /* wait before trying again */
405 timeout = tryagain_timeout;
408 case RENEW_REQUESTED:
410 if (packet_num < discover_retries) {
411 /* send request packet */
412 if (state == RENEW_REQUESTED) /* unicast */
413 send_renew(xid, server_addr, requested_ip);
415 send_selecting(xid, server_addr, requested_ip);
417 timeout = discover_timeout;
421 /* timed out, go back to init state */
422 if (state == RENEW_REQUESTED)
423 udhcp_run_script(NULL, "deconfig");
424 change_listen_mode(LISTEN_RAW);
425 state = INIT_SELECTING;
430 /* Half of the lease passed, time to enter renewing state */
431 change_listen_mode(LISTEN_KERNEL);
432 DEBUG("Entering renew state");
434 /* fall right through */
437 /* send a request packet */
438 send_renew(xid, server_addr, requested_ip); /* unicast */
442 /* Timed out, enter rebinding state */
443 DEBUG("Entering rebinding state");
445 /* fall right through */
447 /* Lease is *really* about to run out,
448 * try to find DHCP server using broadcast */
450 /* send a request packet */
451 send_renew(xid, 0, requested_ip); /* broadcast */
455 /* Timed out, enter init state */
456 bb_info_msg("Lease lost, entering init state");
457 udhcp_run_script(NULL, "deconfig");
458 change_listen_mode(LISTEN_RAW);
459 state = INIT_SELECTING;
460 /*timeout = 0; - already is */
465 /* yah, I know, *you* say it would never happen */
467 continue; /* back to main loop */
470 /* select() didn't timeout, something did happen. */
471 /* Is is a packet? */
472 if (listen_mode != LISTEN_NONE && FD_ISSET(sockfd, &rfds)) {
474 /* A packet is ready, read it */
476 if (listen_mode == LISTEN_KERNEL)
477 len = udhcp_recv_kernel_packet(&packet, sockfd);
479 len = udhcp_recv_raw_packet(&packet, sockfd);
480 if (len == -1) { /* error is severe, reopen socket */
481 DEBUG("error on read, %s, reopening socket", strerror(errno));
482 sleep(discover_timeout); /* 3 seconds by default */
483 change_listen_mode(listen_mode); /* just close and reopen */
485 /* If this packet will turn out to be unrelated/bogus,
486 * we will go back and wait for next one.
487 * Be sure timeout is properly decreased. */
488 already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
492 if (packet.xid != xid) {
493 DEBUG("Ignoring XID %x (our xid is %x)",
494 (unsigned)packet.xid, (unsigned)xid);
498 /* Ignore packets that aren't for us */
499 if (memcmp(packet.chaddr, client_config.arp, 6)) {
500 DEBUG("Packet does not have our chaddr - ignoring");
504 message = get_option(&packet, DHCP_MESSAGE_TYPE);
505 if (message == NULL) {
506 bb_error_msg("cannot get message type from packet - ignoring");
512 /* Must be a DHCPOFFER to one of our xid's */
513 if (*message == DHCPOFFER) {
514 /* TODO: why we don't just fetch server's IP from IP header? */
515 temp = get_option(&packet, DHCP_SERVER_ID);
517 bb_error_msg("no server ID in message");
519 /* still selecting - this server looks bad */
521 /* it IS unaligned sometimes, don't "optimize" */
522 server_addr = get_unaligned_u32p((uint32_t*)temp);
524 requested_ip = packet.yiaddr;
526 /* enter requesting state */
530 already_waited_sec = 0;
533 case RENEW_REQUESTED:
537 if (*message == DHCPACK) {
538 temp = get_option(&packet, DHCP_LEASE_TIME);
540 bb_error_msg("no lease time with ACK, using 1 hour lease");
541 lease_seconds = 60 * 60;
543 /* can be misaligned, thus memcpy */
544 memcpy(&lease_seconds, temp, 4);
545 lease_seconds = ntohl(lease_seconds);
546 lease_seconds &= 0x0fffffff; /* paranoia: must not be prone to overflows */
547 if (lease_seconds < 10) /* and not too small */
550 #if ENABLE_FEATURE_UDHCPC_ARPING
552 if (!arpping(packet.yiaddr,
555 client_config.interface)
557 bb_info_msg("offered address is in use "
558 "(got ARP reply), declining");
559 send_decline(xid, server_addr, packet.yiaddr);
561 if (state != REQUESTING)
562 udhcp_run_script(NULL, "deconfig");
563 change_listen_mode(LISTEN_RAW);
564 state = INIT_SELECTING;
566 timeout = tryagain_timeout;
568 already_waited_sec = 0;
569 continue; /* back to main loop */
573 /* enter bound state */
574 timeout = lease_seconds / 2;
576 struct in_addr temp_addr;
577 temp_addr.s_addr = packet.yiaddr;
578 bb_info_msg("Lease of %s obtained, lease time %u",
579 inet_ntoa(temp_addr), (unsigned)lease_seconds);
581 requested_ip = packet.yiaddr;
582 udhcp_run_script(&packet,
583 ((state == RENEWING || state == REBINDING) ? "renew" : "bound"));
586 change_listen_mode(LISTEN_NONE);
587 if (client_config.quit_after_lease) {
588 if (client_config.release_on_quit)
589 perform_release(requested_ip, server_addr);
592 if (!client_config.foreground)
595 already_waited_sec = 0;
596 continue; /* back to main loop */
598 if (*message == DHCPNAK) {
599 /* return to init state */
600 bb_info_msg("Received DHCP NAK");
601 udhcp_run_script(&packet, "nak");
602 if (state != REQUESTING)
603 udhcp_run_script(NULL, "deconfig");
604 change_listen_mode(LISTEN_RAW);
605 sleep(3); /* avoid excessive network traffic */
606 state = INIT_SELECTING;
610 already_waited_sec = 0;
613 /* case BOUND, RELEASED: - ignore all packets */
615 continue; /* back to main loop */
618 /* select() didn't timeout, something did happen.
619 * But it wasn't a packet. It's a signal pipe then. */
621 int signo = udhcp_sp_read(&rfds);
625 /* start things over */
627 /* Kill any timeouts because the user wants this to hurry along */
631 perform_release(requested_ip, server_addr);
635 bb_info_msg("Received SIGTERM");
636 if (client_config.release_on_quit)
637 perform_release(requested_ip, server_addr);
641 } /* for (;;) - main loop ends */
646 /*if (client_config.pidfile) - remove_pidfile has its own check */
647 remove_pidfile(client_config.pidfile);