SSID: Respect ASCII character Label.
[tomato.git] / release / src / router / busybox / networking / udhcp / d6_dhcpc.c
bloba792a9dcab49d8fc006574af85103893a1513de3
1 /* vi: set sw=4 ts=4: */
2 /*
3 * DHCPv6 client.
5 * 2011-11.
6 * WARNING: THIS CODE IS INCOMPLETE. IT IS NOWHERE NEAR
7 * TO BE READY FOR PRODUCTION USE.
9 * Copyright (C) 2011 Denys Vlasenko.
11 * Licensed under GPLv2, see file LICENSE in this source tree.
14 //config:config UDHCPC6
15 //config: bool "udhcp client for DHCPv6 (udhcpc6)"
16 //config: default n # not yet ready
17 //config: help
18 //config: udhcpc6 is a DHCPv6 client
20 //applet:IF_UDHCPC6(APPLET(udhcpc6, BB_DIR_USR_BIN, BB_SUID_DROP))
22 //kbuild:lib-$(CONFIG_UDHCPC6) += d6_dhcpc.o d6_packet.o d6_socket.o common.o socket.o signalpipe.o
25 #include <syslog.h>
26 /* Override ENABLE_FEATURE_PIDFILE - ifupdown needs our pidfile to always exist */
27 #define WANT_PIDFILE 1
28 #include "common.h"
29 #include "dhcpd.h"
30 #include "dhcpc.h"
31 #include "d6_common.h"
33 #include <netinet/if_ether.h>
34 #include <netpacket/packet.h>
35 #include <linux/filter.h>
37 /* "struct client_config_t client_config" is in bb_common_bufsiz1 */
40 #if ENABLE_LONG_OPTS
41 static const char udhcpc6_longopts[] ALIGN1 =
42 "interface\0" Required_argument "i"
43 "now\0" No_argument "n"
44 "pidfile\0" Required_argument "p"
45 "quit\0" No_argument "q"
46 "release\0" No_argument "R"
47 "request\0" Required_argument "r"
48 "script\0" Required_argument "s"
49 "timeout\0" Required_argument "T"
50 "retries\0" Required_argument "t"
51 "tryagain\0" Required_argument "A"
52 "syslog\0" No_argument "S"
53 "request-option\0" Required_argument "O"
54 "no-default-options\0" No_argument "o"
55 "foreground\0" No_argument "f"
56 "background\0" No_argument "b"
57 /// IF_FEATURE_UDHCPC_ARPING("arping\0" No_argument "a")
58 IF_FEATURE_UDHCP_PORT("client-port\0" Required_argument "P")
60 #endif
61 /* Must match getopt32 option string order */
62 enum {
63 OPT_i = 1 << 0,
64 OPT_n = 1 << 1,
65 OPT_p = 1 << 2,
66 OPT_q = 1 << 3,
67 OPT_R = 1 << 4,
68 OPT_r = 1 << 5,
69 OPT_s = 1 << 6,
70 OPT_T = 1 << 7,
71 OPT_t = 1 << 8,
72 OPT_S = 1 << 9,
73 OPT_A = 1 << 10,
74 OPT_O = 1 << 11,
75 OPT_o = 1 << 12,
76 OPT_x = 1 << 13,
77 OPT_f = 1 << 14,
78 /* The rest has variable bit positions, need to be clever */
79 OPTBIT_f = 14,
80 USE_FOR_MMU( OPTBIT_b,)
81 ///IF_FEATURE_UDHCPC_ARPING(OPTBIT_a,)
82 IF_FEATURE_UDHCP_PORT( OPTBIT_P,)
83 USE_FOR_MMU( OPT_b = 1 << OPTBIT_b,)
84 ///IF_FEATURE_UDHCPC_ARPING(OPT_a = 1 << OPTBIT_a,)
85 IF_FEATURE_UDHCP_PORT( OPT_P = 1 << OPTBIT_P,)
89 /*** Utility functions ***/
91 static void *d6_find_option(uint8_t *option, uint8_t *option_end, unsigned code)
93 /* "length minus 4" */
94 int len_m4 = option_end - option - 4;
95 while (len_m4 >= 0) {
96 /* Next option's len is too big? */
97 if (option[3] > len_m4)
98 return NULL; /* yes. bogus packet! */
99 /* So far we treat any opts with code >255
100 * or len >255 as bogus, and stop at once.
101 * This simplifies big-endian handling.
103 if (option[0] != 0 || option[2] != 0)
104 return NULL;
105 /* Option seems to be valid */
106 /* Does its code match? */
107 if (option[1] == code)
108 return option; /* yes! */
109 option += option[3] + 4;
110 len_m4 -= option[3] + 4;
112 return NULL;
115 static void *d6_copy_option(uint8_t *option, uint8_t *option_end, unsigned code)
117 uint8_t *opt = d6_find_option(option, option_end, code);
118 if (!opt)
119 return opt;
120 return memcpy(xmalloc(opt[3] + 4), opt, opt[3] + 4);
123 static void *d6_store_blob(void *dst, const void *src, unsigned len)
125 memcpy(dst, src, len);
126 return dst + len;
130 /*** Script execution code ***/
132 static char** new_env(void)
134 client6_data.env_ptr = xrealloc_vector(client6_data.env_ptr, 3, client6_data.env_idx);
135 return &client6_data.env_ptr[client6_data.env_idx++];
138 /* put all the parameters into the environment */
139 static void option_to_env(uint8_t *option, uint8_t *option_end)
141 /* "length minus 4" */
142 int len_m4 = option_end - option - 4;
143 while (len_m4 >= 0) {
144 uint32_t v32;
145 char ipv6str[sizeof("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")];
147 if (option[0] != 0 || option[2] != 0)
148 break;
150 switch (option[1]) {
151 //case D6_OPT_CLIENTID:
152 //case D6_OPT_SERVERID:
153 case D6_OPT_IA_NA:
154 case D6_OPT_IA_PD:
155 option_to_env(option + 16, option + 4 + option[3]);
156 break;
157 //case D6_OPT_IA_TA:
158 case D6_OPT_IAADDR:
159 /* 0 1 2 3
160 * 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
161 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
162 * | OPTION_IAADDR | option-len |
163 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
164 * | |
165 * | IPv6 address |
166 * | |
167 * | |
168 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
169 * | preferred-lifetime |
170 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
171 * | valid-lifetime |
172 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
174 sprint_nip6(ipv6str, option + 4);
175 *new_env() = xasprintf("ipv6=%s", ipv6str);
177 move_from_unaligned32(v32, option + 4 + 16 + 4);
178 *new_env() = xasprintf("lease=%u", (unsigned)v32);
179 break;
181 //case D6_OPT_ORO:
182 //case D6_OPT_PREFERENCE:
183 //case D6_OPT_ELAPSED_TIME:
184 //case D6_OPT_RELAY_MSG:
185 //case D6_OPT_AUTH:
186 //case D6_OPT_UNICAST:
187 //case D6_OPT_STATUS_CODE:
188 //case D6_OPT_RAPID_COMMIT:
189 //case D6_OPT_USER_CLASS:
190 //case D6_OPT_VENDOR_CLASS:
191 //case D6_OPT_VENDOR_OPTS:
192 //case D6_OPT_INTERFACE_ID:
193 //case D6_OPT_RECONF_MSG:
194 //case D6_OPT_RECONF_ACCEPT:
196 case D6_OPT_IAPREFIX:
197 /* 0 1 2 3
198 * 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
199 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
200 * | OPTION_IAPREFIX | option-length |
201 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
202 * | preferred-lifetime |
203 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
204 * | valid-lifetime |
205 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
206 * | prefix-length | |
207 * +-+-+-+-+-+-+-+-+ IPv6 prefix |
208 * | (16 octets) |
209 * | |
210 * | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
211 * | |
212 * +-+-+-+-+-+-+-+-+
214 //move_from_unaligned32(v32, option + 4 + 4);
215 //*new_env() = xasprintf("lease=%u", (unsigned)v32);
217 sprint_nip6(ipv6str, option + 4 + 4 + 1);
218 *new_env() = xasprintf("ipv6prefix=%s/%u", ipv6str, (unsigned)(option[4 + 4]));
220 option += 4 + option[3];
221 len_m4 -= 4 + option[3];
225 static char **fill_envp(struct d6_packet *packet)
227 char **envp, **curr;
229 client6_data.env_ptr = NULL;
230 client6_data.env_idx = 0;
232 *new_env() = xasprintf("interface=%s", client_config.interface);
234 if (packet)
235 option_to_env(packet->d6_options, packet->d6_options + sizeof(packet->d6_options));
237 envp = curr = client6_data.env_ptr;
238 while (*curr)
239 putenv(*curr++);
241 return envp;
244 /* Call a script with a par file and env vars */
245 static void d6_run_script(struct d6_packet *packet, const char *name)
247 char **envp, **curr;
248 char *argv[3];
250 envp = fill_envp(packet);
252 /* call script */
253 log1("Executing %s %s", client_config.script, name);
254 argv[0] = (char*) client_config.script;
255 argv[1] = (char*) name;
256 argv[2] = NULL;
257 spawn_and_wait(argv);
259 for (curr = envp; *curr; curr++) {
260 log2(" %s", *curr);
261 bb_unsetenv_and_free(*curr);
263 free(envp);
267 /*** Sending/receiving packets ***/
269 static ALWAYS_INLINE uint32_t random_xid(void)
271 uint32_t t = rand() & htonl(0x00ffffff);
272 return t;
275 /* Initialize the packet with the proper defaults */
276 static uint8_t *init_d6_packet(struct d6_packet *packet, char type, uint32_t xid)
278 struct d6_option *clientid;
280 memset(packet, 0, sizeof(*packet));
282 packet->d6_xid32 = xid;
283 packet->d6_msg_type = type;
285 clientid = (void*)client_config.clientid;
286 return d6_store_blob(packet->d6_options, clientid, clientid->len + 2+2);
289 static uint8_t *add_d6_client_options(uint8_t *ptr)
291 return ptr;
292 //uint8_t c;
293 //int i, end, len;
295 /* Add a "param req" option with the list of options we'd like to have
296 * from stubborn DHCP servers. Pull the data from the struct in common.c.
297 * No bounds checking because it goes towards the head of the packet. */
298 //...
300 /* Add -x options if any */
301 //...
304 static int d6_mcast_from_client_config_ifindex(struct d6_packet *packet, uint8_t *end)
306 static const uint8_t FF02__1_2[16] = {
307 0xFF, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
308 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02,
311 return d6_send_raw_packet(
312 packet, (end - (uint8_t*) packet),
313 /*src*/ NULL, CLIENT_PORT,
314 /*dst*/ (struct in6_addr*)FF02__1_2, SERVER_PORT, MAC_BCAST_ADDR,
315 client_config.ifindex
319 /* Milticast a DHCPv6 Solicit packet to the network, with an optionally requested IP.
321 * RFC 3315 17.1.1. Creation of Solicit Messages
323 * The client MUST include a Client Identifier option to identify itself
324 * to the server. The client includes IA options for any IAs to which
325 * it wants the server to assign addresses. The client MAY include
326 * addresses in the IAs as a hint to the server about addresses for
327 * which the client has a preference. ...
329 * The client uses IA_NA options to request the assignment of non-
330 * temporary addresses and uses IA_TA options to request the assignment
331 * of temporary addresses. Either IA_NA or IA_TA options, or a
332 * combination of both, can be included in DHCP messages.
334 * The client SHOULD include an Option Request option (see section 22.7)
335 * to indicate the options the client is interested in receiving. The
336 * client MAY additionally include instances of those options that are
337 * identified in the Option Request option, with data values as hints to
338 * the server about parameter values the client would like to have
339 * returned.
341 * The client includes a Reconfigure Accept option (see section 22.20)
342 * if the client is willing to accept Reconfigure messages from the
343 * server.
344 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
345 | OPTION_CLIENTID | option-len |
346 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
348 . DUID .
349 . (variable length) .
351 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
354 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
355 | OPTION_IA_NA | option-len |
356 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
357 | IAID (4 octets) |
358 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
359 | T1 |
360 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
361 | T2 |
362 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
364 . IA_NA-options .
366 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
369 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
370 | OPTION_IAADDR | option-len |
371 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
373 | IPv6 address |
376 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
377 | preferred-lifetime |
378 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
379 | valid-lifetime |
380 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
382 . IAaddr-options .
384 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
387 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
388 | OPTION_ORO | option-len |
389 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
390 | requested-option-code-1 | requested-option-code-2 |
391 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
392 | ... |
393 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
396 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
397 | OPTION_RECONF_ACCEPT | 0 |
398 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
400 /* NOINLINE: limit stack usage in caller */
401 static NOINLINE int send_d6_discover(uint32_t xid, struct in6_addr *requested_ipv6)
403 struct d6_packet packet;
404 uint8_t *opt_ptr;
405 unsigned len;
407 /* Fill in: msg type, client id */
408 opt_ptr = init_d6_packet(&packet, D6_MSG_SOLICIT, xid);
410 /* Create new IA_NA, optionally with included IAADDR with requested IP */
411 free(client6_data.ia_na);
412 len = requested_ipv6 ? 2+2+4+4+4 + 2+2+16+4+4 : 2+2+4+4+4;
413 client6_data.ia_na = xzalloc(len);
414 client6_data.ia_na->code = D6_OPT_IA_NA;
415 client6_data.ia_na->len = len - 4;
416 *(uint32_t*)client6_data.ia_na->data = rand(); /* IAID */
417 if (requested_ipv6) {
418 struct d6_option *iaaddr = (void*)(client6_data.ia_na->data + 4+4+4);
419 iaaddr->code = D6_OPT_IAADDR;
420 iaaddr->len = 16+4+4;
421 memcpy(iaaddr->data, requested_ipv6, 16);
423 opt_ptr = d6_store_blob(opt_ptr, client6_data.ia_na, len);
425 /* Add options:
426 * "param req" option according to -O, options specified with -x
428 opt_ptr = add_d6_client_options(opt_ptr);
430 bb_info_msg("Sending discover...");
431 return d6_mcast_from_client_config_ifindex(&packet, opt_ptr);
434 /* Multicast a DHCPv6 request message
436 * RFC 3315 18.1.1. Creation and Transmission of Request Messages
438 * The client uses a Request message to populate IAs with addresses and
439 * obtain other configuration information. The client includes one or
440 * more IA options in the Request message. The server then returns
441 * addresses and other information about the IAs to the client in IA
442 * options in a Reply message.
444 * The client generates a transaction ID and inserts this value in the
445 * "transaction-id" field.
447 * The client places the identifier of the destination server in a
448 * Server Identifier option.
450 * The client MUST include a Client Identifier option to identify itself
451 * to the server. The client adds any other appropriate options,
452 * including one or more IA options (if the client is requesting that
453 * the server assign it some network addresses).
455 * The client MUST include an Option Request option (see section 22.7)
456 * to indicate the options the client is interested in receiving. The
457 * client MAY include options with data values as hints to the server
458 * about parameter values the client would like to have returned.
460 * The client includes a Reconfigure Accept option (see section 22.20)
461 * indicating whether or not the client is willing to accept Reconfigure
462 * messages from the server.
464 /* NOINLINE: limit stack usage in caller */
465 static NOINLINE int send_d6_select(uint32_t xid)
467 struct d6_packet packet;
468 uint8_t *opt_ptr;
470 /* Fill in: msg type, client id */
471 opt_ptr = init_d6_packet(&packet, D6_MSG_REQUEST, xid);
473 /* server id */
474 opt_ptr = d6_store_blob(opt_ptr, client6_data.server_id, client6_data.server_id->len + 2+2);
475 /* IA NA (contains requested IP) */
476 opt_ptr = d6_store_blob(opt_ptr, client6_data.ia_na, client6_data.ia_na->len + 2+2);
478 /* Add options:
479 * "param req" option according to -O, options specified with -x
481 opt_ptr = add_d6_client_options(opt_ptr);
483 bb_info_msg("Sending select...");
484 return d6_mcast_from_client_config_ifindex(&packet, opt_ptr);
487 /* Unicast or broadcast a DHCP renew message
489 * RFC 3315 18.1.3. Creation and Transmission of Renew Messages
491 * To extend the valid and preferred lifetimes for the addresses
492 * associated with an IA, the client sends a Renew message to the server
493 * from which the client obtained the addresses in the IA containing an
494 * IA option for the IA. The client includes IA Address options in the
495 * IA option for the addresses associated with the IA. The server
496 * determines new lifetimes for the addresses in the IA according to the
497 * administrative configuration of the server. The server may also add
498 * new addresses to the IA. The server may remove addresses from the IA
499 * by setting the preferred and valid lifetimes of those addresses to
500 * zero.
502 * The server controls the time at which the client contacts the server
503 * to extend the lifetimes on assigned addresses through the T1 and T2
504 * parameters assigned to an IA.
506 * At time T1 for an IA, the client initiates a Renew/Reply message
507 * exchange to extend the lifetimes on any addresses in the IA. The
508 * client includes an IA option with all addresses currently assigned to
509 * the IA in its Renew message.
511 * If T1 or T2 is set to 0 by the server (for an IA_NA) or there are no
512 * T1 or T2 times (for an IA_TA), the client may send a Renew or Rebind
513 * message, respectively, at the client's discretion.
515 * The client sets the "msg-type" field to RENEW. The client generates
516 * a transaction ID and inserts this value in the "transaction-id"
517 * field.
519 * The client places the identifier of the destination server in a
520 * Server Identifier option.
522 * The client MUST include a Client Identifier option to identify itself
523 * to the server. The client adds any appropriate options, including
524 * one or more IA options. The client MUST include the list of
525 * addresses the client currently has associated with the IAs in the
526 * Renew message.
528 * The client MUST include an Option Request option (see section 22.7)
529 * to indicate the options the client is interested in receiving. The
530 * client MAY include options with data values as hints to the server
531 * about parameter values the client would like to have returned.
533 /* NOINLINE: limit stack usage in caller */
534 static NOINLINE int send_d6_renew(uint32_t xid, struct in6_addr *server_ipv6, struct in6_addr *our_cur_ipv6)
536 struct d6_packet packet;
537 uint8_t *opt_ptr;
539 /* Fill in: msg type, client id */
540 opt_ptr = init_d6_packet(&packet, DHCPREQUEST, xid);
542 /* server id */
543 opt_ptr = d6_store_blob(opt_ptr, client6_data.server_id, client6_data.server_id->len + 2+2);
544 /* IA NA (contains requested IP) */
545 opt_ptr = d6_store_blob(opt_ptr, client6_data.ia_na, client6_data.ia_na->len + 2+2);
547 /* Add options:
548 * "param req" option according to -O, options specified with -x
550 opt_ptr = add_d6_client_options(opt_ptr);
552 bb_info_msg("Sending renew...");
553 if (server_ipv6)
554 return d6_send_kernel_packet(
555 &packet, (opt_ptr - (uint8_t*) &packet),
556 our_cur_ipv6, CLIENT_PORT,
557 server_ipv6, SERVER_PORT
559 return d6_mcast_from_client_config_ifindex(&packet, opt_ptr);
562 /* Unicast a DHCP release message */
563 static int send_d6_release(struct in6_addr *server_ipv6, struct in6_addr *our_cur_ipv6)
565 struct d6_packet packet;
566 uint8_t *opt_ptr;
568 /* Fill in: msg type, client id */
569 opt_ptr = init_d6_packet(&packet, D6_MSG_RELEASE, random_xid());
570 /* server id */
571 opt_ptr = d6_store_blob(opt_ptr, client6_data.server_id, client6_data.server_id->len + 2+2);
572 /* IA NA (contains our current IP) */
573 opt_ptr = d6_store_blob(opt_ptr, client6_data.ia_na, client6_data.ia_na->len + 2+2);
575 bb_info_msg("Sending release...");
576 return d6_send_kernel_packet(
577 &packet, (opt_ptr - (uint8_t*) &packet),
578 our_cur_ipv6, CLIENT_PORT,
579 server_ipv6, SERVER_PORT
583 /* Returns -1 on errors that are fatal for the socket, -2 for those that aren't */
584 /* NOINLINE: limit stack usage in caller */
585 static NOINLINE int d6_recv_raw_packet(struct in6_addr *peer_ipv6
586 UNUSED_PARAM
587 , struct d6_packet *d6_pkt, int fd)
589 int bytes;
590 struct ip6_udp_d6_packet packet;
592 bytes = safe_read(fd, &packet, sizeof(packet));
593 if (bytes < 0) {
594 log1("Packet read error, ignoring");
595 /* NB: possible down interface, etc. Caller should pause. */
596 return bytes; /* returns -1 */
599 if (bytes < (int) (sizeof(packet.ip6) + sizeof(packet.udp))) {
600 log1("Packet is too short, ignoring");
601 return -2;
604 if (bytes < sizeof(packet.ip6) + ntohs(packet.ip6.ip6_plen)) {
605 /* packet is bigger than sizeof(packet), we did partial read */
606 log1("Oversized packet, ignoring");
607 return -2;
610 /* ignore any extra garbage bytes */
611 bytes = sizeof(packet.ip6) + ntohs(packet.ip6.ip6_plen);
613 /* make sure its the right packet for us, and that it passes sanity checks */
614 if (packet.ip6.ip6_nxt != IPPROTO_UDP
615 || (packet.ip6.ip6_vfc >> 4) != 6
616 || packet.udp.dest != htons(CLIENT_PORT)
617 /* || bytes > (int) sizeof(packet) - can't happen */
618 || packet.udp.len != packet.ip6.ip6_plen
620 log1("Unrelated/bogus packet, ignoring");
621 return -2;
624 //How to do this for ipv6?
625 // /* verify UDP checksum. IP header has to be modified for this */
626 // memset(&packet.ip, 0, offsetof(struct iphdr, protocol));
627 // /* ip.xx fields which are not memset: protocol, check, saddr, daddr */
628 // packet.ip.tot_len = packet.udp.len; /* yes, this is needed */
629 // check = packet.udp.check;
630 // packet.udp.check = 0;
631 // if (check && check != inet_cksum((uint16_t *)&packet, bytes)) {
632 // log1("Packet with bad UDP checksum received, ignoring");
633 // return -2;
634 // }
636 log1("Received a packet");
637 d6_dump_packet(&packet.data);
639 bytes -= sizeof(packet.ip6) + sizeof(packet.udp);
640 memcpy(d6_pkt, &packet.data, bytes);
641 return bytes;
645 /*** Main ***/
647 static int sockfd = -1;
649 #define LISTEN_NONE 0
650 #define LISTEN_KERNEL 1
651 #define LISTEN_RAW 2
652 static smallint listen_mode;
654 /* initial state: (re)start DHCP negotiation */
655 #define INIT_SELECTING 0
656 /* discover was sent, DHCPOFFER reply received */
657 #define REQUESTING 1
658 /* select/renew was sent, DHCPACK reply received */
659 #define BOUND 2
660 /* half of lease passed, want to renew it by sending unicast renew requests */
661 #define RENEWING 3
662 /* renew requests were not answered, lease is almost over, send broadcast renew */
663 #define REBINDING 4
664 /* manually requested renew (SIGUSR1) */
665 #define RENEW_REQUESTED 5
666 /* release, possibly manually requested (SIGUSR2) */
667 #define RELEASED 6
668 static smallint state;
670 static int d6_raw_socket(int ifindex)
672 int fd;
673 struct sockaddr_ll sock;
676 * Comment:
678 * I've selected not to see LL header, so BPF doesn't see it, too.
679 * The filter may also pass non-IP and non-ARP packets, but we do
680 * a more complete check when receiving the message in userspace.
682 * and filter shamelessly stolen from:
684 * http://www.flamewarmaster.de/software/dhcpclient/
686 * There are a few other interesting ideas on that page (look under
687 * "Motivation"). Use of netlink events is most interesting. Think
688 * of various network servers listening for events and reconfiguring.
689 * That would obsolete sending HUP signals and/or make use of restarts.
691 * Copyright: 2006, 2007 Stefan Rompf <sux@loplof.de>.
692 * License: GPL v2.
694 * TODO: make conditional?
696 #if 0
697 static const struct sock_filter filter_instr[] = {
698 /* load 9th byte (protocol) */
699 BPF_STMT(BPF_LD|BPF_B|BPF_ABS, 9),
700 /* jump to L1 if it is IPPROTO_UDP, else to L4 */
701 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, IPPROTO_UDP, 0, 6),
702 /* L1: load halfword from offset 6 (flags and frag offset) */
703 BPF_STMT(BPF_LD|BPF_H|BPF_ABS, 6),
704 /* jump to L4 if any bits in frag offset field are set, else to L2 */
705 BPF_JUMP(BPF_JMP|BPF_JSET|BPF_K, 0x1fff, 4, 0),
706 /* L2: skip IP header (load index reg with header len) */
707 BPF_STMT(BPF_LDX|BPF_B|BPF_MSH, 0),
708 /* load udp destination port from halfword[header_len + 2] */
709 BPF_STMT(BPF_LD|BPF_H|BPF_IND, 2),
710 /* jump to L3 if udp dport is CLIENT_PORT, else to L4 */
711 BPF_JUMP(BPF_JMP|BPF_JEQ|BPF_K, 68, 0, 1),
712 /* L3: accept packet */
713 BPF_STMT(BPF_RET|BPF_K, 0xffffffff),
714 /* L4: discard packet */
715 BPF_STMT(BPF_RET|BPF_K, 0),
717 static const struct sock_fprog filter_prog = {
718 .len = sizeof(filter_instr) / sizeof(filter_instr[0]),
719 /* casting const away: */
720 .filter = (struct sock_filter *) filter_instr,
722 #endif
724 log1("Opening raw socket on ifindex %d", ifindex); //log2?
726 fd = xsocket(PF_PACKET, SOCK_DGRAM, htons(ETH_P_IPV6));
727 log1("Got raw socket fd %d", fd); //log2?
729 sock.sll_family = AF_PACKET;
730 sock.sll_protocol = htons(ETH_P_IPV6);
731 sock.sll_ifindex = ifindex;
732 xbind(fd, (struct sockaddr *) &sock, sizeof(sock));
734 #if 0
735 if (CLIENT_PORT == 68) {
736 /* Use only if standard port is in use */
737 /* Ignoring error (kernel may lack support for this) */
738 if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &filter_prog,
739 sizeof(filter_prog)) >= 0)
740 log1("Attached filter to raw socket fd %d", fd); // log?
742 #endif
744 log1("Created raw socket");
746 return fd;
749 static void change_listen_mode(int new_mode)
751 log1("Entering listen mode: %s",
752 new_mode != LISTEN_NONE
753 ? (new_mode == LISTEN_KERNEL ? "kernel" : "raw")
754 : "none"
757 listen_mode = new_mode;
758 if (sockfd >= 0) {
759 close(sockfd);
760 sockfd = -1;
762 if (new_mode == LISTEN_KERNEL)
763 sockfd = udhcp_listen_socket(/*INADDR_ANY,*/ CLIENT_PORT, client_config.interface);
764 else if (new_mode != LISTEN_NONE)
765 sockfd = d6_raw_socket(client_config.ifindex);
766 /* else LISTEN_NONE: sockfd stays closed */
769 /* Called only on SIGUSR1 */
770 static void perform_renew(void)
772 bb_info_msg("Performing a DHCP renew");
773 switch (state) {
774 case BOUND:
775 change_listen_mode(LISTEN_KERNEL);
776 case RENEWING:
777 case REBINDING:
778 state = RENEW_REQUESTED;
779 break;
780 case RENEW_REQUESTED: /* impatient are we? fine, square 1 */
781 d6_run_script(NULL, "deconfig");
782 case REQUESTING:
783 case RELEASED:
784 change_listen_mode(LISTEN_RAW);
785 state = INIT_SELECTING;
786 break;
787 case INIT_SELECTING:
788 break;
792 static void perform_d6_release(struct in6_addr *server_ipv6, struct in6_addr *our_cur_ipv6)
794 /* send release packet */
795 if (state == BOUND || state == RENEWING || state == REBINDING) {
796 bb_info_msg("Unicasting a release");
797 send_d6_release(server_ipv6, our_cur_ipv6); /* unicast */
798 d6_run_script(NULL, "deconfig");
800 bb_info_msg("Entering released state");
802 change_listen_mode(LISTEN_NONE);
803 state = RELEASED;
806 ///static uint8_t* alloc_dhcp_option(int code, const char *str, int extra)
807 ///{
808 /// uint8_t *storage;
809 /// int len = strnlen(str, 255);
810 /// storage = xzalloc(len + extra + OPT_DATA);
811 /// storage[OPT_CODE] = code;
812 /// storage[OPT_LEN] = len + extra;
813 /// memcpy(storage + extra + OPT_DATA, str, len);
814 /// return storage;
815 ///}
817 #if BB_MMU
818 static void client_background(void)
820 bb_daemonize(0);
821 logmode &= ~LOGMODE_STDIO;
822 /* rewrite pidfile, as our pid is different now */
823 write_pidfile(client_config.pidfile);
825 #endif
827 //usage:#if defined CONFIG_UDHCP_DEBUG && CONFIG_UDHCP_DEBUG >= 1
828 //usage:# define IF_UDHCP_VERBOSE(...) __VA_ARGS__
829 //usage:#else
830 //usage:# define IF_UDHCP_VERBOSE(...)
831 //usage:#endif
832 //usage:#define udhcpc6_trivial_usage
833 //usage: "[-fbnq"IF_UDHCP_VERBOSE("v")"oR] [-i IFACE] [-r IP] [-s PROG] [-p PIDFILE]\n"
834 //usage: " [-x OPT:VAL]... [-O OPT]..." IF_FEATURE_UDHCP_PORT(" [-P N]")
835 //usage:#define udhcpc6_full_usage "\n"
836 //usage: IF_LONG_OPTS(
837 //usage: "\n -i,--interface IFACE Interface to use (default eth0)"
838 //usage: "\n -p,--pidfile FILE Create pidfile"
839 //usage: "\n -s,--script PROG Run PROG at DHCP events (default "CONFIG_UDHCPC_DEFAULT_SCRIPT")"
840 //usage: "\n -B,--broadcast Request broadcast replies"
841 //usage: "\n -t,--retries N Send up to N discover packets"
842 //usage: "\n -T,--timeout N Pause between packets (default 3 seconds)"
843 //usage: "\n -A,--tryagain N Wait N seconds after failure (default 20)"
844 //usage: "\n -f,--foreground Run in foreground"
845 //usage: USE_FOR_MMU(
846 //usage: "\n -b,--background Background if lease is not obtained"
847 //usage: )
848 //usage: "\n -n,--now Exit if lease is not obtained"
849 //usage: "\n -q,--quit Exit after obtaining lease"
850 //usage: "\n -R,--release Release IP on exit"
851 //usage: "\n -S,--syslog Log to syslog too"
852 //usage: IF_FEATURE_UDHCP_PORT(
853 //usage: "\n -P,--client-port N Use port N (default 546)"
854 //usage: )
855 ////usage: IF_FEATURE_UDHCPC_ARPING(
856 ////usage: "\n -a,--arping Use arping to validate offered address"
857 ////usage: )
858 //usage: "\n -O,--request-option OPT Request option OPT from server (cumulative)"
859 //usage: "\n -o,--no-default-options Don't request any options (unless -O is given)"
860 //usage: "\n -r,--request IP Request this IP address"
861 //usage: "\n -x OPT:VAL Include option OPT in sent packets (cumulative)"
862 //usage: "\n Examples of string, numeric, and hex byte opts:"
863 //usage: "\n -x hostname:bbox - option 12"
864 //usage: "\n -x lease:3600 - option 51 (lease time)"
865 //usage: "\n -x 0x3d:0100BEEFC0FFEE - option 61 (client id)"
866 //usage: IF_UDHCP_VERBOSE(
867 //usage: "\n -v Verbose"
868 //usage: )
869 //usage: )
870 //usage: IF_NOT_LONG_OPTS(
871 //usage: "\n -i IFACE Interface to use (default eth0)"
872 //usage: "\n -p FILE Create pidfile"
873 //usage: "\n -s PROG Run PROG at DHCP events (default "CONFIG_UDHCPC_DEFAULT_SCRIPT")"
874 //usage: "\n -B Request broadcast replies"
875 //usage: "\n -t N Send up to N discover packets"
876 //usage: "\n -T N Pause between packets (default 3 seconds)"
877 //usage: "\n -A N Wait N seconds (default 20) after failure"
878 //usage: "\n -f Run in foreground"
879 //usage: USE_FOR_MMU(
880 //usage: "\n -b Background if lease is not obtained"
881 //usage: )
882 //usage: "\n -n Exit if lease is not obtained"
883 //usage: "\n -q Exit after obtaining lease"
884 //usage: "\n -R Release IP on exit"
885 //usage: "\n -S Log to syslog too"
886 //usage: IF_FEATURE_UDHCP_PORT(
887 //usage: "\n -P N Use port N (default 546)"
888 //usage: )
889 ////usage: IF_FEATURE_UDHCPC_ARPING(
890 ////usage: "\n -a Use arping to validate offered address"
891 ////usage: )
892 //usage: "\n -O OPT Request option OPT from server (cumulative)"
893 //usage: "\n -o Don't request any options (unless -O is given)"
894 //usage: "\n -r IP Request this IP address"
895 //usage: "\n -x OPT:VAL Include option OPT in sent packets (cumulative)"
896 //usage: "\n Examples of string, numeric, and hex byte opts:"
897 //usage: "\n -x hostname:bbox - option 12"
898 //usage: "\n -x lease:3600 - option 51 (lease time)"
899 //usage: "\n -x 0x3d:0100BEEFC0FFEE - option 61 (client id)"
900 //usage: IF_UDHCP_VERBOSE(
901 //usage: "\n -v Verbose"
902 //usage: )
903 //usage: )
904 //usage: "\nSignals:"
905 //usage: "\n USR1 Renew lease"
906 //usage: "\n USR2 Release lease"
909 int udhcpc6_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
910 int udhcpc6_main(int argc UNUSED_PARAM, char **argv)
912 const char *str_r;
913 IF_FEATURE_UDHCP_PORT(char *str_P;)
914 void *clientid_mac_ptr;
915 llist_t *list_O = NULL;
916 llist_t *list_x = NULL;
917 int tryagain_timeout = 20;
918 int discover_timeout = 3;
919 int discover_retries = 3;
920 struct in6_addr srv6_buf;
921 struct in6_addr ipv6_buf;
922 struct in6_addr *requested_ipv6;
923 uint32_t xid = 0;
924 int packet_num;
925 int timeout; /* must be signed */
926 unsigned already_waited_sec;
927 unsigned opt;
928 int max_fd;
929 int retval;
930 fd_set rfds;
932 /* Default options */
933 IF_FEATURE_UDHCP_PORT(SERVER_PORT = 547;)
934 IF_FEATURE_UDHCP_PORT(CLIENT_PORT = 546;)
935 client_config.interface = "eth0";
936 client_config.script = CONFIG_UDHCPC_DEFAULT_SCRIPT;
938 /* Parse command line */
939 /* O,x: list; -T,-t,-A take numeric param */
940 opt_complementary = "O::x::T+:t+:A+" IF_UDHCP_VERBOSE(":vv") ;
941 IF_LONG_OPTS(applet_long_options = udhcpc6_longopts;)
942 opt = getopt32(argv, "i:np:qRr:s:T:t:SA:O:ox:f"
943 USE_FOR_MMU("b")
944 ///IF_FEATURE_UDHCPC_ARPING("a")
945 IF_FEATURE_UDHCP_PORT("P:")
947 , &client_config.interface, &client_config.pidfile, &str_r /* i,p */
948 , &client_config.script /* s */
949 , &discover_timeout, &discover_retries, &tryagain_timeout /* T,t,A */
950 , &list_O
951 , &list_x
952 IF_FEATURE_UDHCP_PORT(, &str_P)
953 IF_UDHCP_VERBOSE(, &dhcp_verbose)
955 requested_ipv6 = NULL;
956 if (opt & OPT_r) {
957 if (inet_pton(AF_INET6, str_r, &ipv6_buf) <= 0)
958 bb_error_msg_and_die("bad IPv6 address '%s'", str_r);
959 requested_ipv6 = &ipv6_buf;
961 #if ENABLE_FEATURE_UDHCP_PORT
962 if (opt & OPT_P) {
963 CLIENT_PORT = xatou16(str_P);
964 SERVER_PORT = CLIENT_PORT - 1;
966 #endif
967 if (opt & OPT_o)
968 client_config.no_default_options = 1;
969 while (list_O) {
970 char *optstr = llist_pop(&list_O);
971 unsigned n = bb_strtou(optstr, NULL, 0);
972 if (errno || n > 254) {
973 n = udhcp_option_idx(optstr);
974 n = dhcp_optflags[n].code;
976 client_config.opt_mask[n >> 3] |= 1 << (n & 7);
978 while (list_x) {
979 char *optstr = llist_pop(&list_x);
980 char *colon = strchr(optstr, ':');
981 if (colon)
982 *colon = ' ';
983 /* now it looks similar to udhcpd's config file line:
984 * "optname optval", using the common routine: */
985 udhcp_str2optset(optstr, &client_config.options);
988 if (udhcp_read_interface(client_config.interface,
989 &client_config.ifindex,
990 NULL,
991 client_config.client_mac)
993 return 1;
996 /* Create client ID based on mac, set clientid_mac_ptr */
998 struct d6_option *clientid;
999 clientid = xzalloc(2+2+2+2+6);
1000 clientid->code = D6_OPT_CLIENTID;
1001 clientid->len = 2+2+6;
1002 clientid->data[1] = 3; /* DUID-LL */
1003 clientid->data[3] = 1; /* ethernet */
1004 clientid_mac_ptr = clientid->data + 2+2;
1005 memcpy(clientid_mac_ptr, client_config.client_mac, 6);
1006 client_config.clientid = (void*)clientid;
1009 #if !BB_MMU
1010 /* on NOMMU reexec (i.e., background) early */
1011 if (!(opt & OPT_f)) {
1012 bb_daemonize_or_rexec(0 /* flags */, argv);
1013 logmode = LOGMODE_NONE;
1015 #endif
1016 if (opt & OPT_S) {
1017 openlog(applet_name, LOG_PID, LOG_DAEMON);
1018 logmode |= LOGMODE_SYSLOG;
1021 /* Make sure fd 0,1,2 are open */
1022 bb_sanitize_stdio();
1023 /* Equivalent of doing a fflush after every \n */
1024 setlinebuf(stdout);
1025 /* Create pidfile */
1026 write_pidfile(client_config.pidfile);
1027 /* Goes to stdout (unless NOMMU) and possibly syslog */
1028 bb_info_msg("%s (v"BB_VER") started", applet_name);
1029 /* Set up the signal pipe */
1030 udhcp_sp_setup();
1031 /* We want random_xid to be random... */
1032 srand(monotonic_us());
1034 state = INIT_SELECTING;
1035 d6_run_script(NULL, "deconfig");
1036 change_listen_mode(LISTEN_RAW);
1037 packet_num = 0;
1038 timeout = 0;
1039 already_waited_sec = 0;
1041 /* Main event loop. select() waits on signal pipe and possibly
1042 * on sockfd.
1043 * "continue" statements in code below jump to the top of the loop.
1045 for (;;) {
1046 struct timeval tv;
1047 struct d6_packet packet;
1048 uint8_t *packet_end;
1049 /* silence "uninitialized!" warning */
1050 unsigned timestamp_before_wait = timestamp_before_wait;
1052 //bb_error_msg("sockfd:%d, listen_mode:%d", sockfd, listen_mode);
1054 /* Was opening raw or udp socket here
1055 * if (listen_mode != LISTEN_NONE && sockfd < 0),
1056 * but on fast network renew responses return faster
1057 * than we open sockets. Thus this code is moved
1058 * to change_listen_mode(). Thus we open listen socket
1059 * BEFORE we send renew request (see "case BOUND:"). */
1061 max_fd = udhcp_sp_fd_set(&rfds, sockfd);
1063 tv.tv_sec = timeout - already_waited_sec;
1064 tv.tv_usec = 0;
1065 retval = 0;
1066 /* If we already timed out, fall through with retval = 0, else... */
1067 if ((int)tv.tv_sec > 0) {
1068 timestamp_before_wait = (unsigned)monotonic_sec();
1069 log1("Waiting on select...");
1070 retval = select(max_fd + 1, &rfds, NULL, NULL, &tv);
1071 if (retval < 0) {
1072 /* EINTR? A signal was caught, don't panic */
1073 if (errno == EINTR) {
1074 already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
1075 continue;
1077 /* Else: an error occured, panic! */
1078 bb_perror_msg_and_die("select");
1082 /* If timeout dropped to zero, time to become active:
1083 * resend discover/renew/whatever
1085 if (retval == 0) {
1086 /* When running on a bridge, the ifindex may have changed
1087 * (e.g. if member interfaces were added/removed
1088 * or if the status of the bridge changed).
1089 * Refresh ifindex and client_mac:
1091 if (udhcp_read_interface(client_config.interface,
1092 &client_config.ifindex,
1093 NULL,
1094 client_config.client_mac)
1096 goto ret0; /* iface is gone? */
1098 memcpy(clientid_mac_ptr, client_config.client_mac, 6);
1100 /* We will restart the wait in any case */
1101 already_waited_sec = 0;
1103 switch (state) {
1104 case INIT_SELECTING:
1105 if (packet_num < discover_retries) {
1106 if (packet_num == 0)
1107 xid = random_xid();
1108 /* multicast */
1109 send_d6_discover(xid, requested_ipv6);
1110 timeout = discover_timeout;
1111 packet_num++;
1112 continue;
1114 leasefail:
1115 d6_run_script(NULL, "leasefail");
1116 #if BB_MMU /* -b is not supported on NOMMU */
1117 if (opt & OPT_b) { /* background if no lease */
1118 bb_info_msg("No lease, forking to background");
1119 client_background();
1120 /* do not background again! */
1121 opt = ((opt & ~OPT_b) | OPT_f);
1122 } else
1123 #endif
1124 if (opt & OPT_n) { /* abort if no lease */
1125 bb_info_msg("No lease, failing");
1126 retval = 1;
1127 goto ret;
1129 /* wait before trying again */
1130 timeout = tryagain_timeout;
1131 packet_num = 0;
1132 continue;
1133 case REQUESTING:
1134 if (packet_num < discover_retries) {
1135 /* send multicast select packet */
1136 send_d6_select(xid);
1137 timeout = discover_timeout;
1138 packet_num++;
1139 continue;
1141 /* Timed out, go back to init state.
1142 * "discover...select...discover..." loops
1143 * were seen in the wild. Treat them similarly
1144 * to "no response to discover" case */
1145 change_listen_mode(LISTEN_RAW);
1146 state = INIT_SELECTING;
1147 goto leasefail;
1148 case BOUND:
1149 /* 1/2 lease passed, enter renewing state */
1150 state = RENEWING;
1151 client_config.first_secs = 0; /* make secs field count from 0 */
1152 change_listen_mode(LISTEN_KERNEL);
1153 log1("Entering renew state");
1154 /* fall right through */
1155 case RENEW_REQUESTED: /* manual (SIGUSR1) renew */
1156 case_RENEW_REQUESTED:
1157 case RENEWING:
1158 if (timeout > 60) {
1159 /* send an unicast renew request */
1160 /* Sometimes observed to fail (EADDRNOTAVAIL) to bind
1161 * a new UDP socket for sending inside send_renew.
1162 * I hazard to guess existing listening socket
1163 * is somehow conflicting with it, but why is it
1164 * not deterministic then?! Strange.
1165 * Anyway, it does recover by eventually failing through
1166 * into INIT_SELECTING state.
1168 send_d6_renew(xid, &srv6_buf, requested_ipv6);
1169 timeout >>= 1;
1170 continue;
1172 /* Timed out, enter rebinding state */
1173 log1("Entering rebinding state");
1174 state = REBINDING;
1175 /* fall right through */
1176 case REBINDING:
1177 /* Switch to bcast receive */
1178 change_listen_mode(LISTEN_RAW);
1179 /* Lease is *really* about to run out,
1180 * try to find DHCP server using broadcast */
1181 if (timeout > 0) {
1182 /* send a broadcast renew request */
1183 send_d6_renew(xid, /*server_ipv6:*/ NULL, requested_ipv6);
1184 timeout >>= 1;
1185 continue;
1187 /* Timed out, enter init state */
1188 bb_info_msg("Lease lost, entering init state");
1189 d6_run_script(NULL, "deconfig");
1190 state = INIT_SELECTING;
1191 client_config.first_secs = 0; /* make secs field count from 0 */
1192 /*timeout = 0; - already is */
1193 packet_num = 0;
1194 continue;
1195 /* case RELEASED: */
1197 /* yah, I know, *you* say it would never happen */
1198 timeout = INT_MAX;
1199 continue; /* back to main loop */
1200 } /* if select timed out */
1202 /* select() didn't timeout, something happened */
1204 /* Is it a signal? */
1205 /* note: udhcp_sp_read checks FD_ISSET before reading */
1206 switch (udhcp_sp_read(&rfds)) {
1207 case SIGUSR1:
1208 client_config.first_secs = 0; /* make secs field count from 0 */
1209 already_waited_sec = 0;
1210 perform_renew();
1211 if (state == RENEW_REQUESTED) {
1212 /* We might be either on the same network
1213 * (in which case renew might work),
1214 * or we might be on a completely different one
1215 * (in which case renew won't ever succeed).
1216 * For the second case, must make sure timeout
1217 * is not too big, or else we can send
1218 * futile renew requests for hours.
1219 * (Ab)use -A TIMEOUT value (usually 20 sec)
1220 * as a cap on the timeout.
1222 if (timeout > tryagain_timeout)
1223 timeout = tryagain_timeout;
1224 goto case_RENEW_REQUESTED;
1226 /* Start things over */
1227 packet_num = 0;
1228 /* Kill any timeouts, user wants this to hurry along */
1229 timeout = 0;
1230 continue;
1231 case SIGUSR2:
1232 perform_d6_release(&srv6_buf, requested_ipv6);
1233 timeout = INT_MAX;
1234 continue;
1235 case SIGTERM:
1236 bb_info_msg("Received SIGTERM");
1237 goto ret0;
1240 /* Is it a packet? */
1241 if (listen_mode == LISTEN_NONE || !FD_ISSET(sockfd, &rfds))
1242 continue; /* no */
1245 int len;
1247 /* A packet is ready, read it */
1248 if (listen_mode == LISTEN_KERNEL)
1249 len = d6_recv_kernel_packet(&srv6_buf, &packet, sockfd);
1250 else
1251 len = d6_recv_raw_packet(&srv6_buf, &packet, sockfd);
1252 if (len == -1) {
1253 /* Error is severe, reopen socket */
1254 bb_info_msg("Read error: %s, reopening socket", strerror(errno));
1255 sleep(discover_timeout); /* 3 seconds by default */
1256 change_listen_mode(listen_mode); /* just close and reopen */
1258 /* If this packet will turn out to be unrelated/bogus,
1259 * we will go back and wait for next one.
1260 * Be sure timeout is properly decreased. */
1261 already_waited_sec += (unsigned)monotonic_sec() - timestamp_before_wait;
1262 if (len < 0)
1263 continue;
1264 packet_end = (uint8_t*)&packet + len;
1267 if ((packet.d6_xid32 & htonl(0x00ffffff)) != xid) {
1268 log1("xid %x (our is %x), ignoring packet",
1269 (unsigned)(packet.d6_xid32 & htonl(0x00ffffff)), (unsigned)xid);
1270 continue;
1273 switch (state) {
1274 case INIT_SELECTING:
1275 if (packet.d6_msg_type == D6_MSG_ADVERTISE)
1276 goto type_is_ok;
1277 /* DHCPv6 has "Rapid Commit", when instead of Advertise,
1278 * server sends Reply right away.
1279 * Fall through to check for this case.
1281 case REQUESTING:
1282 case RENEWING:
1283 case RENEW_REQUESTED:
1284 case REBINDING:
1285 if (packet.d6_msg_type == D6_MSG_REPLY) {
1286 uint32_t lease_seconds;
1287 struct d6_option *option, *iaaddr;
1288 type_is_ok:
1289 option = d6_find_option(packet.d6_options, packet_end, D6_OPT_STATUS_CODE);
1290 if (option && option->data[4] != 0) {
1291 /* return to init state */
1292 bb_info_msg("Received DHCP NAK (%u)", option->data[4]);
1293 d6_run_script(&packet, "nak");
1294 if (state != REQUESTING)
1295 d6_run_script(NULL, "deconfig");
1296 change_listen_mode(LISTEN_RAW);
1297 sleep(3); /* avoid excessive network traffic */
1298 state = INIT_SELECTING;
1299 client_config.first_secs = 0; /* make secs field count from 0 */
1300 requested_ipv6 = NULL;
1301 timeout = 0;
1302 packet_num = 0;
1303 already_waited_sec = 0;
1304 continue;
1306 option = d6_copy_option(packet.d6_options, packet_end, D6_OPT_SERVERID);
1307 if (!option) {
1308 bb_error_msg("no server ID, ignoring packet");
1309 continue;
1310 /* still selecting - this server looks bad */
1312 //Note: we do not bother comparing server IDs in Advertise and Reply msgs.
1313 //server_id variable is used solely for creation of proper server_id option
1314 //in outgoing packets. (why DHCPv6 even introduced it is a mystery).
1315 free(client6_data.server_id);
1316 client6_data.server_id = option;
1317 if (packet.d6_msg_type == D6_MSG_ADVERTISE) {
1318 /* enter requesting state */
1319 state = REQUESTING;
1320 timeout = 0;
1321 packet_num = 0;
1322 already_waited_sec = 0;
1323 continue;
1325 /* It's a D6_MSG_REPLY */
1327 * RFC 3315 18.1.8. Receipt of Reply Messages
1329 * Upon the receipt of a valid Reply message in response to a Solicit
1330 * (with a Rapid Commit option), Request, Confirm, Renew, Rebind or
1331 * Information-request message, the client extracts the configuration
1332 * information contained in the Reply. The client MAY choose to report
1333 * any status code or message from the status code option in the Reply
1334 * message.
1336 * The client SHOULD perform duplicate address detection [17] on each of
1337 * the addresses in any IAs it receives in the Reply message before
1338 * using that address for traffic. If any of the addresses are found to
1339 * be in use on the link, the client sends a Decline message to the
1340 * server as described in section 18.1.7.
1342 * If the Reply was received in response to a Solicit (with a Rapid
1343 * Commit option), Request, Renew or Rebind message, the client updates
1344 * the information it has recorded about IAs from the IA options
1345 * contained in the Reply message:
1347 * - Record T1 and T2 times.
1349 * - Add any new addresses in the IA option to the IA as recorded by
1350 * the client.
1352 * - Update lifetimes for any addresses in the IA option that the
1353 * client already has recorded in the IA.
1355 * - Discard any addresses from the IA, as recorded by the client, that
1356 * have a valid lifetime of 0 in the IA Address option.
1358 * - Leave unchanged any information about addresses the client has
1359 * recorded in the IA but that were not included in the IA from the
1360 * server.
1362 * Management of the specific configuration information is detailed in
1363 * the definition of each option in section 22.
1365 * If the client receives a Reply message with a Status Code containing
1366 * UnspecFail, the server is indicating that it was unable to process
1367 * the message due to an unspecified failure condition. If the client
1368 * retransmits the original message to the same server to retry the
1369 * desired operation, the client MUST limit the rate at which it
1370 * retransmits the message and limit the duration of the time during
1371 * which it retransmits the message.
1373 * When the client receives a Reply message with a Status Code option
1374 * with the value UseMulticast, the client records the receipt of the
1375 * message and sends subsequent messages to the server through the
1376 * interface on which the message was received using multicast. The
1377 * client resends the original message using multicast.
1379 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1380 * | OPTION_IA_NA | option-len |
1381 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1382 * | IAID (4 octets) |
1383 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1384 * | T1 |
1385 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1386 * | T2 |
1387 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1388 * | |
1389 * . IA_NA-options .
1390 * . .
1391 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1394 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1395 * | OPTION_IAADDR | option-len |
1396 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1397 * | |
1398 * | IPv6 address |
1399 * | |
1400 * | |
1401 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1402 * | preferred-lifetime |
1403 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1404 * | valid-lifetime |
1405 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1406 * . .
1407 * . IAaddr-options .
1408 * . .
1409 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
1411 free(client6_data.ia_na);
1412 client6_data.ia_na = d6_copy_option(packet.d6_options, packet_end, D6_OPT_IA_NA);
1413 if (!client6_data.ia_na) {
1414 bb_error_msg("no %s option, ignoring packet", "IA_NA");
1415 continue;
1417 if (client6_data.ia_na->len < (4 + 4 + 4) + (2 + 2 + 16 + 4 + 4)) {
1418 bb_error_msg("IA_NA option is too short:%d bytes", client6_data.ia_na->len);
1419 continue;
1421 iaaddr = d6_find_option(client6_data.ia_na->data + 4 + 4 + 4,
1422 client6_data.ia_na->data + client6_data.ia_na->len,
1423 D6_OPT_IAADDR
1425 if (!iaaddr) {
1426 bb_error_msg("no %s option, ignoring packet", "IAADDR");
1427 continue;
1429 if (iaaddr->len < (16 + 4 + 4)) {
1430 bb_error_msg("IAADDR option is too short:%d bytes", iaaddr->len);
1431 continue;
1433 /* Note: the address is sufficiently aligned for cast:
1434 * we _copied_ IA-NA, and copy is always well-aligned.
1436 requested_ipv6 = (struct in6_addr*) iaaddr->data;
1437 move_from_unaligned32(lease_seconds, iaaddr->data + 16 + 4);
1438 lease_seconds = ntohl(lease_seconds);
1439 /* paranoia: must not be too small and not prone to overflows */
1440 if (lease_seconds < 0x10)
1441 lease_seconds = 0x10;
1442 /// TODO: check for 0 lease time?
1443 if (lease_seconds >= 0x10000000)
1444 lease_seconds = 0x0fffffff;
1445 /* enter bound state */
1446 timeout = lease_seconds / 2;
1447 bb_info_msg("Lease obtained, lease time %u",
1448 /*inet_ntoa(temp_addr),*/ (unsigned)lease_seconds);
1449 d6_run_script(&packet, state == REQUESTING ? "bound" : "renew");
1451 state = BOUND;
1452 change_listen_mode(LISTEN_NONE);
1453 if (opt & OPT_q) { /* quit after lease */
1454 goto ret0;
1456 /* future renew failures should not exit (JM) */
1457 opt &= ~OPT_n;
1458 #if BB_MMU /* NOMMU case backgrounded earlier */
1459 if (!(opt & OPT_f)) {
1460 client_background();
1461 /* do not background again! */
1462 opt = ((opt & ~OPT_b) | OPT_f);
1464 #endif
1465 already_waited_sec = 0;
1466 continue; /* back to main loop */
1468 continue;
1469 /* case BOUND: - ignore all packets */
1470 /* case RELEASED: - ignore all packets */
1472 /* back to main loop */
1473 } /* for (;;) - main loop ends */
1475 ret0:
1476 if (opt & OPT_R) /* release on quit */
1477 perform_d6_release(&srv6_buf, requested_ipv6);
1478 retval = 0;
1479 ret:
1480 /*if (client_config.pidfile) - remove_pidfile has its own check */
1481 remove_pidfile(client_config.pidfile);
1482 return retval;