1 /* vi: set sw=4 ts=4: */
5 * WARNING: THIS CODE IS INCOMPLETE.
7 * Copyright (C) 2011-2017 Denys Vlasenko.
9 * Licensed under GPLv2, see file LICENSE in this source tree.
11 //config:config UDHCPC6
12 //config: bool "udhcpc6"
13 //config: default n # not yet ready
14 //config: depends on FEATURE_IPV6
16 //config: udhcpc6 is a DHCPv6 client
18 //config:config FEATURE_UDHCPC6_RFC3646
19 //config: bool "Support RFC 3646 (DNS server and search list)"
21 //config: depends on UDHCPC6
23 //config: List of DNS servers and domain search list can be requested with
24 //config: "-O dns" and "-O search". If server gives these values,
25 //config: they will be set in environment variables "dns" and "search".
27 //config:config FEATURE_UDHCPC6_RFC4704
28 //config: bool "Support RFC 4704 (Client FQDN)"
30 //config: depends on UDHCPC6
32 //config: You can request FQDN to be given by server using "-O fqdn".
34 //config:config FEATURE_UDHCPC6_RFC4833
35 //config: bool "Support RFC 4833 (Timezones)"
37 //config: depends on UDHCPC6
39 //config: You can request POSIX timezone with "-O tz" and timezone name
40 //config: with "-O timezone".
42 //applet:IF_UDHCPC6(APPLET(udhcpc6, BB_DIR_USR_BIN, BB_SUID_DROP))
44 //kbuild:lib-$(CONFIG_UDHCPC6) += d6_dhcpc.o d6_packet.o d6_socket.o common.o socket.o signalpipe.o
45 //kbuild:lib-$(CONFIG_FEATURE_UDHCPC6_RFC3646) += domain_codec.o
46 //kbuild:lib-$(CONFIG_FEATURE_UDHCPC6_RFC4704) += domain_codec.o
49 /* Override ENABLE_FEATURE_PIDFILE - ifupdown needs our pidfile to always exist */
50 #define WANT_PIDFILE 1
54 #include "d6_common.h"
56 #include <netinet/if_ether.h>
57 #include <netpacket/packet.h>
58 #include <linux/filter.h>
60 /* "struct client_config_t client_config" is in bb_common_bufsiz1 */
62 static const struct dhcp_optflag d6_optflags[] = {
63 #if ENABLE_FEATURE_UDHCPC6_RFC3646
64 { OPTION_6RD | OPTION_LIST | OPTION_REQ, D6_OPT_DNS_SERVERS },
65 { OPTION_DNS_STRING | OPTION_LIST | OPTION_REQ, D6_OPT_DOMAIN_LIST },
67 #if ENABLE_FEATURE_UDHCPC6_RFC4704
68 { OPTION_DNS_STRING, D6_OPT_CLIENT_FQDN },
70 #if ENABLE_FEATURE_UDHCPC6_RFC4833
71 { OPTION_STRING, D6_OPT_TZ_POSIX },
72 { OPTION_STRING, D6_OPT_TZ_NAME },
76 /* Must match d6_optflags[] order */
77 static const char d6_option_strings[] ALIGN1 =
78 #if ENABLE_FEATURE_UDHCPC6_RFC3646
79 "dns" "\0" /* D6_OPT_DNS_SERVERS */
80 "search" "\0" /* D6_OPT_DOMAIN_LIST */
82 #if ENABLE_FEATURE_UDHCPC6_RFC4704
83 "fqdn" "\0" /* D6_OPT_CLIENT_FQDN */
85 #if ENABLE_FEATURE_UDHCPC6_RFC4833
86 "tz" "\0" /* D6_OPT_TZ_POSIX */
87 "timezone" "\0" /* D6_OPT_TZ_NAME */
92 static const char udhcpc6_longopts[] ALIGN1 =
93 "interface\0" Required_argument "i"
94 "now\0" No_argument "n"
95 "pidfile\0" Required_argument "p"
96 "quit\0" No_argument "q"
97 "release\0" No_argument "R"
98 "request\0" Required_argument "r"
99 "script\0" Required_argument "s"
100 "timeout\0" Required_argument "T"
101 "retries\0" Required_argument "t"
102 "tryagain\0" Required_argument "A"
103 "syslog\0" No_argument "S"
104 "request-option\0" Required_argument "O"
105 "no-default-options\0" No_argument "o"
106 "foreground\0" No_argument "f"
108 "background\0" No_argument "b"
110 /// IF_FEATURE_UDHCPC_ARPING("arping\0" No_argument "a")
111 IF_FEATURE_UDHCP_PORT("client-port\0" Required_argument "P")
114 /* Must match getopt32 option string order */
131 /* The rest has variable bit positions, need to be clever */
133 USE_FOR_MMU( OPTBIT_b,)
134 ///IF_FEATURE_UDHCPC_ARPING(OPTBIT_a,)
135 IF_FEATURE_UDHCP_PORT( OPTBIT_P,)
136 USE_FOR_MMU( OPT_b = 1 << OPTBIT_b,)
137 ///IF_FEATURE_UDHCPC_ARPING(OPT_a = 1 << OPTBIT_a,)
138 IF_FEATURE_UDHCP_PORT( OPT_P = 1 << OPTBIT_P,)
141 #if ENABLE_FEATURE_UDHCPC6_RFC4704
142 static const char opt_fqdn_req[] = {
143 (D6_OPT_CLIENT_FQDN >> 8), (D6_OPT_CLIENT_FQDN & 0xff),
146 /* S=0: server SHOULD NOT perform AAAA RR updates */
147 /* O=0: client MUST set this bit to 0 */
148 /* N=0: server SHOULD perform updates (PTR RR only in our case, since S=0) */
149 0 /* empty DNS-encoded name */
153 /*** Utility functions ***/
155 static void *d6_find_option(uint8_t *option, uint8_t *option_end, unsigned code)
157 /* "length minus 4" */
158 int len_m4 = option_end - option - 4;
159 while (len_m4 >= 0) {
160 /* Next option's len is too big? */
161 if (option[3] > len_m4)
162 return NULL; /* yes. bogus packet! */
163 /* So far we treat any opts with code >255
164 * or len >255 as bogus, and stop at once.
165 * This simplifies big-endian handling.
167 if (option[0] != 0 || option[2] != 0)
169 /* Option seems to be valid */
170 /* Does its code match? */
171 if (option[1] == code)
172 return option; /* yes! */
173 len_m4 -= option[3] + 4;
174 option += option[3] + 4;
179 static void *d6_copy_option(uint8_t *option, uint8_t *option_end, unsigned code)
181 uint8_t *opt = d6_find_option(option, option_end, code);
184 return xmemdup(opt, opt[3] + 4);
188 /*** Script execution code ***/
190 static char** new_env(void)
192 client6_data.env_ptr = xrealloc_vector(client6_data.env_ptr, 3, client6_data.env_idx);
193 return &client6_data.env_ptr[client6_data.env_idx++];
196 /* put all the parameters into the environment */
197 static void option_to_env(uint8_t *option, uint8_t *option_end)
199 #if ENABLE_FEATURE_UDHCPC6_RFC3646
200 int addrs, option_offset;
202 /* "length minus 4" */
203 int len_m4 = option_end - option - 4;
205 while (len_m4 >= 0) {
207 char ipv6str[sizeof("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")];
209 if (option[0] != 0 || option[2] != 0)
212 /* Check if option-length exceeds size of option */
213 if (option[3] > len_m4)
217 //case D6_OPT_CLIENTID:
218 //case D6_OPT_SERVERID:
221 option_to_env(option + 16, option + 4 + option[3]);
226 * 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
227 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
228 * | OPTION_IAADDR | option-len |
229 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
234 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
235 * | preferred-lifetime |
236 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
238 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
240 sprint_nip6(ipv6str, option + 4);
241 *new_env() = xasprintf("ipv6=%s", ipv6str);
243 move_from_unaligned32(v32, option + 4 + 16 + 4);
244 *new_env() = xasprintf("lease=%u", (unsigned)v32);
248 //case D6_OPT_PREFERENCE:
249 //case D6_OPT_ELAPSED_TIME:
250 //case D6_OPT_RELAY_MSG:
252 //case D6_OPT_UNICAST:
253 //case D6_OPT_STATUS_CODE:
254 //case D6_OPT_RAPID_COMMIT:
255 //case D6_OPT_USER_CLASS:
256 //case D6_OPT_VENDOR_CLASS:
257 //case D6_OPT_VENDOR_OPTS:
258 //case D6_OPT_INTERFACE_ID:
259 //case D6_OPT_RECONF_MSG:
260 //case D6_OPT_RECONF_ACCEPT:
262 case D6_OPT_IAPREFIX:
264 * 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
265 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
266 * | OPTION_IAPREFIX | option-length |
267 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
268 * | preferred-lifetime |
269 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
271 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
272 * | prefix-length | |
273 * +-+-+-+-+-+-+-+-+ IPv6 prefix |
276 * | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
280 //move_from_unaligned32(v32, option + 4 + 4);
281 //*new_env() = xasprintf("lease=%u", (unsigned)v32);
283 sprint_nip6(ipv6str, option + 4 + 4 + 1);
284 *new_env() = xasprintf("ipv6prefix=%s/%u", ipv6str, (unsigned)(option[4 + 4]));
286 #if ENABLE_FEATURE_UDHCPC6_RFC3646
287 case D6_OPT_DNS_SERVERS: {
290 /* Make sure payload-size is a multiple of 16 */
291 if ((option[3] & 0x0f) != 0)
294 /* Get the number of addresses on the option */
295 addrs = option[3] >> 4;
297 /* Setup environment variable */
298 *new_env() = dlist = xmalloc(4 + addrs * 40 - 1);
299 dlist = stpcpy(dlist, "dns=");
303 sprint_nip6(dlist, option + 4 + option_offset);
312 case D6_OPT_DOMAIN_LIST: {
315 dlist = dname_dec(option + 4, (option[2] << 8) | option[3], "search=");
322 #if ENABLE_FEATURE_UDHCPC6_RFC4704
323 case D6_OPT_CLIENT_FQDN: {
328 /* Work around broken ISC DHCPD6.
329 * ISC DHCPD6 does not implement RFC 4704 correctly: It says the first
330 * byte of option-payload should contain flags where the bits 7-3 are
331 * reserved for future use and MUST be zero. Instead ISC DHCPD6 just
332 * writes the entire FQDN as string to option-payload. We assume a
333 * broken server here if any of the reserved bits are set.
335 if (option[4] & 0xf8) {
336 *new_env() = xasprintf("fqdn=%.*s", (int)option[3], (char*)option + 4);
339 dlist = dname_dec(option + 5, (/*(option[2] << 8) |*/ option[3]) - 1, "fqdn=");
346 #if ENABLE_FEATURE_UDHCPC6_RFC4833
347 /* RFC 4833 Timezones */
348 case D6_OPT_TZ_POSIX:
349 *new_env() = xasprintf("tz=%.*s", (int)option[3], (char*)option + 4);
352 *new_env() = xasprintf("tz_name=%.*s", (int)option[3], (char*)option + 4);
356 len_m4 -= 4 + option[3];
357 option += 4 + option[3];
361 static char **fill_envp(struct d6_packet *packet)
365 client6_data.env_ptr = NULL;
366 client6_data.env_idx = 0;
368 *new_env() = xasprintf("interface=%s", client_config.interface);
371 option_to_env(packet->d6_options, packet->d6_options + sizeof(packet->d6_options));
373 envp = curr = client6_data.env_ptr;
380 /* Call a script with a par file and env vars */
381 static void d6_run_script(struct d6_packet *packet, const char *name)
386 envp = fill_envp(packet);
389 log1("executing %s %s", client_config.script, name);
390 argv[0] = (char*) client_config.script;
391 argv[1] = (char*) name;
393 spawn_and_wait(argv);
395 for (curr = envp; *curr; curr++) {
397 bb_unsetenv_and_free(*curr);
403 /*** Sending/receiving packets ***/
405 static ALWAYS_INLINE uint32_t random_xid(void)
407 uint32_t t = rand() & htonl(0x00ffffff);
411 /* Initialize the packet with the proper defaults */
412 static uint8_t *init_d6_packet(struct d6_packet *packet, char type, uint32_t xid)
414 struct d6_option *clientid;
416 memset(packet, 0, sizeof(*packet));
418 packet->d6_xid32 = xid;
419 packet->d6_msg_type = type;
421 clientid = (void*)client_config.clientid;
422 return mempcpy(packet->d6_options, clientid, clientid->len + 2+2);
425 static uint8_t *add_d6_client_options(uint8_t *ptr)
427 uint8_t *start = ptr;
431 for (option = 1; option < 256; option++) {
432 if (client_config.opt_mask[option >> 3] & (1 << (option & 7))) {
433 ptr[0] = (option >> 8);
439 if ((ptr - start - 4) != 0) {
440 start[0] = (D6_OPT_ORO >> 8);
441 start[1] = D6_OPT_ORO;
442 start[2] = ((ptr - start - 4) >> 8);
443 start[3] = (ptr - start - 4);
447 #if ENABLE_FEATURE_UDHCPC6_RFC4704
448 ptr = mempcpy(ptr, &opt_fqdn_req, sizeof(opt_fqdn_req));
450 /* Add -x options if any */
456 static int d6_mcast_from_client_config_ifindex(struct d6_packet *packet, uint8_t *end)
458 static const uint8_t FF02__1_2[16] = {
459 0xFF, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
460 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02,
463 return d6_send_raw_packet(
464 packet, (end - (uint8_t*) packet),
465 /*src*/ &client6_data.ll_ip6, CLIENT_PORT6,
466 /*dst*/ (struct in6_addr*)FF02__1_2, SERVER_PORT6, MAC_BCAST_ADDR,
467 client_config.ifindex
471 /* Milticast a DHCPv6 Solicit packet to the network, with an optionally requested IP.
473 * RFC 3315 17.1.1. Creation of Solicit Messages
475 * The client MUST include a Client Identifier option to identify itself
476 * to the server. The client includes IA options for any IAs to which
477 * it wants the server to assign addresses. The client MAY include
478 * addresses in the IAs as a hint to the server about addresses for
479 * which the client has a preference. ...
481 * The client uses IA_NA options to request the assignment of non-
482 * temporary addresses and uses IA_TA options to request the assignment
483 * of temporary addresses. Either IA_NA or IA_TA options, or a
484 * combination of both, can be included in DHCP messages.
486 * The client SHOULD include an Option Request option (see section 22.7)
487 * to indicate the options the client is interested in receiving. The
488 * client MAY additionally include instances of those options that are
489 * identified in the Option Request option, with data values as hints to
490 * the server about parameter values the client would like to have
493 * The client includes a Reconfigure Accept option (see section 22.20)
494 * if the client is willing to accept Reconfigure messages from the
496 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
497 | OPTION_CLIENTID | option-len |
498 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
501 . (variable length) .
503 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
506 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
507 | OPTION_IA_NA | option-len |
508 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
510 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
512 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
514 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
518 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
521 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
522 | OPTION_IAADDR | option-len |
523 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
528 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
529 | preferred-lifetime |
530 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
532 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
536 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
539 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
540 | OPTION_ORO | option-len |
541 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
542 | requested-option-code-1 | requested-option-code-2 |
543 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
545 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
548 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
549 | OPTION_RECONF_ACCEPT | 0 |
550 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
552 /* NOINLINE: limit stack usage in caller */
553 static NOINLINE int send_d6_discover(uint32_t xid, struct in6_addr *requested_ipv6)
555 struct d6_packet packet;
559 /* Fill in: msg type, client id */
560 opt_ptr = init_d6_packet(&packet, D6_MSG_SOLICIT, xid);
562 /* Create new IA_NA, optionally with included IAADDR with requested IP */
563 free(client6_data.ia_na);
564 len = requested_ipv6 ? 2+2+4+4+4 + 2+2+16+4+4 : 2+2+4+4+4;
565 client6_data.ia_na = xzalloc(len);
566 client6_data.ia_na->code = D6_OPT_IA_NA;
567 client6_data.ia_na->len = len - 4;
568 *(uint32_t*)client6_data.ia_na->data = rand(); /* IAID */
569 if (requested_ipv6) {
570 struct d6_option *iaaddr = (void*)(client6_data.ia_na->data + 4+4+4);
571 iaaddr->code = D6_OPT_IAADDR;
572 iaaddr->len = 16+4+4;
573 memcpy(iaaddr->data, requested_ipv6, 16);
575 opt_ptr = mempcpy(opt_ptr, client6_data.ia_na, len);
578 * "param req" option according to -O, options specified with -x
580 opt_ptr = add_d6_client_options(opt_ptr);
582 bb_error_msg("sending %s", "discover");
583 return d6_mcast_from_client_config_ifindex(&packet, opt_ptr);
586 /* Multicast a DHCPv6 request message
588 * RFC 3315 18.1.1. Creation and Transmission of Request Messages
590 * The client uses a Request message to populate IAs with addresses and
591 * obtain other configuration information. The client includes one or
592 * more IA options in the Request message. The server then returns
593 * addresses and other information about the IAs to the client in IA
594 * options in a Reply message.
596 * The client generates a transaction ID and inserts this value in the
597 * "transaction-id" field.
599 * The client places the identifier of the destination server in a
600 * Server Identifier option.
602 * The client MUST include a Client Identifier option to identify itself
603 * to the server. The client adds any other appropriate options,
604 * including one or more IA options (if the client is requesting that
605 * the server assign it some network addresses).
607 * The client MUST include an Option Request option (see section 22.7)
608 * to indicate the options the client is interested in receiving. The
609 * client MAY include options with data values as hints to the server
610 * about parameter values the client would like to have returned.
612 * The client includes a Reconfigure Accept option (see section 22.20)
613 * indicating whether or not the client is willing to accept Reconfigure
614 * messages from the server.
616 /* NOINLINE: limit stack usage in caller */
617 static NOINLINE int send_d6_select(uint32_t xid)
619 struct d6_packet packet;
622 /* Fill in: msg type, client id */
623 opt_ptr = init_d6_packet(&packet, D6_MSG_REQUEST, xid);
626 opt_ptr = mempcpy(opt_ptr, client6_data.server_id, client6_data.server_id->len + 2+2);
627 /* IA NA (contains requested IP) */
628 opt_ptr = mempcpy(opt_ptr, client6_data.ia_na, client6_data.ia_na->len + 2+2);
631 * "param req" option according to -O, options specified with -x
633 opt_ptr = add_d6_client_options(opt_ptr);
635 bb_error_msg("sending %s", "select");
636 return d6_mcast_from_client_config_ifindex(&packet, opt_ptr);
639 /* Unicast or broadcast a DHCP renew message
641 * RFC 3315 18.1.3. Creation and Transmission of Renew Messages
643 * To extend the valid and preferred lifetimes for the addresses
644 * associated with an IA, the client sends a Renew message to the server
645 * from which the client obtained the addresses in the IA containing an
646 * IA option for the IA. The client includes IA Address options in the
647 * IA option for the addresses associated with the IA. The server
648 * determines new lifetimes for the addresses in the IA according to the
649 * administrative configuration of the server. The server may also add
650 * new addresses to the IA. The server may remove addresses from the IA
651 * by setting the preferred and valid lifetimes of those addresses to
654 * The server controls the time at which the client contacts the server
655 * to extend the lifetimes on assigned addresses through the T1 and T2
656 * parameters assigned to an IA.
658 * At time T1 for an IA, the client initiates a Renew/Reply message
659 * exchange to extend the lifetimes on any addresses in the IA. The
660 * client includes an IA option with all addresses currently assigned to
661 * the IA in its Renew message.
663 * If T1 or T2 is set to 0 by the server (for an IA_NA) or there are no
664 * T1 or T2 times (for an IA_TA), the client may send a Renew or Rebind
665 * message, respectively, at the client's discretion.
667 * The client sets the "msg-type" field to RENEW. The client generates
668 * a transaction ID and inserts this value in the "transaction-id"
671 * The client places the identifier of the destination server in a
672 * Server Identifier option.
674 * The client MUST include a Client Identifier option to identify itself
675 * to the server. The client adds any appropriate options, including
676 * one or more IA options. The client MUST include the list of
677 * addresses the client currently has associated with the IAs in the
680 * The client MUST include an Option Request option (see section 22.7)
681 * to indicate the options the client is interested in receiving. The
682 * client MAY include options with data values as hints to the server
683 * about parameter values the client would like to have returned.
685 /* NOINLINE: limit stack usage in caller */
686 static NOINLINE int send_d6_renew(uint32_t xid, struct in6_addr *server_ipv6, struct in6_addr *our_cur_ipv6)
688 struct d6_packet packet;
691 /* Fill in: msg type, client id */
692 opt_ptr = init_d6_packet(&packet, DHCPREQUEST, xid);
695 opt_ptr = mempcpy(opt_ptr, client6_data.server_id, client6_data.server_id->len + 2+2);
696 /* IA NA (contains requested IP) */
697 opt_ptr = mempcpy(opt_ptr, client6_data.ia_na, client6_data.ia_na->len + 2+2);
700 * "param req" option according to -O, options specified with -x
702 opt_ptr = add_d6_client_options(opt_ptr);
704 bb_error_msg("sending %s", "renew");
706 return d6_send_kernel_packet(
707 &packet, (opt_ptr - (uint8_t*) &packet),
708 our_cur_ipv6, CLIENT_PORT6,
709 server_ipv6, SERVER_PORT6,
710 client_config.ifindex
711 /* TODO? send_flags: MSG_DONTROUTE (see IPv4 code for reason why) */
714 return d6_mcast_from_client_config_ifindex(&packet, opt_ptr);
717 /* Unicast a DHCP release message */
718 static int send_d6_release(struct in6_addr *server_ipv6, struct in6_addr *our_cur_ipv6)
720 struct d6_packet packet;
723 /* Fill in: msg type, client id */
724 opt_ptr = init_d6_packet(&packet, D6_MSG_RELEASE, random_xid());
726 opt_ptr = mempcpy(opt_ptr, client6_data.server_id, client6_data.server_id->len + 2+2);
727 /* IA NA (contains our current IP) */
728 opt_ptr = mempcpy(opt_ptr, client6_data.ia_na, client6_data.ia_na->len + 2+2);
730 bb_error_msg("sending %s", "release");
731 return d6_send_kernel_packet(
732 &packet, (opt_ptr - (uint8_t*) &packet),
733 our_cur_ipv6, CLIENT_PORT6,
734 server_ipv6, SERVER_PORT6,
735 client_config.ifindex
739 /* Returns -1 on errors that are fatal for the socket, -2 for those that aren't */
740 /* NOINLINE: limit stack usage in caller */
741 static NOINLINE int d6_recv_raw_packet(struct in6_addr *peer_ipv6, struct d6_packet *d6_pkt, int fd)
744 struct ip6_udp_d6_packet packet;
746 bytes = safe_read(fd, &packet, sizeof(packet));
748 log1("packet read error, ignoring");
749 /* NB: possible down interface, etc. Caller should pause. */
750 return bytes; /* returns -1 */
753 if (bytes < (int) (sizeof(packet.ip6) + sizeof(packet.udp))) {
754 log1("packet is too short, ignoring");
758 if (bytes < sizeof(packet.ip6) + ntohs(packet.ip6.ip6_plen)) {
759 /* packet is bigger than sizeof(packet), we did partial read */
760 log1("oversized packet, ignoring");
764 /* ignore any extra garbage bytes */
765 bytes = sizeof(packet.ip6) + ntohs(packet.ip6.ip6_plen);
767 /* make sure its the right packet for us, and that it passes sanity checks */
768 if (packet.ip6.ip6_nxt != IPPROTO_UDP
769 || (packet.ip6.ip6_vfc >> 4) != 6
770 || packet.udp.dest != htons(CLIENT_PORT6)
771 /* || bytes > (int) sizeof(packet) - can't happen */
772 || packet.udp.len != packet.ip6.ip6_plen
774 log1("unrelated/bogus packet, ignoring");
778 //How to do this for ipv6?
779 // /* verify UDP checksum. IP header has to be modified for this */
780 // memset(&packet.ip, 0, offsetof(struct iphdr, protocol));
781 // /* ip.xx fields which are not memset: protocol, check, saddr, daddr */
782 // packet.ip.tot_len = packet.udp.len; /* yes, this is needed */
783 // check = packet.udp.check;
784 // packet.udp.check = 0;
785 // if (check && check != inet_cksum((uint16_t *)&packet, bytes)) {
786 // log1("packet with bad UDP checksum received, ignoring");
791 *peer_ipv6 = packet.ip6.ip6_src; /* struct copy */
793 log1("received %s", "a packet");
794 d6_dump_packet(&packet.data);
796 bytes -= sizeof(packet.ip6) + sizeof(packet.udp);
797 memcpy(d6_pkt, &packet.data, bytes);
804 static int sockfd = -1;
806 #define LISTEN_NONE 0
807 #define LISTEN_KERNEL 1
809 static smallint listen_mode;
811 /* initial state: (re)start DHCP negotiation */
812 #define INIT_SELECTING 0
813 /* discover was sent, DHCPOFFER reply received */
815 /* select/renew was sent, DHCPACK reply received */
817 /* half of lease passed, want to renew it by sending unicast renew requests */
819 /* renew requests were not answered, lease is almost over, send broadcast renew */
821 /* manually requested renew (SIGUSR1) */
822 #define RENEW_REQUESTED 5
823 /* release, possibly manually requested (SIGUSR2) */
825 static smallint state;
827 static int d6_raw_socket(int ifindex)
830 struct sockaddr_ll sock;
835 * I've selected not to see LL header, so BPF doesn't see it, too.
836 * The filter may also pass non-IP and non-ARP packets, but we do
837 * a more complete check when receiving the message in userspace.
839 * and filter shamelessly stolen from:
841 * http://www.flamewarmaster.de/software/dhcpclient/
843 * There are a few other interesting ideas on that page (look under
844 * "Motivation"). Use of netlink events is most interesting. Think
845 * of various network servers listening for events and reconfiguring.
846 * That would obsolete sending HUP signals and/or make use of restarts.
848 * Copyright: 2006, 2007 Stefan Rompf <sux@loplof.de>.
851 * TODO: make conditional?
854 static const struct sock_filter filter_instr[] = {
855 /* load 9th byte (protocol) */
856 BPF_STMT(BPF_LD|BPF_B|BPF_ABS, 9),
857 /* jump to L1 if it is IPPROTO_UDP, else to L4 */
858 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, IPPROTO_UDP, 0, 6),
859 /* L1: load halfword from offset 6 (flags and frag offset) */
860 BPF_STMT(BPF_LD|BPF_H|BPF_ABS, 6),
861 /* jump to L4 if any bits in frag offset field are set, else to L2 */
862 BPF_JUMP(BPF_JMP|BPF_JSET|BPF_K, 0x1fff, 4, 0),
863 /* L2: skip IP header (load index reg with header len) */
864 BPF_STMT(BPF_LDX|BPF_B|BPF_MSH, 0),
865 /* load udp destination port from halfword[header_len + 2] */
866 BPF_STMT(BPF_LD|BPF_H|BPF_IND, 2),
867 /* jump to L3 if udp dport is CLIENT_PORT6, else to L4 */
868 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 68, 0, 1),
869 /* L3: accept packet */
870 BPF_STMT(BPF_RET|BPF_K, 0x7fffffff),
871 /* L4: discard packet */
872 BPF_STMT(BPF_RET|BPF_K, 0),
874 static const struct sock_fprog filter_prog = {
875 .len = sizeof(filter_instr) / sizeof(filter_instr[0]),
876 /* casting const away: */
877 .filter = (struct sock_filter *) filter_instr,
881 log2("opening raw socket on ifindex %d", ifindex);
883 fd = xsocket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IPV6));
884 log2("got raw socket fd %d", fd);
886 memset(&sock, 0, sizeof(sock)); /* let's be deterministic */
887 sock.sll_family = AF_PACKET;
888 sock.sll_protocol = htons(ETH_P_IPV6);
889 sock.sll_ifindex = ifindex;
890 /*sock.sll_hatype = ARPHRD_???;*/
891 /*sock.sll_pkttype = PACKET_???;*/
892 /*sock.sll_halen = ???;*/
893 /*sock.sll_addr[8] = ???;*/
894 xbind(fd, (struct sockaddr *) &sock, sizeof(sock));
897 if (CLIENT_PORT6 == 546) {
898 /* Use only if standard port is in use */
899 /* Ignoring error (kernel may lack support for this) */
900 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog,
901 sizeof(filter_prog)) >= 0)
902 log1("attached filter to raw socket fd %d", fd); // log?
906 log1("created raw socket");
911 static void change_listen_mode(int new_mode)
913 log1("entering listen mode: %s",
914 new_mode != LISTEN_NONE
915 ? (new_mode == LISTEN_KERNEL ? "kernel" : "raw")
919 listen_mode = new_mode;
924 if (new_mode == LISTEN_KERNEL)
925 sockfd = udhcp_listen_socket(/*INADDR_ANY,*/ CLIENT_PORT6, client_config.interface);
926 else if (new_mode != LISTEN_NONE)
927 sockfd = d6_raw_socket(client_config.ifindex);
928 /* else LISTEN_NONE: sockfd stays closed */
931 /* Called only on SIGUSR1 */
932 static void perform_renew(void)
934 bb_error_msg("performing DHCP renew");
937 change_listen_mode(LISTEN_KERNEL);
940 state = RENEW_REQUESTED;
942 case RENEW_REQUESTED: /* impatient are we? fine, square 1 */
943 d6_run_script(NULL, "deconfig");
946 change_listen_mode(LISTEN_RAW);
947 state = INIT_SELECTING;
954 static void perform_d6_release(struct in6_addr *server_ipv6, struct in6_addr *our_cur_ipv6)
956 /* send release packet */
959 || state == REBINDING
960 || state == RENEW_REQUESTED
962 bb_error_msg("unicasting a release");
963 send_d6_release(server_ipv6, our_cur_ipv6); /* unicast */
965 bb_error_msg("entering released state");
967 * We can be here on: SIGUSR2,
968 * or on exit (SIGTERM) and -R "release on quit" is specified.
969 * Users requested to be notified in all cases, even if not in one
970 * of the states above.
972 d6_run_script(NULL, "deconfig");
973 change_listen_mode(LISTEN_NONE);
977 ///static uint8_t* alloc_dhcp_option(int code, const char *str, int extra)
979 /// uint8_t *storage;
980 /// int len = strnlen(str, 255);
981 /// storage = xzalloc(len + extra + OPT_DATA);
982 /// storage[OPT_CODE] = code;
983 /// storage[OPT_LEN] = len + extra;
984 /// memcpy(storage + extra + OPT_DATA, str, len);
989 static void client_background(void)
992 logmode &= ~LOGMODE_STDIO;
993 /* rewrite pidfile, as our pid is different now */
994 write_pidfile(client_config.pidfile);
998 //usage:#if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
999 //usage:# define IF_UDHCP_VERBOSE(...) __VA_ARGS__
1001 //usage:# define IF_UDHCP_VERBOSE(...)
1003 //usage:#define udhcpc6_trivial_usage
1004 //usage: "[-fbnq"IF_UDHCP_VERBOSE("v")"oR] [-i IFACE] [-r IP] [-s PROG] [-p PIDFILE]\n"
1005 //usage: " [-x OPT:VAL]... [-O OPT]..." IF_FEATURE_UDHCP_PORT(" [-P N]")
1006 //usage:#define udhcpc6_full_usage "\n"
1007 //usage: IF_LONG_OPTS(
1008 //usage: "\n -i,--interface IFACE Interface to use (default eth0)"
1009 //usage: "\n -p,--pidfile FILE Create pidfile"
1010 //usage: "\n -s,--script PROG Run PROG at DHCP events (default "CONFIG_UDHCPC_DEFAULT_SCRIPT")"
1011 //usage: "\n -B,--broadcast Request broadcast replies"
1012 //usage: "\n -t,--retries N Send up to N discover packets"
1013 //usage: "\n -T,--timeout N Pause between packets (default 3 seconds)"
1014 //usage: "\n -A,--tryagain N Wait N seconds after failure (default 20)"
1015 //usage: "\n -f,--foreground Run in foreground"
1016 //usage: USE_FOR_MMU(
1017 //usage: "\n -b,--background Background if lease is not obtained"
1019 //usage: "\n -n,--now Exit if lease is not obtained"
1020 //usage: "\n -q,--quit Exit after obtaining lease"
1021 //usage: "\n -R,--release Release IP on exit"
1022 //usage: "\n -S,--syslog Log to syslog too"
1023 //usage: IF_FEATURE_UDHCP_PORT(
1024 //usage: "\n -P,--client-port N Use port N (default 546)"
1026 ////usage: IF_FEATURE_UDHCPC_ARPING(
1027 ////usage: "\n -a,--arping Use arping to validate offered address"
1029 //usage: "\n -O,--request-option OPT Request option OPT from server (cumulative)"
1030 //usage: "\n -o,--no-default-options Don't request any options (unless -O is given)"
1031 //usage: "\n -r,--request IP Request this IP address"
1032 //usage: "\n -x OPT:VAL Include option OPT in sent packets (cumulative)"
1033 //usage: "\n Examples of string, numeric, and hex byte opts:"
1034 //usage: "\n -x hostname:bbox - option 12"
1035 //usage: "\n -x lease:3600 - option 51 (lease time)"
1036 //usage: "\n -x 0x3d:0100BEEFC0FFEE - option 61 (client id)"
1037 //usage: IF_UDHCP_VERBOSE(
1038 //usage: "\n -v Verbose"
1041 //usage: IF_NOT_LONG_OPTS(
1042 //usage: "\n -i IFACE Interface to use (default eth0)"
1043 //usage: "\n -p FILE Create pidfile"
1044 //usage: "\n -s PROG Run PROG at DHCP events (default "CONFIG_UDHCPC_DEFAULT_SCRIPT")"
1045 //usage: "\n -B Request broadcast replies"
1046 //usage: "\n -t N Send up to N discover packets"
1047 //usage: "\n -T N Pause between packets (default 3 seconds)"
1048 //usage: "\n -A N Wait N seconds (default 20) after failure"
1049 //usage: "\n -f Run in foreground"
1050 //usage: USE_FOR_MMU(
1051 //usage: "\n -b Background if lease is not obtained"
1053 //usage: "\n -n Exit if lease is not obtained"
1054 //usage: "\n -q Exit after obtaining lease"
1055 //usage: "\n -R Release IP on exit"
1056 //usage: "\n -S Log to syslog too"
1057 //usage: IF_FEATURE_UDHCP_PORT(
1058 //usage: "\n -P N Use port N (default 546)"
1060 ////usage: IF_FEATURE_UDHCPC_ARPING(
1061 ////usage: "\n -a Use arping to validate offered address"
1063 //usage: "\n -O OPT Request option OPT from server (cumulative)"
1064 //usage: "\n -o Don't request any options (unless -O is given)"
1065 //usage: "\n -r IP Request this IP address"
1066 //usage: "\n -x OPT:VAL Include option OPT in sent packets (cumulative)"
1067 //usage: "\n Examples of string, numeric, and hex byte opts:"
1068 //usage: "\n -x hostname:bbox - option 12"
1069 //usage: "\n -x lease:3600 - option 51 (lease time)"
1070 //usage: "\n -x 0x3d:0100BEEFC0FFEE - option 61 (client id)"
1071 //usage: IF_UDHCP_VERBOSE(
1072 //usage: "\n -v Verbose"
1075 //usage: "\nSignals:"
1076 //usage: "\n USR1 Renew lease"
1077 //usage: "\n USR2 Release lease"
1080 int udhcpc6_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1081 int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
1084 IF_FEATURE_UDHCP_PORT(char *str_P;)
1085 void *clientid_mac_ptr;
1086 llist_t *list_O = NULL;
1087 llist_t *list_x = NULL;
1088 int tryagain_timeout = 20;
1089 int discover_timeout = 3;
1090 int discover_retries = 3;
1091 struct in6_addr srv6_buf;
1092 struct in6_addr ipv6_buf;
1093 struct in6_addr *requested_ipv6;
1096 int timeout; /* must be signed */
1097 unsigned already_waited_sec;
1101 setup_common_bufsiz();
1103 /* Default options */
1104 IF_FEATURE_UDHCP_PORT(SERVER_PORT6 = 547;)
1105 IF_FEATURE_UDHCP_PORT(CLIENT_PORT6 = 546;)
1106 client_config.interface = "eth0";
1107 client_config.script = CONFIG_UDHCPC_DEFAULT_SCRIPT;
1109 /* Parse command line */
1110 opt = getopt32long(argv, "^"
1111 /* O,x: list; -T,-t,-A take numeric param */
1112 "i:np:qRr:s:T:+t:+SA:+O:*ox:*f"
1114 ///IF_FEATURE_UDHCPC_ARPING("a")
1115 IF_FEATURE_UDHCP_PORT("P:")
1117 "\0" IF_UDHCP_VERBOSE("vv") /* -v is a counter */
1119 , &client_config.interface, &client_config.pidfile, &str_r /* i,p */
1120 , &client_config.script /* s */
1121 , &discover_timeout, &discover_retries, &tryagain_timeout /* T,t,A */
1124 IF_FEATURE_UDHCP_PORT(, &str_P)
1125 IF_UDHCP_VERBOSE(, &dhcp_verbose)
1127 requested_ipv6 = NULL;
1129 if (inet_pton(AF_INET6, str_r, &ipv6_buf) <= 0)
1130 bb_error_msg_and_die("bad IPv6 address '%s'", str_r);
1131 requested_ipv6 = &ipv6_buf;
1133 #if ENABLE_FEATURE_UDHCP_PORT
1135 CLIENT_PORT6 = xatou16(str_P);
1136 SERVER_PORT6 = CLIENT_PORT6 + 1;
1140 char *optstr = llist_pop(&list_O);
1141 unsigned n = bb_strtou(optstr, NULL, 0);
1142 if (errno || n > 254) {
1143 n = udhcp_option_idx(optstr, d6_option_strings);
1144 n = d6_optflags[n].code;
1146 client_config.opt_mask[n >> 3] |= 1 << (n & 7);
1148 if (!(opt & OPT_o)) {
1150 for (i = 0; (n = d6_optflags[i].code) != 0; i++) {
1151 if (d6_optflags[i].flags & OPTION_REQ) {
1152 client_config.opt_mask[n >> 3] |= 1 << (n & 7);
1157 char *optstr = llist_pop(&list_x);
1158 char *colon = strchr(optstr, ':');
1161 /* now it looks similar to udhcpd's config file line:
1162 * "optname optval", using the common routine: */
1163 udhcp_str2optset(optstr, &client_config.options, d6_optflags, d6_option_strings);
1165 *colon = ':'; /* restore it for NOMMU reexec */
1168 if (d6_read_interface(client_config.interface,
1169 &client_config.ifindex,
1170 &client6_data.ll_ip6,
1171 client_config.client_mac)
1176 /* Create client ID based on mac, set clientid_mac_ptr */
1178 struct d6_option *clientid;
1179 clientid = xzalloc(2+2+2+2+6);
1180 clientid->code = D6_OPT_CLIENTID;
1181 clientid->len = 2+2+6;
1182 clientid->data[1] = 3; /* DUID-LL */
1183 clientid->data[3] = 1; /* ethernet */
1184 clientid_mac_ptr = clientid->data + 2+2;
1185 memcpy(clientid_mac_ptr, client_config.client_mac, 6);
1186 client_config.clientid = (void*)clientid;
1190 /* on NOMMU reexec (i.e., background) early */
1191 if (!(opt & OPT_f)) {
1192 bb_daemonize_or_rexec(0 /* flags */, argv);
1193 logmode = LOGMODE_NONE;
1197 openlog(applet_name, LOG_PID, LOG_DAEMON);
1198 logmode |= LOGMODE_SYSLOG;
1201 /* Make sure fd 0,1,2 are open */
1202 bb_sanitize_stdio();
1203 /* Equivalent of doing a fflush after every \n */
1205 /* Create pidfile */
1206 write_pidfile(client_config.pidfile);
1207 /* Goes to stdout (unless NOMMU) and possibly syslog */
1208 bb_error_msg("started, v"BB_VER);
1209 /* Set up the signal pipe */
1211 /* We want random_xid to be random... */
1212 srand(monotonic_us());
1214 state = INIT_SELECTING;
1215 d6_run_script(NULL, "deconfig");
1216 change_listen_mode(LISTEN_RAW);
1219 already_waited_sec = 0;
1221 /* Main event loop. select() waits on signal pipe and possibly
1223 * "continue" statements in code below jump to the top of the loop.
1227 struct pollfd pfds[2];
1228 struct d6_packet packet;
1229 uint8_t *packet_end;
1230 /* silence "uninitialized!" warning */
1231 unsigned timestamp_before_wait = timestamp_before_wait;
1233 //bb_error_msg("sockfd:%d, listen_mode:%d", sockfd, listen_mode);
1235 /* Was opening raw or udp socket here
1236 * if (listen_mode != LISTEN_NONE && sockfd < 0),
1237 * but on fast network renew responses return faster
1238 * than we open sockets. Thus this code is moved
1239 * to change_listen_mode(). Thus we open listen socket
1240 * BEFORE we send renew request (see "case BOUND:"). */
1242 udhcp_sp_fd_set(pfds, sockfd);
1244 tv = timeout - already_waited_sec;
1246 /* If we already timed out, fall through with retval = 0, else... */
1248 log1("waiting %u seconds", tv);
1249 timestamp_before_wait = (unsigned)monotonic_sec();
1250 retval = poll(pfds, 2, tv < INT_MAX/1000 ? tv * 1000 : INT_MAX);
1252 /* EINTR? A signal was caught, don't panic */
1253 if (errno == EINTR) {
1254 already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
1257 /* Else: an error occured, panic! */
1258 bb_perror_msg_and_die("poll");
1262 /* If timeout dropped to zero, time to become active:
1263 * resend discover/renew/whatever
1266 /* When running on a bridge, the ifindex may have changed
1267 * (e.g. if member interfaces were added/removed
1268 * or if the status of the bridge changed).
1269 * Refresh ifindex and client_mac:
1271 if (d6_read_interface(client_config.interface,
1272 &client_config.ifindex,
1273 &client6_data.ll_ip6,
1274 client_config.client_mac)
1276 goto ret0; /* iface is gone? */
1279 memcpy(clientid_mac_ptr, client_config.client_mac, 6);
1281 /* We will restart the wait in any case */
1282 already_waited_sec = 0;
1285 case INIT_SELECTING:
1286 if (!discover_retries || packet_num < discover_retries) {
1287 if (packet_num == 0)
1290 send_d6_discover(xid, requested_ipv6);
1291 timeout = discover_timeout;
1296 d6_run_script(NULL, "leasefail");
1297 #if BB_MMU /* -b is not supported on NOMMU */
1298 if (opt & OPT_b) { /* background if no lease */
1299 bb_error_msg("no lease, forking to background");
1300 client_background();
1301 /* do not background again! */
1302 opt = ((opt & ~OPT_b) | OPT_f);
1305 if (opt & OPT_n) { /* abort if no lease */
1306 bb_error_msg("no lease, failing");
1310 /* wait before trying again */
1311 timeout = tryagain_timeout;
1315 if (!discover_retries || packet_num < discover_retries) {
1316 /* send multicast select packet */
1317 send_d6_select(xid);
1318 timeout = discover_timeout;
1322 /* Timed out, go back to init state.
1323 * "discover...select...discover..." loops
1324 * were seen in the wild. Treat them similarly
1325 * to "no response to discover" case */
1326 change_listen_mode(LISTEN_RAW);
1327 state = INIT_SELECTING;
1330 /* 1/2 lease passed, enter renewing state */
1332 client_config.first_secs = 0; /* make secs field count from 0 */
1333 change_listen_mode(LISTEN_KERNEL);
1334 log1("entering renew state");
1335 /* fall right through */
1336 case RENEW_REQUESTED: /* manual (SIGUSR1) renew */
1337 case_RENEW_REQUESTED:
1340 /* send an unicast renew request */
1341 /* Sometimes observed to fail (EADDRNOTAVAIL) to bind
1342 * a new UDP socket for sending inside send_renew.
1343 * I hazard to guess existing listening socket
1344 * is somehow conflicting with it, but why is it
1345 * not deterministic then?! Strange.
1346 * Anyway, it does recover by eventually failing through
1347 * into INIT_SELECTING state.
1349 send_d6_renew(xid, &srv6_buf, requested_ipv6);
1353 /* Timed out, enter rebinding state */
1354 log1("entering rebinding state");
1356 /* fall right through */
1358 /* Switch to bcast receive */
1359 change_listen_mode(LISTEN_RAW);
1360 /* Lease is *really* about to run out,
1361 * try to find DHCP server using broadcast */
1363 /* send a broadcast renew request */
1364 send_d6_renew(xid, /*server_ipv6:*/ NULL, requested_ipv6);
1368 /* Timed out, enter init state */
1369 bb_error_msg("lease lost, entering init state");
1370 d6_run_script(NULL, "deconfig");
1371 state = INIT_SELECTING;
1372 client_config.first_secs = 0; /* make secs field count from 0 */
1373 /*timeout = 0; - already is */
1376 /* case RELEASED: */
1378 /* yah, I know, *you* say it would never happen */
1380 continue; /* back to main loop */
1381 } /* if select timed out */
1383 /* select() didn't timeout, something happened */
1385 /* Is it a signal? */
1386 /* note: udhcp_sp_read checks poll result before reading */
1387 switch (udhcp_sp_read(pfds)) {
1389 client_config.first_secs = 0; /* make secs field count from 0 */
1390 already_waited_sec = 0;
1392 if (state == RENEW_REQUESTED) {
1393 /* We might be either on the same network
1394 * (in which case renew might work),
1395 * or we might be on a completely different one
1396 * (in which case renew won't ever succeed).
1397 * For the second case, must make sure timeout
1398 * is not too big, or else we can send
1399 * futile renew requests for hours.
1400 * (Ab)use -A TIMEOUT value (usually 20 sec)
1401 * as a cap on the timeout.
1403 if (timeout > tryagain_timeout)
1404 timeout = tryagain_timeout;
1405 goto case_RENEW_REQUESTED;
1407 /* Start things over */
1409 /* Kill any timeouts, user wants this to hurry along */
1413 perform_d6_release(&srv6_buf, requested_ipv6);
1417 bb_error_msg("received %s", "SIGTERM");
1421 /* Is it a packet? */
1422 if (listen_mode == LISTEN_NONE || !pfds[1].revents)
1428 /* A packet is ready, read it */
1429 if (listen_mode == LISTEN_KERNEL)
1430 len = d6_recv_kernel_packet(&srv6_buf, &packet, sockfd);
1432 len = d6_recv_raw_packet(&srv6_buf, &packet, sockfd);
1434 /* Error is severe, reopen socket */
1435 bb_error_msg("read error: %s, reopening socket", strerror(errno));
1436 sleep(discover_timeout); /* 3 seconds by default */
1437 change_listen_mode(listen_mode); /* just close and reopen */
1439 /* If this packet will turn out to be unrelated/bogus,
1440 * we will go back and wait for next one.
1441 * Be sure timeout is properly decreased. */
1442 already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
1445 packet_end = (uint8_t*)&packet + len;
1448 if ((packet.d6_xid32 & htonl(0x00ffffff)) != xid) {
1449 log1("xid %x (our is %x), ignoring packet",
1450 (unsigned)(packet.d6_xid32 & htonl(0x00ffffff)), (unsigned)xid);
1455 case INIT_SELECTING:
1456 if (packet.d6_msg_type == D6_MSG_ADVERTISE)
1458 /* DHCPv6 has "Rapid Commit", when instead of Advertise,
1459 * server sends Reply right away.
1460 * Fall through to check for this case.
1464 case RENEW_REQUESTED:
1466 if (packet.d6_msg_type == D6_MSG_REPLY) {
1467 uint32_t lease_seconds;
1468 struct d6_option *option, *iaaddr;
1470 option = d6_find_option(packet.d6_options, packet_end, D6_OPT_STATUS_CODE);
1471 if (option && (option->data[0] | option->data[1]) != 0) {
1472 /* return to init state */
1473 bb_error_msg("received DHCP NAK (%u)", option->data[4]);
1474 d6_run_script(&packet, "nak");
1475 if (state != REQUESTING)
1476 d6_run_script(NULL, "deconfig");
1477 change_listen_mode(LISTEN_RAW);
1478 sleep(3); /* avoid excessive network traffic */
1479 state = INIT_SELECTING;
1480 client_config.first_secs = 0; /* make secs field count from 0 */
1481 requested_ipv6 = NULL;
1484 already_waited_sec = 0;
1487 option = d6_copy_option(packet.d6_options, packet_end, D6_OPT_SERVERID);
1489 bb_error_msg("no server ID, ignoring packet");
1491 /* still selecting - this server looks bad */
1493 //Note: we do not bother comparing server IDs in Advertise and Reply msgs.
1494 //server_id variable is used solely for creation of proper server_id option
1495 //in outgoing packets. (why DHCPv6 even introduced it is a mystery).
1496 free(client6_data.server_id);
1497 client6_data.server_id = option;
1498 if (packet.d6_msg_type == D6_MSG_ADVERTISE) {
1499 /* enter requesting state */
1503 already_waited_sec = 0;
1506 /* It's a D6_MSG_REPLY */
1508 * RFC 3315 18.1.8. Receipt of Reply Messages
1510 * Upon the receipt of a valid Reply message in response to a Solicit
1511 * (with a Rapid Commit option), Request, Confirm, Renew, Rebind or
1512 * Information-request message, the client extracts the configuration
1513 * information contained in the Reply. The client MAY choose to report
1514 * any status code or message from the status code option in the Reply
1517 * The client SHOULD perform duplicate address detection [17] on each of
1518 * the addresses in any IAs it receives in the Reply message before
1519 * using that address for traffic. If any of the addresses are found to
1520 * be in use on the link, the client sends a Decline message to the
1521 * server as described in section 18.1.7.
1523 * If the Reply was received in response to a Solicit (with a Rapid
1524 * Commit option), Request, Renew or Rebind message, the client updates
1525 * the information it has recorded about IAs from the IA options
1526 * contained in the Reply message:
1528 * - Record T1 and T2 times.
1530 * - Add any new addresses in the IA option to the IA as recorded by
1533 * - Update lifetimes for any addresses in the IA option that the
1534 * client already has recorded in the IA.
1536 * - Discard any addresses from the IA, as recorded by the client, that
1537 * have a valid lifetime of 0 in the IA Address option.
1539 * - Leave unchanged any information about addresses the client has
1540 * recorded in the IA but that were not included in the IA from the
1543 * Management of the specific configuration information is detailed in
1544 * the definition of each option in section 22.
1546 * If the client receives a Reply message with a Status Code containing
1547 * UnspecFail, the server is indicating that it was unable to process
1548 * the message due to an unspecified failure condition. If the client
1549 * retransmits the original message to the same server to retry the
1550 * desired operation, the client MUST limit the rate at which it
1551 * retransmits the message and limit the duration of the time during
1552 * which it retransmits the message.
1554 * When the client receives a Reply message with a Status Code option
1555 * with the value UseMulticast, the client records the receipt of the
1556 * message and sends subsequent messages to the server through the
1557 * interface on which the message was received using multicast. The
1558 * client resends the original message using multicast.
1560 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1561 * | OPTION_IA_NA | option-len |
1562 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1563 * | IAID (4 octets) |
1564 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1566 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1568 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1572 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1575 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1576 * | OPTION_IAADDR | option-len |
1577 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1582 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1583 * | preferred-lifetime |
1584 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1585 * | valid-lifetime |
1586 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1588 * . IAaddr-options .
1590 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1592 free(client6_data.ia_na);
1593 client6_data.ia_na = d6_copy_option(packet.d6_options, packet_end, D6_OPT_IA_NA);
1594 if (!client6_data.ia_na) {
1595 bb_error_msg("no %s option, ignoring packet", "IA_NA");
1598 if (client6_data.ia_na->len < (4 + 4 + 4) + (2 + 2 + 16 + 4 + 4)) {
1599 bb_error_msg("IA_NA option is too short:%d bytes", client6_data.ia_na->len);
1602 iaaddr = d6_find_option(client6_data.ia_na->data + 4 + 4 + 4,
1603 client6_data.ia_na->data + client6_data.ia_na->len,
1607 bb_error_msg("no %s option, ignoring packet", "IAADDR");
1610 if (iaaddr->len < (16 + 4 + 4)) {
1611 bb_error_msg("IAADDR option is too short:%d bytes", iaaddr->len);
1614 /* Note: the address is sufficiently aligned for cast:
1615 * we _copied_ IA-NA, and copy is always well-aligned.
1617 requested_ipv6 = (struct in6_addr*) iaaddr->data;
1618 move_from_unaligned32(lease_seconds, iaaddr->data + 16 + 4);
1619 lease_seconds = ntohl(lease_seconds);
1620 /* paranoia: must not be too small and not prone to overflows */
1621 if (lease_seconds < 0x10)
1622 lease_seconds = 0x10;
1623 /// TODO: check for 0 lease time?
1624 if (lease_seconds > 0x7fffffff / 1000)
1625 lease_seconds = 0x7fffffff / 1000;
1626 /* enter bound state */
1627 timeout = lease_seconds / 2;
1628 bb_error_msg("lease obtained, lease time %u",
1629 /*inet_ntoa(temp_addr),*/ (unsigned)lease_seconds);
1630 d6_run_script(&packet, state == REQUESTING ? "bound" : "renew");
1633 change_listen_mode(LISTEN_NONE);
1634 if (opt & OPT_q) { /* quit after lease */
1637 /* future renew failures should not exit (JM) */
1639 #if BB_MMU /* NOMMU case backgrounded earlier */
1640 if (!(opt & OPT_f)) {
1641 client_background();
1642 /* do not background again! */
1643 opt = ((opt & ~OPT_b) | OPT_f);
1646 already_waited_sec = 0;
1647 continue; /* back to main loop */
1650 /* case BOUND: - ignore all packets */
1651 /* case RELEASED: - ignore all packets */
1653 /* back to main loop */
1654 } /* for (;;) - main loop ends */
1657 if (opt & OPT_R) /* release on quit */
1658 perform_d6_release(&srv6_buf, requested_ipv6);
1661 /*if (client_config.pidfile) - remove_pidfile has its own check */
1662 remove_pidfile(client_config.pidfile);