Start 1.33.0 development cycle
[oweals/busybox.git] / networking / udhcp / d6_dhcpc.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * DHCPv6 client.
4  *
5  * Copyright (C) 2011-2017 Denys Vlasenko.
6  *
7  * Licensed under GPLv2, see file LICENSE in this source tree.
8  */
9 //config:config UDHCPC6
10 //config:       bool "udhcpc6 (21 kb)"
11 //config:       default y
12 //config:       depends on FEATURE_IPV6
13 //config:       help
14 //config:       udhcpc6 is a DHCPv6 client
15 //config:
16 //config:config FEATURE_UDHCPC6_RFC3646
17 //config:       bool "Support RFC 3646 (DNS server and search list)"
18 //config:       default y
19 //config:       depends on UDHCPC6
20 //config:       help
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".
24 //config:
25 //config:config FEATURE_UDHCPC6_RFC4704
26 //config:       bool "Support RFC 4704 (Client FQDN)"
27 //config:       default y
28 //config:       depends on UDHCPC6
29 //config:       help
30 //config:       You can request FQDN to be given by server using "-O fqdn".
31 //config:
32 //config:config FEATURE_UDHCPC6_RFC4833
33 //config:       bool "Support RFC 4833 (Timezones)"
34 //config:       default y
35 //config:       depends on UDHCPC6
36 //config:       help
37 //config:       You can request POSIX timezone with "-O tz" and timezone name
38 //config:       with "-O timezone".
39 //config:
40 //config:config FEATURE_UDHCPC6_RFC5970
41 //config:       bool "Support RFC 5970 (Network Boot)"
42 //config:       default y
43 //config:       depends on UDHCPC6
44 //config:       help
45 //config:       You can request bootfile-url with "-O bootfile_url" and
46 //config:       bootfile-params with "-O bootfile_params".
47
48 //applet:IF_UDHCPC6(APPLET(udhcpc6, BB_DIR_USR_BIN, BB_SUID_DROP))
49
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
53
54 #include <syslog.h>
55 /* Override ENABLE_FEATURE_PIDFILE - ifupdown needs our pidfile to always exist */
56 #define WANT_PIDFILE 1
57 #include "common.h"
58 #include "dhcpd.h"
59 #include "dhcpc.h"
60 #include "d6_common.h"
61
62 #include <netinet/if_ether.h>
63 #include <netpacket/packet.h>
64 #include <linux/filter.h>
65
66 /* "struct client_data_t client_data" is in bb_common_bufsiz1 */
67
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 },
72 #endif
73 #if ENABLE_FEATURE_UDHCPC6_RFC4704
74         { OPTION_DNS_STRING,                            D6_OPT_CLIENT_FQDN },
75 #endif
76 #if ENABLE_FEATURE_UDHCPC6_RFC4833
77         { OPTION_STRING,                                D6_OPT_TZ_POSIX },
78         { OPTION_STRING,                                D6_OPT_TZ_NAME },
79 #endif
80 #if ENABLE_FEATURE_UDHCPC6_RFC5970
81         { OPTION_STRING,                                D6_OPT_BOOT_URL },
82         { OPTION_STRING,                                D6_OPT_BOOT_PARAM },
83 #endif
84         { OPTION_STRING,                                0xd1 }, /* DHCP_PXE_CONF_FILE */
85         { OPTION_STRING,                                0xd2 }, /* DHCP_PXE_PATH_PREFIX */
86         { 0, 0 }
87 };
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 */
93 #endif
94 #if ENABLE_FEATURE_UDHCPC6_RFC4704
95         "fqdn" "\0"     /* D6_OPT_CLIENT_FQDN */
96 #endif
97 #if ENABLE_FEATURE_UDHCPC6_RFC4833
98         "tz" "\0"       /* D6_OPT_TZ_POSIX */
99         "timezone" "\0" /* D6_OPT_TZ_NAME */
100 #endif
101 #if ENABLE_FEATURE_UDHCPC6_RFC5970
102         "bootfile_url" "\0" /* D6_OPT_BOOT_URL */
103         "bootfile_param" "\0" /* D6_OPT_BOOT_PARAM */
104 #endif
105         "pxeconffile" "\0" /* DHCP_PXE_CONF_FILE  */
106         "pxepathprefix" "\0" /* DHCP_PXE_PATH_PREFIX  */
107         "\0";
108
109 #if ENABLE_LONG_OPTS
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"
127         USE_FOR_MMU(
128         "background\0"     No_argument       "b"
129         )
130 ///     IF_FEATURE_UDHCPC_ARPING("arping\0"     No_argument       "a")
131         IF_FEATURE_UDHCP_PORT("client-port\0"   Required_argument "P")
132         ;
133 #endif
134 /* Must match getopt32 option string order */
135 enum {
136         OPT_i = 1 << 0,
137         OPT_n = 1 << 1,
138         OPT_p = 1 << 2,
139         OPT_q = 1 << 3,
140         OPT_R = 1 << 4,
141         OPT_r = 1 << 5,
142         OPT_s = 1 << 6,
143         OPT_T = 1 << 7,
144         OPT_t = 1 << 8,
145         OPT_S = 1 << 9,
146         OPT_A = 1 << 10,
147         OPT_O = 1 << 11,
148         OPT_o = 1 << 12,
149         OPT_x = 1 << 13,
150         OPT_f = 1 << 14,
151         OPT_l = 1 << 15,
152         OPT_d = 1 << 16,
153 /* The rest has variable bit positions, need to be clever */
154         OPTBIT_d = 16,
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,)
161 };
162
163 #if ENABLE_FEATURE_UDHCPC6_RFC4704
164 static const char opt_fqdn_req[] = {
165         (D6_OPT_CLIENT_FQDN >> 8), (D6_OPT_CLIENT_FQDN & 0xff),
166         0, 2, /* optlen */
167         0, /* flags: */
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 */
172 };
173 #endif
174
175 /*** Utility functions ***/
176
177 static void *d6_find_option(uint8_t *option, uint8_t *option_end, unsigned code)
178 {
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.
188                  */
189                 if (option[0] != 0 || option[2] != 0)
190                         return NULL;
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;
197         }
198         return NULL;
199 }
200
201 static void *d6_copy_option(uint8_t *option, uint8_t *option_end, unsigned code)
202 {
203         uint8_t *opt = d6_find_option(option, option_end, code);
204         if (!opt)
205                 return opt;
206         return xmemdup(opt, opt[3] + 4);
207 }
208
209 /*** Script execution code ***/
210
211 static char** new_env(void)
212 {
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++];
215 }
216
217 static char *string_option_to_env(const uint8_t *option,
218                 const uint8_t *option_end)
219 {
220         const char *ptr, *name = NULL;
221         unsigned val_len;
222         int i;
223
224         ptr = d6_option_strings;
225         i = 0;
226         while (*ptr) {
227                 if (d6_optflags[i].code == option[1]) {
228                         name = ptr;
229                         goto found;
230                 }
231                 ptr += strlen(ptr) + 1;
232                 i++;
233         }
234         bb_error_msg("can't find option name for 0x%x, skipping", option[1]);
235         return NULL;
236
237  found:
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");
241                 return NULL;
242         }
243         return xasprintf("%s=%.*s", name, val_len, (char*)option + 4);
244 }
245
246 /* put all the parameters into the environment */
247 static void option_to_env(const uint8_t *option, const uint8_t *option_end)
248 {
249 #if ENABLE_FEATURE_UDHCPC6_RFC3646
250         int addrs, option_offset;
251 #endif
252         /* "length minus 4" */
253         int len_m4 = option_end - option - 4;
254
255         while (len_m4 >= 0) {
256                 uint32_t v32;
257                 char ipv6str[sizeof("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")];
258
259                 if (option[0] != 0 || option[2] != 0)
260                         break;
261
262                 /* Check if option-length exceeds size of option */
263                 if (option[3] > len_m4)
264                         break;
265
266                 switch (option[1]) {
267                 //case D6_OPT_CLIENTID:
268                 //case D6_OPT_SERVERID:
269                 case D6_OPT_IA_NA:
270                 case D6_OPT_IA_PD:
271                         option_to_env(option + 16, option + 4 + option[3]);
272                         break;
273                 //case D6_OPT_IA_TA:
274                 case D6_OPT_IAADDR:
275 /*  0                   1                   2                   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  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
280  * |                                                               |
281  * |                         IPv6 address                          |
282  * |                                                               |
283  * |                                                               |
284  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
285  * |                      preferred-lifetime                       |
286  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
287  * |                        valid-lifetime                         |
288  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
289  */
290                         /* Make sure payload contains an address */
291                         if (option[3] < 24)
292                                 break;
293
294                         sprint_nip6(ipv6str, option + 4);
295                         *new_env() = xasprintf("ipv6=%s", ipv6str);
296
297                         move_from_unaligned32(v32, option + 4 + 16 + 4);
298                         *new_env() = xasprintf("lease=%u", (unsigned)v32);
299                         break;
300
301                 //case D6_OPT_ORO:
302                 //case D6_OPT_PREFERENCE:
303                 //case D6_OPT_ELAPSED_TIME:
304                 //case D6_OPT_RELAY_MSG:
305                 //case D6_OPT_AUTH:
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:
315
316                 case D6_OPT_IAPREFIX:
317 /*  0                   1                   2                   3
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  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
324  * |                        valid-lifetime                         |
325  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
326  * | prefix-length |                                               |
327  * +-+-+-+-+-+-+-+-+          IPv6 prefix                          |
328  * |                           (16 octets)                         |
329  * |                                                               |
330  * |               +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
331  * |               |
332  * +-+-+-+-+-+-+-+-+
333  */
334                         move_from_unaligned32(v32, option + 4 + 4);
335                         *new_env() = xasprintf("ipv6prefix_lease=%u", (unsigned)v32);
336
337                         sprint_nip6(ipv6str, option + 4 + 4 + 4 + 1);
338                         *new_env() = xasprintf("ipv6prefix=%s/%u", ipv6str, (unsigned)(option[4 + 4 + 4]));
339                         break;
340 #if ENABLE_FEATURE_UDHCPC6_RFC3646
341                 case D6_OPT_DNS_SERVERS: {
342                         char *dlist;
343
344                         /* Make sure payload-size is a multiple of 16 */
345                         if ((option[3] & 0x0f) != 0)
346                                 break;
347
348                         /* Get the number of addresses on the option */
349                         addrs = option[3] >> 4;
350
351                         /* Setup environment variable */
352                         *new_env() = dlist = xmalloc(4 + addrs * 40 - 1);
353                         dlist = stpcpy(dlist, "dns=");
354                         option_offset = 0;
355
356                         while (addrs--) {
357                                 sprint_nip6(dlist, option + 4 + option_offset);
358                                 dlist += 39;
359                                 option_offset += 16;
360                                 if (addrs)
361                                         *dlist++ = ' ';
362                         }
363
364                         break;
365                 }
366                 case D6_OPT_DOMAIN_LIST: {
367                         char *dlist;
368
369                         dlist = dname_dec(option + 4, (option[2] << 8) | option[3], "search=");
370                         if (!dlist)
371                                 break;
372                         *new_env() = dlist;
373                         break;
374                 }
375 #endif
376 #if ENABLE_FEATURE_UDHCPC6_RFC4704
377                 case D6_OPT_CLIENT_FQDN: {
378                         char *dlist;
379
380                         if (option[3] == 0)
381                                 break;
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.
388                          */
389                         if (option[4] & 0xf8) {
390                                 *new_env() = xasprintf("fqdn=%.*s", (int)option[3], (char*)option + 4);
391                                 break;
392                         }
393                         dlist = dname_dec(option + 5, (/*(option[2] << 8) |*/ option[3]) - 1, "fqdn=");
394                         if (!dlist)
395                                 break;
396                         *new_env() = dlist;
397                         break;
398                 }
399 #endif
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);
404                         break;
405                 case D6_OPT_TZ_NAME:
406                         *new_env() = xasprintf("tz_name=%.*s", (int)option[3], (char*)option + 4);
407                         break;
408 #endif
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 */
413                         {
414                         char *tmp = string_option_to_env(option, option_end);
415                         if (tmp)
416                                 *new_env() = tmp;
417                         break;
418                         }
419                 }
420                 len_m4 -= 4 + option[3];
421                 option += 4 + option[3];
422         }
423 }
424
425 static char **fill_envp(const uint8_t *option, const uint8_t *option_end)
426 {
427         char **envp, **curr;
428
429         client6_data.env_ptr = NULL;
430         client6_data.env_idx = 0;
431
432         *new_env() = xasprintf("interface=%s", client_data.interface);
433
434         if (option)
435                 option_to_env(option, option_end);
436
437         envp = curr = client6_data.env_ptr;
438         while (*curr)
439                 putenv(*curr++);
440
441         return envp;
442 }
443
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,
446                 const char *name)
447 {
448         char **envp, **curr;
449         char *argv[3];
450
451         envp = fill_envp(option, option_end);
452
453         /* call script */
454         log1("executing %s %s", client_data.script, name);
455         argv[0] = (char*) client_data.script;
456         argv[1] = (char*) name;
457         argv[2] = NULL;
458         spawn_and_wait(argv);
459
460         for (curr = envp; *curr; curr++) {
461                 log2(" %s", *curr);
462                 bb_unsetenv_and_free(*curr);
463         }
464         free(envp);
465 }
466
467 /* Call a script with a par file and no env var */
468 static void d6_run_script_no_option(const char *name)
469 {
470         d6_run_script(NULL, NULL, name);
471 }
472
473 /*** Sending/receiving packets ***/
474
475 static ALWAYS_INLINE uint32_t random_xid(void)
476 {
477         uint32_t t = rand() & htonl(0x00ffffff);
478         return t;
479 }
480
481 /* Initialize the packet with the proper defaults */
482 static uint8_t *init_d6_packet(struct d6_packet *packet, char type, uint32_t xid)
483 {
484         uint8_t *ptr;
485         struct d6_option *clientid;
486         unsigned secs;
487
488         memset(packet, 0, sizeof(*packet));
489
490         packet->d6_xid32 = xid;
491         packet->d6_msg_type = type;
492
493         /* ELAPSED_TIME option is required to be present by the RFC,
494          * and some servers do check for its presense. [which?]
495          */
496         ptr = packet->d6_options; /* NB: it is 32-bit aligned */
497         *((uint32_t*)ptr) = htonl((D6_OPT_ELAPSED_TIME << 16) + 2);
498         ptr += 4;
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;
504         ptr += 2;
505
506         /* add CLIENTID option */
507         clientid = (void*)client_data.clientid;
508         return mempcpy(ptr, clientid, clientid->len + 2+2);
509 }
510
511 static uint8_t *add_d6_client_options(uint8_t *ptr)
512 {
513         struct option_set *curr;
514         uint8_t *start = ptr;
515         unsigned option;
516         uint16_t len;
517
518         ptr += 4;
519         for (option = 1; option < 256; option++) {
520                 if (client_data.opt_mask[option >> 3] & (1 << (option & 7))) {
521                         ptr[0] = (option >> 8);
522                         ptr[1] = option;
523                         ptr += 2;
524                 }
525         }
526
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);
532         } else
533                 ptr = start;
534
535 #if ENABLE_FEATURE_UDHCPC6_RFC4704
536         ptr = mempcpy(ptr, &opt_fqdn_req, sizeof(opt_fqdn_req));
537 #endif
538         /* Add -x options if any */
539         curr = client_data.options;
540         while (curr) {
541                 len = (curr->data[D6_OPT_LEN] << 8) | curr->data[D6_OPT_LEN + 1];
542                 ptr = mempcpy(ptr, curr->data, D6_OPT_DATA + len);
543                 curr = curr->next;
544         }
545
546         return ptr;
547 }
548
549 static int d6_mcast_from_client_data_ifindex(struct d6_packet *packet, uint8_t *end)
550 {
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,
555         };
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,
559         };
560
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,
565                 client_data.ifindex
566         );
567 }
568
569 /* RFC 3315 18.1.5. Creation and Transmission of Information-request Messages
570  *
571  * The client uses an Information-request message to obtain
572  * configuration information without having addresses assigned to it.
573  *
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.
577  *
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
584  * authenticated.
585  *
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.
590  */
591 /* NOINLINE: limit stack usage in caller */
592 static NOINLINE int send_d6_info_request(uint32_t xid)
593 {
594         struct d6_packet packet;
595         uint8_t *opt_ptr;
596
597         /* Fill in: msg type, client id */
598         opt_ptr = init_d6_packet(&packet, D6_MSG_INFORMATION_REQUEST, xid);
599
600         /* Add options:
601          * "param req" option according to -O, options specified with -x
602          */
603         opt_ptr = add_d6_client_options(opt_ptr);
604
605         bb_error_msg("sending %s", "info request");
606         return d6_mcast_from_client_data_ifindex(&packet, opt_ptr);
607 }
608
609 /* Milticast a DHCPv6 Solicit packet to the network, with an optionally requested IP.
610  *
611  * RFC 3315 17.1.1. Creation of Solicit Messages
612  *
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. ...
618  *
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.
623  *
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
629  * returned.
630  *
631  * The client includes a Reconfigure Accept option (see section 22.20)
632  * if the client is willing to accept Reconfigure messages from the
633  * server.
634       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
635       |        OPTION_CLIENTID        |          option-len           |
636       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
637       .                                                               .
638       .                              DUID                             .
639       .                        (variable length)                      .
640       .                                                               .
641       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
642
643
644       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
645       |          OPTION_IA_NA         |          option-len           |
646       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
647       |                        IAID (4 octets)                        |
648       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
649       |                              T1                               |
650       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
651       |                              T2                               |
652       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
653       |                                                               |
654       .                         IA_NA-options                         .
655       .                                                               .
656       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
657
658
659       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
660       |          OPTION_IAADDR        |          option-len           |
661       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
662       |                                                               |
663       |                         IPv6 address                          |
664       |                                                               |
665       |                                                               |
666       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
667       |                      preferred-lifetime                       |
668       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
669       |                        valid-lifetime                         |
670       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
671       .                                                               .
672       .                        IAaddr-options                         .
673       .                                                               .
674       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
675
676
677       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
678       |           OPTION_ORO          |           option-len          |
679       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
680       |    requested-option-code-1    |    requested-option-code-2    |
681       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
682       |                              ...                              |
683       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
684
685
686       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
687       |     OPTION_RECONF_ACCEPT      |               0               |
688       +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
689  */
690 /* NOINLINE: limit stack usage in caller */
691 static NOINLINE int send_d6_discover(uint32_t xid, struct in6_addr *requested_ipv6)
692 {
693         struct d6_packet packet;
694         uint8_t *opt_ptr;
695         unsigned len;
696
697         /* Fill in: msg type, client id */
698         opt_ptr = init_d6_packet(&packet, D6_MSG_SOLICIT, xid);
699
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);
714                 }
715                 opt_ptr = mempcpy(opt_ptr, client6_data.ia_na, len);
716         }
717
718         /* IA_PD */
719         free(client6_data.ia_pd);
720         client6_data.ia_pd = NULL;
721         if (option_mask32 & OPT_d) {
722                 len = 2+2+4+4+4;
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);
728         }
729
730         /* Add options:
731          * "param req" option according to -O, options specified with -x
732          */
733         opt_ptr = add_d6_client_options(opt_ptr);
734
735         bb_info_msg("sending %s", "discover");
736         return d6_mcast_from_client_data_ifindex(&packet, opt_ptr);
737 }
738
739 /* Multicast a DHCPv6 request message
740  *
741  * RFC 3315 18.1.1. Creation and Transmission of Request Messages
742  *
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.
748  *
749  * The client generates a transaction ID and inserts this value in the
750  * "transaction-id" field.
751  *
752  * The client places the identifier of the destination server in a
753  * Server Identifier option.
754  *
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).
759  *
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.
764  *
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.
768  */
769 /* NOINLINE: limit stack usage in caller */
770 static NOINLINE int send_d6_select(uint32_t xid)
771 {
772         struct d6_packet packet;
773         uint8_t *opt_ptr;
774
775         /* Fill in: msg type, client id */
776         opt_ptr = init_d6_packet(&packet, D6_MSG_REQUEST, xid);
777
778         /* server id */
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);
783         /* IA PD */
784         if (client6_data.ia_pd)
785                 opt_ptr = mempcpy(opt_ptr, client6_data.ia_pd, client6_data.ia_pd->len + 2+2);
786
787         /* Add options:
788          * "param req" option according to -O, options specified with -x
789          */
790         opt_ptr = add_d6_client_options(opt_ptr);
791
792         bb_info_msg("sending %s", "select");
793         return d6_mcast_from_client_data_ifindex(&packet, opt_ptr);
794 }
795
796 /* Unicast or broadcast a DHCP renew message
797  *
798  * RFC 3315 18.1.3. Creation and Transmission of Renew Messages
799  *
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
809  * zero.
810  *
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.
814  *
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.
819  *
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.
823  *
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"
826  * field.
827  *
828  * The client places the identifier of the destination server in a
829  * Server Identifier option.
830  *
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
835  * Renew message.
836  *
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.
841  */
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)
844 {
845         struct d6_packet packet;
846         uint8_t *opt_ptr;
847
848         /* Fill in: msg type, client id */
849         opt_ptr = init_d6_packet(&packet, DHCPREQUEST, xid);
850
851         /* server id */
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);
856         /* IA PD */
857         if (client6_data.ia_pd)
858                 opt_ptr = mempcpy(opt_ptr, client6_data.ia_pd, client6_data.ia_pd->len + 2+2);
859
860         /* Add options:
861          * "param req" option according to -O, options specified with -x
862          */
863         opt_ptr = add_d6_client_options(opt_ptr);
864
865         bb_info_msg("sending %s", "renew");
866         if (server_ipv6)
867                 return d6_send_kernel_packet(
868                         &packet, (opt_ptr - (uint8_t*) &packet),
869                         our_cur_ipv6, CLIENT_PORT6,
870                         server_ipv6, SERVER_PORT6,
871                         client_data.ifindex
872                 );
873         return d6_mcast_from_client_data_ifindex(&packet, opt_ptr);
874 }
875
876 /* Unicast a DHCP release message */
877 static
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)
880 {
881         struct d6_packet packet;
882         uint8_t *opt_ptr;
883
884         /* Fill in: msg type, client id */
885         opt_ptr = init_d6_packet(&packet, D6_MSG_RELEASE, random_xid());
886         /* server id */
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);
891         /* IA PD */
892         if (client6_data.ia_pd)
893                 opt_ptr = mempcpy(opt_ptr, client6_data.ia_pd, client6_data.ia_pd->len + 2+2);
894
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,
900                 client_data.ifindex
901         );
902 }
903
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)
907 {
908         int bytes;
909         struct ip6_udp_d6_packet packet;
910
911         bytes = safe_read(fd, &packet, sizeof(packet));
912         if (bytes < 0) {
913                 log1s("packet read error, ignoring");
914                 /* NB: possible down interface, etc. Caller should pause. */
915                 return bytes; /* returns -1 */
916         }
917
918         if (bytes < (int) (sizeof(packet.ip6) + sizeof(packet.udp))) {
919                 log1s("packet is too short, ignoring");
920                 return -2;
921         }
922
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");
926                 return -2;
927         }
928
929         /* ignore any extra garbage bytes */
930         bytes = sizeof(packet.ip6) + ntohs(packet.ip6.ip6_plen);
931
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
938         ) {
939                 log1s("unrelated/bogus packet, ignoring");
940                 return -2;
941         }
942
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");
952 //              return -2;
953 //      }
954
955         if (peer_ipv6)
956                 *peer_ipv6 = packet.ip6.ip6_src; /* struct copy */
957
958         log1("received %s", "a packet");
959         d6_dump_packet(&packet.data);
960
961         bytes -= sizeof(packet.ip6) + sizeof(packet.udp);
962         memcpy(d6_pkt, &packet.data, bytes);
963         return bytes;
964 }
965
966 /*** Main ***/
967
968 /* Values for client_data.listen_mode */
969 #define LISTEN_NONE   0
970 #define LISTEN_KERNEL 1
971 #define LISTEN_RAW    2
972
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 */
977 #define REQUESTING      1
978 /* select/renew was sent, DHCPACK reply received */
979 #define BOUND           2
980 /* half of lease passed, want to renew it by sending unicast renew requests */
981 #define RENEWING        3
982 /* renew requests were not answered, lease is almost over, send broadcast renew */
983 #define REBINDING       4
984 /* manually requested renew (SIGUSR1) */
985 #define RENEW_REQUESTED 5
986 /* release, possibly manually requested (SIGUSR2) */
987 #define RELEASED        6
988
989 static int d6_raw_socket(int ifindex)
990 {
991         int fd;
992         struct sockaddr_ll sock;
993
994         /*
995          * Comment:
996          *
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.
1000          *
1001          * and filter shamelessly stolen from:
1002          *
1003          *      http://www.flamewarmaster.de/software/dhcpclient/
1004          *
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.
1009          *
1010          * Copyright: 2006, 2007 Stefan Rompf <sux@loplof.de>.
1011          * License: GPL v2.
1012          *
1013          * TODO: make conditional?
1014          */
1015 #if 0
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),
1035         };
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,
1040         };
1041 #endif
1042
1043         log2("opening raw socket on ifindex %d", ifindex);
1044
1045         fd = xsocket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IPV6));
1046         log3("got raw socket fd %d", fd);
1047
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));
1057
1058 #if 0
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?
1065         }
1066 #endif
1067
1068         log1s("created raw socket");
1069
1070         return fd;
1071 }
1072
1073 static void change_listen_mode(int new_mode)
1074 {
1075         log1("entering listen mode: %s",
1076                 new_mode != LISTEN_NONE
1077                         ? (new_mode == LISTEN_KERNEL ? "kernel" : "raw")
1078                         : "none"
1079         );
1080
1081         client_data.listen_mode = new_mode;
1082         if (client_data.sockfd >= 0) {
1083                 close(client_data.sockfd);
1084                 client_data.sockfd = -1;
1085         }
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 */
1091 }
1092
1093 /* Called only on SIGUSR1 */
1094 static void perform_renew(void)
1095 {
1096         bb_simple_info_msg("performing DHCP renew");
1097         switch (client_data.state) {
1098         case BOUND:
1099                 change_listen_mode(LISTEN_KERNEL);
1100         case RENEWING:
1101         case REBINDING:
1102                 client_data.state = RENEW_REQUESTED;
1103                 break;
1104         case RENEW_REQUESTED: /* impatient are we? fine, square 1 */
1105                 d6_run_script_no_option("deconfig");
1106         case REQUESTING:
1107         case RELEASED:
1108                 change_listen_mode(LISTEN_RAW);
1109                 client_data.state = INIT_SELECTING;
1110                 break;
1111         case INIT_SELECTING:
1112                 break;
1113         }
1114 }
1115
1116 static void perform_d6_release(struct in6_addr *server_ipv6, struct in6_addr *our_cur_ipv6)
1117 {
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
1123         ) {
1124                 bb_simple_info_msg("unicasting a release");
1125                 send_d6_release(server_ipv6, our_cur_ipv6); /* unicast */
1126         }
1127         bb_simple_info_msg("entering released state");
1128 /*
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.
1133  */
1134         d6_run_script_no_option("deconfig");
1135         change_listen_mode(LISTEN_NONE);
1136         client_data.state = RELEASED;
1137 }
1138
1139 ///static uint8_t* alloc_dhcp_option(int code, const char *str, int extra)
1140 ///{
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);
1147 ///     return storage;
1148 ///}
1149
1150 #if BB_MMU
1151 static void client_background(void)
1152 {
1153         bb_daemonize(0);
1154         logmode &= ~LOGMODE_STDIO;
1155         /* rewrite pidfile, as our pid is different now */
1156         write_pidfile(client_data.pidfile);
1157 }
1158 #endif
1159
1160 //usage:#if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
1161 //usage:# define IF_UDHCP_VERBOSE(...) __VA_ARGS__
1162 //usage:#else
1163 //usage:# define IF_UDHCP_VERBOSE(...)
1164 //usage:#endif
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"
1179 //usage:        )
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)"
1186 //usage:        )
1187 ////usage:      IF_FEATURE_UDHCPC_ARPING(
1188 ////usage:     "\n      -a              Use arping to validate offered address"
1189 ////usage:      )
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"
1204 //usage:        )
1205 //usage:     "\nSignals:"
1206 //usage:     "\n        USR1    Renew lease"
1207 //usage:     "\n        USR2    Release lease"
1208
1209 int udhcpc6_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1210 int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
1211 {
1212         const char *str_r;
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;
1223         uint32_t xid = 0;
1224         int packet_num;
1225         int timeout; /* must be signed */
1226         unsigned already_waited_sec;
1227         unsigned opt;
1228         int retval;
1229
1230         setup_common_bufsiz();
1231         /* We want random_xid to be random */
1232         srand(monotonic_us());
1233
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;
1240
1241         /* Make sure fd 0,1,2 are open */
1242         /* Set up the signal pipe on fds 3,4 - must be before openlog() */
1243         udhcp_sp_setup();
1244
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"
1249                 USE_FOR_MMU("b")
1250                 ///IF_FEATURE_UDHCPC_ARPING("a")
1251                 IF_FEATURE_UDHCP_PORT("P:")
1252                 "v"
1253                 "\0" IF_UDHCP_VERBOSE("vv") /* -v is a counter */
1254                 , udhcpc6_longopts
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 */
1258                 , &list_O
1259                 , &list_x
1260                 IF_FEATURE_UDHCP_PORT(, &str_P)
1261                 IF_UDHCP_VERBOSE(, &dhcp_verbose)
1262         );
1263         requested_ipv6 = NULL;
1264         option_mask32 |= OPT_r;
1265         if (opt & OPT_l) {
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;
1272                 } else {
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;
1276                 }
1277         }
1278
1279 #if ENABLE_FEATURE_UDHCP_PORT
1280         if (opt & OPT_P) {
1281                 CLIENT_PORT6 = xatou16(str_P);
1282                 SERVER_PORT6 = CLIENT_PORT6 + 1;
1283         }
1284 #endif
1285         while (list_O) {
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;
1291                 }
1292                 client_data.opt_mask[n >> 3] |= 1 << (n & 7);
1293         }
1294         if (!(opt & OPT_o)) {
1295                 unsigned i, n;
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);
1299                         }
1300                 }
1301         }
1302         while (list_x) {
1303                 char *optstr = xstrdup(llist_pop(&list_x));
1304                 udhcp_str2optset(optstr, &client_data.options,
1305                                 d6_optflags, d6_option_strings,
1306                                 /*dhcpv6:*/ 1
1307                 );
1308                 free(optstr);
1309         }
1310
1311         if (d6_read_interface(client_data.interface,
1312                         &client_data.ifindex,
1313                         &client6_data.ll_ip6,
1314                         client_data.client_mac)
1315         ) {
1316                 return 1;
1317         }
1318
1319         /* Create client ID based on mac, set clientid_mac_ptr */
1320         {
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;
1330         }
1331
1332 #if !BB_MMU
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;
1337         }
1338 #endif
1339         if (opt & OPT_S) {
1340                 openlog(applet_name, LOG_PID, LOG_DAEMON);
1341                 logmode |= LOGMODE_SYSLOG;
1342         }
1343
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);
1348
1349         client_data.state = INIT_SELECTING;
1350         d6_run_script_no_option("deconfig");
1351         change_listen_mode(LISTEN_RAW);
1352         packet_num = 0;
1353         timeout = 0;
1354         already_waited_sec = 0;
1355
1356         /* Main event loop. select() waits on signal pipe and possibly
1357          * on sockfd.
1358          * "continue" statements in code below jump to the top of the loop.
1359          */
1360         for (;;) {
1361                 int tv;
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;
1367
1368                 //bb_error_msg("sockfd:%d, listen_mode:%d", client_data.sockfd, client_data.listen_mode);
1369
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:"). */
1376
1377                 udhcp_sp_fd_set(pfds, client_data.sockfd);
1378
1379                 tv = timeout - already_waited_sec;
1380                 retval = 0;
1381                 /* If we already timed out, fall through with retval = 0, else... */
1382                 if (tv > 0) {
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);
1386                         if (retval < 0) {
1387                                 /* EINTR? A signal was caught, don't panic */
1388                                 if (errno == EINTR) {
1389                                         already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
1390                                         continue;
1391                                 }
1392                                 /* Else: an error occured, panic! */
1393                                 bb_simple_perror_msg_and_die("poll");
1394                         }
1395                 }
1396
1397                 /* If timeout dropped to zero, time to become active:
1398                  * resend discover/renew/whatever
1399                  */
1400                 if (retval == 0) {
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:
1405                          */
1406                         if (d6_read_interface(client_data.interface,
1407                                         &client_data.ifindex,
1408                                         &client6_data.ll_ip6,
1409                                         client_data.client_mac)
1410                         ) {
1411                                 goto ret0; /* iface is gone? */
1412                         }
1413
1414                         memcpy(clientid_mac_ptr, client_data.client_mac, 6);
1415
1416                         /* We will restart the wait in any case */
1417                         already_waited_sec = 0;
1418
1419                         switch (client_data.state) {
1420                         case INIT_SELECTING:
1421                                 if (!discover_retries || packet_num < discover_retries) {
1422                                         if (packet_num == 0)
1423                                                 xid = random_xid();
1424                                         /* multicast */
1425                                         if (opt & OPT_l)
1426                                                 send_d6_info_request(xid);
1427                                         else
1428                                                 send_d6_discover(xid, requested_ipv6);
1429                                         timeout = discover_timeout;
1430                                         packet_num++;
1431                                         continue;
1432                                 }
1433  leasefail:
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
1445                                          * _and not exit_.
1446                                          */
1447                                 } else
1448 #endif
1449                                 if (opt & OPT_n) { /* abort if no lease */
1450                                         bb_simple_info_msg("no lease, failing");
1451                                         retval = 1;
1452                                         goto ret;
1453                                 }
1454                                 /* wait before trying again */
1455                                 timeout = tryagain_timeout;
1456                                 packet_num = 0;
1457                                 continue;
1458                         case REQUESTING:
1459                                 if (!discover_retries || packet_num < discover_retries) {
1460                                         /* send multicast select packet */
1461                                         send_d6_select(xid);
1462                                         timeout = discover_timeout;
1463                                         packet_num++;
1464                                         continue;
1465                                 }
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;
1472                                 goto leasefail;
1473                         case BOUND:
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:
1482                         case RENEWING:
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.
1492                          */
1493                                         if (opt & OPT_l)
1494                                                 send_d6_info_request(xid);
1495                                         else
1496                                                 send_d6_renew(xid, &srv6_buf, requested_ipv6);
1497                                         timeout >>= 1;
1498                                         continue;
1499                                 }
1500                                 /* Timed out, enter rebinding state */
1501                                 log1s("entering rebinding state");
1502                                 client_data.state = REBINDING;
1503                                 /* fall right through */
1504                         case REBINDING:
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 */
1509                                 if (timeout > 0) {
1510                                         if (opt & OPT_l)
1511                                                 send_d6_info_request(xid);
1512                                         else /* send a broadcast renew request */
1513                                                 send_d6_renew(xid, /*server_ipv6:*/ NULL, requested_ipv6);
1514                                         timeout >>= 1;
1515                                         continue;
1516                                 }
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 */
1523                                 packet_num = 0;
1524                                 continue;
1525                         /* case RELEASED: */
1526                         }
1527                         /* yah, I know, *you* say it would never happen */
1528                         timeout = INT_MAX;
1529                         continue; /* back to main loop */
1530                 } /* if poll timed out */
1531
1532                 /* poll() didn't timeout, something happened */
1533
1534                 /* Is it a signal? */
1535                 switch (udhcp_sp_read()) {
1536                 case SIGUSR1:
1537                         client_data.first_secs = 0; /* make secs field count from 0 */
1538                         already_waited_sec = 0;
1539                         perform_renew();
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.
1548                                  */
1549                                 if (timeout > 60)
1550                                         timeout = 60;
1551                                 goto case_RENEW_REQUESTED;
1552                         }
1553                         /* Start things over */
1554                         packet_num = 0;
1555                         /* Kill any timeouts, user wants this to hurry along */
1556                         timeout = 0;
1557                         continue;
1558                 case SIGUSR2:
1559                         perform_d6_release(&srv6_buf, requested_ipv6);
1560                         timeout = INT_MAX;
1561                         continue;
1562                 case SIGTERM:
1563                         bb_info_msg("received %s", "SIGTERM");
1564                         goto ret0;
1565                 }
1566
1567                 /* Is it a packet? */
1568                 if (!pfds[1].revents)
1569                         continue; /* no */
1570
1571                 {
1572                         int len;
1573
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);
1577                         else
1578                                 len = d6_recv_raw_packet(&srv6_buf, &packet, client_data.sockfd);
1579                         if (len == -1) {
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 */
1584                         }
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;
1589                         if (len < 0)
1590                                 continue;
1591                         packet_end = (uint8_t*)&packet + len;
1592                 }
1593
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);
1597                         continue;
1598                 }
1599
1600                 switch (client_data.state) {
1601                 case INIT_SELECTING:
1602                         if (packet.d6_msg_type == D6_MSG_ADVERTISE)
1603                                 goto type_is_ok;
1604                         /* DHCPv6 has "Rapid Commit", when instead of Advertise,
1605                          * server sends Reply right away.
1606                          * Fall through to check for this case.
1607                          */
1608                 case REQUESTING:
1609                 case RENEWING:
1610                 case RENEW_REQUESTED:
1611                 case REBINDING:
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;
1617  type_is_ok:
1618                                 address_timeout = 0;
1619                                 prefix_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,
1625                                                         packet_end, "nak");
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;
1633                                         timeout = 0;
1634                                         packet_num = 0;
1635                                         already_waited_sec = 0;
1636                                         continue;
1637                                 }
1638                                 option = d6_copy_option(packet.d6_options, packet_end, D6_OPT_SERVERID);
1639                                 if (!option) {
1640                                         bb_simple_info_msg("no server ID, ignoring packet");
1641                                         continue;
1642                                         /* still selecting - this server looks bad */
1643                                 }
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;
1652                                         timeout = 0;
1653                                         packet_num = 0;
1654                                         already_waited_sec = 0;
1655                                         continue;
1656                                 }
1657                                 /* It's a D6_MSG_REPLY */
1658 /*
1659  * RFC 3315 18.1.8. Receipt of Reply Messages
1660  *
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
1666  * message.
1667  *
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.
1673  *
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:
1678  *
1679  * -  Record T1 and T2 times.
1680  *
1681  * -  Add any new addresses in the IA option to the IA as recorded by
1682  *    the client.
1683  *
1684  * -  Update lifetimes for any addresses in the IA option that the
1685  *    client already has recorded in the IA.
1686  *
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.
1689  *
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
1692  *    server.
1693  *
1694  * Management of the specific configuration information is detailed in
1695  * the definition of each option in section 22.
1696  *
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.
1704  *
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.
1710  *
1711  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1712  * |          OPTION_IA_NA         |          option-len           |
1713  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1714  * |                        IAID (4 octets)                        |
1715  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1716  * |                              T1                               |
1717  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1718  * |                              T2                               |
1719  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1720  * |                                                               |
1721  * .                         IA_NA-options                         .
1722  * .                                                               .
1723  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1724  *
1725  *
1726  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1727  * |          OPTION_IAADDR        |          option-len           |
1728  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1729  * |                                                               |
1730  * |                         IPv6 address                          |
1731  * |                                                               |
1732  * |                                                               |
1733  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1734  * |                      preferred-lifetime                       |
1735  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1736  * |                        valid-lifetime                         |
1737  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1738  * .                                                               .
1739  * .                        IAaddr-options                         .
1740  * .                                                               .
1741  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1742  */
1743                                 if (option_mask32 & OPT_r) {
1744                                         struct d6_option *iaaddr;
1745
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");
1750                                                 continue;
1751                                         }
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);
1755                                                 continue;
1756                                         }
1757                                         iaaddr = d6_find_option(client6_data.ia_na->data + 4 + 4 + 4,
1758                                                         client6_data.ia_na->data + client6_data.ia_na->len,
1759                                                         D6_OPT_IAADDR
1760                                         );
1761                                         if (!iaaddr) {
1762                                                 bb_info_msg("no %s option, ignoring packet", "IAADDR");
1763                                                 continue;
1764                                         }
1765                                         if (iaaddr->len < (16 + 4 + 4)) {
1766                                                 bb_info_msg("%s option is too short:%d bytes",
1767                                                         "IAADDR", iaaddr->len);
1768                                                 continue;
1769                                         }
1770                                         /* Note: the address is sufficiently aligned for cast:
1771                                          * we _copied_ IA-NA, and copy is always well-aligned.
1772                                          */
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;
1780                                 }
1781                                 if (option_mask32 & OPT_d) {
1782                                         struct d6_option *iaprefix;
1783
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");
1788                                                 continue;
1789                                         }
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);
1793                                                 continue;
1794                                         }
1795                                         iaprefix = d6_find_option(client6_data.ia_pd->data + 4 + 4 + 4,
1796                                                         client6_data.ia_pd->data + client6_data.ia_pd->len,
1797                                                         D6_OPT_IAPREFIX
1798                                         );
1799                                         if (!iaprefix) {
1800                                                 bb_info_msg("no %s option, ignoring packet", "IAPREFIX");
1801                                                 continue;
1802                                         }
1803                                         if (iaprefix->len < (4 + 4 + 1 + 16)) {
1804                                                 bb_info_msg("%s option is too short:%d bytes",
1805                                                         "IAPREFIX", iaprefix->len);
1806                                                 continue;
1807                                         }
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;
1813                                 }
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;
1820                                 if (opt & OPT_l) {
1821                                         /* TODO: request OPTION_INFORMATION_REFRESH_TIME (32)
1822                                          * and use its value instead of the default 1 day.
1823                                          */
1824                                         timeout = 24 * 60 * 60;
1825                                 }
1826                                 /* paranoia: must not be too small */
1827                                 /* timeout > 60 - ensures at least one unicast renew attempt */
1828                                 if (timeout < 61)
1829                                         timeout = 61;
1830                                 /* enter bound state */
1831                                 d6_run_script(packet.d6_options, packet_end,
1832                                         (client_data.state == REQUESTING ? "bound" : "renew"));
1833
1834                                 client_data.state = BOUND;
1835                                 change_listen_mode(LISTEN_NONE);
1836                                 if (opt & OPT_q) { /* quit after lease */
1837                                         goto ret0;
1838                                 }
1839                                 /* future renew failures should not exit (JM) */
1840                                 opt &= ~OPT_n;
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);
1846                                 }
1847 #endif
1848                                 already_waited_sec = 0;
1849                                 continue; /* back to main loop */
1850                         }
1851                         continue;
1852                 /* case BOUND: - ignore all packets */
1853                 /* case RELEASED: - ignore all packets */
1854                 }
1855                 /* back to main loop */
1856         } /* for (;;) - main loop ends */
1857
1858  ret0:
1859         if (opt & OPT_R) /* release on quit */
1860                 perform_d6_release(&srv6_buf, requested_ipv6);
1861         retval = 0;
1862  ret:
1863         /*if (client_data.pidfile) - remove_pidfile has its own check */
1864                 remove_pidfile(client_data.pidfile);
1865         return retval;
1866 }