1 /* vi: set sw=4 ts=4: */
5 * Copyright (C) 2011-2017 Denys Vlasenko.
7 * Licensed under GPLv2, see file LICENSE in this source tree.
9 //config:config UDHCPC6
10 //config: bool "udhcpc6 (21 kb)"
12 //config: depends on FEATURE_IPV6
14 //config: udhcpc6 is a DHCPv6 client
16 //config:config FEATURE_UDHCPC6_RFC3646
17 //config: bool "Support RFC 3646 (DNS server and search list)"
19 //config: depends on UDHCPC6
21 //config: List of DNS servers and domain search list can be requested with
22 //config: "-O dns" and "-O search". If server gives these values,
23 //config: they will be set in environment variables "dns" and "search".
25 //config:config FEATURE_UDHCPC6_RFC4704
26 //config: bool "Support RFC 4704 (Client FQDN)"
28 //config: depends on UDHCPC6
30 //config: You can request FQDN to be given by server using "-O fqdn".
32 //config:config FEATURE_UDHCPC6_RFC4833
33 //config: bool "Support RFC 4833 (Timezones)"
35 //config: depends on UDHCPC6
37 //config: You can request POSIX timezone with "-O tz" and timezone name
38 //config: with "-O timezone".
40 //config:config FEATURE_UDHCPC6_RFC5970
41 //config: bool "Support RFC 5970 (Network Boot)"
43 //config: depends on UDHCPC6
45 //config: You can request bootfile-url with "-O bootfile_url" and
46 //config: bootfile-params with "-O bootfile_params".
48 //applet:IF_UDHCPC6(APPLET(udhcpc6, BB_DIR_USR_BIN, BB_SUID_DROP))
50 //kbuild:lib-$(CONFIG_UDHCPC6) += d6_dhcpc.o d6_packet.o d6_socket.o common.o socket.o signalpipe.o
51 //kbuild:lib-$(CONFIG_FEATURE_UDHCPC6_RFC3646) += domain_codec.o
52 //kbuild:lib-$(CONFIG_FEATURE_UDHCPC6_RFC4704) += domain_codec.o
55 /* Override ENABLE_FEATURE_PIDFILE - ifupdown needs our pidfile to always exist */
56 #define WANT_PIDFILE 1
60 #include "d6_common.h"
62 #include <netinet/if_ether.h>
63 #include <netpacket/packet.h>
64 #include <linux/filter.h>
66 /* "struct client_data_t client_data" is in bb_common_bufsiz1 */
68 static const struct dhcp_optflag d6_optflags[] = {
69 #if ENABLE_FEATURE_UDHCPC6_RFC3646
70 { OPTION_6RD | OPTION_LIST | OPTION_REQ, D6_OPT_DNS_SERVERS },
71 { OPTION_DNS_STRING | OPTION_LIST | OPTION_REQ, D6_OPT_DOMAIN_LIST },
73 #if ENABLE_FEATURE_UDHCPC6_RFC4704
74 { OPTION_DNS_STRING, D6_OPT_CLIENT_FQDN },
76 #if ENABLE_FEATURE_UDHCPC6_RFC4833
77 { OPTION_STRING, D6_OPT_TZ_POSIX },
78 { OPTION_STRING, D6_OPT_TZ_NAME },
80 #if ENABLE_FEATURE_UDHCPC6_RFC5970
81 { OPTION_STRING, D6_OPT_BOOT_URL },
82 { OPTION_STRING, D6_OPT_BOOT_PARAM },
84 { OPTION_STRING, 0xd1 }, /* DHCP_PXE_CONF_FILE */
85 { OPTION_STRING, 0xd2 }, /* DHCP_PXE_PATH_PREFIX */
88 /* Must match d6_optflags[] order */
89 static const char d6_option_strings[] ALIGN1 =
90 #if ENABLE_FEATURE_UDHCPC6_RFC3646
91 "dns" "\0" /* D6_OPT_DNS_SERVERS */
92 "search" "\0" /* D6_OPT_DOMAIN_LIST */
94 #if ENABLE_FEATURE_UDHCPC6_RFC4704
95 "fqdn" "\0" /* D6_OPT_CLIENT_FQDN */
97 #if ENABLE_FEATURE_UDHCPC6_RFC4833
98 "tz" "\0" /* D6_OPT_TZ_POSIX */
99 "timezone" "\0" /* D6_OPT_TZ_NAME */
101 #if ENABLE_FEATURE_UDHCPC6_RFC5970
102 "bootfile_url" "\0" /* D6_OPT_BOOT_URL */
103 "bootfile_param" "\0" /* D6_OPT_BOOT_PARAM */
105 "pxeconffile" "\0" /* DHCP_PXE_CONF_FILE */
106 "pxepathprefix" "\0" /* DHCP_PXE_PATH_PREFIX */
110 static const char udhcpc6_longopts[] ALIGN1 =
111 "interface\0" Required_argument "i"
112 "now\0" No_argument "n"
113 "pidfile\0" Required_argument "p"
114 "quit\0" No_argument "q"
115 "release\0" No_argument "R"
116 "request\0" Required_argument "r"
117 "requestprefix\0" No_argument "d"
118 "script\0" Required_argument "s"
119 "timeout\0" Required_argument "T"
120 "retries\0" Required_argument "t"
121 "tryagain\0" Required_argument "A"
122 "syslog\0" No_argument "S"
123 "request-option\0" Required_argument "O"
124 "no-default-options\0" No_argument "o"
125 "foreground\0" No_argument "f"
126 "stateless\0" No_argument "l"
128 "background\0" No_argument "b"
130 /// IF_FEATURE_UDHCPC_ARPING("arping\0" No_argument "a")
131 IF_FEATURE_UDHCP_PORT("client-port\0" Required_argument "P")
134 /* Must match getopt32 option string order */
153 /* The rest has variable bit positions, need to be clever */
155 USE_FOR_MMU( OPTBIT_b,)
156 ///IF_FEATURE_UDHCPC_ARPING(OPTBIT_a,)
157 IF_FEATURE_UDHCP_PORT( OPTBIT_P,)
158 USE_FOR_MMU( OPT_b = 1 << OPTBIT_b,)
159 ///IF_FEATURE_UDHCPC_ARPING(OPT_a = 1 << OPTBIT_a,)
160 IF_FEATURE_UDHCP_PORT( OPT_P = 1 << OPTBIT_P,)
163 #if ENABLE_FEATURE_UDHCPC6_RFC4704
164 static const char opt_fqdn_req[] = {
165 (D6_OPT_CLIENT_FQDN >> 8), (D6_OPT_CLIENT_FQDN & 0xff),
168 /* S=0: server SHOULD NOT perform AAAA RR updates */
169 /* O=0: client MUST set this bit to 0 */
170 /* N=0: server SHOULD perform updates (PTR RR only in our case, since S=0) */
171 0 /* empty DNS-encoded name */
175 /*** Utility functions ***/
177 static void *d6_find_option(uint8_t *option, uint8_t *option_end, unsigned code)
179 /* "length minus 4" */
180 int len_m4 = option_end - option - 4;
181 while (len_m4 >= 0) {
182 /* Next option's len is too big? */
183 if (option[3] > len_m4)
184 return NULL; /* yes. bogus packet! */
185 /* So far we treat any opts with code >255
186 * or len >255 as bogus, and stop at once.
187 * This simplifies big-endian handling.
189 if (option[0] != 0 || option[2] != 0)
191 /* Option seems to be valid */
192 /* Does its code match? */
193 if (option[1] == code)
194 return option; /* yes! */
195 len_m4 -= option[3] + 4;
196 option += option[3] + 4;
201 static void *d6_copy_option(uint8_t *option, uint8_t *option_end, unsigned code)
203 uint8_t *opt = d6_find_option(option, option_end, code);
206 return xmemdup(opt, opt[3] + 4);
209 /*** Script execution code ***/
211 static char** new_env(void)
213 client6_data.env_ptr = xrealloc_vector(client6_data.env_ptr, 3, client6_data.env_idx);
214 return &client6_data.env_ptr[client6_data.env_idx++];
217 static char *string_option_to_env(const uint8_t *option,
218 const uint8_t *option_end)
220 const char *ptr, *name = NULL;
224 ptr = d6_option_strings;
227 if (d6_optflags[i].code == option[1]) {
231 ptr += strlen(ptr) + 1;
234 bb_error_msg("can't find option name for 0x%x, skipping", option[1]);
238 val_len = (option[2] << 8) | option[3];
239 if (val_len + &option[D6_OPT_DATA] > option_end) {
240 bb_simple_error_msg("option data exceeds option length");
243 return xasprintf("%s=%.*s", name, val_len, (char*)option + 4);
246 /* put all the parameters into the environment */
247 static void option_to_env(const uint8_t *option, const uint8_t *option_end)
249 #if ENABLE_FEATURE_UDHCPC6_RFC3646
250 int addrs, option_offset;
252 /* "length minus 4" */
253 int len_m4 = option_end - option - 4;
255 while (len_m4 >= 0) {
257 char ipv6str[sizeof("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")];
259 if (option[0] != 0 || option[2] != 0)
262 /* Check if option-length exceeds size of option */
263 if (option[3] > len_m4)
267 //case D6_OPT_CLIENTID:
268 //case D6_OPT_SERVERID:
271 option_to_env(option + 16, option + 4 + option[3]);
276 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
277 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
278 * | OPTION_IAADDR | option-len |
279 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
284 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
285 * | preferred-lifetime |
286 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
288 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
290 /* Make sure payload contains an address */
294 sprint_nip6(ipv6str, option + 4);
295 *new_env() = xasprintf("ipv6=%s", ipv6str);
297 move_from_unaligned32(v32, option + 4 + 16 + 4);
298 *new_env() = xasprintf("lease=%u", (unsigned)v32);
302 //case D6_OPT_PREFERENCE:
303 //case D6_OPT_ELAPSED_TIME:
304 //case D6_OPT_RELAY_MSG:
306 //case D6_OPT_UNICAST:
307 //case D6_OPT_STATUS_CODE:
308 //case D6_OPT_RAPID_COMMIT:
309 //case D6_OPT_USER_CLASS:
310 //case D6_OPT_VENDOR_CLASS:
311 //case D6_OPT_VENDOR_OPTS:
312 //case D6_OPT_INTERFACE_ID:
313 //case D6_OPT_RECONF_MSG:
314 //case D6_OPT_RECONF_ACCEPT:
316 case D6_OPT_IAPREFIX:
318 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
319 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
320 * | OPTION_IAPREFIX | option-length |
321 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
322 * | preferred-lifetime |
323 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
325 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
326 * | prefix-length | |
327 * +-+-+-+-+-+-+-+-+ IPv6 prefix |
330 * | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
334 move_from_unaligned32(v32, option + 4 + 4);
335 *new_env() = xasprintf("ipv6prefix_lease=%u", (unsigned)v32);
337 sprint_nip6(ipv6str, option + 4 + 4 + 4 + 1);
338 *new_env() = xasprintf("ipv6prefix=%s/%u", ipv6str, (unsigned)(option[4 + 4 + 4]));
340 #if ENABLE_FEATURE_UDHCPC6_RFC3646
341 case D6_OPT_DNS_SERVERS: {
344 /* Make sure payload-size is a multiple of 16 */
345 if ((option[3] & 0x0f) != 0)
348 /* Get the number of addresses on the option */
349 addrs = option[3] >> 4;
351 /* Setup environment variable */
352 *new_env() = dlist = xmalloc(4 + addrs * 40 - 1);
353 dlist = stpcpy(dlist, "dns=");
357 sprint_nip6(dlist, option + 4 + option_offset);
366 case D6_OPT_DOMAIN_LIST: {
369 dlist = dname_dec(option + 4, (option[2] << 8) | option[3], "search=");
376 #if ENABLE_FEATURE_UDHCPC6_RFC4704
377 case D6_OPT_CLIENT_FQDN: {
382 /* Work around broken ISC DHCPD6.
383 * ISC DHCPD6 does not implement RFC 4704 correctly: It says the first
384 * byte of option-payload should contain flags where the bits 7-3 are
385 * reserved for future use and MUST be zero. Instead ISC DHCPD6 just
386 * writes the entire FQDN as string to option-payload. We assume a
387 * broken server here if any of the reserved bits are set.
389 if (option[4] & 0xf8) {
390 *new_env() = xasprintf("fqdn=%.*s", (int)option[3], (char*)option + 4);
393 dlist = dname_dec(option + 5, (/*(option[2] << 8) |*/ option[3]) - 1, "fqdn=");
400 #if ENABLE_FEATURE_UDHCPC6_RFC4833
401 /* RFC 4833 Timezones */
402 case D6_OPT_TZ_POSIX:
403 *new_env() = xasprintf("tz=%.*s", (int)option[3], (char*)option + 4);
406 *new_env() = xasprintf("tz_name=%.*s", (int)option[3], (char*)option + 4);
409 case D6_OPT_BOOT_URL:
410 case D6_OPT_BOOT_PARAM:
411 case 0xd1: /* DHCP_PXE_CONF_FILE */
412 case 0xd2: /* DHCP_PXE_PATH_PREFIX */
414 char *tmp = string_option_to_env(option, option_end);
420 len_m4 -= 4 + option[3];
421 option += 4 + option[3];
425 static char **fill_envp(const uint8_t *option, const uint8_t *option_end)
429 client6_data.env_ptr = NULL;
430 client6_data.env_idx = 0;
432 *new_env() = xasprintf("interface=%s", client_data.interface);
435 option_to_env(option, option_end);
437 envp = curr = client6_data.env_ptr;
444 /* Call a script with a par file and env vars */
445 static void d6_run_script(const uint8_t *option, const uint8_t *option_end,
451 envp = fill_envp(option, option_end);
454 log1("executing %s %s", client_data.script, name);
455 argv[0] = (char*) client_data.script;
456 argv[1] = (char*) name;
458 spawn_and_wait(argv);
460 for (curr = envp; *curr; curr++) {
462 bb_unsetenv_and_free(*curr);
467 /* Call a script with a par file and no env var */
468 static void d6_run_script_no_option(const char *name)
470 d6_run_script(NULL, NULL, name);
473 /*** Sending/receiving packets ***/
475 static ALWAYS_INLINE uint32_t random_xid(void)
477 uint32_t t = rand() & htonl(0x00ffffff);
481 /* Initialize the packet with the proper defaults */
482 static uint8_t *init_d6_packet(struct d6_packet *packet, char type, uint32_t xid)
485 struct d6_option *clientid;
488 memset(packet, 0, sizeof(*packet));
490 packet->d6_xid32 = xid;
491 packet->d6_msg_type = type;
493 /* ELAPSED_TIME option is required to be present by the RFC,
494 * and some servers do check for its presense. [which?]
496 ptr = packet->d6_options; /* NB: it is 32-bit aligned */
497 *((uint32_t*)ptr) = htonl((D6_OPT_ELAPSED_TIME << 16) + 2);
499 client_data.last_secs = monotonic_sec();
500 if (client_data.first_secs == 0)
501 client_data.first_secs = client_data.last_secs;
502 secs = client_data.last_secs - client_data.first_secs;
503 *((uint16_t*)ptr) = (secs < 0xffff) ? htons(secs) : 0xffff;
506 /* add CLIENTID option */
507 clientid = (void*)client_data.clientid;
508 return mempcpy(ptr, clientid, clientid->len + 2+2);
511 static uint8_t *add_d6_client_options(uint8_t *ptr)
513 struct option_set *curr;
514 uint8_t *start = ptr;
519 for (option = 1; option < 256; option++) {
520 if (client_data.opt_mask[option >> 3] & (1 << (option & 7))) {
521 ptr[0] = (option >> 8);
527 if ((ptr - start - 4) != 0) {
528 start[0] = (D6_OPT_ORO >> 8);
529 start[1] = D6_OPT_ORO;
530 start[2] = ((ptr - start - 4) >> 8);
531 start[3] = (ptr - start - 4);
535 #if ENABLE_FEATURE_UDHCPC6_RFC4704
536 ptr = mempcpy(ptr, &opt_fqdn_req, sizeof(opt_fqdn_req));
538 /* Add -x options if any */
539 curr = client_data.options;
541 len = (curr->data[D6_OPT_LEN] << 8) | curr->data[D6_OPT_LEN + 1];
542 ptr = mempcpy(ptr, curr->data, D6_OPT_DATA + len);
549 static int d6_mcast_from_client_data_ifindex(struct d6_packet *packet, uint8_t *end)
551 /* FF02::1:2 is "All_DHCP_Relay_Agents_and_Servers" address */
552 static const uint8_t FF02__1_2[16] = {
553 0xFF, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
554 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02,
556 /* IPv6 requires different multicast contents in Ethernet Frame (RFC 2464) */
557 static const uint8_t MAC_DHCP6MCAST_ADDR[6] ALIGN2 = {
558 0x33, 0x33, 0x00, 0x01, 0x00, 0x02,
561 return d6_send_raw_packet(
562 packet, (end - (uint8_t*) packet),
563 /*src*/ &client6_data.ll_ip6, CLIENT_PORT6,
564 /*dst*/ (struct in6_addr*)FF02__1_2, SERVER_PORT6, MAC_DHCP6MCAST_ADDR,
569 /* RFC 3315 18.1.5. Creation and Transmission of Information-request Messages
571 * The client uses an Information-request message to obtain
572 * configuration information without having addresses assigned to it.
574 * The client sets the "msg-type" field to INFORMATION-REQUEST. The
575 * client generates a transaction ID and inserts this value in the
576 * "transaction-id" field.
578 * The client SHOULD include a Client Identifier option to identify
579 * itself to the server. If the client does not include a Client
580 * Identifier option, the server will not be able to return any client-
581 * specific options to the client, or the server may choose not to
582 * respond to the message at all. The client MUST include a Client
583 * Identifier option if the Information-Request message will be
586 * The client MUST include an Option Request option (see section 22.7)
587 * to indicate the options the client is interested in receiving. The
588 * client MAY include options with data values as hints to the server
589 * about parameter values the client would like to have returned.
591 /* NOINLINE: limit stack usage in caller */
592 static NOINLINE int send_d6_info_request(uint32_t xid)
594 struct d6_packet packet;
597 /* Fill in: msg type, client id */
598 opt_ptr = init_d6_packet(&packet, D6_MSG_INFORMATION_REQUEST, xid);
601 * "param req" option according to -O, options specified with -x
603 opt_ptr = add_d6_client_options(opt_ptr);
605 bb_error_msg("sending %s", "info request");
606 return d6_mcast_from_client_data_ifindex(&packet, opt_ptr);
609 /* Milticast a DHCPv6 Solicit packet to the network, with an optionally requested IP.
611 * RFC 3315 17.1.1. Creation of Solicit Messages
613 * The client MUST include a Client Identifier option to identify itself
614 * to the server. The client includes IA options for any IAs to which
615 * it wants the server to assign addresses. The client MAY include
616 * addresses in the IAs as a hint to the server about addresses for
617 * which the client has a preference. ...
619 * The client uses IA_NA options to request the assignment of non-
620 * temporary addresses and uses IA_TA options to request the assignment
621 * of temporary addresses. Either IA_NA or IA_TA options, or a
622 * combination of both, can be included in DHCP messages.
624 * The client SHOULD include an Option Request option (see section 22.7)
625 * to indicate the options the client is interested in receiving. The
626 * client MAY additionally include instances of those options that are
627 * identified in the Option Request option, with data values as hints to
628 * the server about parameter values the client would like to have
631 * The client includes a Reconfigure Accept option (see section 22.20)
632 * if the client is willing to accept Reconfigure messages from the
634 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
635 | OPTION_CLIENTID | option-len |
636 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
639 . (variable length) .
641 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
644 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
645 | OPTION_IA_NA | option-len |
646 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
648 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
650 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
652 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
656 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
659 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
660 | OPTION_IAADDR | option-len |
661 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
666 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
667 | preferred-lifetime |
668 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
670 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
674 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
677 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
678 | OPTION_ORO | option-len |
679 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
680 | requested-option-code-1 | requested-option-code-2 |
681 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
683 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
686 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
687 | OPTION_RECONF_ACCEPT | 0 |
688 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
690 /* NOINLINE: limit stack usage in caller */
691 static NOINLINE int send_d6_discover(uint32_t xid, struct in6_addr *requested_ipv6)
693 struct d6_packet packet;
697 /* Fill in: msg type, client id */
698 opt_ptr = init_d6_packet(&packet, D6_MSG_SOLICIT, xid);
700 /* Create new IA_NA, optionally with included IAADDR with requested IP */
701 free(client6_data.ia_na);
702 client6_data.ia_na = NULL;
703 if (option_mask32 & OPT_r) {
704 len = requested_ipv6 ? 2+2+4+4+4 + 2+2+16+4+4 : 2+2+4+4+4;
705 client6_data.ia_na = xzalloc(len);
706 client6_data.ia_na->code = D6_OPT_IA_NA;
707 client6_data.ia_na->len = len - 4;
708 *(bb__aliased_uint32_t*)client6_data.ia_na->data = rand(); /* IAID */
709 if (requested_ipv6) {
710 struct d6_option *iaaddr = (void*)(client6_data.ia_na->data + 4+4+4);
711 iaaddr->code = D6_OPT_IAADDR;
712 iaaddr->len = 16+4+4;
713 memcpy(iaaddr->data, requested_ipv6, 16);
715 opt_ptr = mempcpy(opt_ptr, client6_data.ia_na, len);
719 free(client6_data.ia_pd);
720 client6_data.ia_pd = NULL;
721 if (option_mask32 & OPT_d) {
723 client6_data.ia_pd = xzalloc(len);
724 client6_data.ia_pd->code = D6_OPT_IA_PD;
725 client6_data.ia_pd->len = len - 4;
726 *(bb__aliased_uint32_t*)client6_data.ia_pd->data = rand(); /* IAID */
727 opt_ptr = mempcpy(opt_ptr, client6_data.ia_pd, len);
731 * "param req" option according to -O, options specified with -x
733 opt_ptr = add_d6_client_options(opt_ptr);
735 bb_info_msg("sending %s", "discover");
736 return d6_mcast_from_client_data_ifindex(&packet, opt_ptr);
739 /* Multicast a DHCPv6 request message
741 * RFC 3315 18.1.1. Creation and Transmission of Request Messages
743 * The client uses a Request message to populate IAs with addresses and
744 * obtain other configuration information. The client includes one or
745 * more IA options in the Request message. The server then returns
746 * addresses and other information about the IAs to the client in IA
747 * options in a Reply message.
749 * The client generates a transaction ID and inserts this value in the
750 * "transaction-id" field.
752 * The client places the identifier of the destination server in a
753 * Server Identifier option.
755 * The client MUST include a Client Identifier option to identify itself
756 * to the server. The client adds any other appropriate options,
757 * including one or more IA options (if the client is requesting that
758 * the server assign it some network addresses).
760 * The client MUST include an Option Request option (see section 22.7)
761 * to indicate the options the client is interested in receiving. The
762 * client MAY include options with data values as hints to the server
763 * about parameter values the client would like to have returned.
765 * The client includes a Reconfigure Accept option (see section 22.20)
766 * indicating whether or not the client is willing to accept Reconfigure
767 * messages from the server.
769 /* NOINLINE: limit stack usage in caller */
770 static NOINLINE int send_d6_select(uint32_t xid)
772 struct d6_packet packet;
775 /* Fill in: msg type, client id */
776 opt_ptr = init_d6_packet(&packet, D6_MSG_REQUEST, xid);
779 opt_ptr = mempcpy(opt_ptr, client6_data.server_id, client6_data.server_id->len + 2+2);
780 /* IA NA (contains requested IP) */
781 if (client6_data.ia_na)
782 opt_ptr = mempcpy(opt_ptr, client6_data.ia_na, client6_data.ia_na->len + 2+2);
784 if (client6_data.ia_pd)
785 opt_ptr = mempcpy(opt_ptr, client6_data.ia_pd, client6_data.ia_pd->len + 2+2);
788 * "param req" option according to -O, options specified with -x
790 opt_ptr = add_d6_client_options(opt_ptr);
792 bb_info_msg("sending %s", "select");
793 return d6_mcast_from_client_data_ifindex(&packet, opt_ptr);
796 /* Unicast or broadcast a DHCP renew message
798 * RFC 3315 18.1.3. Creation and Transmission of Renew Messages
800 * To extend the valid and preferred lifetimes for the addresses
801 * associated with an IA, the client sends a Renew message to the server
802 * from which the client obtained the addresses in the IA containing an
803 * IA option for the IA. The client includes IA Address options in the
804 * IA option for the addresses associated with the IA. The server
805 * determines new lifetimes for the addresses in the IA according to the
806 * administrative configuration of the server. The server may also add
807 * new addresses to the IA. The server may remove addresses from the IA
808 * by setting the preferred and valid lifetimes of those addresses to
811 * The server controls the time at which the client contacts the server
812 * to extend the lifetimes on assigned addresses through the T1 and T2
813 * parameters assigned to an IA.
815 * At time T1 for an IA, the client initiates a Renew/Reply message
816 * exchange to extend the lifetimes on any addresses in the IA. The
817 * client includes an IA option with all addresses currently assigned to
818 * the IA in its Renew message.
820 * If T1 or T2 is set to 0 by the server (for an IA_NA) or there are no
821 * T1 or T2 times (for an IA_TA), the client may send a Renew or Rebind
822 * message, respectively, at the client's discretion.
824 * The client sets the "msg-type" field to RENEW. The client generates
825 * a transaction ID and inserts this value in the "transaction-id"
828 * The client places the identifier of the destination server in a
829 * Server Identifier option.
831 * The client MUST include a Client Identifier option to identify itself
832 * to the server. The client adds any appropriate options, including
833 * one or more IA options. The client MUST include the list of
834 * addresses the client currently has associated with the IAs in the
837 * The client MUST include an Option Request option (see section 22.7)
838 * to indicate the options the client is interested in receiving. The
839 * client MAY include options with data values as hints to the server
840 * about parameter values the client would like to have returned.
842 /* NOINLINE: limit stack usage in caller */
843 static NOINLINE int send_d6_renew(uint32_t xid, struct in6_addr *server_ipv6, struct in6_addr *our_cur_ipv6)
845 struct d6_packet packet;
848 /* Fill in: msg type, client id */
849 opt_ptr = init_d6_packet(&packet, DHCPREQUEST, xid);
852 opt_ptr = mempcpy(opt_ptr, client6_data.server_id, client6_data.server_id->len + 2+2);
853 /* IA NA (contains requested IP) */
854 if (client6_data.ia_na)
855 opt_ptr = mempcpy(opt_ptr, client6_data.ia_na, client6_data.ia_na->len + 2+2);
857 if (client6_data.ia_pd)
858 opt_ptr = mempcpy(opt_ptr, client6_data.ia_pd, client6_data.ia_pd->len + 2+2);
861 * "param req" option according to -O, options specified with -x
863 opt_ptr = add_d6_client_options(opt_ptr);
865 bb_info_msg("sending %s", "renew");
867 return d6_send_kernel_packet(
868 &packet, (opt_ptr - (uint8_t*) &packet),
869 our_cur_ipv6, CLIENT_PORT6,
870 server_ipv6, SERVER_PORT6,
873 return d6_mcast_from_client_data_ifindex(&packet, opt_ptr);
876 /* Unicast a DHCP release message */
878 ALWAYS_INLINE /* one caller, help compiler to use this fact */
879 int send_d6_release(struct in6_addr *server_ipv6, struct in6_addr *our_cur_ipv6)
881 struct d6_packet packet;
884 /* Fill in: msg type, client id */
885 opt_ptr = init_d6_packet(&packet, D6_MSG_RELEASE, random_xid());
887 opt_ptr = mempcpy(opt_ptr, client6_data.server_id, client6_data.server_id->len + 2+2);
888 /* IA NA (contains our current IP) */
889 if (client6_data.ia_na)
890 opt_ptr = mempcpy(opt_ptr, client6_data.ia_na, client6_data.ia_na->len + 2+2);
892 if (client6_data.ia_pd)
893 opt_ptr = mempcpy(opt_ptr, client6_data.ia_pd, client6_data.ia_pd->len + 2+2);
895 bb_info_msg("sending %s", "release");
896 return d6_send_kernel_packet(
897 &packet, (opt_ptr - (uint8_t*) &packet),
898 our_cur_ipv6, CLIENT_PORT6,
899 server_ipv6, SERVER_PORT6,
904 /* Returns -1 on errors that are fatal for the socket, -2 for those that aren't */
905 /* NOINLINE: limit stack usage in caller */
906 static NOINLINE int d6_recv_raw_packet(struct in6_addr *peer_ipv6, struct d6_packet *d6_pkt, int fd)
909 struct ip6_udp_d6_packet packet;
911 bytes = safe_read(fd, &packet, sizeof(packet));
913 log1s("packet read error, ignoring");
914 /* NB: possible down interface, etc. Caller should pause. */
915 return bytes; /* returns -1 */
918 if (bytes < (int) (sizeof(packet.ip6) + sizeof(packet.udp))) {
919 log1s("packet is too short, ignoring");
923 if (bytes < sizeof(packet.ip6) + ntohs(packet.ip6.ip6_plen)) {
924 /* packet is bigger than sizeof(packet), we did partial read */
925 log1s("oversized packet, ignoring");
929 /* ignore any extra garbage bytes */
930 bytes = sizeof(packet.ip6) + ntohs(packet.ip6.ip6_plen);
932 /* make sure its the right packet for us, and that it passes sanity checks */
933 if (packet.ip6.ip6_nxt != IPPROTO_UDP
934 || (packet.ip6.ip6_vfc >> 4) != 6
935 || packet.udp.dest != htons(CLIENT_PORT6)
936 /* || bytes > (int) sizeof(packet) - can't happen */
937 || packet.udp.len != packet.ip6.ip6_plen
939 log1s("unrelated/bogus packet, ignoring");
943 //How to do this for ipv6?
944 // /* verify UDP checksum. IP header has to be modified for this */
945 // memset(&packet.ip, 0, offsetof(struct iphdr, protocol));
946 // /* ip.xx fields which are not memset: protocol, check, saddr, daddr */
947 // packet.ip.tot_len = packet.udp.len; /* yes, this is needed */
948 // check = packet.udp.check;
949 // packet.udp.check = 0;
950 // if (check && check != inet_cksum((uint16_t *)&packet, bytes)) {
951 // log1("packet with bad UDP checksum received, ignoring");
956 *peer_ipv6 = packet.ip6.ip6_src; /* struct copy */
958 log1("received %s", "a packet");
959 d6_dump_packet(&packet.data);
961 bytes -= sizeof(packet.ip6) + sizeof(packet.udp);
962 memcpy(d6_pkt, &packet.data, bytes);
968 /* Values for client_data.listen_mode */
969 #define LISTEN_NONE 0
970 #define LISTEN_KERNEL 1
973 /* Values for client_data.state */
974 /* initial state: (re)start DHCP negotiation */
975 #define INIT_SELECTING 0
976 /* discover was sent, DHCPOFFER reply received */
978 /* select/renew was sent, DHCPACK reply received */
980 /* half of lease passed, want to renew it by sending unicast renew requests */
982 /* renew requests were not answered, lease is almost over, send broadcast renew */
984 /* manually requested renew (SIGUSR1) */
985 #define RENEW_REQUESTED 5
986 /* release, possibly manually requested (SIGUSR2) */
989 static int d6_raw_socket(int ifindex)
992 struct sockaddr_ll sock;
997 * I've selected not to see LL header, so BPF doesn't see it, too.
998 * The filter may also pass non-IP and non-ARP packets, but we do
999 * a more complete check when receiving the message in userspace.
1001 * and filter shamelessly stolen from:
1003 * http://www.flamewarmaster.de/software/dhcpclient/
1005 * There are a few other interesting ideas on that page (look under
1006 * "Motivation"). Use of netlink events is most interesting. Think
1007 * of various network servers listening for events and reconfiguring.
1008 * That would obsolete sending HUP signals and/or make use of restarts.
1010 * Copyright: 2006, 2007 Stefan Rompf <sux@loplof.de>.
1013 * TODO: make conditional?
1016 static const struct sock_filter filter_instr[] = {
1017 /* load 9th byte (protocol) */
1018 BPF_STMT(BPF_LD|BPF_B|BPF_ABS, 9),
1019 /* jump to L1 if it is IPPROTO_UDP, else to L4 */
1020 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, IPPROTO_UDP, 0, 6),
1021 /* L1: load halfword from offset 6 (flags and frag offset) */
1022 BPF_STMT(BPF_LD|BPF_H|BPF_ABS, 6),
1023 /* jump to L4 if any bits in frag offset field are set, else to L2 */
1024 BPF_JUMP(BPF_JMP|BPF_JSET|BPF_K, 0x1fff, 4, 0),
1025 /* L2: skip IP header (load index reg with header len) */
1026 BPF_STMT(BPF_LDX|BPF_B|BPF_MSH, 0),
1027 /* load udp destination port from halfword[header_len + 2] */
1028 BPF_STMT(BPF_LD|BPF_H|BPF_IND, 2),
1029 /* jump to L3 if udp dport is CLIENT_PORT6, else to L4 */
1030 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 68, 0, 1),
1031 /* L3: accept packet */
1032 BPF_STMT(BPF_RET|BPF_K, 0x7fffffff),
1033 /* L4: discard packet */
1034 BPF_STMT(BPF_RET|BPF_K, 0),
1036 static const struct sock_fprog filter_prog = {
1037 .len = sizeof(filter_instr) / sizeof(filter_instr[0]),
1038 /* casting const away: */
1039 .filter = (struct sock_filter *) filter_instr,
1043 log2("opening raw socket on ifindex %d", ifindex);
1045 fd = xsocket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IPV6));
1046 log3("got raw socket fd %d", fd);
1048 memset(&sock, 0, sizeof(sock)); /* let's be deterministic */
1049 sock.sll_family = AF_PACKET;
1050 sock.sll_protocol = htons(ETH_P_IPV6);
1051 sock.sll_ifindex = ifindex;
1052 /*sock.sll_hatype = ARPHRD_???;*/
1053 /*sock.sll_pkttype = PACKET_???;*/
1054 /*sock.sll_halen = ???;*/
1055 /*sock.sll_addr[8] = ???;*/
1056 xbind(fd, (struct sockaddr *) &sock, sizeof(sock));
1059 if (CLIENT_PORT6 == 546) {
1060 /* Use only if standard port is in use */
1061 /* Ignoring error (kernel may lack support for this) */
1062 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog,
1063 sizeof(filter_prog)) >= 0)
1064 log1("attached filter to raw socket fd %d", fd); // log?
1068 log1s("created raw socket");
1073 static void change_listen_mode(int new_mode)
1075 log1("entering listen mode: %s",
1076 new_mode != LISTEN_NONE
1077 ? (new_mode == LISTEN_KERNEL ? "kernel" : "raw")
1081 client_data.listen_mode = new_mode;
1082 if (client_data.sockfd >= 0) {
1083 close(client_data.sockfd);
1084 client_data.sockfd = -1;
1086 if (new_mode == LISTEN_KERNEL)
1087 client_data.sockfd = udhcp_listen_socket(/*INADDR_ANY,*/ CLIENT_PORT6, client_data.interface);
1088 else if (new_mode != LISTEN_NONE)
1089 client_data.sockfd = d6_raw_socket(client_data.ifindex);
1090 /* else LISTEN_NONE: client_data.sockfd stays closed */
1093 /* Called only on SIGUSR1 */
1094 static void perform_renew(void)
1096 bb_simple_info_msg("performing DHCP renew");
1097 switch (client_data.state) {
1099 change_listen_mode(LISTEN_KERNEL);
1102 client_data.state = RENEW_REQUESTED;
1104 case RENEW_REQUESTED: /* impatient are we? fine, square 1 */
1105 d6_run_script_no_option("deconfig");
1108 change_listen_mode(LISTEN_RAW);
1109 client_data.state = INIT_SELECTING;
1111 case INIT_SELECTING:
1116 static void perform_d6_release(struct in6_addr *server_ipv6, struct in6_addr *our_cur_ipv6)
1118 /* send release packet */
1119 if (client_data.state == BOUND
1120 || client_data.state == RENEWING
1121 || client_data.state == REBINDING
1122 || client_data.state == RENEW_REQUESTED
1124 bb_simple_info_msg("unicasting a release");
1125 send_d6_release(server_ipv6, our_cur_ipv6); /* unicast */
1127 bb_simple_info_msg("entering released state");
1129 * We can be here on: SIGUSR2,
1130 * or on exit (SIGTERM) and -R "release on quit" is specified.
1131 * Users requested to be notified in all cases, even if not in one
1132 * of the states above.
1134 d6_run_script_no_option("deconfig");
1135 change_listen_mode(LISTEN_NONE);
1136 client_data.state = RELEASED;
1139 ///static uint8_t* alloc_dhcp_option(int code, const char *str, int extra)
1141 /// uint8_t *storage;
1142 /// int len = strnlen(str, 255);
1143 /// storage = xzalloc(len + extra + OPT_DATA);
1144 /// storage[OPT_CODE] = code;
1145 /// storage[OPT_LEN] = len + extra;
1146 /// memcpy(storage + extra + OPT_DATA, str, len);
1151 static void client_background(void)
1154 logmode &= ~LOGMODE_STDIO;
1155 /* rewrite pidfile, as our pid is different now */
1156 write_pidfile(client_data.pidfile);
1160 //usage:#if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
1161 //usage:# define IF_UDHCP_VERBOSE(...) __VA_ARGS__
1163 //usage:# define IF_UDHCP_VERBOSE(...)
1165 //usage:#define udhcpc6_trivial_usage
1166 //usage: "[-fbnq"IF_UDHCP_VERBOSE("v")"odR] [-i IFACE] [-r IPv6] [-s PROG] [-p PIDFILE]\n"
1167 //usage: " [-x OPT:VAL]... [-O OPT]..." IF_FEATURE_UDHCP_PORT(" [-P N]")
1168 //usage:#define udhcpc6_full_usage "\n"
1169 //usage: "\n -i IFACE Interface to use (default eth0)"
1170 //usage: "\n -p FILE Create pidfile"
1171 //usage: "\n -s PROG Run PROG at DHCP events (default "CONFIG_UDHCPC_DEFAULT_SCRIPT")"
1172 //usage: "\n -B Request broadcast replies"
1173 //usage: "\n -t N Send up to N discover packets"
1174 //usage: "\n -T N Pause between packets (default 3 seconds)"
1175 //usage: "\n -A N Wait N seconds (default 20) after failure"
1176 //usage: "\n -f Run in foreground"
1177 //usage: USE_FOR_MMU(
1178 //usage: "\n -b Background if lease is not obtained"
1180 //usage: "\n -n Exit if lease is not obtained"
1181 //usage: "\n -q Exit after obtaining lease"
1182 //usage: "\n -R Release IP on exit"
1183 //usage: "\n -S Log to syslog too"
1184 //usage: IF_FEATURE_UDHCP_PORT(
1185 //usage: "\n -P N Use port N (default 546)"
1187 ////usage: IF_FEATURE_UDHCPC_ARPING(
1188 ////usage: "\n -a Use arping to validate offered address"
1190 //usage: "\n -O OPT Request option OPT from server (cumulative)"
1191 //usage: "\n -o Don't request any options (unless -O is given)"
1192 //usage: "\n -r IPv6 Request this address ('no' to not request any IP)"
1193 //usage: "\n -d Request prefix"
1194 //usage: "\n -l Send 'information request' instead of 'solicit'"
1195 //usage: "\n (used for servers which do not assign IPv6 addresses)"
1196 //usage: "\n -x OPT:VAL Include option OPT in sent packets (cumulative)"
1197 //usage: "\n Examples of string, numeric, and hex byte opts:"
1198 //usage: "\n -x hostname:bbox - option 12"
1199 //usage: "\n -x lease:3600 - option 51 (lease time)"
1200 //usage: "\n -x 0x3d:0100BEEFC0FFEE - option 61 (client id)"
1201 //usage: "\n -x 14:'\"dumpfile\"' - option 14 (shell-quoted)"
1202 //usage: IF_UDHCP_VERBOSE(
1203 //usage: "\n -v Verbose"
1205 //usage: "\nSignals:"
1206 //usage: "\n USR1 Renew lease"
1207 //usage: "\n USR2 Release lease"
1209 int udhcpc6_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1210 int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
1213 IF_FEATURE_UDHCP_PORT(char *str_P;)
1214 void *clientid_mac_ptr;
1215 llist_t *list_O = NULL;
1216 llist_t *list_x = NULL;
1217 int tryagain_timeout = 20;
1218 int discover_timeout = 3;
1219 int discover_retries = 3;
1220 struct in6_addr srv6_buf;
1221 struct in6_addr ipv6_buf;
1222 struct in6_addr *requested_ipv6;
1225 int timeout; /* must be signed */
1226 unsigned already_waited_sec;
1230 setup_common_bufsiz();
1231 /* We want random_xid to be random */
1232 srand(monotonic_us());
1234 /* Default options */
1235 IF_FEATURE_UDHCP_PORT(SERVER_PORT6 = 547;)
1236 IF_FEATURE_UDHCP_PORT(CLIENT_PORT6 = 546;)
1237 client_data.interface = "eth0";
1238 client_data.script = CONFIG_UDHCPC_DEFAULT_SCRIPT;
1239 client_data.sockfd = -1;
1241 /* Make sure fd 0,1,2 are open */
1242 /* Set up the signal pipe on fds 3,4 - must be before openlog() */
1245 /* Parse command line */
1246 opt = getopt32long(argv, "^"
1247 /* O,x: list; -T,-t,-A take numeric param */
1248 "i:np:qRr:s:T:+t:+SA:+O:*ox:*fld"
1250 ///IF_FEATURE_UDHCPC_ARPING("a")
1251 IF_FEATURE_UDHCP_PORT("P:")
1253 "\0" IF_UDHCP_VERBOSE("vv") /* -v is a counter */
1255 , &client_data.interface, &client_data.pidfile, &str_r /* i,p */
1256 , &client_data.script /* s */
1257 , &discover_timeout, &discover_retries, &tryagain_timeout /* T,t,A */
1260 IF_FEATURE_UDHCP_PORT(, &str_P)
1261 IF_UDHCP_VERBOSE(, &dhcp_verbose)
1263 requested_ipv6 = NULL;
1264 option_mask32 |= OPT_r;
1266 /* for -l, do not require IPv6 assignment from server */
1267 option_mask32 &= ~OPT_r;
1268 } else if (opt & OPT_r) {
1269 /* explicit "-r ARG" given */
1270 if (strcmp(str_r, "no") == 0) {
1271 option_mask32 &= ~OPT_r;
1273 if (inet_pton(AF_INET6, str_r, &ipv6_buf) <= 0)
1274 bb_error_msg_and_die("bad IPv6 address '%s'", str_r);
1275 requested_ipv6 = &ipv6_buf;
1279 #if ENABLE_FEATURE_UDHCP_PORT
1281 CLIENT_PORT6 = xatou16(str_P);
1282 SERVER_PORT6 = CLIENT_PORT6 + 1;
1286 char *optstr = llist_pop(&list_O);
1287 unsigned n = bb_strtou(optstr, NULL, 0);
1288 if (errno || n > 254) {
1289 n = udhcp_option_idx(optstr, d6_option_strings);
1290 n = d6_optflags[n].code;
1292 client_data.opt_mask[n >> 3] |= 1 << (n & 7);
1294 if (!(opt & OPT_o)) {
1296 for (i = 0; (n = d6_optflags[i].code) != 0; i++) {
1297 if (d6_optflags[i].flags & OPTION_REQ) {
1298 client_data.opt_mask[n >> 3] |= 1 << (n & 7);
1303 char *optstr = xstrdup(llist_pop(&list_x));
1304 udhcp_str2optset(optstr, &client_data.options,
1305 d6_optflags, d6_option_strings,
1311 if (d6_read_interface(client_data.interface,
1312 &client_data.ifindex,
1313 &client6_data.ll_ip6,
1314 client_data.client_mac)
1319 /* Create client ID based on mac, set clientid_mac_ptr */
1321 struct d6_option *clientid;
1322 clientid = xzalloc(2+2+2+2+6);
1323 clientid->code = D6_OPT_CLIENTID;
1324 clientid->len = 2+2+6;
1325 clientid->data[1] = 3; /* DUID-LL */
1326 clientid->data[3] = 1; /* ethernet */
1327 clientid_mac_ptr = clientid->data + 2+2;
1328 memcpy(clientid_mac_ptr, client_data.client_mac, 6);
1329 client_data.clientid = (void*)clientid;
1333 /* on NOMMU reexec (i.e., background) early */
1334 if (!(opt & OPT_f)) {
1335 bb_daemonize_or_rexec(0 /* flags */, argv);
1336 logmode = LOGMODE_NONE;
1340 openlog(applet_name, LOG_PID, LOG_DAEMON);
1341 logmode |= LOGMODE_SYSLOG;
1344 /* Create pidfile */
1345 write_pidfile(client_data.pidfile);
1346 /* Goes to stdout (unless NOMMU) and possibly syslog */
1347 bb_simple_info_msg("started, v"BB_VER);
1349 client_data.state = INIT_SELECTING;
1350 d6_run_script_no_option("deconfig");
1351 change_listen_mode(LISTEN_RAW);
1354 already_waited_sec = 0;
1356 /* Main event loop. select() waits on signal pipe and possibly
1358 * "continue" statements in code below jump to the top of the loop.
1362 struct pollfd pfds[2];
1363 struct d6_packet packet;
1364 uint8_t *packet_end;
1365 /* silence "uninitialized!" warning */
1366 unsigned timestamp_before_wait = timestamp_before_wait;
1368 //bb_error_msg("sockfd:%d, listen_mode:%d", client_data.sockfd, client_data.listen_mode);
1370 /* Was opening raw or udp socket here
1371 * if (client_data.listen_mode != LISTEN_NONE && client_data.sockfd < 0),
1372 * but on fast network renew responses return faster
1373 * than we open sockets. Thus this code is moved
1374 * to change_listen_mode(). Thus we open listen socket
1375 * BEFORE we send renew request (see "case BOUND:"). */
1377 udhcp_sp_fd_set(pfds, client_data.sockfd);
1379 tv = timeout - already_waited_sec;
1381 /* If we already timed out, fall through with retval = 0, else... */
1383 log1("waiting %u seconds", tv);
1384 timestamp_before_wait = (unsigned)monotonic_sec();
1385 retval = poll(pfds, 2, tv < INT_MAX/1000 ? tv * 1000 : INT_MAX);
1387 /* EINTR? A signal was caught, don't panic */
1388 if (errno == EINTR) {
1389 already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
1392 /* Else: an error occured, panic! */
1393 bb_simple_perror_msg_and_die("poll");
1397 /* If timeout dropped to zero, time to become active:
1398 * resend discover/renew/whatever
1401 /* When running on a bridge, the ifindex may have changed
1402 * (e.g. if member interfaces were added/removed
1403 * or if the status of the bridge changed).
1404 * Refresh ifindex and client_mac:
1406 if (d6_read_interface(client_data.interface,
1407 &client_data.ifindex,
1408 &client6_data.ll_ip6,
1409 client_data.client_mac)
1411 goto ret0; /* iface is gone? */
1414 memcpy(clientid_mac_ptr, client_data.client_mac, 6);
1416 /* We will restart the wait in any case */
1417 already_waited_sec = 0;
1419 switch (client_data.state) {
1420 case INIT_SELECTING:
1421 if (!discover_retries || packet_num < discover_retries) {
1422 if (packet_num == 0)
1426 send_d6_info_request(xid);
1428 send_d6_discover(xid, requested_ipv6);
1429 timeout = discover_timeout;
1434 d6_run_script_no_option("leasefail");
1435 #if BB_MMU /* -b is not supported on NOMMU */
1436 if (opt & OPT_b) { /* background if no lease */
1437 bb_simple_info_msg("no lease, forking to background");
1438 client_background();
1439 /* do not background again! */
1440 opt = ((opt & ~(OPT_b|OPT_n)) | OPT_f);
1441 /* ^^^ also disables -n (-b takes priority over -n):
1442 * ifup's default udhcpc options are -R -n,
1443 * and users want to be able to add -b
1444 * (in a config file) to make it background
1449 if (opt & OPT_n) { /* abort if no lease */
1450 bb_simple_info_msg("no lease, failing");
1454 /* wait before trying again */
1455 timeout = tryagain_timeout;
1459 if (!discover_retries || packet_num < discover_retries) {
1460 /* send multicast select packet */
1461 send_d6_select(xid);
1462 timeout = discover_timeout;
1466 /* Timed out, go back to init state.
1467 * "discover...select...discover..." loops
1468 * were seen in the wild. Treat them similarly
1469 * to "no response to discover" case */
1470 change_listen_mode(LISTEN_RAW);
1471 client_data.state = INIT_SELECTING;
1474 /* 1/2 lease passed, enter renewing state */
1475 client_data.state = RENEWING;
1476 client_data.first_secs = 0; /* make secs field count from 0 */
1477 change_listen_mode(LISTEN_KERNEL);
1478 log1s("entering renew state");
1479 /* fall right through */
1480 case RENEW_REQUESTED: /* manual (SIGUSR1) renew */
1481 case_RENEW_REQUESTED:
1483 if (timeout >= 60) {
1484 /* send an unicast renew request */
1485 /* Sometimes observed to fail (EADDRNOTAVAIL) to bind
1486 * a new UDP socket for sending inside send_renew.
1487 * I hazard to guess existing listening socket
1488 * is somehow conflicting with it, but why is it
1489 * not deterministic then?! Strange.
1490 * Anyway, it does recover by eventually failing through
1491 * into INIT_SELECTING state.
1494 send_d6_info_request(xid);
1496 send_d6_renew(xid, &srv6_buf, requested_ipv6);
1500 /* Timed out, enter rebinding state */
1501 log1s("entering rebinding state");
1502 client_data.state = REBINDING;
1503 /* fall right through */
1505 /* Switch to bcast receive */
1506 change_listen_mode(LISTEN_RAW);
1507 /* Lease is *really* about to run out,
1508 * try to find DHCP server using broadcast */
1511 send_d6_info_request(xid);
1512 else /* send a broadcast renew request */
1513 send_d6_renew(xid, /*server_ipv6:*/ NULL, requested_ipv6);
1517 /* Timed out, enter init state */
1518 bb_simple_info_msg("lease lost, entering init state");
1519 d6_run_script_no_option("deconfig");
1520 client_data.state = INIT_SELECTING;
1521 client_data.first_secs = 0; /* make secs field count from 0 */
1522 /*timeout = 0; - already is */
1525 /* case RELEASED: */
1527 /* yah, I know, *you* say it would never happen */
1529 continue; /* back to main loop */
1530 } /* if poll timed out */
1532 /* poll() didn't timeout, something happened */
1534 /* Is it a signal? */
1535 switch (udhcp_sp_read()) {
1537 client_data.first_secs = 0; /* make secs field count from 0 */
1538 already_waited_sec = 0;
1540 if (client_data.state == RENEW_REQUESTED) {
1541 /* We might be either on the same network
1542 * (in which case renew might work),
1543 * or we might be on a completely different one
1544 * (in which case renew won't ever succeed).
1545 * For the second case, must make sure timeout
1546 * is not too big, or else we can send
1547 * futile renew requests for hours.
1551 goto case_RENEW_REQUESTED;
1553 /* Start things over */
1555 /* Kill any timeouts, user wants this to hurry along */
1559 perform_d6_release(&srv6_buf, requested_ipv6);
1563 bb_info_msg("received %s", "SIGTERM");
1567 /* Is it a packet? */
1568 if (!pfds[1].revents)
1574 /* A packet is ready, read it */
1575 if (client_data.listen_mode == LISTEN_KERNEL)
1576 len = d6_recv_kernel_packet(&srv6_buf, &packet, client_data.sockfd);
1578 len = d6_recv_raw_packet(&srv6_buf, &packet, client_data.sockfd);
1580 /* Error is severe, reopen socket */
1581 bb_error_msg("read error: "STRERROR_FMT", reopening socket" STRERROR_ERRNO);
1582 sleep(discover_timeout); /* 3 seconds by default */
1583 change_listen_mode(client_data.listen_mode); /* just close and reopen */
1585 /* If this packet will turn out to be unrelated/bogus,
1586 * we will go back and wait for next one.
1587 * Be sure timeout is properly decreased. */
1588 already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
1591 packet_end = (uint8_t*)&packet + len;
1594 if ((packet.d6_xid32 & htonl(0x00ffffff)) != xid) {
1595 log1("xid %x (our is %x), ignoring packet",
1596 (unsigned)(packet.d6_xid32 & htonl(0x00ffffff)), (unsigned)xid);
1600 switch (client_data.state) {
1601 case INIT_SELECTING:
1602 if (packet.d6_msg_type == D6_MSG_ADVERTISE)
1604 /* DHCPv6 has "Rapid Commit", when instead of Advertise,
1605 * server sends Reply right away.
1606 * Fall through to check for this case.
1610 case RENEW_REQUESTED:
1612 if (packet.d6_msg_type == D6_MSG_REPLY) {
1613 uint32_t lease_seconds;
1614 struct d6_option *option;
1615 unsigned address_timeout;
1616 unsigned prefix_timeout;
1618 address_timeout = 0;
1620 option = d6_find_option(packet.d6_options, packet_end, D6_OPT_STATUS_CODE);
1621 if (option && (option->data[0] | option->data[1]) != 0) {
1622 /* return to init state */
1623 bb_info_msg("received DHCP NAK (%u)", option->data[4]);
1624 d6_run_script(packet.d6_options,
1626 if (client_data.state != REQUESTING)
1627 d6_run_script_no_option("deconfig");
1628 change_listen_mode(LISTEN_RAW);
1629 sleep(3); /* avoid excessive network traffic */
1630 client_data.state = INIT_SELECTING;
1631 client_data.first_secs = 0; /* make secs field count from 0 */
1632 requested_ipv6 = NULL;
1635 already_waited_sec = 0;
1638 option = d6_copy_option(packet.d6_options, packet_end, D6_OPT_SERVERID);
1640 bb_simple_info_msg("no server ID, ignoring packet");
1642 /* still selecting - this server looks bad */
1644 //Note: we do not bother comparing server IDs in Advertise and Reply msgs.
1645 //server_id variable is used solely for creation of proper server_id option
1646 //in outgoing packets. (why DHCPv6 even introduced it is a mystery).
1647 free(client6_data.server_id);
1648 client6_data.server_id = option;
1649 if (packet.d6_msg_type == D6_MSG_ADVERTISE) {
1650 /* enter requesting state */
1651 client_data.state = REQUESTING;
1654 already_waited_sec = 0;
1657 /* It's a D6_MSG_REPLY */
1659 * RFC 3315 18.1.8. Receipt of Reply Messages
1661 * Upon the receipt of a valid Reply message in response to a Solicit
1662 * (with a Rapid Commit option), Request, Confirm, Renew, Rebind or
1663 * Information-request message, the client extracts the configuration
1664 * information contained in the Reply. The client MAY choose to report
1665 * any status code or message from the status code option in the Reply
1668 * The client SHOULD perform duplicate address detection [17] on each of
1669 * the addresses in any IAs it receives in the Reply message before
1670 * using that address for traffic. If any of the addresses are found to
1671 * be in use on the link, the client sends a Decline message to the
1672 * server as described in section 18.1.7.
1674 * If the Reply was received in response to a Solicit (with a Rapid
1675 * Commit option), Request, Renew or Rebind message, the client updates
1676 * the information it has recorded about IAs from the IA options
1677 * contained in the Reply message:
1679 * - Record T1 and T2 times.
1681 * - Add any new addresses in the IA option to the IA as recorded by
1684 * - Update lifetimes for any addresses in the IA option that the
1685 * client already has recorded in the IA.
1687 * - Discard any addresses from the IA, as recorded by the client, that
1688 * have a valid lifetime of 0 in the IA Address option.
1690 * - Leave unchanged any information about addresses the client has
1691 * recorded in the IA but that were not included in the IA from the
1694 * Management of the specific configuration information is detailed in
1695 * the definition of each option in section 22.
1697 * If the client receives a Reply message with a Status Code containing
1698 * UnspecFail, the server is indicating that it was unable to process
1699 * the message due to an unspecified failure condition. If the client
1700 * retransmits the original message to the same server to retry the
1701 * desired operation, the client MUST limit the rate at which it
1702 * retransmits the message and limit the duration of the time during
1703 * which it retransmits the message.
1705 * When the client receives a Reply message with a Status Code option
1706 * with the value UseMulticast, the client records the receipt of the
1707 * message and sends subsequent messages to the server through the
1708 * interface on which the message was received using multicast. The
1709 * client resends the original message using multicast.
1711 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1712 * | OPTION_IA_NA | option-len |
1713 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1714 * | IAID (4 octets) |
1715 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1717 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1719 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1723 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1726 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1727 * | OPTION_IAADDR | option-len |
1728 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1733 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1734 * | preferred-lifetime |
1735 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1736 * | valid-lifetime |
1737 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1739 * . IAaddr-options .
1741 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1743 if (option_mask32 & OPT_r) {
1744 struct d6_option *iaaddr;
1746 free(client6_data.ia_na);
1747 client6_data.ia_na = d6_copy_option(packet.d6_options, packet_end, D6_OPT_IA_NA);
1748 if (!client6_data.ia_na) {
1749 bb_info_msg("no %s option, ignoring packet", "IA_NA");
1752 if (client6_data.ia_na->len < (4 + 4 + 4) + (2 + 2 + 16 + 4 + 4)) {
1753 bb_info_msg("%s option is too short:%d bytes",
1754 "IA_NA", client6_data.ia_na->len);
1757 iaaddr = d6_find_option(client6_data.ia_na->data + 4 + 4 + 4,
1758 client6_data.ia_na->data + client6_data.ia_na->len,
1762 bb_info_msg("no %s option, ignoring packet", "IAADDR");
1765 if (iaaddr->len < (16 + 4 + 4)) {
1766 bb_info_msg("%s option is too short:%d bytes",
1767 "IAADDR", iaaddr->len);
1770 /* Note: the address is sufficiently aligned for cast:
1771 * we _copied_ IA-NA, and copy is always well-aligned.
1773 requested_ipv6 = (struct in6_addr*) iaaddr->data;
1774 move_from_unaligned32(lease_seconds, iaaddr->data + 16 + 4);
1775 lease_seconds = ntohl(lease_seconds);
1776 /// TODO: check for 0 lease time?
1777 bb_info_msg("%s obtained, lease time %u",
1778 "IPv6", /*inet_ntoa(temp_addr),*/ (unsigned)lease_seconds);
1779 address_timeout = lease_seconds;
1781 if (option_mask32 & OPT_d) {
1782 struct d6_option *iaprefix;
1784 free(client6_data.ia_pd);
1785 client6_data.ia_pd = d6_copy_option(packet.d6_options, packet_end, D6_OPT_IA_PD);
1786 if (!client6_data.ia_pd) {
1787 bb_info_msg("no %s option, ignoring packet", "IA_PD");
1790 if (client6_data.ia_pd->len < (4 + 4 + 4) + (2 + 2 + 4 + 4 + 1 + 16)) {
1791 bb_info_msg("%s option is too short:%d bytes",
1792 "IA_PD", client6_data.ia_pd->len);
1795 iaprefix = d6_find_option(client6_data.ia_pd->data + 4 + 4 + 4,
1796 client6_data.ia_pd->data + client6_data.ia_pd->len,
1800 bb_info_msg("no %s option, ignoring packet", "IAPREFIX");
1803 if (iaprefix->len < (4 + 4 + 1 + 16)) {
1804 bb_info_msg("%s option is too short:%d bytes",
1805 "IAPREFIX", iaprefix->len);
1808 move_from_unaligned32(lease_seconds, iaprefix->data + 4);
1809 lease_seconds = ntohl(lease_seconds);
1810 bb_info_msg("%s obtained, lease time %u",
1811 "prefix", /*inet_ntoa(temp_addr),*/ (unsigned)lease_seconds);
1812 prefix_timeout = lease_seconds;
1814 if (!address_timeout)
1815 address_timeout = prefix_timeout;
1816 if (!prefix_timeout)
1817 prefix_timeout = address_timeout;
1818 /* note: "int timeout" will not overflow even with 0xffffffff inputs here: */
1819 timeout = (prefix_timeout < address_timeout ? prefix_timeout : address_timeout) / 2;
1821 /* TODO: request OPTION_INFORMATION_REFRESH_TIME (32)
1822 * and use its value instead of the default 1 day.
1824 timeout = 24 * 60 * 60;
1826 /* paranoia: must not be too small */
1827 /* timeout > 60 - ensures at least one unicast renew attempt */
1830 /* enter bound state */
1831 d6_run_script(packet.d6_options, packet_end,
1832 (client_data.state == REQUESTING ? "bound" : "renew"));
1834 client_data.state = BOUND;
1835 change_listen_mode(LISTEN_NONE);
1836 if (opt & OPT_q) { /* quit after lease */
1839 /* future renew failures should not exit (JM) */
1841 #if BB_MMU /* NOMMU case backgrounded earlier */
1842 if (!(opt & OPT_f)) {
1843 client_background();
1844 /* do not background again! */
1845 opt = ((opt & ~OPT_b) | OPT_f);
1848 already_waited_sec = 0;
1849 continue; /* back to main loop */
1852 /* case BOUND: - ignore all packets */
1853 /* case RELEASED: - ignore all packets */
1855 /* back to main loop */
1856 } /* for (;;) - main loop ends */
1859 if (opt & OPT_R) /* release on quit */
1860 perform_d6_release(&srv6_buf, requested_ipv6);
1863 /*if (client_data.pidfile) - remove_pidfile has its own check */
1864 remove_pidfile(client_data.pidfile);