blob: 289df66ee630b220202b071b3ceb776f8c57d3ca [file] [log] [blame]
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001/* vi: set sw=4 ts=4: */
2/*
3 * DHCPv6 client.
4 *
Denys Vlasenkoba4fbca2017-06-28 19:18:17 +02005 * WARNING: THIS CODE IS INCOMPLETE.
Denys Vlasenko9ba75042011-11-07 15:55:39 +01006 *
Denys Vlasenkoba4fbca2017-06-28 19:18:17 +02007 * Copyright (C) 2011-2017 Denys Vlasenko.
Denys Vlasenko9ba75042011-11-07 15:55:39 +01008 *
9 * Licensed under GPLv2, see file LICENSE in this source tree.
10 */
Denys Vlasenko9ba75042011-11-07 15:55:39 +010011//config:config UDHCPC6
Denys Vlasenko68b653b2017-07-27 10:53:09 +020012//config: bool "udhcpc6"
Mike Frysinger3da46c82012-05-02 21:45:35 -040013//config: default n # not yet ready
14//config: depends on FEATURE_IPV6
15//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +020016//config: udhcpc6 is a DHCPv6 client
Denys Vlasenkoba4fbca2017-06-28 19:18:17 +020017//config:
18//config:config FEATURE_UDHCPC6_RFC3646
19//config: bool "Support RFC 3646 (DNS server and search list)"
20//config: default y
21//config: depends on UDHCPC6
22//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +020023//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".
Denys Vlasenkoba4fbca2017-06-28 19:18:17 +020026//config:
27//config:config FEATURE_UDHCPC6_RFC4704
28//config: bool "Support RFC 4704 (Client FQDN)"
29//config: default y
30//config: depends on UDHCPC6
31//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +020032//config: You can request FQDN to be given by server using "-O fqdn".
Denys Vlasenkoba4fbca2017-06-28 19:18:17 +020033//config:
34//config:config FEATURE_UDHCPC6_RFC4833
35//config: bool "Support RFC 4833 (Timezones)"
36//config: default y
37//config: depends on UDHCPC6
38//config: help
Denys Vlasenko72089cf2017-07-21 09:50:55 +020039//config: You can request POSIX timezone with "-O tz" and timezone name
40//config: with "-O timezone".
Denys Vlasenko9ba75042011-11-07 15:55:39 +010041
42//applet:IF_UDHCPC6(APPLET(udhcpc6, BB_DIR_USR_BIN, BB_SUID_DROP))
43
Denys Vlasenko8cab6672012-04-20 14:48:00 +020044//kbuild:lib-$(CONFIG_UDHCPC6) += d6_dhcpc.o d6_packet.o d6_socket.o common.o socket.o signalpipe.o
Denys Vlasenkoba4fbca2017-06-28 19:18:17 +020045//kbuild:lib-$(CONFIG_FEATURE_UDHCPC6_RFC3646) += domain_codec.o
46//kbuild:lib-$(CONFIG_FEATURE_UDHCPC6_RFC4704) += domain_codec.o
Denys Vlasenko9ba75042011-11-07 15:55:39 +010047
48#include <syslog.h>
49/* Override ENABLE_FEATURE_PIDFILE - ifupdown needs our pidfile to always exist */
50#define WANT_PIDFILE 1
51#include "common.h"
52#include "dhcpd.h"
53#include "dhcpc.h"
54#include "d6_common.h"
55
56#include <netinet/if_ether.h>
57#include <netpacket/packet.h>
58#include <linux/filter.h>
59
60/* "struct client_config_t client_config" is in bb_common_bufsiz1 */
61
Denys Vlasenkoba4fbca2017-06-28 19:18:17 +020062static 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 },
66#endif
67#if ENABLE_FEATURE_UDHCPC6_RFC4704
68 { OPTION_DNS_STRING, D6_OPT_CLIENT_FQDN },
69#endif
70#if ENABLE_FEATURE_UDHCPC6_RFC4833
71 { OPTION_STRING, D6_OPT_TZ_POSIX },
72 { OPTION_STRING, D6_OPT_TZ_NAME },
73#endif
74 { 0, 0 }
75};
76/* Must match d6_optflags[] order */
77static 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 */
81#endif
82#if ENABLE_FEATURE_UDHCPC6_RFC4704
83 "fqdn" "\0" /* D6_OPT_CLIENT_FQDN */
84#endif
85#if ENABLE_FEATURE_UDHCPC6_RFC4833
86 "tz" "\0" /* D6_OPT_TZ_POSIX */
87 "timezone" "\0" /* D6_OPT_TZ_NAME */
88#endif
89 "\0";
Denys Vlasenko9ba75042011-11-07 15:55:39 +010090
91#if ENABLE_LONG_OPTS
Denys Vlasenko7e21f042011-11-08 11:39:41 +010092static const char udhcpc6_longopts[] ALIGN1 =
Denys Vlasenko9ba75042011-11-07 15:55:39 +010093 "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"
Denys Vlasenkoef5207f2018-01-16 21:39:14 +010099 "requestprefix\0" No_argument "d"
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100100 "script\0" Required_argument "s"
101 "timeout\0" Required_argument "T"
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100102 "retries\0" Required_argument "t"
103 "tryagain\0" Required_argument "A"
104 "syslog\0" No_argument "S"
105 "request-option\0" Required_argument "O"
106 "no-default-options\0" No_argument "o"
107 "foreground\0" No_argument "f"
Denys Vlasenkoed820cc2017-05-08 15:11:02 +0200108 USE_FOR_MMU(
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100109 "background\0" No_argument "b"
Denys Vlasenkoed820cc2017-05-08 15:11:02 +0200110 )
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100111/// IF_FEATURE_UDHCPC_ARPING("arping\0" No_argument "a")
112 IF_FEATURE_UDHCP_PORT("client-port\0" Required_argument "P")
113 ;
114#endif
115/* Must match getopt32 option string order */
116enum {
117 OPT_i = 1 << 0,
118 OPT_n = 1 << 1,
119 OPT_p = 1 << 2,
120 OPT_q = 1 << 3,
121 OPT_R = 1 << 4,
122 OPT_r = 1 << 5,
123 OPT_s = 1 << 6,
124 OPT_T = 1 << 7,
125 OPT_t = 1 << 8,
126 OPT_S = 1 << 9,
127 OPT_A = 1 << 10,
128 OPT_O = 1 << 11,
129 OPT_o = 1 << 12,
130 OPT_x = 1 << 13,
131 OPT_f = 1 << 14,
Denys Vlasenkoef5207f2018-01-16 21:39:14 +0100132 OPT_d = 1 << 15,
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100133/* The rest has variable bit positions, need to be clever */
Denys Vlasenkoef5207f2018-01-16 21:39:14 +0100134 OPTBIT_d = 15,
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100135 USE_FOR_MMU( OPTBIT_b,)
136 ///IF_FEATURE_UDHCPC_ARPING(OPTBIT_a,)
137 IF_FEATURE_UDHCP_PORT( OPTBIT_P,)
138 USE_FOR_MMU( OPT_b = 1 << OPTBIT_b,)
139 ///IF_FEATURE_UDHCPC_ARPING(OPT_a = 1 << OPTBIT_a,)
140 IF_FEATURE_UDHCP_PORT( OPT_P = 1 << OPTBIT_P,)
141};
142
Denys Vlasenkoba4fbca2017-06-28 19:18:17 +0200143#if ENABLE_FEATURE_UDHCPC6_RFC4704
Denys Vlasenko64d58aa2017-03-27 22:22:09 +0200144static const char opt_fqdn_req[] = {
145 (D6_OPT_CLIENT_FQDN >> 8), (D6_OPT_CLIENT_FQDN & 0xff),
Denys Vlasenko470bebe2017-06-27 18:31:08 +0200146 0, 2, /* optlen */
147 0, /* flags: */
148 /* S=0: server SHOULD NOT perform AAAA RR updates */
149 /* O=0: client MUST set this bit to 0 */
150 /* N=0: server SHOULD perform updates (PTR RR only in our case, since S=0) */
151 0 /* empty DNS-encoded name */
Denys Vlasenko64d58aa2017-03-27 22:22:09 +0200152};
Denys Vlasenkoba4fbca2017-06-28 19:18:17 +0200153#endif
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100154
155/*** Utility functions ***/
156
157static void *d6_find_option(uint8_t *option, uint8_t *option_end, unsigned code)
158{
159 /* "length minus 4" */
160 int len_m4 = option_end - option - 4;
161 while (len_m4 >= 0) {
162 /* Next option's len is too big? */
Denys Vlasenko68c5b282011-11-07 16:21:24 +0100163 if (option[3] > len_m4)
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100164 return NULL; /* yes. bogus packet! */
165 /* So far we treat any opts with code >255
166 * or len >255 as bogus, and stop at once.
167 * This simplifies big-endian handling.
168 */
Denys Vlasenko68c5b282011-11-07 16:21:24 +0100169 if (option[0] != 0 || option[2] != 0)
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100170 return NULL;
171 /* Option seems to be valid */
172 /* Does its code match? */
Denys Vlasenko68c5b282011-11-07 16:21:24 +0100173 if (option[1] == code)
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100174 return option; /* yes! */
Denys Vlasenko68c5b282011-11-07 16:21:24 +0100175 len_m4 -= option[3] + 4;
Denys Vlasenko64d58aa2017-03-27 22:22:09 +0200176 option += option[3] + 4;
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100177 }
178 return NULL;
179}
180
181static void *d6_copy_option(uint8_t *option, uint8_t *option_end, unsigned code)
182{
183 uint8_t *opt = d6_find_option(option, option_end, code);
184 if (!opt)
185 return opt;
Ron Yorstond840c5d2015-07-19 23:05:20 +0200186 return xmemdup(opt, opt[3] + 4);
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100187}
188
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100189
190/*** Script execution code ***/
191
Denys Vlasenkoa092a892011-11-16 20:17:12 +0100192static char** new_env(void)
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100193{
Denys Vlasenkoa092a892011-11-16 20:17:12 +0100194 client6_data.env_ptr = xrealloc_vector(client6_data.env_ptr, 3, client6_data.env_idx);
195 return &client6_data.env_ptr[client6_data.env_idx++];
196}
197
198/* put all the parameters into the environment */
199static void option_to_env(uint8_t *option, uint8_t *option_end)
200{
Denys Vlasenkoba4fbca2017-06-28 19:18:17 +0200201#if ENABLE_FEATURE_UDHCPC6_RFC3646
202 int addrs, option_offset;
203#endif
Denys Vlasenkoab030612017-03-27 22:49:12 +0200204 /* "length minus 4" */
Denys Vlasenkoa092a892011-11-16 20:17:12 +0100205 int len_m4 = option_end - option - 4;
Denys Vlasenkoba4fbca2017-06-28 19:18:17 +0200206
Denys Vlasenkoa092a892011-11-16 20:17:12 +0100207 while (len_m4 >= 0) {
208 uint32_t v32;
209 char ipv6str[sizeof("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")];
210
211 if (option[0] != 0 || option[2] != 0)
212 break;
213
Denys Vlasenko234b82c2017-06-26 19:42:48 +0200214 /* Check if option-length exceeds size of option */
215 if (option[3] > len_m4)
216 break;
217
Denys Vlasenkoa092a892011-11-16 20:17:12 +0100218 switch (option[1]) {
219 //case D6_OPT_CLIENTID:
220 //case D6_OPT_SERVERID:
221 case D6_OPT_IA_NA:
222 case D6_OPT_IA_PD:
223 option_to_env(option + 16, option + 4 + option[3]);
224 break;
225 //case D6_OPT_IA_TA:
226 case D6_OPT_IAADDR:
Denys Vlasenko234b82c2017-06-26 19:42:48 +0200227/* 0 1 2 3
Denys Vlasenkoa092a892011-11-16 20:17:12 +0100228 * 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
229 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
230 * | OPTION_IAADDR | option-len |
231 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
232 * | |
233 * | IPv6 address |
234 * | |
235 * | |
236 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
237 * | preferred-lifetime |
238 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
239 * | valid-lifetime |
240 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
241 */
242 sprint_nip6(ipv6str, option + 4);
243 *new_env() = xasprintf("ipv6=%s", ipv6str);
244
245 move_from_unaligned32(v32, option + 4 + 16 + 4);
246 *new_env() = xasprintf("lease=%u", (unsigned)v32);
247 break;
248
249 //case D6_OPT_ORO:
250 //case D6_OPT_PREFERENCE:
251 //case D6_OPT_ELAPSED_TIME:
252 //case D6_OPT_RELAY_MSG:
253 //case D6_OPT_AUTH:
254 //case D6_OPT_UNICAST:
255 //case D6_OPT_STATUS_CODE:
256 //case D6_OPT_RAPID_COMMIT:
257 //case D6_OPT_USER_CLASS:
258 //case D6_OPT_VENDOR_CLASS:
259 //case D6_OPT_VENDOR_OPTS:
260 //case D6_OPT_INTERFACE_ID:
261 //case D6_OPT_RECONF_MSG:
262 //case D6_OPT_RECONF_ACCEPT:
263
264 case D6_OPT_IAPREFIX:
265/* 0 1 2 3
266 * 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
267 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
268 * | OPTION_IAPREFIX | option-length |
269 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
270 * | preferred-lifetime |
271 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
272 * | valid-lifetime |
273 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
274 * | prefix-length | |
275 * +-+-+-+-+-+-+-+-+ IPv6 prefix |
276 * | (16 octets) |
277 * | |
278 * | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
279 * | |
280 * +-+-+-+-+-+-+-+-+
281 */
Denys Vlasenko688cb3b2018-01-16 16:00:13 +0100282 move_from_unaligned32(v32, option + 4 + 4);
283 *new_env() = xasprintf("ipv6prefix_lease=%u", (unsigned)v32);
Denys Vlasenkoa092a892011-11-16 20:17:12 +0100284
Denys Vlasenko688cb3b2018-01-16 16:00:13 +0100285 sprint_nip6(ipv6str, option + 4 + 4 + 4 + 1);
286 *new_env() = xasprintf("ipv6prefix=%s/%u", ipv6str, (unsigned)(option[4 + 4 + 4]));
Denys Vlasenko64d58aa2017-03-27 22:22:09 +0200287 break;
Denys Vlasenkoba4fbca2017-06-28 19:18:17 +0200288#if ENABLE_FEATURE_UDHCPC6_RFC3646
289 case D6_OPT_DNS_SERVERS: {
290 char *dlist;
291
Denys Vlasenko234b82c2017-06-26 19:42:48 +0200292 /* Make sure payload-size is a multiple of 16 */
293 if ((option[3] & 0x0f) != 0)
294 break;
Denys Vlasenko64d58aa2017-03-27 22:22:09 +0200295
Denys Vlasenko234b82c2017-06-26 19:42:48 +0200296 /* Get the number of addresses on the option */
297 addrs = option[3] >> 4;
Denys Vlasenko64d58aa2017-03-27 22:22:09 +0200298
Denys Vlasenko234b82c2017-06-26 19:42:48 +0200299 /* Setup environment variable */
300 *new_env() = dlist = xmalloc(4 + addrs * 40 - 1);
301 dlist = stpcpy(dlist, "dns=");
302 option_offset = 0;
303
304 while (addrs--) {
305 sprint_nip6(dlist, option + 4 + option_offset);
306 dlist += 39;
307 option_offset += 16;
308 if (addrs)
309 *dlist++ = ' ';
Denys Vlasenko64d58aa2017-03-27 22:22:09 +0200310 }
311
Denys Vlasenko64d58aa2017-03-27 22:22:09 +0200312 break;
Denys Vlasenkoba4fbca2017-06-28 19:18:17 +0200313 }
314 case D6_OPT_DOMAIN_LIST: {
315 char *dlist;
316
Denys Vlasenko64d58aa2017-03-27 22:22:09 +0200317 dlist = dname_dec(option + 4, (option[2] << 8) | option[3], "search=");
318 if (!dlist)
319 break;
320 *new_env() = dlist;
321 break;
Denys Vlasenkoba4fbca2017-06-28 19:18:17 +0200322 }
323#endif
324#if ENABLE_FEATURE_UDHCPC6_RFC4704
325 case D6_OPT_CLIENT_FQDN: {
326 char *dlist;
327
Denys Vlasenko234b82c2017-06-26 19:42:48 +0200328 if (option[3] == 0)
329 break;
330 /* Work around broken ISC DHCPD6.
331 * ISC DHCPD6 does not implement RFC 4704 correctly: It says the first
332 * byte of option-payload should contain flags where the bits 7-3 are
333 * reserved for future use and MUST be zero. Instead ISC DHCPD6 just
334 * writes the entire FQDN as string to option-payload. We assume a
335 * broken server here if any of the reserved bits are set.
336 */
Denys Vlasenko64d58aa2017-03-27 22:22:09 +0200337 if (option[4] & 0xf8) {
Denys Vlasenko234b82c2017-06-26 19:42:48 +0200338 *new_env() = xasprintf("fqdn=%.*s", (int)option[3], (char*)option + 4);
Denys Vlasenko64d58aa2017-03-27 22:22:09 +0200339 break;
340 }
Denys Vlasenko234b82c2017-06-26 19:42:48 +0200341 dlist = dname_dec(option + 5, (/*(option[2] << 8) |*/ option[3]) - 1, "fqdn=");
Denys Vlasenko64d58aa2017-03-27 22:22:09 +0200342 if (!dlist)
343 break;
344 *new_env() = dlist;
345 break;
Denys Vlasenkoba4fbca2017-06-28 19:18:17 +0200346 }
347#endif
348#if ENABLE_FEATURE_UDHCPC6_RFC4833
Denys Vlasenko234b82c2017-06-26 19:42:48 +0200349 /* RFC 4833 Timezones */
350 case D6_OPT_TZ_POSIX:
351 *new_env() = xasprintf("tz=%.*s", (int)option[3], (char*)option + 4);
352 break;
353 case D6_OPT_TZ_NAME:
354 *new_env() = xasprintf("tz_name=%.*s", (int)option[3], (char*)option + 4);
355 break;
Denys Vlasenkoba4fbca2017-06-28 19:18:17 +0200356#endif
Denys Vlasenkoa092a892011-11-16 20:17:12 +0100357 }
Denys Vlasenkoa092a892011-11-16 20:17:12 +0100358 len_m4 -= 4 + option[3];
Denys Vlasenko64d58aa2017-03-27 22:22:09 +0200359 option += 4 + option[3];
Denys Vlasenkoa092a892011-11-16 20:17:12 +0100360 }
361}
362
363static char **fill_envp(struct d6_packet *packet)
364{
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100365 char **envp, **curr;
366
Denys Vlasenkoa092a892011-11-16 20:17:12 +0100367 client6_data.env_ptr = NULL;
368 client6_data.env_idx = 0;
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100369
Denys Vlasenkoa092a892011-11-16 20:17:12 +0100370 *new_env() = xasprintf("interface=%s", client_config.interface);
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100371
Denys Vlasenkoa092a892011-11-16 20:17:12 +0100372 if (packet)
373 option_to_env(packet->d6_options, packet->d6_options + sizeof(packet->d6_options));
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100374
Denys Vlasenkoa092a892011-11-16 20:17:12 +0100375 envp = curr = client6_data.env_ptr;
376 while (*curr)
377 putenv(*curr++);
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100378
379 return envp;
380}
381
382/* Call a script with a par file and env vars */
383static void d6_run_script(struct d6_packet *packet, const char *name)
384{
385 char **envp, **curr;
386 char *argv[3];
387
388 envp = fill_envp(packet);
389
390 /* call script */
Denys Vlasenko8f2e99c2016-03-30 18:41:23 +0200391 log1("executing %s %s", client_config.script, name);
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100392 argv[0] = (char*) client_config.script;
393 argv[1] = (char*) name;
394 argv[2] = NULL;
395 spawn_and_wait(argv);
396
397 for (curr = envp; *curr; curr++) {
398 log2(" %s", *curr);
399 bb_unsetenv_and_free(*curr);
400 }
401 free(envp);
402}
403
404
405/*** Sending/receiving packets ***/
406
407static ALWAYS_INLINE uint32_t random_xid(void)
408{
409 uint32_t t = rand() & htonl(0x00ffffff);
410 return t;
411}
412
413/* Initialize the packet with the proper defaults */
414static uint8_t *init_d6_packet(struct d6_packet *packet, char type, uint32_t xid)
415{
416 struct d6_option *clientid;
417
418 memset(packet, 0, sizeof(*packet));
419
420 packet->d6_xid32 = xid;
421 packet->d6_msg_type = type;
422
423 clientid = (void*)client_config.clientid;
Denys Vlasenko234b82c2017-06-26 19:42:48 +0200424 return mempcpy(packet->d6_options, clientid, clientid->len + 2+2);
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100425}
426
427static uint8_t *add_d6_client_options(uint8_t *ptr)
428{
Denys Vlasenkoba4fbca2017-06-28 19:18:17 +0200429 uint8_t *start = ptr;
430 unsigned option;
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100431
Denys Vlasenkoba4fbca2017-06-28 19:18:17 +0200432 ptr += 4;
433 for (option = 1; option < 256; option++) {
434 if (client_config.opt_mask[option >> 3] & (1 << (option & 7))) {
435 ptr[0] = (option >> 8);
436 ptr[1] = option;
437 ptr += 2;
438 }
439 }
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100440
Denys Vlasenkoba4fbca2017-06-28 19:18:17 +0200441 if ((ptr - start - 4) != 0) {
442 start[0] = (D6_OPT_ORO >> 8);
443 start[1] = D6_OPT_ORO;
444 start[2] = ((ptr - start - 4) >> 8);
445 start[3] = (ptr - start - 4);
446 } else
447 ptr = start;
448
449#if ENABLE_FEATURE_UDHCPC6_RFC4704
450 ptr = mempcpy(ptr, &opt_fqdn_req, sizeof(opt_fqdn_req));
451#endif
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100452 /* Add -x options if any */
453 //...
Denys Vlasenkoba4fbca2017-06-28 19:18:17 +0200454
455 return ptr;
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100456}
457
458static int d6_mcast_from_client_config_ifindex(struct d6_packet *packet, uint8_t *end)
459{
460 static const uint8_t FF02__1_2[16] = {
461 0xFF, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
462 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02,
463 };
464
465 return d6_send_raw_packet(
466 packet, (end - (uint8_t*) packet),
Denys Vlasenkoe09f5e32017-03-27 22:10:15 +0200467 /*src*/ &client6_data.ll_ip6, CLIENT_PORT6,
Denys Vlasenko04ac6e02013-01-28 15:25:35 +0100468 /*dst*/ (struct in6_addr*)FF02__1_2, SERVER_PORT6, MAC_BCAST_ADDR,
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100469 client_config.ifindex
470 );
471}
472
473/* Milticast a DHCPv6 Solicit packet to the network, with an optionally requested IP.
474 *
475 * RFC 3315 17.1.1. Creation of Solicit Messages
476 *
477 * The client MUST include a Client Identifier option to identify itself
478 * to the server. The client includes IA options for any IAs to which
479 * it wants the server to assign addresses. The client MAY include
480 * addresses in the IAs as a hint to the server about addresses for
481 * which the client has a preference. ...
482 *
483 * The client uses IA_NA options to request the assignment of non-
484 * temporary addresses and uses IA_TA options to request the assignment
485 * of temporary addresses. Either IA_NA or IA_TA options, or a
486 * combination of both, can be included in DHCP messages.
487 *
488 * The client SHOULD include an Option Request option (see section 22.7)
489 * to indicate the options the client is interested in receiving. The
490 * client MAY additionally include instances of those options that are
491 * identified in the Option Request option, with data values as hints to
492 * the server about parameter values the client would like to have
493 * returned.
494 *
495 * The client includes a Reconfigure Accept option (see section 22.20)
496 * if the client is willing to accept Reconfigure messages from the
497 * server.
498 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
499 | OPTION_CLIENTID | option-len |
500 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
501 . .
502 . DUID .
503 . (variable length) .
504 . .
505 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
506
507
508 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
509 | OPTION_IA_NA | option-len |
510 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
511 | IAID (4 octets) |
512 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
513 | T1 |
514 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
515 | T2 |
516 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
517 | |
518 . IA_NA-options .
519 . .
520 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
521
522
523 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
524 | OPTION_IAADDR | option-len |
525 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
526 | |
527 | IPv6 address |
528 | |
529 | |
530 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
531 | preferred-lifetime |
532 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
533 | valid-lifetime |
534 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
535 . .
536 . IAaddr-options .
537 . .
538 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
539
540
541 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
542 | OPTION_ORO | option-len |
543 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
544 | requested-option-code-1 | requested-option-code-2 |
545 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
546 | ... |
547 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
548
549
550 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
551 | OPTION_RECONF_ACCEPT | 0 |
552 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
553 */
554/* NOINLINE: limit stack usage in caller */
555static NOINLINE int send_d6_discover(uint32_t xid, struct in6_addr *requested_ipv6)
556{
557 struct d6_packet packet;
558 uint8_t *opt_ptr;
559 unsigned len;
560
561 /* Fill in: msg type, client id */
562 opt_ptr = init_d6_packet(&packet, D6_MSG_SOLICIT, xid);
563
564 /* Create new IA_NA, optionally with included IAADDR with requested IP */
565 free(client6_data.ia_na);
Denys Vlasenkoef5207f2018-01-16 21:39:14 +0100566 client6_data.ia_na = NULL;
567 if (option_mask32 & OPT_r) {
568 len = requested_ipv6 ? 2+2+4+4+4 + 2+2+16+4+4 : 2+2+4+4+4;
569 client6_data.ia_na = xzalloc(len);
570 client6_data.ia_na->code = D6_OPT_IA_NA;
571 client6_data.ia_na->len = len - 4;
572 *(uint32_t*)client6_data.ia_na->data = rand(); /* IAID */
573 if (requested_ipv6) {
574 struct d6_option *iaaddr = (void*)(client6_data.ia_na->data + 4+4+4);
575 iaaddr->code = D6_OPT_IAADDR;
576 iaaddr->len = 16+4+4;
577 memcpy(iaaddr->data, requested_ipv6, 16);
578 }
579 opt_ptr = mempcpy(opt_ptr, client6_data.ia_na, len);
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100580 }
Denys Vlasenkoef5207f2018-01-16 21:39:14 +0100581
582 /* IA_PD */
583 free(client6_data.ia_pd);
584 client6_data.ia_pd = NULL;
585 if (option_mask32 & OPT_d) {
586 len = 2+2+4+4+4;
587 client6_data.ia_pd = xzalloc(len);
588 client6_data.ia_pd->code = D6_OPT_IA_PD;
589 client6_data.ia_pd->len = len - 4;
590 *(uint32_t*)client6_data.ia_pd->data = rand(); /* IAID */
591 opt_ptr = mempcpy(opt_ptr, client6_data.ia_pd, len);
592 }
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100593
594 /* Add options:
595 * "param req" option according to -O, options specified with -x
596 */
597 opt_ptr = add_d6_client_options(opt_ptr);
598
Denys Vlasenko8f2e99c2016-03-30 18:41:23 +0200599 bb_error_msg("sending %s", "discover");
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100600 return d6_mcast_from_client_config_ifindex(&packet, opt_ptr);
601}
602
603/* Multicast a DHCPv6 request message
604 *
605 * RFC 3315 18.1.1. Creation and Transmission of Request Messages
606 *
607 * The client uses a Request message to populate IAs with addresses and
608 * obtain other configuration information. The client includes one or
609 * more IA options in the Request message. The server then returns
610 * addresses and other information about the IAs to the client in IA
611 * options in a Reply message.
612 *
613 * The client generates a transaction ID and inserts this value in the
614 * "transaction-id" field.
615 *
616 * The client places the identifier of the destination server in a
617 * Server Identifier option.
618 *
619 * The client MUST include a Client Identifier option to identify itself
620 * to the server. The client adds any other appropriate options,
621 * including one or more IA options (if the client is requesting that
622 * the server assign it some network addresses).
623 *
624 * The client MUST include an Option Request option (see section 22.7)
625 * to indicate the options the client is interested in receiving. The
626 * client MAY include options with data values as hints to the server
627 * about parameter values the client would like to have returned.
628 *
629 * The client includes a Reconfigure Accept option (see section 22.20)
630 * indicating whether or not the client is willing to accept Reconfigure
631 * messages from the server.
632 */
633/* NOINLINE: limit stack usage in caller */
634static NOINLINE int send_d6_select(uint32_t xid)
635{
636 struct d6_packet packet;
637 uint8_t *opt_ptr;
638
639 /* Fill in: msg type, client id */
640 opt_ptr = init_d6_packet(&packet, D6_MSG_REQUEST, xid);
641
642 /* server id */
Denys Vlasenko234b82c2017-06-26 19:42:48 +0200643 opt_ptr = mempcpy(opt_ptr, client6_data.server_id, client6_data.server_id->len + 2+2);
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100644 /* IA NA (contains requested IP) */
Denys Vlasenkoef5207f2018-01-16 21:39:14 +0100645 if (client6_data.ia_na)
646 opt_ptr = mempcpy(opt_ptr, client6_data.ia_na, client6_data.ia_na->len + 2+2);
647 /* IA PD */
648 if (client6_data.ia_pd)
649 opt_ptr = mempcpy(opt_ptr, client6_data.ia_pd, client6_data.ia_pd->len + 2+2);
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100650
651 /* Add options:
652 * "param req" option according to -O, options specified with -x
653 */
654 opt_ptr = add_d6_client_options(opt_ptr);
655
Denys Vlasenko8f2e99c2016-03-30 18:41:23 +0200656 bb_error_msg("sending %s", "select");
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100657 return d6_mcast_from_client_config_ifindex(&packet, opt_ptr);
658}
659
660/* Unicast or broadcast a DHCP renew message
661 *
662 * RFC 3315 18.1.3. Creation and Transmission of Renew Messages
663 *
664 * To extend the valid and preferred lifetimes for the addresses
665 * associated with an IA, the client sends a Renew message to the server
666 * from which the client obtained the addresses in the IA containing an
667 * IA option for the IA. The client includes IA Address options in the
668 * IA option for the addresses associated with the IA. The server
669 * determines new lifetimes for the addresses in the IA according to the
670 * administrative configuration of the server. The server may also add
671 * new addresses to the IA. The server may remove addresses from the IA
672 * by setting the preferred and valid lifetimes of those addresses to
673 * zero.
674 *
675 * The server controls the time at which the client contacts the server
676 * to extend the lifetimes on assigned addresses through the T1 and T2
677 * parameters assigned to an IA.
678 *
679 * At time T1 for an IA, the client initiates a Renew/Reply message
680 * exchange to extend the lifetimes on any addresses in the IA. The
681 * client includes an IA option with all addresses currently assigned to
682 * the IA in its Renew message.
683 *
684 * If T1 or T2 is set to 0 by the server (for an IA_NA) or there are no
685 * T1 or T2 times (for an IA_TA), the client may send a Renew or Rebind
686 * message, respectively, at the client's discretion.
687 *
688 * The client sets the "msg-type" field to RENEW. The client generates
689 * a transaction ID and inserts this value in the "transaction-id"
690 * field.
691 *
692 * The client places the identifier of the destination server in a
693 * Server Identifier option.
694 *
695 * The client MUST include a Client Identifier option to identify itself
696 * to the server. The client adds any appropriate options, including
697 * one or more IA options. The client MUST include the list of
698 * addresses the client currently has associated with the IAs in the
699 * Renew message.
700 *
701 * The client MUST include an Option Request option (see section 22.7)
702 * to indicate the options the client is interested in receiving. The
703 * client MAY include options with data values as hints to the server
704 * about parameter values the client would like to have returned.
705 */
706/* NOINLINE: limit stack usage in caller */
707static NOINLINE int send_d6_renew(uint32_t xid, struct in6_addr *server_ipv6, struct in6_addr *our_cur_ipv6)
708{
709 struct d6_packet packet;
710 uint8_t *opt_ptr;
711
712 /* Fill in: msg type, client id */
713 opt_ptr = init_d6_packet(&packet, DHCPREQUEST, xid);
714
715 /* server id */
Denys Vlasenko234b82c2017-06-26 19:42:48 +0200716 opt_ptr = mempcpy(opt_ptr, client6_data.server_id, client6_data.server_id->len + 2+2);
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100717 /* IA NA (contains requested IP) */
Denys Vlasenkoef5207f2018-01-16 21:39:14 +0100718 if (client6_data.ia_na)
719 opt_ptr = mempcpy(opt_ptr, client6_data.ia_na, client6_data.ia_na->len + 2+2);
720 /* IA PD */
721 if (client6_data.ia_pd)
722 opt_ptr = mempcpy(opt_ptr, client6_data.ia_pd, client6_data.ia_pd->len + 2+2);
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100723
724 /* Add options:
725 * "param req" option according to -O, options specified with -x
726 */
727 opt_ptr = add_d6_client_options(opt_ptr);
728
Denys Vlasenko8f2e99c2016-03-30 18:41:23 +0200729 bb_error_msg("sending %s", "renew");
Denys Vlasenkoa6a3ad32017-09-29 15:55:24 +0200730 if (server_ipv6) {
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100731 return d6_send_kernel_packet(
732 &packet, (opt_ptr - (uint8_t*) &packet),
Denys Vlasenko04ac6e02013-01-28 15:25:35 +0100733 our_cur_ipv6, CLIENT_PORT6,
Denys Vlasenkoed898ed2017-03-27 22:32:44 +0200734 server_ipv6, SERVER_PORT6,
735 client_config.ifindex
Denys Vlasenkoa6a3ad32017-09-29 15:55:24 +0200736 /* TODO? send_flags: MSG_DONTROUTE (see IPv4 code for reason why) */
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100737 );
Denys Vlasenkoa6a3ad32017-09-29 15:55:24 +0200738 }
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100739 return d6_mcast_from_client_config_ifindex(&packet, opt_ptr);
740}
741
742/* Unicast a DHCP release message */
743static int send_d6_release(struct in6_addr *server_ipv6, struct in6_addr *our_cur_ipv6)
744{
745 struct d6_packet packet;
746 uint8_t *opt_ptr;
747
748 /* Fill in: msg type, client id */
749 opt_ptr = init_d6_packet(&packet, D6_MSG_RELEASE, random_xid());
750 /* server id */
Denys Vlasenko234b82c2017-06-26 19:42:48 +0200751 opt_ptr = mempcpy(opt_ptr, client6_data.server_id, client6_data.server_id->len + 2+2);
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100752 /* IA NA (contains our current IP) */
Denys Vlasenkoef5207f2018-01-16 21:39:14 +0100753 if (client6_data.ia_na)
754 opt_ptr = mempcpy(opt_ptr, client6_data.ia_na, client6_data.ia_na->len + 2+2);
755 /* IA PD */
756 if (client6_data.ia_pd)
757 opt_ptr = mempcpy(opt_ptr, client6_data.ia_pd, client6_data.ia_pd->len + 2+2);
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100758
Denys Vlasenko8f2e99c2016-03-30 18:41:23 +0200759 bb_error_msg("sending %s", "release");
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100760 return d6_send_kernel_packet(
761 &packet, (opt_ptr - (uint8_t*) &packet),
Denys Vlasenko04ac6e02013-01-28 15:25:35 +0100762 our_cur_ipv6, CLIENT_PORT6,
Denys Vlasenkoed898ed2017-03-27 22:32:44 +0200763 server_ipv6, SERVER_PORT6,
764 client_config.ifindex
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100765 );
766}
767
768/* Returns -1 on errors that are fatal for the socket, -2 for those that aren't */
769/* NOINLINE: limit stack usage in caller */
Denys Vlasenkoed898ed2017-03-27 22:32:44 +0200770static NOINLINE int d6_recv_raw_packet(struct in6_addr *peer_ipv6, struct d6_packet *d6_pkt, int fd)
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100771{
772 int bytes;
773 struct ip6_udp_d6_packet packet;
774
775 bytes = safe_read(fd, &packet, sizeof(packet));
776 if (bytes < 0) {
Denys Vlasenko8f2e99c2016-03-30 18:41:23 +0200777 log1("packet read error, ignoring");
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100778 /* NB: possible down interface, etc. Caller should pause. */
779 return bytes; /* returns -1 */
780 }
781
782 if (bytes < (int) (sizeof(packet.ip6) + sizeof(packet.udp))) {
Denys Vlasenko8f2e99c2016-03-30 18:41:23 +0200783 log1("packet is too short, ignoring");
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100784 return -2;
785 }
786
787 if (bytes < sizeof(packet.ip6) + ntohs(packet.ip6.ip6_plen)) {
788 /* packet is bigger than sizeof(packet), we did partial read */
Denys Vlasenko8f2e99c2016-03-30 18:41:23 +0200789 log1("oversized packet, ignoring");
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100790 return -2;
791 }
792
793 /* ignore any extra garbage bytes */
794 bytes = sizeof(packet.ip6) + ntohs(packet.ip6.ip6_plen);
795
796 /* make sure its the right packet for us, and that it passes sanity checks */
797 if (packet.ip6.ip6_nxt != IPPROTO_UDP
798 || (packet.ip6.ip6_vfc >> 4) != 6
Denys Vlasenko04ac6e02013-01-28 15:25:35 +0100799 || packet.udp.dest != htons(CLIENT_PORT6)
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100800 /* || bytes > (int) sizeof(packet) - can't happen */
801 || packet.udp.len != packet.ip6.ip6_plen
802 ) {
Denys Vlasenko8f2e99c2016-03-30 18:41:23 +0200803 log1("unrelated/bogus packet, ignoring");
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100804 return -2;
805 }
806
807//How to do this for ipv6?
808// /* verify UDP checksum. IP header has to be modified for this */
809// memset(&packet.ip, 0, offsetof(struct iphdr, protocol));
810// /* ip.xx fields which are not memset: protocol, check, saddr, daddr */
811// packet.ip.tot_len = packet.udp.len; /* yes, this is needed */
812// check = packet.udp.check;
813// packet.udp.check = 0;
814// if (check && check != inet_cksum((uint16_t *)&packet, bytes)) {
Denys Vlasenko8f2e99c2016-03-30 18:41:23 +0200815// log1("packet with bad UDP checksum received, ignoring");
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100816// return -2;
817// }
818
Denys Vlasenkoed898ed2017-03-27 22:32:44 +0200819 if (peer_ipv6)
820 *peer_ipv6 = packet.ip6.ip6_src; /* struct copy */
821
Denys Vlasenko8f2e99c2016-03-30 18:41:23 +0200822 log1("received %s", "a packet");
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100823 d6_dump_packet(&packet.data);
824
825 bytes -= sizeof(packet.ip6) + sizeof(packet.udp);
826 memcpy(d6_pkt, &packet.data, bytes);
827 return bytes;
828}
829
830
831/*** Main ***/
832
833static int sockfd = -1;
834
835#define LISTEN_NONE 0
836#define LISTEN_KERNEL 1
837#define LISTEN_RAW 2
838static smallint listen_mode;
839
840/* initial state: (re)start DHCP negotiation */
841#define INIT_SELECTING 0
842/* discover was sent, DHCPOFFER reply received */
843#define REQUESTING 1
844/* select/renew was sent, DHCPACK reply received */
845#define BOUND 2
846/* half of lease passed, want to renew it by sending unicast renew requests */
847#define RENEWING 3
848/* renew requests were not answered, lease is almost over, send broadcast renew */
849#define REBINDING 4
850/* manually requested renew (SIGUSR1) */
851#define RENEW_REQUESTED 5
852/* release, possibly manually requested (SIGUSR2) */
853#define RELEASED 6
854static smallint state;
855
856static int d6_raw_socket(int ifindex)
857{
858 int fd;
859 struct sockaddr_ll sock;
860
861 /*
862 * Comment:
863 *
864 * I've selected not to see LL header, so BPF doesn't see it, too.
865 * The filter may also pass non-IP and non-ARP packets, but we do
866 * a more complete check when receiving the message in userspace.
867 *
868 * and filter shamelessly stolen from:
869 *
870 * http://www.flamewarmaster.de/software/dhcpclient/
871 *
872 * There are a few other interesting ideas on that page (look under
873 * "Motivation"). Use of netlink events is most interesting. Think
874 * of various network servers listening for events and reconfiguring.
875 * That would obsolete sending HUP signals and/or make use of restarts.
876 *
877 * Copyright: 2006, 2007 Stefan Rompf <sux@loplof.de>.
878 * License: GPL v2.
879 *
880 * TODO: make conditional?
881 */
882#if 0
883 static const struct sock_filter filter_instr[] = {
884 /* load 9th byte (protocol) */
885 BPF_STMT(BPF_LD|BPF_B|BPF_ABS, 9),
886 /* jump to L1 if it is IPPROTO_UDP, else to L4 */
887 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, IPPROTO_UDP, 0, 6),
888 /* L1: load halfword from offset 6 (flags and frag offset) */
889 BPF_STMT(BPF_LD|BPF_H|BPF_ABS, 6),
890 /* jump to L4 if any bits in frag offset field are set, else to L2 */
891 BPF_JUMP(BPF_JMP|BPF_JSET|BPF_K, 0x1fff, 4, 0),
892 /* L2: skip IP header (load index reg with header len) */
893 BPF_STMT(BPF_LDX|BPF_B|BPF_MSH, 0),
894 /* load udp destination port from halfword[header_len + 2] */
895 BPF_STMT(BPF_LD|BPF_H|BPF_IND, 2),
Denys Vlasenko04ac6e02013-01-28 15:25:35 +0100896 /* jump to L3 if udp dport is CLIENT_PORT6, else to L4 */
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100897 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 68, 0, 1),
898 /* L3: accept packet */
Denys Vlasenkoffc3a932014-02-19 14:17:11 +0100899 BPF_STMT(BPF_RET|BPF_K, 0x7fffffff),
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100900 /* L4: discard packet */
901 BPF_STMT(BPF_RET|BPF_K, 0),
902 };
903 static const struct sock_fprog filter_prog = {
904 .len = sizeof(filter_instr) / sizeof(filter_instr[0]),
905 /* casting const away: */
906 .filter = (struct sock_filter *) filter_instr,
907 };
908#endif
909
Denys Vlasenko168f0ef2017-07-21 12:04:22 +0200910 log2("opening raw socket on ifindex %d", ifindex);
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100911
912 fd = xsocket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IPV6));
Denys Vlasenko168f0ef2017-07-21 12:04:22 +0200913 log2("got raw socket fd %d", fd);
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100914
Denys Vlasenko2b9acc62017-09-29 14:09:02 +0200915 memset(&sock, 0, sizeof(sock)); /* let's be deterministic */
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100916 sock.sll_family = AF_PACKET;
917 sock.sll_protocol = htons(ETH_P_IPV6);
918 sock.sll_ifindex = ifindex;
Denys Vlasenko2b9acc62017-09-29 14:09:02 +0200919 /*sock.sll_hatype = ARPHRD_???;*/
920 /*sock.sll_pkttype = PACKET_???;*/
921 /*sock.sll_halen = ???;*/
922 /*sock.sll_addr[8] = ???;*/
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100923 xbind(fd, (struct sockaddr *) &sock, sizeof(sock));
924
925#if 0
Denys Vlasenko04ac6e02013-01-28 15:25:35 +0100926 if (CLIENT_PORT6 == 546) {
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100927 /* Use only if standard port is in use */
928 /* Ignoring error (kernel may lack support for this) */
929 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog,
930 sizeof(filter_prog)) >= 0)
Denys Vlasenko8f2e99c2016-03-30 18:41:23 +0200931 log1("attached filter to raw socket fd %d", fd); // log?
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100932 }
933#endif
934
Denys Vlasenko8f2e99c2016-03-30 18:41:23 +0200935 log1("created raw socket");
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100936
937 return fd;
938}
939
940static void change_listen_mode(int new_mode)
941{
Denys Vlasenko8f2e99c2016-03-30 18:41:23 +0200942 log1("entering listen mode: %s",
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100943 new_mode != LISTEN_NONE
944 ? (new_mode == LISTEN_KERNEL ? "kernel" : "raw")
945 : "none"
946 );
947
948 listen_mode = new_mode;
949 if (sockfd >= 0) {
950 close(sockfd);
951 sockfd = -1;
952 }
953 if (new_mode == LISTEN_KERNEL)
Denys Vlasenko04ac6e02013-01-28 15:25:35 +0100954 sockfd = udhcp_listen_socket(/*INADDR_ANY,*/ CLIENT_PORT6, client_config.interface);
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100955 else if (new_mode != LISTEN_NONE)
956 sockfd = d6_raw_socket(client_config.ifindex);
957 /* else LISTEN_NONE: sockfd stays closed */
958}
959
960/* Called only on SIGUSR1 */
961static void perform_renew(void)
962{
Denys Vlasenko8f2e99c2016-03-30 18:41:23 +0200963 bb_error_msg("performing DHCP renew");
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100964 switch (state) {
965 case BOUND:
966 change_listen_mode(LISTEN_KERNEL);
967 case RENEWING:
968 case REBINDING:
969 state = RENEW_REQUESTED;
970 break;
971 case RENEW_REQUESTED: /* impatient are we? fine, square 1 */
972 d6_run_script(NULL, "deconfig");
973 case REQUESTING:
974 case RELEASED:
975 change_listen_mode(LISTEN_RAW);
976 state = INIT_SELECTING;
977 break;
978 case INIT_SELECTING:
979 break;
980 }
981}
982
983static void perform_d6_release(struct in6_addr *server_ipv6, struct in6_addr *our_cur_ipv6)
984{
985 /* send release packet */
Denys Vlasenko44399e02016-07-03 20:26:44 +0200986 if (state == BOUND
987 || state == RENEWING
988 || state == REBINDING
989 || state == RENEW_REQUESTED
990 ) {
Denys Vlasenko8f2e99c2016-03-30 18:41:23 +0200991 bb_error_msg("unicasting a release");
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100992 send_d6_release(server_ipv6, our_cur_ipv6); /* unicast */
Denys Vlasenko9ba75042011-11-07 15:55:39 +0100993 }
Denys Vlasenko8f2e99c2016-03-30 18:41:23 +0200994 bb_error_msg("entering released state");
Peter Korsgaardb6355e22016-08-26 18:46:34 +0200995/*
996 * We can be here on: SIGUSR2,
997 * or on exit (SIGTERM) and -R "release on quit" is specified.
998 * Users requested to be notified in all cases, even if not in one
999 * of the states above.
1000 */
1001 d6_run_script(NULL, "deconfig");
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001002 change_listen_mode(LISTEN_NONE);
1003 state = RELEASED;
1004}
1005
1006///static uint8_t* alloc_dhcp_option(int code, const char *str, int extra)
1007///{
1008/// uint8_t *storage;
1009/// int len = strnlen(str, 255);
1010/// storage = xzalloc(len + extra + OPT_DATA);
1011/// storage[OPT_CODE] = code;
1012/// storage[OPT_LEN] = len + extra;
1013/// memcpy(storage + extra + OPT_DATA, str, len);
1014/// return storage;
1015///}
1016
1017#if BB_MMU
1018static void client_background(void)
1019{
1020 bb_daemonize(0);
1021 logmode &= ~LOGMODE_STDIO;
1022 /* rewrite pidfile, as our pid is different now */
1023 write_pidfile(client_config.pidfile);
1024}
1025#endif
1026
1027//usage:#if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
1028//usage:# define IF_UDHCP_VERBOSE(...) __VA_ARGS__
1029//usage:#else
1030//usage:# define IF_UDHCP_VERBOSE(...)
1031//usage:#endif
1032//usage:#define udhcpc6_trivial_usage
Denys Vlasenko64211ce2018-01-16 22:23:38 +01001033//usage: "[-fbnq"IF_UDHCP_VERBOSE("v")"odR] [-i IFACE] [-r IPv6] [-s PROG] [-p PIDFILE]\n"
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001034//usage: " [-x OPT:VAL]... [-O OPT]..." IF_FEATURE_UDHCP_PORT(" [-P N]")
1035//usage:#define udhcpc6_full_usage "\n"
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001036//usage: "\n -i IFACE Interface to use (default eth0)"
1037//usage: "\n -p FILE Create pidfile"
1038//usage: "\n -s PROG Run PROG at DHCP events (default "CONFIG_UDHCPC_DEFAULT_SCRIPT")"
1039//usage: "\n -B Request broadcast replies"
1040//usage: "\n -t N Send up to N discover packets"
1041//usage: "\n -T N Pause between packets (default 3 seconds)"
1042//usage: "\n -A N Wait N seconds (default 20) after failure"
1043//usage: "\n -f Run in foreground"
1044//usage: USE_FOR_MMU(
1045//usage: "\n -b Background if lease is not obtained"
1046//usage: )
1047//usage: "\n -n Exit if lease is not obtained"
1048//usage: "\n -q Exit after obtaining lease"
1049//usage: "\n -R Release IP on exit"
1050//usage: "\n -S Log to syslog too"
1051//usage: IF_FEATURE_UDHCP_PORT(
Denys Vlasenko7e21f042011-11-08 11:39:41 +01001052//usage: "\n -P N Use port N (default 546)"
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001053//usage: )
1054////usage: IF_FEATURE_UDHCPC_ARPING(
1055////usage: "\n -a Use arping to validate offered address"
1056////usage: )
1057//usage: "\n -O OPT Request option OPT from server (cumulative)"
1058//usage: "\n -o Don't request any options (unless -O is given)"
Denys Vlasenko64211ce2018-01-16 22:23:38 +01001059//usage: "\n -r IPv6 Request this address ('no' to not request any IP)"
Denys Vlasenkoef5207f2018-01-16 21:39:14 +01001060//usage: "\n -d Request prefix"
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001061//usage: "\n -x OPT:VAL Include option OPT in sent packets (cumulative)"
1062//usage: "\n Examples of string, numeric, and hex byte opts:"
1063//usage: "\n -x hostname:bbox - option 12"
1064//usage: "\n -x lease:3600 - option 51 (lease time)"
1065//usage: "\n -x 0x3d:0100BEEFC0FFEE - option 61 (client id)"
1066//usage: IF_UDHCP_VERBOSE(
1067//usage: "\n -v Verbose"
1068//usage: )
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001069//usage: "\nSignals:"
1070//usage: "\n USR1 Renew lease"
1071//usage: "\n USR2 Release lease"
1072
1073
1074int udhcpc6_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1075int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
1076{
1077 const char *str_r;
1078 IF_FEATURE_UDHCP_PORT(char *str_P;)
1079 void *clientid_mac_ptr;
1080 llist_t *list_O = NULL;
1081 llist_t *list_x = NULL;
1082 int tryagain_timeout = 20;
1083 int discover_timeout = 3;
1084 int discover_retries = 3;
1085 struct in6_addr srv6_buf;
1086 struct in6_addr ipv6_buf;
1087 struct in6_addr *requested_ipv6;
1088 uint32_t xid = 0;
1089 int packet_num;
1090 int timeout; /* must be signed */
1091 unsigned already_waited_sec;
1092 unsigned opt;
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001093 int retval;
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001094
Denys Vlasenkodf70a432016-04-21 18:54:36 +02001095 setup_common_bufsiz();
Denys Vlasenkof6dd9e02018-01-19 18:44:19 +01001096 /* We want random_xid to be random */
1097 srand(monotonic_us());
Denys Vlasenkodf70a432016-04-21 18:54:36 +02001098
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001099 /* Default options */
Denys Vlasenko04ac6e02013-01-28 15:25:35 +01001100 IF_FEATURE_UDHCP_PORT(SERVER_PORT6 = 547;)
1101 IF_FEATURE_UDHCP_PORT(CLIENT_PORT6 = 546;)
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001102 client_config.interface = "eth0";
1103 client_config.script = CONFIG_UDHCPC_DEFAULT_SCRIPT;
1104
1105 /* Parse command line */
Denys Vlasenko22542ec2017-08-08 21:55:02 +02001106 opt = getopt32long(argv, "^"
1107 /* O,x: list; -T,-t,-A take numeric param */
Denys Vlasenkoef5207f2018-01-16 21:39:14 +01001108 "i:np:qRr:s:T:+t:+SA:+O:*ox:*fd"
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001109 USE_FOR_MMU("b")
1110 ///IF_FEATURE_UDHCPC_ARPING("a")
1111 IF_FEATURE_UDHCP_PORT("P:")
1112 "v"
Denys Vlasenko22542ec2017-08-08 21:55:02 +02001113 "\0" IF_UDHCP_VERBOSE("vv") /* -v is a counter */
Denys Vlasenko036585a2017-08-08 16:38:18 +02001114 , udhcpc6_longopts
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001115 , &client_config.interface, &client_config.pidfile, &str_r /* i,p */
1116 , &client_config.script /* s */
1117 , &discover_timeout, &discover_retries, &tryagain_timeout /* T,t,A */
1118 , &list_O
1119 , &list_x
1120 IF_FEATURE_UDHCP_PORT(, &str_P)
1121 IF_UDHCP_VERBOSE(, &dhcp_verbose)
Denys Vlasenko7e21f042011-11-08 11:39:41 +01001122 );
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001123 requested_ipv6 = NULL;
Denys Vlasenkoef5207f2018-01-16 21:39:14 +01001124 option_mask32 |= OPT_r;
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001125 if (opt & OPT_r) {
Denys Vlasenkoef5207f2018-01-16 21:39:14 +01001126 if (strcmp(str_r, "no") == 0) {
1127 option_mask32 -= OPT_r;
1128 } else {
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;
1132 }
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001133 }
1134#if ENABLE_FEATURE_UDHCP_PORT
1135 if (opt & OPT_P) {
Denys Vlasenko04ac6e02013-01-28 15:25:35 +01001136 CLIENT_PORT6 = xatou16(str_P);
1137 SERVER_PORT6 = CLIENT_PORT6 + 1;
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001138 }
1139#endif
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001140 while (list_O) {
1141 char *optstr = llist_pop(&list_O);
1142 unsigned n = bb_strtou(optstr, NULL, 0);
1143 if (errno || n > 254) {
Denys Vlasenkoba4fbca2017-06-28 19:18:17 +02001144 n = udhcp_option_idx(optstr, d6_option_strings);
1145 n = d6_optflags[n].code;
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001146 }
1147 client_config.opt_mask[n >> 3] |= 1 << (n & 7);
1148 }
Denys Vlasenko293c9452012-07-27 13:25:07 +02001149 if (!(opt & OPT_o)) {
Denys Vlasenko293c9452012-07-27 13:25:07 +02001150 unsigned i, n;
Denys Vlasenkoba4fbca2017-06-28 19:18:17 +02001151 for (i = 0; (n = d6_optflags[i].code) != 0; i++) {
1152 if (d6_optflags[i].flags & OPTION_REQ) {
Denys Vlasenko293c9452012-07-27 13:25:07 +02001153 client_config.opt_mask[n >> 3] |= 1 << (n & 7);
1154 }
1155 }
Denys Vlasenko293c9452012-07-27 13:25:07 +02001156 }
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001157 while (list_x) {
1158 char *optstr = llist_pop(&list_x);
1159 char *colon = strchr(optstr, ':');
1160 if (colon)
1161 *colon = ' ';
1162 /* now it looks similar to udhcpd's config file line:
1163 * "optname optval", using the common routine: */
Denys Vlasenkoba4fbca2017-06-28 19:18:17 +02001164 udhcp_str2optset(optstr, &client_config.options, d6_optflags, d6_option_strings);
Denys Vlasenko741bfa92017-05-08 15:02:07 +02001165 if (colon)
1166 *colon = ':'; /* restore it for NOMMU reexec */
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001167 }
1168
Denys Vlasenkoe09f5e32017-03-27 22:10:15 +02001169 if (d6_read_interface(client_config.interface,
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001170 &client_config.ifindex,
Denys Vlasenkoe09f5e32017-03-27 22:10:15 +02001171 &client6_data.ll_ip6,
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001172 client_config.client_mac)
1173 ) {
1174 return 1;
1175 }
1176
1177 /* Create client ID based on mac, set clientid_mac_ptr */
1178 {
1179 struct d6_option *clientid;
1180 clientid = xzalloc(2+2+2+2+6);
1181 clientid->code = D6_OPT_CLIENTID;
1182 clientid->len = 2+2+6;
Denys Vlasenko68c5b282011-11-07 16:21:24 +01001183 clientid->data[1] = 3; /* DUID-LL */
1184 clientid->data[3] = 1; /* ethernet */
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001185 clientid_mac_ptr = clientid->data + 2+2;
1186 memcpy(clientid_mac_ptr, client_config.client_mac, 6);
1187 client_config.clientid = (void*)clientid;
1188 }
1189
1190#if !BB_MMU
1191 /* on NOMMU reexec (i.e., background) early */
1192 if (!(opt & OPT_f)) {
1193 bb_daemonize_or_rexec(0 /* flags */, argv);
1194 logmode = LOGMODE_NONE;
1195 }
1196#endif
1197 if (opt & OPT_S) {
1198 openlog(applet_name, LOG_PID, LOG_DAEMON);
1199 logmode |= LOGMODE_SYSLOG;
1200 }
1201
1202 /* Make sure fd 0,1,2 are open */
1203 bb_sanitize_stdio();
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001204 /* Create pidfile */
1205 write_pidfile(client_config.pidfile);
1206 /* Goes to stdout (unless NOMMU) and possibly syslog */
Denys Vlasenko8f2e99c2016-03-30 18:41:23 +02001207 bb_error_msg("started, v"BB_VER);
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001208 /* Set up the signal pipe */
1209 udhcp_sp_setup();
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001210
1211 state = INIT_SELECTING;
1212 d6_run_script(NULL, "deconfig");
1213 change_listen_mode(LISTEN_RAW);
1214 packet_num = 0;
1215 timeout = 0;
1216 already_waited_sec = 0;
1217
1218 /* Main event loop. select() waits on signal pipe and possibly
1219 * on sockfd.
1220 * "continue" statements in code below jump to the top of the loop.
1221 */
1222 for (;;) {
Denys Vlasenko52a515d2017-02-16 23:25:44 +01001223 int tv;
1224 struct pollfd pfds[2];
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001225 struct d6_packet packet;
1226 uint8_t *packet_end;
1227 /* silence "uninitialized!" warning */
1228 unsigned timestamp_before_wait = timestamp_before_wait;
1229
1230 //bb_error_msg("sockfd:%d, listen_mode:%d", sockfd, listen_mode);
1231
1232 /* Was opening raw or udp socket here
1233 * if (listen_mode != LISTEN_NONE && sockfd < 0),
1234 * but on fast network renew responses return faster
1235 * than we open sockets. Thus this code is moved
1236 * to change_listen_mode(). Thus we open listen socket
1237 * BEFORE we send renew request (see "case BOUND:"). */
1238
Denys Vlasenko52a515d2017-02-16 23:25:44 +01001239 udhcp_sp_fd_set(pfds, sockfd);
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001240
Denys Vlasenko52a515d2017-02-16 23:25:44 +01001241 tv = timeout - already_waited_sec;
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001242 retval = 0;
1243 /* If we already timed out, fall through with retval = 0, else... */
Denys Vlasenko52a515d2017-02-16 23:25:44 +01001244 if (tv > 0) {
Denys Vlasenkode6cb412017-07-24 12:01:28 +02001245 log1("waiting %u seconds", tv);
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001246 timestamp_before_wait = (unsigned)monotonic_sec();
Denys Vlasenko7c67f1e2017-02-17 19:20:32 +01001247 retval = poll(pfds, 2, tv < INT_MAX/1000 ? tv * 1000 : INT_MAX);
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001248 if (retval < 0) {
1249 /* EINTR? A signal was caught, don't panic */
1250 if (errno == EINTR) {
1251 already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
1252 continue;
1253 }
1254 /* Else: an error occured, panic! */
Denys Vlasenkode6cb412017-07-24 12:01:28 +02001255 bb_perror_msg_and_die("poll");
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001256 }
1257 }
1258
1259 /* If timeout dropped to zero, time to become active:
1260 * resend discover/renew/whatever
1261 */
1262 if (retval == 0) {
1263 /* When running on a bridge, the ifindex may have changed
1264 * (e.g. if member interfaces were added/removed
1265 * or if the status of the bridge changed).
1266 * Refresh ifindex and client_mac:
1267 */
Denys Vlasenkoe09f5e32017-03-27 22:10:15 +02001268 if (d6_read_interface(client_config.interface,
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001269 &client_config.ifindex,
Denys Vlasenkoe09f5e32017-03-27 22:10:15 +02001270 &client6_data.ll_ip6,
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001271 client_config.client_mac)
1272 ) {
1273 goto ret0; /* iface is gone? */
1274 }
Denys Vlasenkoe09f5e32017-03-27 22:10:15 +02001275
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001276 memcpy(clientid_mac_ptr, client_config.client_mac, 6);
1277
1278 /* We will restart the wait in any case */
1279 already_waited_sec = 0;
1280
1281 switch (state) {
1282 case INIT_SELECTING:
Felix Fietkau1c7a58d2012-09-27 16:22:24 +02001283 if (!discover_retries || packet_num < discover_retries) {
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001284 if (packet_num == 0)
1285 xid = random_xid();
1286 /* multicast */
1287 send_d6_discover(xid, requested_ipv6);
1288 timeout = discover_timeout;
1289 packet_num++;
1290 continue;
1291 }
1292 leasefail:
1293 d6_run_script(NULL, "leasefail");
1294#if BB_MMU /* -b is not supported on NOMMU */
1295 if (opt & OPT_b) { /* background if no lease */
Denys Vlasenko8f2e99c2016-03-30 18:41:23 +02001296 bb_error_msg("no lease, forking to background");
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001297 client_background();
1298 /* do not background again! */
1299 opt = ((opt & ~OPT_b) | OPT_f);
1300 } else
1301#endif
1302 if (opt & OPT_n) { /* abort if no lease */
Denys Vlasenko8f2e99c2016-03-30 18:41:23 +02001303 bb_error_msg("no lease, failing");
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001304 retval = 1;
1305 goto ret;
1306 }
1307 /* wait before trying again */
1308 timeout = tryagain_timeout;
1309 packet_num = 0;
1310 continue;
1311 case REQUESTING:
Felix Fietkau1c7a58d2012-09-27 16:22:24 +02001312 if (!discover_retries || packet_num < discover_retries) {
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001313 /* send multicast select packet */
1314 send_d6_select(xid);
1315 timeout = discover_timeout;
1316 packet_num++;
1317 continue;
1318 }
1319 /* Timed out, go back to init state.
1320 * "discover...select...discover..." loops
1321 * were seen in the wild. Treat them similarly
1322 * to "no response to discover" case */
1323 change_listen_mode(LISTEN_RAW);
1324 state = INIT_SELECTING;
1325 goto leasefail;
1326 case BOUND:
1327 /* 1/2 lease passed, enter renewing state */
1328 state = RENEWING;
1329 client_config.first_secs = 0; /* make secs field count from 0 */
1330 change_listen_mode(LISTEN_KERNEL);
Denys Vlasenko8f2e99c2016-03-30 18:41:23 +02001331 log1("entering renew state");
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001332 /* fall right through */
1333 case RENEW_REQUESTED: /* manual (SIGUSR1) renew */
1334 case_RENEW_REQUESTED:
1335 case RENEWING:
1336 if (timeout > 60) {
1337 /* send an unicast renew request */
1338 /* Sometimes observed to fail (EADDRNOTAVAIL) to bind
1339 * a new UDP socket for sending inside send_renew.
1340 * I hazard to guess existing listening socket
1341 * is somehow conflicting with it, but why is it
1342 * not deterministic then?! Strange.
1343 * Anyway, it does recover by eventually failing through
1344 * into INIT_SELECTING state.
1345 */
1346 send_d6_renew(xid, &srv6_buf, requested_ipv6);
1347 timeout >>= 1;
1348 continue;
1349 }
1350 /* Timed out, enter rebinding state */
Denys Vlasenko8f2e99c2016-03-30 18:41:23 +02001351 log1("entering rebinding state");
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001352 state = REBINDING;
1353 /* fall right through */
1354 case REBINDING:
1355 /* Switch to bcast receive */
1356 change_listen_mode(LISTEN_RAW);
1357 /* Lease is *really* about to run out,
1358 * try to find DHCP server using broadcast */
1359 if (timeout > 0) {
1360 /* send a broadcast renew request */
1361 send_d6_renew(xid, /*server_ipv6:*/ NULL, requested_ipv6);
1362 timeout >>= 1;
1363 continue;
1364 }
1365 /* Timed out, enter init state */
Denys Vlasenko8f2e99c2016-03-30 18:41:23 +02001366 bb_error_msg("lease lost, entering init state");
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001367 d6_run_script(NULL, "deconfig");
1368 state = INIT_SELECTING;
1369 client_config.first_secs = 0; /* make secs field count from 0 */
1370 /*timeout = 0; - already is */
1371 packet_num = 0;
1372 continue;
1373 /* case RELEASED: */
1374 }
1375 /* yah, I know, *you* say it would never happen */
1376 timeout = INT_MAX;
1377 continue; /* back to main loop */
Denys Vlasenko3293bc12018-03-10 19:01:48 +01001378 } /* if poll timed out */
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001379
Denys Vlasenko3293bc12018-03-10 19:01:48 +01001380 /* poll() didn't timeout, something happened */
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001381
1382 /* Is it a signal? */
Denys Vlasenko3293bc12018-03-10 19:01:48 +01001383 switch (udhcp_sp_read()) {
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001384 case SIGUSR1:
1385 client_config.first_secs = 0; /* make secs field count from 0 */
1386 already_waited_sec = 0;
1387 perform_renew();
1388 if (state == RENEW_REQUESTED) {
1389 /* We might be either on the same network
1390 * (in which case renew might work),
1391 * or we might be on a completely different one
1392 * (in which case renew won't ever succeed).
1393 * For the second case, must make sure timeout
1394 * is not too big, or else we can send
1395 * futile renew requests for hours.
1396 * (Ab)use -A TIMEOUT value (usually 20 sec)
1397 * as a cap on the timeout.
1398 */
1399 if (timeout > tryagain_timeout)
1400 timeout = tryagain_timeout;
1401 goto case_RENEW_REQUESTED;
1402 }
1403 /* Start things over */
1404 packet_num = 0;
1405 /* Kill any timeouts, user wants this to hurry along */
1406 timeout = 0;
1407 continue;
1408 case SIGUSR2:
1409 perform_d6_release(&srv6_buf, requested_ipv6);
1410 timeout = INT_MAX;
1411 continue;
1412 case SIGTERM:
Denys Vlasenko8f2e99c2016-03-30 18:41:23 +02001413 bb_error_msg("received %s", "SIGTERM");
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001414 goto ret0;
1415 }
1416
1417 /* Is it a packet? */
Denys Vlasenko3293bc12018-03-10 19:01:48 +01001418 if (!pfds[1].revents)
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001419 continue; /* no */
1420
1421 {
1422 int len;
1423
1424 /* A packet is ready, read it */
1425 if (listen_mode == LISTEN_KERNEL)
1426 len = d6_recv_kernel_packet(&srv6_buf, &packet, sockfd);
1427 else
1428 len = d6_recv_raw_packet(&srv6_buf, &packet, sockfd);
1429 if (len == -1) {
1430 /* Error is severe, reopen socket */
Denys Vlasenko6f97b302017-09-29 18:17:25 +02001431 bb_error_msg("read error: "STRERROR_FMT", reopening socket" STRERROR_ERRNO);
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001432 sleep(discover_timeout); /* 3 seconds by default */
1433 change_listen_mode(listen_mode); /* just close and reopen */
1434 }
1435 /* If this packet will turn out to be unrelated/bogus,
1436 * we will go back and wait for next one.
1437 * Be sure timeout is properly decreased. */
1438 already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
1439 if (len < 0)
1440 continue;
1441 packet_end = (uint8_t*)&packet + len;
1442 }
1443
1444 if ((packet.d6_xid32 & htonl(0x00ffffff)) != xid) {
1445 log1("xid %x (our is %x), ignoring packet",
1446 (unsigned)(packet.d6_xid32 & htonl(0x00ffffff)), (unsigned)xid);
1447 continue;
1448 }
1449
1450 switch (state) {
1451 case INIT_SELECTING:
1452 if (packet.d6_msg_type == D6_MSG_ADVERTISE)
1453 goto type_is_ok;
1454 /* DHCPv6 has "Rapid Commit", when instead of Advertise,
1455 * server sends Reply right away.
1456 * Fall through to check for this case.
1457 */
1458 case REQUESTING:
1459 case RENEWING:
1460 case RENEW_REQUESTED:
1461 case REBINDING:
1462 if (packet.d6_msg_type == D6_MSG_REPLY) {
1463 uint32_t lease_seconds;
Denys Vlasenko14f13202018-01-16 21:47:10 +01001464 struct d6_option *option;
Denys Vlasenko7c44b602018-01-17 13:55:51 +01001465 unsigned address_timeout;
1466 unsigned prefix_timeout;
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001467 type_is_ok:
Denys Vlasenko14f13202018-01-16 21:47:10 +01001468 address_timeout = 0;
1469 prefix_timeout = 0;
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001470 option = d6_find_option(packet.d6_options, packet_end, D6_OPT_STATUS_CODE);
Denys Vlasenko64d58aa2017-03-27 22:22:09 +02001471 if (option && (option->data[0] | option->data[1]) != 0) {
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001472 /* return to init state */
Denys Vlasenko8f2e99c2016-03-30 18:41:23 +02001473 bb_error_msg("received DHCP NAK (%u)", option->data[4]);
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001474 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;
1482 timeout = 0;
1483 packet_num = 0;
1484 already_waited_sec = 0;
1485 continue;
1486 }
1487 option = d6_copy_option(packet.d6_options, packet_end, D6_OPT_SERVERID);
1488 if (!option) {
1489 bb_error_msg("no server ID, ignoring packet");
1490 continue;
1491 /* still selecting - this server looks bad */
1492 }
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 */
1500 state = REQUESTING;
1501 timeout = 0;
1502 packet_num = 0;
1503 already_waited_sec = 0;
1504 continue;
1505 }
1506 /* It's a D6_MSG_REPLY */
1507/*
1508 * RFC 3315 18.1.8. Receipt of Reply Messages
1509 *
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
1515 * message.
1516 *
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.
1522 *
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:
1527 *
1528 * - Record T1 and T2 times.
1529 *
1530 * - Add any new addresses in the IA option to the IA as recorded by
1531 * the client.
1532 *
1533 * - Update lifetimes for any addresses in the IA option that the
1534 * client already has recorded in the IA.
1535 *
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.
1538 *
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
1541 * server.
1542 *
1543 * Management of the specific configuration information is detailed in
1544 * the definition of each option in section 22.
1545 *
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.
1553 *
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.
1559 *
1560 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1561 * | OPTION_IA_NA | option-len |
1562 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1563 * | IAID (4 octets) |
1564 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1565 * | T1 |
1566 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1567 * | T2 |
1568 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1569 * | |
1570 * . IA_NA-options .
1571 * . .
1572 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1573 *
1574 *
1575 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1576 * | OPTION_IAADDR | option-len |
1577 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1578 * | |
1579 * | IPv6 address |
1580 * | |
1581 * | |
1582 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1583 * | preferred-lifetime |
1584 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1585 * | valid-lifetime |
1586 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1587 * . .
1588 * . IAaddr-options .
1589 * . .
1590 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1591 */
Denys Vlasenkoef5207f2018-01-16 21:39:14 +01001592 if (option_mask32 & OPT_r) {
Denys Vlasenko14f13202018-01-16 21:47:10 +01001593 struct d6_option *iaaddr;
1594
Denys Vlasenko1e8d79b2018-01-16 21:35:39 +01001595 free(client6_data.ia_na);
1596 client6_data.ia_na = d6_copy_option(packet.d6_options, packet_end, D6_OPT_IA_NA);
1597 if (!client6_data.ia_na) {
1598 bb_error_msg("no %s option, ignoring packet", "IA_NA");
1599 continue;
1600 }
1601 if (client6_data.ia_na->len < (4 + 4 + 4) + (2 + 2 + 16 + 4 + 4)) {
Denys Vlasenko14f13202018-01-16 21:47:10 +01001602 bb_error_msg("%s option is too short:%d bytes",
1603 "IA_NA", client6_data.ia_na->len);
Denys Vlasenko1e8d79b2018-01-16 21:35:39 +01001604 continue;
1605 }
1606 iaaddr = d6_find_option(client6_data.ia_na->data + 4 + 4 + 4,
1607 client6_data.ia_na->data + client6_data.ia_na->len,
1608 D6_OPT_IAADDR
1609 );
1610 if (!iaaddr) {
1611 bb_error_msg("no %s option, ignoring packet", "IAADDR");
1612 continue;
1613 }
1614 if (iaaddr->len < (16 + 4 + 4)) {
Denys Vlasenko14f13202018-01-16 21:47:10 +01001615 bb_error_msg("%s option is too short:%d bytes",
1616 "IAADDR", iaaddr->len);
Denys Vlasenko1e8d79b2018-01-16 21:35:39 +01001617 continue;
1618 }
1619 /* Note: the address is sufficiently aligned for cast:
1620 * we _copied_ IA-NA, and copy is always well-aligned.
1621 */
1622 requested_ipv6 = (struct in6_addr*) iaaddr->data;
1623 move_from_unaligned32(lease_seconds, iaaddr->data + 16 + 4);
1624 lease_seconds = ntohl(lease_seconds);
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001625/// TODO: check for 0 lease time?
Denys Vlasenko14f13202018-01-16 21:47:10 +01001626 bb_error_msg("%s obtained, lease time %u",
1627 "IPv6", /*inet_ntoa(temp_addr),*/ (unsigned)lease_seconds);
Denys Vlasenko7c44b602018-01-17 13:55:51 +01001628 address_timeout = lease_seconds;
Denys Vlasenkoef5207f2018-01-16 21:39:14 +01001629 }
1630 if (option_mask32 & OPT_d) {
1631 struct d6_option *iaprefix;
1632
1633 free(client6_data.ia_pd);
1634 client6_data.ia_pd = d6_copy_option(packet.d6_options, packet_end, D6_OPT_IA_PD);
1635 if (!client6_data.ia_pd) {
1636 bb_error_msg("no %s option, ignoring packet", "IA_PD");
1637 continue;
1638 }
1639 if (client6_data.ia_pd->len < (4 + 4 + 4) + (2 + 2 + 4 + 4 + 1 + 16)) {
Denys Vlasenko14f13202018-01-16 21:47:10 +01001640 bb_error_msg("%s option is too short:%d bytes",
1641 "IA_PD", client6_data.ia_pd->len);
Denys Vlasenkoef5207f2018-01-16 21:39:14 +01001642 continue;
1643 }
1644 iaprefix = d6_find_option(client6_data.ia_pd->data + 4 + 4 + 4,
1645 client6_data.ia_pd->data + client6_data.ia_pd->len,
1646 D6_OPT_IAPREFIX
1647 );
1648 if (!iaprefix) {
1649 bb_error_msg("no %s option, ignoring packet", "IAPREFIX");
1650 continue;
1651 }
1652 if (iaprefix->len < (4 + 4 + 1 + 16)) {
Denys Vlasenko14f13202018-01-16 21:47:10 +01001653 bb_error_msg("%s option is too short:%d bytes",
1654 "IAPREFIX", iaprefix->len);
Denys Vlasenkoef5207f2018-01-16 21:39:14 +01001655 continue;
1656 }
1657 move_from_unaligned32(lease_seconds, iaprefix->data + 4);
1658 lease_seconds = ntohl(lease_seconds);
Denys Vlasenko14f13202018-01-16 21:47:10 +01001659 bb_error_msg("%s obtained, lease time %u",
1660 "prefix", /*inet_ntoa(temp_addr),*/ (unsigned)lease_seconds);
Denys Vlasenko7c44b602018-01-17 13:55:51 +01001661 prefix_timeout = lease_seconds;
Denys Vlasenkoef5207f2018-01-16 21:39:14 +01001662 }
Denys Vlasenko6e9e6d82018-01-16 21:52:23 +01001663 if (!address_timeout)
1664 address_timeout = prefix_timeout;
1665 if (!prefix_timeout)
1666 prefix_timeout = address_timeout;
Denys Vlasenko7c44b602018-01-17 13:55:51 +01001667 /* note: "int timeout" will not overflow even with 0xffffffff inputs here: */
1668 timeout = (prefix_timeout < address_timeout ? prefix_timeout : address_timeout) / 2;
Denys Vlasenko14f13202018-01-16 21:47:10 +01001669 /* paranoia: must not be too small */
1670 if (timeout < 0x10)
1671 timeout = 0x10;
1672 /* enter bound state */
Denys Vlasenko9ba75042011-11-07 15:55:39 +01001673 d6_run_script(&packet, state == REQUESTING ? "bound" : "renew");
1674
1675 state = BOUND;
1676 change_listen_mode(LISTEN_NONE);
1677 if (opt & OPT_q) { /* quit after lease */
1678 goto ret0;
1679 }
1680 /* future renew failures should not exit (JM) */
1681 opt &= ~OPT_n;
1682#if BB_MMU /* NOMMU case backgrounded earlier */
1683 if (!(opt & OPT_f)) {
1684 client_background();
1685 /* do not background again! */
1686 opt = ((opt & ~OPT_b) | OPT_f);
1687 }
1688#endif
1689 already_waited_sec = 0;
1690 continue; /* back to main loop */
1691 }
1692 continue;
1693 /* case BOUND: - ignore all packets */
1694 /* case RELEASED: - ignore all packets */
1695 }
1696 /* back to main loop */
1697 } /* for (;;) - main loop ends */
1698
1699 ret0:
1700 if (opt & OPT_R) /* release on quit */
1701 perform_d6_release(&srv6_buf, requested_ipv6);
1702 retval = 0;
1703 ret:
1704 /*if (client_config.pidfile) - remove_pidfile has its own check */
1705 remove_pidfile(client_config.pidfile);
1706 return retval;
1707}