From: Steven Barth Date: Sun, 25 Nov 2012 11:20:36 +0000 (+0100) Subject: Initial commit (expect bugs!) X-Git-Tag: debian/1.1+git20160131-1~218 X-Git-Url: https://git.decadent.org.uk/gitweb/?a=commitdiff_plain;h=0b77e6065dc833da19ddff6e04e4f09c805c6883;p=odhcp6c.git Initial commit (expect bugs!) --- 0b77e6065dc833da19ddff6e04e4f09c805c6883 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4c784af --- /dev/null +++ b/.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 + diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..a268553 --- /dev/null +++ b/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 ") +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) + diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..3912109 --- /dev/null +++ b/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. + + + Copyright (C) + + 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. + + , 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. diff --git a/README b/README new file mode 100644 index 0000000..4af0835 --- /dev/null +++ b/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: + + +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_ Custom option received as base-16 +* PREFIXES A space-separated list of prefixes currently assigned + Format: /,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 diff --git a/src/dhcpv6.c b/src/dhcpv6.c new file mode 100644 index 0000000..9b664ed --- /dev/null +++ b/src/dhcpv6.c @@ -0,0 +1,781 @@ +/** + * Copyright (C) 2012 Steven Barth + * + * 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#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, "", + 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; +} diff --git a/src/odhcp6c.c b/src/odhcp6c.c new file mode 100644 index 0000000..9126986 --- /dev/null +++ b/src/odhcp6c.c @@ -0,0 +1,421 @@ +/** + * Copyright (C) 2012 Steven Barth + * + * 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#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] \n" + "\nFeature options:\n" + " -N Mode for requesting addresses [try|force|none]\n" + " -P Request IPv6-Prefix (0 = auto)\n" + " -c Override client-ID (base-16 encoded)\n" + " -r Options to be requested (comma-separated)\n" + " -s