Browse Source

Initial commit (expect bugs!)

Steven Barth 11 years ago
commit
0b77e6065d
9 changed files with 2146 additions and 0 deletions
  1. 14 0
      .gitignore
  2. 28 0
      CMakeLists.txt
  3. 340 0
      COPYING
  4. 62 0
      README
  5. 781 0
      src/dhcpv6.c
  6. 421 0
      src/odhcp6c.c
  7. 201 0
      src/odhcp6c.h
  8. 115 0
      src/rtnetlink.c
  9. 184 0
      src/script.c

+ 14 - 0
.gitignore

@@ -0,0 +1,14 @@
+.project
+.cproject
+odhcp6c
+config.log
+CMakeCache.txt
+CMakeFiles
+CPackConfig.cmake
+CPackSourceConfig.cmake
+_CPack_Packages
+Makefile
+cmake_install.cmake
+install_manifest.txt
+*.deb
+

+ 28 - 0
CMakeLists.txt

@@ -0,0 +1,28 @@
+cmake_minimum_required(VERSION 2.8)
+cmake_policy(SET CMP0015 NEW)
+
+# Project Definition
+project(odhcp6c C)
+set(CMAKE_SHARED_LIBRARY_LINK_C_FLAGS "")
+set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -g -std=c99")
+add_definitions(-D_GNU_SOURCE -Wall -Werror -Wextra -pedantic)
+
+add_executable(odhcp6c src/odhcp6c.c src/dhcpv6.c 
+	src/rtnetlink.c src/script.c)
+target_link_libraries(odhcp6c resolv)
+
+# Installation
+install(TARGETS odhcp6c DESTINATION sbin/)
+
+# Packaging information
+set(CPACK_PACKAGE_VERSION "1")
+set(CPACK_PACKAGE_CONTACT "Steven Barth <steven@midlink.org>")
+set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "6ac")
+set(CPACK_GENERATOR "DEB;RPM;STGZ")
+set(CPACK_STRIP_FILES true)
+
+SET(CPACK_DEBIAN_PACKAGE_VERSION ${CPACK_PACKAGE_VERSION})
+set(CPACK_PACKAGE_FILE_NAME "${PROJECT_NAME}_${CPACK_DEBIAN_PACKAGE_VERSION}")
+
+include(CPack)
+

+ 340 - 0
COPYING

@@ -0,0 +1,340 @@
+		    GNU GENERAL PUBLIC LICENSE
+		       Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+                       51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+			    Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+		    GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+  2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) Accompany it with the complete corresponding machine-readable
+    source code, which must be distributed under the terms of Sections
+    1 and 2 above on a medium customarily used for software interchange; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable.  However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+  5. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+  7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded.  In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation.  If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission.  For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this.  Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+			    NO WARRANTY
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+		     END OF TERMS AND CONDITIONS
+
+	    How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program; if not, write to the Free Software
+    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
+
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+    Gnomovision version 69, Copyright (C) year name of author
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+  `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+  <signature of Ty Coon>, 1 April 1989
+  Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Library General
+Public License instead of this License.

+ 62 - 0
README

@@ -0,0 +1,62 @@
+odhcp6c - Embedded DHCPv6 Client
+
+
+** Abstract **
+
+odhcp6c is a minimalistic DHCPv6 client for use in embedded Linux systems.
+
+
+** Features **
+
+1. Handling of non-temporary addresses
+	a) assignment of addresses to source interface
+	b) handling of valid and preferred lifetimes
+	c) duplicate address detection
+
+2. Handling of IPv6-Prefixes (Prefix Delegation)
+	a) requesting of prefixes
+
+3. Stateless fallback-support
+
+4. State script support
+
+
+** Compiling **
+
+odhcp6c uses cmake:
+* To prepare a Makefile use:  "cmake ." 
+* To build / install use: "make" / "make install" afterwards.
+* To build DEB or RPM packages use: "make package" afterwards.
+
+
+** State Script **
+
+The state script is called whenever the DHCPv6 state changes.
+The script is called with the following parameters: <interface> <state>
+
+
+States:
+* bound			A suitable server was found and addresses or prefixes acquired		
+* informed		A stateless information request returned updated information
+* timeout		The DHCPv6 operation did not succeed within the defined time
+* updated		Updated information was received from the DHCPv6 server
+* rebound		The DHCPv6 client switched to another server
+* unbound		The DHCPv6 client lost all DHCPv6 servers and will restart
+
+
+Environment:
+* RDNSS			A space-separated list of recursive DNS servers
+* DOMAINS		A space-separated list of DNS search domains
+* OPTION_<num>	Custom option received as base-16
+* PREFIXES		A space-separated list of prefixes currently assigned
+				Format: <prefix>/<length>,preferred,valid
+* PREFIXES_LOST	A space-separated list of prefixes lost since last update
+
+
+
+
+** Wishlist **
+
+Features that I would like to see implemented in the near or far future:
+
+* Reconfigure Authentication 

+ 781 - 0
src/dhcpv6.c

@@ -0,0 +1,781 @@
+/**
+ * Copyright (C) 2012 Steven Barth <steven@midlink.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License v2 as published by
+ * the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ */
+
+#include <time.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <signal.h>
+#include <limits.h>
+#include <resolv.h>
+#include <string.h>
+#include <unistd.h>
+#include <syslog.h>
+#include <stdbool.h>
+#include <sys/time.h>
+#include <sys/ioctl.h>
+#include <sys/socket.h>
+#include <netinet/in.h>
+
+#include <net/if.h>
+#include <net/ethernet.h>
+
+#include "odhcp6c.h"
+
+
+#define ALL_DHCPV6_RELAYS {{{0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
+		0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02}}}
+#define DHCPV6_CLIENT_PORT 546
+#define DHCPV6_SERVER_PORT 547
+#define DHCPV6_DUID_LLADDR 3
+#define DHCPV6_REQ_DELAY 1
+
+
+static bool dhcpv6_response_is_valid(const void *buf, ssize_t len,
+		const uint8_t transaction[3], enum dhcpv6_msg type);
+
+static time_t dhcpv6_parse_ia(void *opt, void *end);
+
+static reply_handler dhcpv6_handle_reply;
+static reply_handler dhcpv6_handle_advert;
+static reply_handler dhcpv6_handle_rebind_reply;
+static reply_handler dhcpv6_handle_reconfigure;
+static int dhcpv6_commit_advert(uint32_t elapsed);
+
+
+
+// RFC 3315 - 5.5 Timeout and Delay values
+static struct dhcpv6_retx dhcpv6_retx[_DHCPV6_MSG_MAX] = {
+	[DHCPV6_MSG_UNKNOWN] = {false, 1, 120, "<POLL>",
+			dhcpv6_handle_reconfigure, NULL},
+	[DHCPV6_MSG_SOLICIT] = {true, 1, 120, "SOLICIT",
+			dhcpv6_handle_advert, dhcpv6_commit_advert},
+	[DHCPV6_MSG_REQUEST] = {true, 30, 10, "REQUEST",
+			dhcpv6_handle_reply, NULL},
+	[DHCPV6_MSG_RENEW] = {false, 10, 600, "RENEW",
+			dhcpv6_handle_reply, NULL},
+	[DHCPV6_MSG_REBIND] = {false, 10, 600, "REBIND",
+			dhcpv6_handle_rebind_reply, NULL},
+	[DHCPV6_MSG_RELEASE] = {false, 1, 600, "RELEASE", NULL, NULL},
+	[DHCPV6_MSG_DECLINE] = {false, 1, 3, "DECLINE", NULL, NULL},
+	[DHCPV6_MSG_INFO_REQ] = {true, 1, 120, "INFOREQ",
+			dhcpv6_handle_reply, NULL},
+};
+
+
+// Sockets
+static int sock = -1;
+static int urandom_fd = -1;
+static int ifindex = -1;
+static time_t t1 = 0, t2 = 0, t3 = 0;
+
+// IA states
+static int request_prefix = -1;
+static enum odhcp6c_ia_mode na_mode = IA_MODE_NONE;
+static bool accept_reconfig = false;
+
+
+
+int init_dhcpv6(const char *ifname, int request_pd)
+{
+	request_prefix = request_pd;
+	urandom_fd = open("/dev/urandom", O_CLOEXEC | O_RDONLY);
+	if (urandom_fd < 0)
+		return -1;
+
+	sock = socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP);
+
+	// Detect interface
+	struct ifreq ifr;
+	strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
+	if (ioctl(sock, SIOCGIFINDEX, &ifr))
+		return -1;
+	ifindex = ifr.ifr_ifindex;
+
+	// Create client DUID
+	size_t client_id_len;
+	odhcp6c_get_state(STATE_CLIENT_ID, &client_id_len);
+	if (client_id_len == 0) {
+		ioctl(sock, SIOCGIFHWADDR, &ifr);
+		uint8_t duid[14] = {0, DHCPV6_OPT_CLIENTID, 0, 10, 0,
+				DHCPV6_DUID_LLADDR, 0, 1};
+		memcpy(&duid[8], ifr.ifr_hwaddr.sa_data, ETHER_ADDR_LEN);
+		odhcp6c_add_state(STATE_CLIENT_ID, duid, sizeof(duid));
+	}
+
+	// Create ORO
+	uint16_t oro[] = {htons(DHCPV6_OPT_DNS_SERVERS),
+			htons(DHCPV6_OPT_DNS_DOMAIN)};
+	odhcp6c_add_state(STATE_ORO, oro, sizeof(oro));
+
+
+	// Configure IPv6-options
+	int val = 1;
+	setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &val, sizeof(val));
+	setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
+	setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, ifname, strlen(ifname));
+
+	struct sockaddr_in6 client_addr = { .sin6_family = AF_INET6,
+		.sin6_port = htons(DHCPV6_CLIENT_PORT), .sin6_flowinfo = 0 };
+	if (bind(sock, (struct sockaddr*)&client_addr, sizeof(client_addr)))
+		return -1;
+
+	return 0;
+}
+
+
+void dhcpv6_set_ia_na_mode(enum odhcp6c_ia_mode mode)
+{
+	na_mode = mode;
+}
+
+
+void dhcpv6_remove_addrs(void)
+{
+	size_t ia_na_len;
+	uint8_t *odata, *ia_na = odhcp6c_get_state(STATE_IA_NA, &ia_na_len);
+	uint16_t otype, olen;
+	dhcpv6_for_each_option(ia_na, ia_na + ia_na_len, otype, olen, odata) {
+		struct dhcpv6_ia_addr *addr = (void*)&odata[-4];
+		set_rtnetlink_addr(ifindex, &addr->addr, 0, 0);
+	}
+}
+
+
+static void dhcpv6_send(enum dhcpv6_msg type, uint8_t trid[3], uint32_t ecs)
+{
+	// Build FQDN
+	char fqdn_buf[256];
+	gethostname(fqdn_buf, sizeof(fqdn_buf));
+	struct {
+		uint16_t type;
+		uint16_t len;
+		uint8_t flags;
+		uint8_t data[256];
+	} fqdn;
+	size_t fqdn_len = 5 + dn_comp(fqdn_buf, fqdn.data,
+			sizeof(fqdn.data), NULL, NULL);
+	fqdn.type = htons(DHCPV6_OPT_FQDN);
+	fqdn.len = htons(fqdn_len - 4);
+	fqdn.flags = 0;
+
+
+	// Build Client ID
+	size_t cl_id_len;
+	void *cl_id = odhcp6c_get_state(STATE_CLIENT_ID, &cl_id_len);
+
+	// Get Server ID
+	size_t srv_id_len;
+	void *srv_id = odhcp6c_get_state(STATE_SERVER_ID, &srv_id_len);
+
+	// Build IA_PDs
+	size_t ia_pd_len;
+	void *ia_pd = odhcp6c_get_state(STATE_IA_PD, &ia_pd_len);
+	struct dhcpv6_ia_hdr hdr_ia_pd = {
+		htons(DHCPV6_OPT_IA_PD),
+		htons(sizeof(hdr_ia_pd) - 4 + ia_pd_len),
+		1, 0, 0
+	};
+
+	struct dhcpv6_ia_prefix pref = {
+		.type = htons(DHCPV6_OPT_IA_PREFIX),
+		.len = htons(25), .prefix = request_prefix
+	};
+
+	if (ia_pd_len == 0 && request_prefix > 0 &&
+			(type == DHCPV6_MSG_SOLICIT ||
+			type == DHCPV6_MSG_REQUEST)) {
+		ia_pd = &pref;
+		ia_pd_len = sizeof(pref);
+	}
+
+	// Build IA_NAs
+	size_t ia_na_len;
+	void *ia_na = odhcp6c_get_state(STATE_IA_NA, &ia_na_len);
+	struct dhcpv6_ia_hdr hdr_ia_na = {
+		htons(DHCPV6_OPT_IA_NA),
+		htons(sizeof(hdr_ia_na) - 4 + ia_na_len),
+		1, 0, 0
+	};
+
+	// Reconfigure Accept
+	struct {
+		uint16_t type;
+		uint16_t length;
+	} reconf_accept = {htons(DHCPV6_OPT_RECONF_ACCEPT), 0};
+
+	// Request Information Refresh
+	uint16_t oro_refresh = htons(DHCPV6_OPT_INFO_REFRESH);
+
+	// Prepare Header
+	size_t oro_len;
+	void *oro = odhcp6c_get_state(STATE_ORO, &oro_len);
+	struct {
+		uint8_t type;
+		uint8_t trid[3];
+		uint16_t elapsed_type;
+		uint16_t elapsed_len;
+		uint16_t elapsed_value;
+		uint16_t oro_type;
+		uint16_t oro_len;
+	} hdr = {
+		type, {trid[0], trid[1], trid[2]},
+		htons(DHCPV6_OPT_ELAPSED), htons(2),
+			htons((ecs > 0xffff) ? 0xffff : ecs),
+		htons(DHCPV6_OPT_ORO), htons(oro_len),
+	};
+
+	struct iovec iov[] = {
+		{&hdr, sizeof(hdr)},
+		{oro, oro_len},
+		{&oro_refresh, 0},
+		{cl_id, cl_id_len},
+		{srv_id, srv_id_len},
+		{&reconf_accept, 0},
+		{&fqdn, fqdn_len},
+		{&hdr_ia_na, sizeof(hdr_ia_na)},
+		{ia_na, ia_na_len},
+		{&hdr_ia_pd, sizeof(hdr_ia_pd)},
+		{ia_pd, ia_pd_len},
+	};
+
+	size_t cnt = ARRAY_SIZE(iov);
+	if (type == DHCPV6_MSG_INFO_REQ) {
+		cnt = 5;
+		iov[2].iov_len = sizeof(oro_refresh);
+		hdr.oro_len = htons(oro_len + sizeof(oro_refresh));
+	} else if (!request_prefix) {
+		cnt = 9;
+	}
+
+	// Disable IAs if not used
+	if (type == DHCPV6_MSG_SOLICIT) {
+		iov[5].iov_len = sizeof(reconf_accept);
+	} else if (type != DHCPV6_MSG_REQUEST) {
+		if (ia_na_len == 0)
+			iov[7].iov_len = 0;
+		if (ia_pd_len == 0)
+			iov[9].iov_len = 0;
+	}
+
+	if (na_mode == IA_MODE_NONE)
+		iov[7].iov_len = 0;
+
+	struct sockaddr_in6 srv = {AF_INET6, htons(DHCPV6_SERVER_PORT),
+		0, ALL_DHCPV6_RELAYS, ifindex};
+	struct msghdr msg = {&srv, sizeof(srv), iov, cnt, NULL, 0, 0};
+
+	sendmsg(sock, &msg, 0);
+}
+
+
+static int64_t dhcpv6_rand_delay(int64_t time)
+{
+	int random;
+	read(urandom_fd, &random, sizeof(random));
+	return (time * (random % 1000)) / 10000;
+}
+
+
+int dhcpv6_request(enum dhcpv6_msg type)
+{
+	uint8_t buf[1536];
+	uint32_t timeout = UINT32_MAX;
+	struct dhcpv6_retx *retx = &dhcpv6_retx[type];
+
+	if (retx->delay) {
+		struct timespec ts = {0, 0};
+		ts.tv_nsec = dhcpv6_rand_delay(10 * DHCPV6_REQ_DELAY);
+		nanosleep(&ts, NULL);
+	}
+
+	if (type == DHCPV6_MSG_RELEASE || type == DHCPV6_MSG_DECLINE)
+		timeout = 3;
+	else if (type == DHCPV6_MSG_UNKNOWN)
+		timeout = t1;
+	else if (type == DHCPV6_MSG_RENEW)
+		timeout = t2 - t1;
+	else if (type == DHCPV6_MSG_REBIND)
+		timeout = t3 - t2;
+
+	if (timeout == 0)
+		return -1;
+
+	syslog(LOG_NOTICE, "Sending %s (timeout %us)", retx->name, timeout);
+
+	uint64_t start = adhc6c_get_milli_time(), round_start = start, elapsed;
+
+	// Generate transaction ID
+	uint8_t trid[3];
+	read(urandom_fd, trid, sizeof(trid));
+	ssize_t len = -1;
+	int64_t rto = 0;
+
+	do {
+		rto = (rto == 0) ? (retx->init_timeo * 1000 +
+				dhcpv6_rand_delay(retx->init_timeo * 1000)) :
+				(2 * rto + dhcpv6_rand_delay(rto));
+
+		if (rto >= retx->max_timeo * 1000)
+			rto = retx->max_timeo * 1000 +
+				dhcpv6_rand_delay(retx->max_timeo * 1000);
+
+		// Calculate end for this round and elapsed time
+		uint64_t round_end = round_start + rto;
+		elapsed = round_start - start;
+
+		// Don't wait too long
+		if (round_end - start > timeout * 1000)
+			round_end = timeout * 1000 + start;
+
+		// Built and send package
+		if (type != DHCPV6_MSG_UNKNOWN)
+			dhcpv6_send(type, trid, elapsed / 10);
+
+		// Receive rounds
+		for (; len < 0 && round_start < round_end;
+				round_start = adhc6c_get_milli_time()) {
+			// Check for pending signal
+			if (odhcp6c_signal_is_pending())
+				return -1;
+
+			// Set timeout for receiving
+			uint64_t t = round_end - round_start;
+			struct timeval timeout = {t / 1000, (t % 1000) * 1000};
+			setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO,
+					&timeout, sizeof(timeout));
+
+			// Receive cycle
+			len = recv(sock, buf, sizeof(buf), 0);
+
+			if (!dhcpv6_response_is_valid(buf, len, trid, type))
+				len = -1;
+
+			if (len > 0) {
+				uint8_t *opt = &buf[4];
+				uint8_t *opt_end = opt + len - 4;
+
+				round_start = adhc6c_get_milli_time();
+				elapsed = round_start - start;
+				syslog(LOG_NOTICE, "Got a valid reply after "
+						"%ums", (unsigned)elapsed);
+
+				if (retx->handler_reply)
+					len = retx->handler_reply(type,
+						opt, opt_end, elapsed / 1000);
+			}
+		}
+
+		// Allow
+		if (retx->handler_finish)
+			len = retx->handler_finish(elapsed / 1000);
+	} while (len < 0 && elapsed / 1000 < timeout);
+
+	return len;
+}
+
+
+static bool dhcpv6_response_is_valid(const void *buf, ssize_t len,
+		const uint8_t transaction[3], enum dhcpv6_msg type)
+{
+	const struct dhcpv6_header *rep = buf;
+	if (len < (ssize_t)sizeof(*rep) || memcmp(rep->tr_id,
+			transaction, sizeof(rep->tr_id)))
+		return false; // Invalid reply
+
+	if (type == DHCPV6_MSG_SOLICIT) {
+		if (rep->msg_type != DHCPV6_MSG_ADVERT &&
+				rep->msg_type != DHCPV6_MSG_REPLY)
+			return false;
+	} else if (type == DHCPV6_MSG_UNKNOWN) {
+		if (!accept_reconfig || rep->msg_type != DHCPV6_MSG_RECONF)
+			return false;
+	} else if (rep->msg_type != DHCPV6_MSG_REPLY) {
+		return false;
+	}
+
+	uint8_t *end = ((uint8_t*)buf) + len, *odata;
+	uint16_t otype, olen;
+	bool clientid_ok = false, serverid_ok = false;
+
+	size_t client_id_len, server_id_len;
+	void *client_id = odhcp6c_get_state(STATE_CLIENT_ID, &client_id_len);
+	void *server_id = odhcp6c_get_state(STATE_SERVER_ID, &server_id_len);
+
+	dhcpv6_for_each_option(&rep[1], end, otype, olen, odata)
+		if (otype == DHCPV6_OPT_CLIENTID)
+			clientid_ok = (olen + 4U == client_id_len) && !memcmp(
+					&odata[-4], client_id, client_id_len);
+		else if (otype == DHCPV6_OPT_SERVERID)
+			serverid_ok = (olen + 4U == server_id_len) && !memcmp(
+					&odata[-4], server_id, server_id_len);
+
+	return clientid_ok && (serverid_ok || server_id_len == 0);
+}
+
+
+int dhcpv6_poll_reconfigure(void)
+{
+	int ret = dhcpv6_request(DHCPV6_MSG_UNKNOWN);
+	if (ret != -1)
+		ret = dhcpv6_request(ret);
+
+	return ret;
+}
+
+
+static int dhcpv6_handle_reconfigure(_unused enum dhcpv6_msg orig,
+		const void *opt, const void *end, uint32_t elapsed)
+{
+	// TODO: should verify the reconfigure message
+	uint16_t otype, olen;
+	uint8_t *odata, msg = DHCPV6_MSG_RENEW;
+	dhcpv6_for_each_option(opt, end, otype, olen, odata)
+		if (otype == DHCPV6_OPT_RECONF_MESSAGE && olen == 1 && (
+				odata[0] == DHCPV6_MSG_RENEW ||
+				odata[0] == DHCPV6_MSG_INFO_REQ))
+			msg = odata[0];
+
+	t1 -= elapsed;
+	t2 -= elapsed;
+	t3 -= elapsed;
+
+	if (t1 < 0)
+		t1 = 0;
+
+	if (t2 < 0)
+		t2 = 0;
+
+	if (t3 < 0)
+		t3 = 0;
+
+	dhcpv6_handle_reply(DHCPV6_MSG_UNKNOWN, NULL, NULL, elapsed);
+	return msg;
+}
+
+
+// Collect all advertised servers
+static int dhcpv6_handle_advert(_unused enum dhcpv6_msg orig,
+		const void *opt, const void *end, _unused uint32_t elapsed)
+{
+	uint16_t olen, otype;
+	uint8_t *odata;
+	struct dhcpv6_server_cand cand = {false, false, 0, 0, {0}};
+
+	dhcpv6_for_each_option(opt, end, otype, olen, odata) {
+		if (otype == DHCPV6_OPT_SERVERID && olen <= 130) {
+			memcpy(cand.duid, odata, olen);
+			cand.duid_len = olen;
+		} else if (otype == DHCPV6_OPT_STATUS && olen >= 2 &&
+				!odata[0] && odata[1] == DHCPV6_NoAddrsAvail) {
+			if (na_mode == IA_MODE_FORCE) {
+				return -1;
+			} else {
+				cand.has_noaddravail = true;
+				cand.preference -= 1000;
+			}
+		} else if (otype == DHCPV6_OPT_PREF && olen >= 1 &&
+				cand.preference >= 0) {
+			cand.preference = odata[1];
+		} else if (otype == DHCPV6_OPT_RECONF_ACCEPT) {
+			cand.wants_reconfigure = true;
+		}
+		else if (otype == DHCPV6_OPT_IA_PD && request_prefix) {
+			struct dhcpv6_ia_hdr *h = (void*)odata;
+			uint8_t *oend = odata + olen, *d;
+			dhcpv6_for_each_option(&h[1], oend, otype, olen, d) {
+				if (otype == DHCPV6_OPT_IA_PREFIX)
+					cand.preference += 2000;
+				else if (otype == DHCPV6_OPT_STATUS &&
+						olen >= 2 && d[0] == 0 &&
+						d[1] == DHCPV6_NoPrefixAvail)
+					return -1;
+			}
+		}
+	}
+
+	if (cand.duid_len > 0)
+		odhcp6c_add_state(STATE_SERVER_CAND, &cand, sizeof(cand));
+
+	return -1;
+}
+
+
+static int dhcpv6_commit_advert(_unused uint32_t elapsed)
+{
+	size_t cand_len;
+	struct dhcpv6_server_cand *c = NULL, *cand =
+			odhcp6c_get_state(STATE_SERVER_CAND, &cand_len);
+
+	bool retry = false;
+	for (size_t i = 0; i < cand_len / sizeof(*c); ++i) {
+		if (cand[i].has_noaddravail)
+			retry = true; // We want to try again
+
+		if (!c || c->preference < cand[i].preference)
+			c = &cand[i];
+	}
+
+	if (retry && na_mode == IA_MODE_TRY) {
+		// We give it a second try without the IA_NA
+		na_mode = IA_MODE_NONE;
+		return dhcpv6_request(DHCPV6_MSG_SOLICIT);
+	}
+
+	if (c) {
+		uint16_t hdr[2] = {htons(DHCPV6_OPT_SERVERID),
+				htons(c->duid_len)};
+		odhcp6c_add_state(STATE_SERVER_ID, hdr, sizeof(hdr));
+		odhcp6c_add_state(STATE_SERVER_ID, c->duid, c->duid_len);
+		accept_reconfig = c->wants_reconfigure;
+	}
+
+	odhcp6c_clear_state(STATE_SERVER_CAND);
+
+	if (!c)
+		return -1;
+	else if (request_prefix || na_mode != IA_MODE_NONE)
+		return DHCPV6_STATEFUL;
+	else
+		return DHCPV6_STATELESS;
+}
+
+
+static int dhcpv6_handle_rebind_reply(enum dhcpv6_msg orig,
+		const void *opt, const void *end, uint32_t elapsed)
+{
+	dhcpv6_handle_advert(orig, opt, end, elapsed);
+	if (dhcpv6_commit_advert(elapsed) < 0)
+		return -1;
+
+	return dhcpv6_handle_reply(orig, opt, end, elapsed);
+}
+
+
+static int dhcpv6_handle_reply(_unused enum dhcpv6_msg orig,
+		const void *opt, const void *end, uint32_t elapsed)
+{
+	uint16_t otype, olen;
+	uint8_t *odata;
+	bool have_update = false;
+
+	t1 = t2 = t3 = 86400;
+
+	size_t ia_na_len, dns_len, search_len;
+	uint8_t *ia_na = odhcp6c_get_state(STATE_IA_NA, &ia_na_len);
+	uint8_t *ia_end;
+	odhcp6c_get_state(STATE_DNS, &dns_len);
+	odhcp6c_get_state(STATE_SEARCH, &search_len);
+
+	// Decrease valid and preferred lifetime of prefixes
+	size_t ia_pd_len;
+	uint8_t *ia_pd = odhcp6c_get_state(STATE_IA_PD, &ia_pd_len);
+	dhcpv6_for_each_option(ia_pd, ia_pd + ia_pd_len, otype, olen, odata) {
+		struct dhcpv6_ia_prefix *p = (void*)&odata[-4];
+		uint32_t valid = ntohl(p->valid);
+		p->valid = (valid < elapsed) ? 0 : htonl(valid - elapsed);
+
+		uint32_t pref = ntohl(p->preferred);
+		p->preferred = (pref < elapsed) ? 0 : htonl(pref - elapsed);
+	}
+
+	// Decrease valid and preferred lifetime of addresses
+	dhcpv6_for_each_option(ia_na, ia_na + ia_na_len, otype, olen, odata) {
+		struct dhcpv6_ia_addr *p = (void*)&odata[-4];
+		uint32_t valid = ntohl(p->valid);
+		p->valid = (valid < elapsed) ? 0 : htonl(valid - elapsed);
+
+		uint32_t pref = ntohl(p->preferred);
+		p->preferred = (pref < elapsed) ? 0 : htonl(pref - elapsed);
+	}
+
+	// Parse and find all matching IAs
+	dhcpv6_for_each_option(opt, end, otype, olen, odata) {
+		if ((otype == DHCPV6_OPT_IA_PD || otype == DHCPV6_OPT_IA_NA)
+				&& olen > sizeof(struct dhcpv6_ia_hdr)) {
+			struct dhcpv6_ia_hdr *ia_hdr = (void*)(&odata[-4]);
+			time_t l_t1 = ntohl(ia_hdr->t1);
+			time_t l_t2 = ntohl(ia_hdr->t2);
+
+			// Test ID and T1-T2 validity
+			if (ia_hdr->iaid != 1 || l_t2 < l_t1)
+				continue;
+
+			uint16_t stype, slen;
+			uint8_t *sdata;
+			// Test status and bail if error
+			dhcpv6_for_each_option(&ia_hdr[1], odata + olen,
+					stype, slen, sdata)
+				if (stype == DHCPV6_OPT_STATUS && slen >= 2 &&
+						(sdata[0] || sdata[1]))
+					continue;
+
+			// Update times
+			if (l_t1 > 0 && t1 > l_t1)
+				t1 = l_t1;
+
+			if (l_t2 > 0 && t2 > l_t2)
+				t2 = l_t2;
+
+
+			time_t n = dhcpv6_parse_ia(&ia_hdr[1], odata + olen);
+
+			if (n < t1)
+				t1 = n;
+
+			if (n < t2)
+				t2 = n;
+
+			if (n < t3)
+				t3 = n;
+
+		} else if (otype == DHCPV6_OPT_DNS_SERVERS) {
+			odhcp6c_add_state(STATE_DNS, odata, olen);
+		} else if (otype == DHCPV6_OPT_DNS_DOMAIN) {
+			odhcp6c_add_state(STATE_SEARCH, odata, olen);
+		} else if (otype == DHCPV6_OPT_INFO_REFRESH && olen >= 4) {
+			uint32_t refresh = ntohl(*((uint32_t*)odata));
+			if (refresh < (uint32_t)t1)
+				t1 = refresh;
+		} else if (otype != DHCPV6_OPT_CLIENTID &&
+				otype != DHCPV6_OPT_SERVERID) {
+			odhcp6c_add_state(STATE_CUSTOM_OPTS,
+					&odata[-4], olen + 4);
+		}
+	}
+
+	if (opt) {
+		have_update |= odhcp6c_commit_state(STATE_DNS, dns_len);
+		have_update |= odhcp6c_commit_state(STATE_SEARCH, search_len);
+		size_t new_ia_pd_len, new_ia_na_len;
+		odhcp6c_get_state(STATE_IA_PD, &new_ia_pd_len);
+		odhcp6c_get_state(STATE_IA_NA, &new_ia_na_len);
+		have_update |= (new_ia_pd_len != ia_pd_len) ||
+				(new_ia_na_len != ia_na_len);
+	}
+
+	// Delete prefixes with 0 valid-time
+	ia_pd = odhcp6c_get_state(STATE_IA_PD, &ia_pd_len);
+	ia_end = ia_pd + ia_pd_len;
+	dhcpv6_for_each_option(ia_pd, ia_end, otype, olen, odata) {
+		struct dhcpv6_ia_prefix *p = (void*)&odata[-4];
+		while (!p->valid) {
+			ia_end = ia_pd + odhcp6c_remove_state(STATE_IA_PD,
+					(uint8_t*)p - ia_pd, olen + 4);
+			have_update = true;
+		}
+	}
+
+
+	// Delete addresses with 0 valid-time
+	ia_na = odhcp6c_get_state(STATE_IA_NA, &ia_na_len);
+	ia_end = ia_na + ia_na_len;
+	dhcpv6_for_each_option(ia_na, ia_end, otype, olen, odata) {
+		struct dhcpv6_ia_addr *p = (void*)&odata[-4];
+		while (!p->valid) {
+			ia_end = ia_na + odhcp6c_remove_state(STATE_IA_NA,
+					(uint8_t*)p - ia_na, olen + 4);
+			have_update = true;
+		}
+	}
+
+	return have_update;
+}
+
+
+static time_t dhcpv6_parse_ia(void *opt, void *end)
+{
+	uint32_t timeout = UINT32_MAX; // Minimum timeout
+	uint16_t otype, olen, stype, slen;
+	uint8_t *odata, *sdata;
+
+	// Update address IA
+	dhcpv6_for_each_option(opt, end, otype, olen, odata) {
+		if (otype == DHCPV6_OPT_IA_PREFIX) {
+			struct dhcpv6_ia_prefix *prefix = (void*)&odata[-4];
+			if (olen + 4U < sizeof(*prefix))
+				continue;
+
+			olen = sizeof(*prefix); // Normalize length
+			uint32_t valid = ntohl(prefix->valid);
+			uint32_t pref = ntohl(prefix->preferred);
+
+			if (pref > valid)
+				continue;
+
+			// Search matching IA
+			struct dhcpv6_ia_prefix *local = NULL;
+			size_t pd_len;
+			uint8_t *pd = odhcp6c_get_state(STATE_IA_PD, &pd_len);
+			dhcpv6_for_each_option(pd, pd + pd_len,
+					stype, slen, sdata)
+				if (!memcmp(sdata + 8, odata + 8,
+						sizeof(local->addr) + 1))
+					local = (void*)&sdata[-4];
+
+			if (local) { // Already know that IA
+				local->preferred = prefix->preferred;
+				local->valid = prefix->valid;
+			} else { // New IA
+				odhcp6c_add_state(STATE_IA_PD, prefix, olen);
+			}
+
+			if (timeout > valid)
+				timeout = valid;
+
+			if (prefix->valid == 0) // We probably lost that prefix
+				odhcp6c_add_state(STATE_IA_PD_LOST,
+						prefix, olen);
+		} else if (otype == DHCPV6_OPT_IA_ADDR) {
+			struct dhcpv6_ia_addr *addr = (void*)&odata[-4];
+			if (olen + 4U < sizeof(*addr))
+				continue;
+
+			olen = sizeof(*addr); // Normalize length
+			uint32_t pref = ntohl(addr->preferred);
+			uint32_t valid = ntohl(addr->valid);
+
+			if (pref > valid)
+				continue;
+
+			// Search matching IA
+			struct dhcpv6_ia_addr *local = NULL;
+			size_t na_len;
+			uint8_t *na = odhcp6c_get_state(STATE_IA_NA, &na_len);
+			dhcpv6_for_each_option(na, na + na_len,
+					stype, slen, sdata)
+				if (!memcmp(sdata, odata, sizeof(local->addr)))
+					local = (void*)&sdata[-4];
+
+
+			if (local) { // Already know that IA
+				local->preferred = addr->preferred;
+				local->valid = addr->valid;
+			} else { // New IA
+				odhcp6c_add_state(STATE_IA_NA, addr, olen);
+			}
+
+
+			if (timeout > valid)
+				timeout = valid;
+
+			if (set_rtnetlink_addr(ifindex, &addr->addr,
+					pref, valid) == -EADDRNOTAVAIL) {
+				dhcpv6_request(DHCPV6_MSG_DECLINE);
+				raise(SIGUSR2);
+			}
+		}
+	}
+
+	return timeout;
+}

+ 421 - 0
src/odhcp6c.c

@@ -0,0 +1,421 @@
+/**
+ * Copyright (C) 2012 Steven Barth <steven@midlink.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License v2 as published by
+ * the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ */
+
+#include <time.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <syslog.h>
+#include <signal.h>
+#include <string.h>
+#include <stdbool.h>
+
+#include <net/if.h>
+#include <sys/wait.h>
+#include <sys/syscall.h>
+
+#include "odhcp6c.h"
+
+
+static void sighandler(int signal);
+static int sysctl_interface(const char *ifname, const char *option,
+		const char *data);
+static int usage(void);
+
+
+static uint8_t *state_data[_STATE_MAX] = {NULL};
+static size_t state_len[_STATE_MAX] = {0};
+
+static volatile int do_signal = 0;
+
+
+int main(_unused int argc, char* const argv[])
+{
+	openlog("odhcp6c", LOG_PERROR | LOG_PID, LOG_DAEMON);
+
+	// Allocate ressources
+	const char *pidfile = NULL;
+	const char *script = "/usr/sbin/odhcp6c-update";
+	ssize_t l;
+	uint8_t buf[134];
+	char *optpos;
+	uint16_t opttype;
+	enum odhcp6c_ia_mode ia_na_mode = IA_MODE_TRY;
+
+	bool help = false, daemonize = false, reset = false;
+	int c, request_pd = 0, timeout = 0;
+	while ((c = getopt(argc, argv, "RN:P:c:r:s:t:hdp:")) != -1) {
+		switch (c) {
+		case 'R':
+			reset = true;
+			break;
+
+		case 'N':
+			if (!strcmp(optarg, "force"))
+				ia_na_mode = IA_MODE_FORCE;
+			else if (!strcmp(optarg, "none"))
+				ia_na_mode = IA_MODE_NONE;
+			else if (!strcmp(optarg, "try"))
+				ia_na_mode = IA_MODE_TRY;
+			else
+				help = true;
+			break;
+
+		case 'P':
+			request_pd = strtoul(optarg, NULL, 10);
+			if (request_pd == 0)
+				request_pd = -1;
+			break;
+
+		case 'c':
+			l = script_unhexlify(&buf[4], sizeof(buf) - 4, optarg);
+			if (l > 0) {
+				buf[0] = 0;
+				buf[1] = DHCPV6_OPT_CLIENTID;
+				buf[2] = 0;
+				buf[4] = l;
+				odhcp6c_add_state(STATE_CLIENT_ID, buf, l + 4);
+			} else {
+				help = true;
+			}
+			break;
+
+		case 'r':
+			optpos = optarg;
+			while (optpos[0]) {
+				opttype = htons(strtoul(optarg, &optpos, 10));
+				if (optpos == optarg)
+					break;
+				else if (optpos[0])
+					optarg = &optpos[1];
+				odhcp6c_add_state(STATE_ORO, &opttype, 2);
+			}
+			break;
+
+		case 's':
+			script = optarg;
+			break;
+
+		case 't':
+			timeout = strtoul(optarg, NULL, 10);
+			break;
+
+		case 'd':
+			daemonize = true;
+			break;
+
+		case 'p':
+			pidfile = optarg;
+			break;
+
+		default:
+			help = true;
+			break;
+		}
+	}
+
+	const char *ifname = argv[optind];
+
+	if (help || !ifname)
+		return usage();
+
+	if (init_dhcpv6(ifname, request_pd) || init_rtnetlink() ||
+			script_init(script, ifname)) {
+		syslog(LOG_ERR, "failed to initialize: %s", strerror(errno));
+		return 3;
+	}
+
+	signal(SIGHUP, sighandler);
+	signal(SIGINT, sighandler);
+	signal(SIGALRM, sighandler);
+	signal(SIGCHLD, sighandler);
+	signal(SIGTERM, sighandler);
+	signal(SIGUSR1, sighandler);
+	signal(SIGUSR2, sighandler);
+
+	// Configure interface to accept RA
+	if (reset) {
+		sysctl_interface(ifname, "disable_ipv6", "1");
+		sysctl_interface(ifname, "accept_ra", "2");
+		sysctl_interface(ifname, "disable_ipv6", "0");
+	}
+
+	if (daemonize) {
+		openlog("odhcp6c", LOG_PID, LOG_DAEMON); // Disable LOG_PERROR
+		if (daemon(0, 0)) {
+			syslog(LOG_ERR, "Failed to daemonize: %s",
+					strerror(errno));
+			return 4;
+		}
+
+		char pidbuf[128];
+		if (!pidfile) {
+			snprintf(pidbuf, sizeof(pidbuf),
+					"/var/run/odhcp6c.%s.pid", ifname);
+			pidfile = pidbuf;
+		}
+
+		int fd = open(pidfile, O_WRONLY | O_CREAT);
+		if (fd >= 0) {
+			char buf[8];
+			int len = snprintf(buf, sizeof(buf), "%i\n", getpid());
+			write(fd, buf, len);
+			close(fd);
+		}
+	}
+
+	while (do_signal != SIGTERM) { // Main logic
+		odhcp6c_clear_state(STATE_SERVER_ID);
+		odhcp6c_clear_state(STATE_SERVER_CAND);
+		odhcp6c_clear_state(STATE_IA_PD);
+		odhcp6c_clear_state(STATE_IA_PD_LOST);
+		dhcpv6_set_ia_na_mode(ia_na_mode);
+
+		alarm(timeout);
+		do_signal = 0;
+		int res = dhcpv6_request(DHCPV6_MSG_SOLICIT);
+
+		if (res < 0) {
+			continue; // Might happen if we got a signal
+		} else if (res == DHCPV6_STATELESS) { // Stateless mode
+			while (do_signal == 0 || do_signal == SIGUSR1) {
+				do_signal = 0;
+
+				res = dhcpv6_request(DHCPV6_MSG_INFO_REQ);
+				if (do_signal == SIGUSR1)
+					continue;
+				else if (res < 0)
+					break;
+				else if (res > 0)
+					script_call("informed");
+
+				alarm(0);
+				if (dhcpv6_poll_reconfigure() > 0)
+					script_call("informed");
+			}
+
+			if (do_signal == SIGALRM)
+				script_call("timeout");
+
+			continue;
+		}
+
+		// Stateful mode
+		if (dhcpv6_request(DHCPV6_MSG_REQUEST) < 0)
+			continue;
+
+		script_call("bound");
+		alarm(0);
+
+		while (do_signal == 0 || do_signal == SIGUSR1) {
+			// Renew Cycle
+			// Wait for T1 to expire or until we get a reconfigure
+			int res = dhcpv6_poll_reconfigure();
+			if (res >= 0) {
+				if (res > 0)
+					script_call("updated");
+
+				continue;
+			}
+
+			// Handle signal, if necessary
+			if (do_signal == SIGUSR1)
+				do_signal = 0; // Acknowledged
+			else if (do_signal > 0)
+				break; // Other signal type
+
+			size_t ia_pd_len, ia_na_len, ia_pd_new, ia_na_new;
+			odhcp6c_get_state(STATE_IA_PD, &ia_pd_len);
+			odhcp6c_get_state(STATE_IA_NA, &ia_na_len);
+
+			// If we have any IAs, send renew, otherwise request
+			int r;
+			if (ia_pd_len == 0 && ia_na_len == 0)
+				r = dhcpv6_request(DHCPV6_MSG_REQUEST);
+			else
+				r = dhcpv6_request(DHCPV6_MSG_RENEW);
+			if (r > 0) // Publish updates
+				script_call("updated");
+			if (r >= 0)
+				continue; // Renew was successful
+
+			odhcp6c_clear_state(STATE_SERVER_ID); // Remove binding
+
+			// If we have IAs, try rebind otherwise restart
+			res = dhcpv6_request(DHCPV6_MSG_REBIND);
+
+			odhcp6c_get_state(STATE_IA_PD, &ia_pd_new);
+			odhcp6c_get_state(STATE_IA_NA, &ia_na_new);
+			if (res < 0 || (ia_pd_new == 0 && ia_pd_len) ||
+					(ia_na_new == 0 && ia_na_len))
+				break; // We lost all our IAs, restart
+			else if (res > 0)
+				script_call("rebound");
+		}
+
+
+		size_t ia_pd_len, ia_na_len, server_id_len;
+		uint8_t *ia_pd = odhcp6c_get_state(STATE_IA_PD, &ia_pd_len);
+		odhcp6c_get_state(STATE_IA_NA, &ia_na_len);
+		odhcp6c_get_state(STATE_SERVER_ID, &server_id_len);
+
+		// Add all prefixes to lost prefixes
+		odhcp6c_add_state(STATE_IA_PD_LOST, ia_pd, ia_pd_len);
+		odhcp6c_clear_state(STATE_IA_PD);
+
+		if (do_signal == SIGALRM)
+			script_call("timeout");
+		else
+			script_call("unbound");
+
+		// Remove assigned addresses
+		if (ia_na_len > 0)
+			dhcpv6_remove_addrs();
+
+		if (server_id_len > 0 && (ia_pd_len > 0 || ia_na_len > 0))
+			dhcpv6_request(DHCPV6_MSG_RELEASE);
+	}
+
+	return 0;
+}
+
+
+static int usage(void)
+{
+	const char buf[] =
+	"Usage: odhcp6c [options] <interface>\n"
+	"\nFeature options:\n"
+	"	-N <mode>	Mode for requesting addresses [try|force|none]\n"
+	"	-P <length>	Request IPv6-Prefix (0 = auto)\n"
+	"	-c <clientid>	Override client-ID (base-16 encoded)\n"
+	"	-r <options>	Options to be requested (comma-separated)\n"
+	"	-s <script>	Status update script (/usr/sbin/odhcp6c-update)\n"
+	"	-t <timeout>	Request timeout after which the script is called\n"
+	"\nInvocation options:\n"
+	"	-p <pidfile>	Set pidfile (/var/run/6relayd.pid)\n"
+	"	-d		Daemonize\n"
+	//"	-v		Increase logging verbosity\n"
+	"	-h		Show this help\n\n";
+	write(STDERR_FILENO, buf, sizeof(buf));
+	return 1;
+}
+
+
+// Don't want to pull-in librt and libpthread just for a monotonic clock...
+uint64_t adhc6c_get_milli_time(void)
+{
+	struct timespec t = {0, 0};
+	syscall(SYS_clock_gettime, CLOCK_MONOTONIC, &t);
+	return t.tv_sec * 1000 + t.tv_nsec / 1000000;
+}
+
+
+static uint8_t* odhcp6c_resize_state(enum odhcp6c_state state, ssize_t len)
+{
+	if (len == 0)
+		return state_data[state] + state_len[state];
+
+	syslog(LOG_WARNING, "state_reisze: %i %i %i", (int)state, (int)state_len[state], (int)len);
+	uint8_t *n = realloc(state_data[state], state_len[state] + len);
+	if (n || state_len[state] + len == 0) {
+		state_data[state] = n;
+		n += state_len[state];
+		state_len[state] += len;
+	}
+	return n;
+}
+
+
+bool odhcp6c_signal_is_pending(void)
+{
+	return do_signal != 0;
+}
+
+
+void odhcp6c_clear_state(enum odhcp6c_state state)
+{
+	state_len[state] = 0;
+}
+
+
+void odhcp6c_add_state(enum odhcp6c_state state, const void *data, size_t len)
+{
+	uint8_t *n = odhcp6c_resize_state(state, len);
+	if (n)
+		memcpy(n, data, len);
+}
+
+
+size_t odhcp6c_remove_state(enum odhcp6c_state state, size_t offset, size_t len)
+{
+	uint8_t *data = state_data[state];
+	ssize_t len_after = state_len[state] - (offset + len);
+	if (len_after < 0)
+		return state_len[state];
+
+	memmove(data + offset, data + offset + len, len_after);
+	return state_len[state] -= len;
+}
+
+
+bool odhcp6c_commit_state(enum odhcp6c_state state, size_t old_len)
+{
+	size_t new_len = state_len[state] - old_len;
+	uint8_t *old_data = state_data[state], *new_data = old_data + old_len;
+	bool upd = new_len != old_len || memcmp(old_data, new_data, new_len);
+
+	memmove(old_data, new_data, new_len);
+	odhcp6c_resize_state(state, -old_len);
+
+	return upd;
+}
+
+
+void* odhcp6c_get_state(enum odhcp6c_state state, size_t *len)
+{
+	*len = state_len[state];
+	return state_data[state];
+}
+
+
+static int sysctl_interface(const char *ifname, const char *option,
+		const char *data)
+{
+	char pathbuf[64];
+	const char *sysctl_pattern = "/proc/sys/net/ipv6/conf/%s/%s";
+	snprintf(pathbuf, sizeof(pathbuf), sysctl_pattern, ifname, option);
+
+	int fd = open(pathbuf, O_WRONLY);
+	int written = write(fd, data, strlen(data));
+	close(fd);
+
+	return (written > 0) ? 0 : -1;
+}
+
+
+static void sighandler(int signal)
+{
+	if (signal == SIGCHLD)
+		while (waitpid(-1, NULL, WNOHANG) > 0);
+	else if (signal == SIGUSR1)
+		do_signal = SIGUSR1;
+	else if (signal == SIGUSR2)
+		do_signal = SIGUSR2;
+	else if (signal == SIGALRM)
+		do_signal = SIGALRM;
+	else
+		do_signal = SIGTERM;
+}

+ 201 - 0
src/odhcp6c.h

@@ -0,0 +1,201 @@
+/**
+ * Copyright (C) 2012 Steven Barth <steven@midlink.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License v2 as published by
+ * the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ */
+#pragma once
+#include <stdint.h>
+#include <stdbool.h>
+#include <netinet/in.h>
+
+#define _unused __attribute__((unused))
+#define _packed __attribute__((packed))
+
+#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
+
+#ifndef SOL_NETLINK
+#define SOL_NETLINK 270
+#endif
+
+#define ND_OPT_RECURSIVE_DNS 25
+#define ND_OPT_DNSSL 31
+
+enum dhcvp6_opt {
+	DHCPV6_OPT_CLIENTID = 1,
+	DHCPV6_OPT_SERVERID = 2,
+	DHCPV6_OPT_IA_NA = 3,
+	DHCPV6_OPT_IA_ADDR = 5,
+	DHCPV6_OPT_ORO = 6,
+	DHCPV6_OPT_PREF = 7,
+	DHCPV6_OPT_ELAPSED = 8,
+	DHCPV6_OPT_RELAY_MSG = 9,
+	DHCPV6_OPT_AUTH = 11,
+	DHCPV6_OPT_STATUS = 13,
+	DHCPV6_OPT_RAPID_COMMIT = 14,
+	DHCPV6_OPT_RECONF_MESSAGE = 19,
+	DHCPV6_OPT_RECONF_ACCEPT = 20,
+	DHCPV6_OPT_DNS_SERVERS = 23,
+	DHCPV6_OPT_DNS_DOMAIN = 24,
+	DHCPV6_OPT_IA_PD = 25,
+	DHCPV6_OPT_IA_PREFIX = 26,
+	DHCPV6_OPT_INFO_REFRESH = 32,
+	DHCPV6_OPT_FQDN = 39,
+};
+
+enum dhcpv6_msg {
+	DHCPV6_MSG_UNKNOWN = 0,
+	DHCPV6_MSG_SOLICIT = 1,
+	DHCPV6_MSG_ADVERT = 2,
+	DHCPV6_MSG_REQUEST = 3,
+	DHCPV6_MSG_RENEW = 5,
+	DHCPV6_MSG_REBIND = 6,
+	DHCPV6_MSG_REPLY = 7,
+	DHCPV6_MSG_RELEASE = 8,
+	DHCPV6_MSG_DECLINE = 9,
+	DHCPV6_MSG_RECONF = 10,
+	DHCPV6_MSG_INFO_REQ = 11,
+	_DHCPV6_MSG_MAX
+};
+
+enum dhcpv6_status {
+	DHCPV6_NoAddrsAvail = 2,
+	DHCPV6_NoPrefixAvail = 6,
+};
+
+typedef int(reply_handler)(enum dhcpv6_msg orig,
+		const void *opt, const void *end, uint32_t elapsed);
+
+// retransmission strategy
+struct dhcpv6_retx {
+	bool delay;
+	uint8_t init_timeo;
+	uint16_t max_timeo;
+	char name[8];
+	reply_handler *handler_reply;
+	int(*handler_finish)(uint32_t elapsed);
+};
+
+
+// DHCPv6 Protocol Headers
+struct dhcpv6_header {
+	uint8_t msg_type;
+	uint8_t tr_id[3];
+} __attribute__((packed));
+
+struct dhcpv6_ia_hdr {
+	uint16_t type;
+	uint16_t len;
+	uint32_t iaid;
+	uint32_t t1;
+	uint32_t t2;
+} _packed;
+
+struct dhcpv6_ia_addr {
+	uint16_t type;
+	uint16_t len;
+	struct in6_addr addr;
+	uint32_t preferred;
+	uint32_t valid;
+} _packed;
+
+struct dhcpv6_ia_prefix {
+	uint16_t type;
+	uint16_t len;
+	uint32_t preferred;
+	uint32_t valid;
+	uint8_t prefix;
+	struct in6_addr addr;
+} _packed;
+
+struct dhcpv6_duid {
+	uint16_t type;
+	uint16_t len;
+	uint16_t duid_type;
+	uint8_t data[128];
+} _packed;
+
+
+#define dhcpv6_for_each_option(start, end, otype, olen, odata)\
+	for (uint8_t *_o = (uint8_t*)(start); _o + 4 <= (uint8_t*)(end) &&\
+		((otype) = _o[0] << 8 | _o[1]) && ((odata) = (void*)&_o[4]) &&\
+		((olen) = _o[2] << 8 | _o[3]) + (odata) <= (uint8_t*)(end); \
+		_o += 4 + (_o[2] << 8 | _o[3]))
+
+
+struct dhcpv6_server_cand {
+	bool has_noaddravail;
+	bool wants_reconfigure;
+	int16_t preference;
+	uint8_t duid_len;
+	uint8_t duid[130];
+};
+
+
+enum odhcp6c_state {
+	STATE_CLIENT_ID,
+	STATE_SERVER_ID,
+	STATE_SERVER_CAND,
+	STATE_ORO,
+	STATE_DNS,
+	STATE_SEARCH,
+	STATE_IA_NA,
+	STATE_IA_PD,
+	STATE_IA_PD_LOST,
+	STATE_CUSTOM_OPTS,
+	_STATE_MAX
+};
+
+
+struct icmp6_opt {
+	uint8_t type;
+	uint8_t len;
+	uint8_t data[6];
+};
+
+
+enum dhcpv6_mode {
+	DHCPV6_UNKNOWN,
+	DHCPV6_STATELESS,
+	DHCPV6_STATEFUL
+};
+
+
+enum odhcp6c_ia_mode {
+	IA_MODE_NONE,
+	IA_MODE_TRY,
+	IA_MODE_FORCE,
+};
+
+
+int init_dhcpv6(const char *ifname, int request_pd);
+void dhcpv6_set_ia_na_mode(enum odhcp6c_ia_mode mode);
+int dhcpv6_request(enum dhcpv6_msg type);
+int dhcpv6_poll_reconfigure(void);
+void dhcpv6_remove_addrs(void);
+
+int init_rtnetlink(void);
+int set_rtnetlink_addr(int ifindex, const struct in6_addr *addr,
+		time_t pref, time_t valid);
+
+int script_init(const char *path, const char *ifname);
+ssize_t script_unhexlify(uint8_t *dst, size_t len, const char *src);
+void script_call(const char *status);
+
+
+// State manipulation
+bool odhcp6c_signal_is_pending(void);
+uint64_t adhc6c_get_milli_time(void);
+void odhcp6c_clear_state(enum odhcp6c_state state);
+void odhcp6c_add_state(enum odhcp6c_state state, const void *data, size_t len);
+size_t odhcp6c_remove_state(enum odhcp6c_state state, size_t offset, size_t len);
+bool odhcp6c_commit_state(enum odhcp6c_state state, size_t old_len);
+void* odhcp6c_get_state(enum odhcp6c_state state, size_t *len);
+

+ 115 - 0
src/rtnetlink.c

@@ -0,0 +1,115 @@
+/**
+ * Copyright (C) 2012 Steven Barth <steven@midlink.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License v2 as published by
+ * the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ */
+
+#include <time.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+#include <syslog.h>
+#include <stdbool.h>
+#include <arpa/inet.h>
+#include <sys/socket.h>
+#include <linux/rtnetlink.h>
+
+#include "odhcp6c.h"
+
+
+static int sock = -1;
+static unsigned seq = 0;
+
+
+// Init rtnetlink socket
+int init_rtnetlink(void)
+{
+	sock = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE);
+	struct sockaddr_nl rtnl_kernel = { .nl_family = AF_NETLINK };
+	if (connect(sock, (struct sockaddr*)&rtnl_kernel, sizeof(rtnl_kernel)))
+		return -1;
+
+	return 0;
+}
+
+
+// CRUD addresses to interface
+int set_rtnetlink_addr(int ifindex, const struct in6_addr *addr,
+		time_t pref, time_t valid)
+{
+	int flags = NLM_F_REQUEST | NLM_F_ACK;
+	int cmd = RTM_DELADDR;
+
+	if (valid > 0) {
+		flags |= NLM_F_CREATE | NLM_F_REPLACE;
+		cmd = RTM_NEWADDR;
+	}
+
+	struct {
+		struct nlmsghdr nhm;
+		struct ifaddrmsg ifa;
+		struct rtattr rta_addr;
+		struct in6_addr addr;
+		struct rtattr rta_local;
+		struct in6_addr local;
+		struct rtattr rta_info;
+		struct ifa_cacheinfo info;
+	} req = {
+		{sizeof(req), cmd, flags, ++seq, 0},
+		{AF_INET6, 128, 0, RT_SCOPE_UNIVERSE, ifindex},
+		{sizeof(req.rta_addr) + sizeof(req.addr), IFA_ADDRESS},
+		*addr,
+		{sizeof(req.rta_local) + sizeof(req.local), IFA_LOCAL},
+		*addr,
+		{sizeof(req.rta_info) + sizeof(req.info), IFA_CACHEINFO},
+		{pref, valid, 0, 0}
+	};
+	send(sock, &req, sizeof(req), 0);
+
+	struct {
+		struct nlmsghdr nhm;
+		struct nlmsgerr err;
+	} reply;
+	recv(sock, &reply, sizeof(reply), 0);
+
+	char buf[INET6_ADDRSTRLEN];
+	inet_ntop(AF_INET6, addr, buf, sizeof(buf));
+	syslog(LOG_WARNING, "%s address %s/128 for iface %i: %s",
+			(valid) ? "assigning" : "removing", buf,
+			ifindex, strerror(-reply.err.error));
+
+	if (reply.err.error < 0 || valid == 0)
+		return reply.err.error;
+
+	// Check for duplicate addresses
+	struct timespec ts = {1, 0};
+	nanosleep(&ts, NULL);
+
+	req.nhm.nlmsg_type = RTM_GETADDR;
+	req.nhm.nlmsg_seq = ++seq;
+	req.nhm.nlmsg_flags = NLM_F_REQUEST;
+	send(sock, &req, sizeof(req), 0);
+
+	struct {
+		struct nlmsghdr nhm;
+		struct ifaddrmsg ifa;
+		uint8_t buf[1024];
+	} dad_reply;
+	recv(sock, &dad_reply, sizeof(dad_reply), 0);
+
+	if (dad_reply.nhm.nlmsg_type != RTM_NEWADDR ||
+			(dad_reply.ifa.ifa_flags & IFA_F_DADFAILED)) {
+		syslog(LOG_WARNING, "Removing duplicate address %s", buf);
+		set_rtnetlink_addr(ifindex, addr, 0, 0);
+		return -EADDRNOTAVAIL;
+	}
+	return 0;
+}

+ 184 - 0
src/script.c

@@ -0,0 +1,184 @@
+/**
+ * Copyright (C) 2012 Steven Barth <steven@midlink.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License v2 as published by
+ * the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ */
+
+#include <stdio.h>
+#include <resolv.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <arpa/inet.h>
+#include <netinet/in.h>
+
+#include "odhcp6c.h"
+
+static const char hexdigits[] = "0123456789abcdef";
+static const char hexvals[] = {
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, -2, -1, -1, -2, -1, -1,
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+    -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+     0,  1,  2,  3,  4,  5,  6,  7,  8,  9, -1, -1, -1, -1, -1, -1,
+    -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+    -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+};
+
+
+
+static char *argv[4] = {NULL, NULL, NULL, NULL};
+
+
+int script_init(const char *path, const char *ifname)
+{
+	argv[0] = (char*)path;
+	argv[1] = (char*)ifname;
+	return 0;
+}
+
+
+ssize_t script_unhexlify(uint8_t *dst, size_t len, const char *src)
+{
+	size_t c;
+	for (c = 0; c < len && src[0] && src[1]; ++c) {
+		int8_t x = (int8_t)*src++;
+		int8_t y = (int8_t)*src++;
+		if (x < 0 || (x = hexvals[x]) < 0
+				|| y < 0 || (y = hexvals[y]) < 0)
+			return -1;
+		dst[c] = x << 4 | y;
+		while (*src < 0 || (*src && hexvals[(uint8_t)*src] < 0))
+			src++;
+	}
+
+	return c;
+}
+
+
+void script_hexlify(char *dst, const uint8_t *src, size_t len) {
+	for (size_t i = 0; i < len; ++i) {
+		*dst++ = hexdigits[src[i] >> 4];
+		*dst++ = hexdigits[src[i] & 0x0f];
+	}
+	*dst = 0;
+}
+
+
+static void ipv6_to_env(const char *name,
+		const struct in6_addr *addr, size_t cnt)
+{
+	size_t buf_len = strlen(name);
+	char *buf = realloc(NULL, cnt * INET6_ADDRSTRLEN + buf_len + 2);
+	memcpy(buf, name, buf_len);
+	buf[buf_len++] = '=';
+	for (size_t i = 0; i < cnt; ++i) {
+		inet_ntop(AF_INET6, &addr[i], &buf[buf_len], INET6_ADDRSTRLEN);
+		buf_len += strlen(&buf[buf_len]);
+		buf[buf_len++] = ' ';
+	}
+	buf[buf_len - 1] = '\0';
+	putenv(buf);
+}
+
+
+static void fqdn_to_env(const char *name, const uint8_t *fqdn, size_t len)
+{
+	size_t buf_len = strlen(name);
+	const uint8_t *fqdn_end = fqdn + len;
+	char *buf = realloc(NULL, len + buf_len + 2);
+	memcpy(buf, name, buf_len);
+	buf[buf_len++] = '=';
+	int l = 1;
+	while (l > 0 && fqdn < fqdn_end) {
+		l = dn_expand(fqdn, &fqdn[len], fqdn, &buf[buf_len], len);
+		fqdn += l;
+		buf_len += strlen(&buf[buf_len]);
+		buf[buf_len++] = ' ';
+	}
+	buf[buf_len - 1] = '\0';
+	putenv(buf);
+}
+
+
+static void bin_to_env(uint8_t *opts, size_t len)
+{
+	uint8_t *oend = opts + len, *odata;
+	uint16_t otype, olen;
+	dhcpv6_for_each_option(opts, oend, otype, olen, odata) {
+		char *buf = realloc(NULL, 14 + (olen * 2));
+		size_t buf_len = 0;
+
+		snprintf(buf, 14, "OPTION_%hu=", otype);
+		buf_len += strlen(buf);
+
+		script_hexlify(&buf[buf_len], odata, olen);
+		putenv(buf);
+	}
+}
+
+
+static void prefix_to_env(const char *name, const uint8_t *fqdn, size_t len)
+{
+	size_t buf_len = strlen(name);
+	struct dhcpv6_ia_prefix *p = NULL;
+	char *buf = realloc(NULL, buf_len + 2 +
+			(len / sizeof(*p)) * (INET6_ADDRSTRLEN + 32));
+	memcpy(buf, name, buf_len);
+	buf[buf_len++] = '=';
+
+	uint16_t otype, olen;
+	uint8_t *odata;
+	dhcpv6_for_each_option(fqdn, &fqdn[len], otype, olen, odata) {
+		if (otype != DHCPV6_OPT_IA_PREFIX || olen + 4U < sizeof(*p))
+			continue;
+
+		p = (struct dhcpv6_ia_prefix*)&odata[-4];
+		inet_ntop(AF_INET6, &p->addr, &buf[buf_len], INET6_ADDRSTRLEN);
+		buf_len += strlen(&buf[buf_len]);
+		buf_len += snprintf(&buf[buf_len], 32, "/%hhu,%u,%u ",
+				p->prefix, ntohl(p->preferred),
+				ntohl(p->valid));
+	}
+	buf[buf_len - 1] = '\0';
+	putenv(buf);
+}
+
+
+void script_call(const char *status)
+{
+	size_t dns_len, search_len, custom_len;
+	struct in6_addr *dns = odhcp6c_get_state(STATE_DNS, &dns_len);
+	uint8_t *search = odhcp6c_get_state(STATE_SEARCH, &search_len);
+	uint8_t *custom = odhcp6c_get_state(STATE_CUSTOM_OPTS, &custom_len);
+
+	size_t prefix_len, lost_pd_len;
+	uint8_t *prefix = odhcp6c_get_state(STATE_IA_PD, &prefix_len);
+	uint8_t *lost_pd = odhcp6c_get_state(STATE_IA_PD_LOST, &lost_pd_len);
+
+	// Don't set environment before forking, because env is leaky.
+	if (fork() == 0) {
+		ipv6_to_env("RDNSS", dns, dns_len / sizeof(*dns));
+		fqdn_to_env("DOMAINS", search, search_len);
+		bin_to_env(custom, custom_len);
+		prefix_to_env("PREFIXES", prefix, prefix_len);
+		prefix_to_env("PREFIXES_LOST", lost_pd, lost_pd_len);
+
+		argv[2] = (char*)status;
+		execv(argv[0], argv);
+		_exit(128);
+	}
+
+	// Delete lost prefixes and user opts
+	odhcp6c_clear_state(STATE_IA_PD_LOST);
+	odhcp6c_clear_state(STATE_CUSTOM_OPTS);
+}