summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorDaniel Drown <dan-android@drown.org>2012-03-23 10:42:54 -0500
committerJP Abgrall <jpa@google.com>2012-11-12 15:59:12 -0800
commita45056e35c1af2a0f0a6eed258fd5fdf4846a79f (patch)
tree5dd035946e9ab1201289292f7343af3230a26433
parent62ea9b6658a4c2116eeb6450c8244269448e79aa (diff)
downloadplatform_external_android-clat-a45056e35c1af2a0f0a6eed258fd5fdf4846a79f.tar.gz
platform_external_android-clat-a45056e35c1af2a0f0a6eed258fd5fdf4846a79f.tar.bz2
platform_external_android-clat-a45056e35c1af2a0f0a6eed258fd5fdf4846a79f.zip
android clat service
This software provides the nat 4->6 translation needed for the "clat" part of the 464xlat standard. It is needed for better IPv4 application support while on an IPv6-only mobile network connection using 464xlat's nat64 (such as T-Mobile's IPv6 trial). A general diagram of how 464xlat works: http://dan.drown.org/android/clat/Clat-Plat.png Depends-on: I2392f8127dcd90d16b0f20ff31bcc5aa096db464 Change-Id: If2bc6916fc66fd4bca7cc241c83cfae839b82e15 Signed-off-by: Daniel Drown <dan-android@drown.org>
-rw-r--r--Android.mk14
-rw-r--r--BUGS9
-rw-r--r--LICENSE201
-rw-r--r--MODULE_LICENSE_APACHE20
-rw-r--r--NOTICE189
-rw-r--r--checksum.c113
-rw-r--r--checksum.h28
-rw-r--r--clatd.c522
-rw-r--r--clatd.conf15
-rw-r--r--clatd.h32
-rw-r--r--config.c302
-rw-r--r--config.h42
-rw-r--r--debug.h24
-rw-r--r--dns64.c91
-rw-r--r--dns64.h23
-rw-r--r--dump.c225
-rw-r--r--dump.h33
-rw-r--r--getaddr.c137
-rw-r--r--getaddr.h28
-rw-r--r--getroute.c143
-rw-r--r--getroute.h35
-rw-r--r--ipv4.c187
-rw-r--r--ipv4.h23
-rw-r--r--ipv6.c194
-rw-r--r--ipv6.h23
-rw-r--r--logging.c53
-rw-r--r--logging.h27
-rw-r--r--mtu.c46
-rw-r--r--mtu.h24
-rw-r--r--netlink_callbacks.c66
-rw-r--r--netlink_callbacks.h24
-rw-r--r--netlink_msg.c168
-rw-r--r--netlink_msg.h29
-rw-r--r--setif.c129
-rw-r--r--setif.h24
-rw-r--r--setroute.c186
-rw-r--r--setroute.h28
-rw-r--r--translate.c404
-rw-r--r--translate.h30
39 files changed, 3871 insertions, 0 deletions
diff --git a/Android.mk b/Android.mk
new file mode 100644
index 0000000..b1238ce
--- /dev/null
+++ b/Android.mk
@@ -0,0 +1,14 @@
+LOCAL_PATH:= $(call my-dir)
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES:=clatd.c dump.c checksum.c translate.c ipv4.c ipv6.c config.c dns64.c logging.c getaddr.c getroute.c netlink_callbacks.c netlink_msg.c setif.c setroute.c mtu.c
+
+LOCAL_C_INCLUDES := external/libnl-headers
+LOCAL_STATIC_LIBRARIES := libnl_2
+LOCAL_SHARED_LIBRARIES := libcutils
+
+LOCAL_MODULE_TAGS := optional
+
+LOCAL_MODULE := clatd
+
+include $(BUILD_EXECUTABLE)
diff --git a/BUGS b/BUGS
new file mode 100644
index 0000000..5494d6b
--- /dev/null
+++ b/BUGS
@@ -0,0 +1,9 @@
+Optional:
+ - ipv6 traceroute to handle 464 transitions
+
+known problems/assumptions:
+ - does not handle ICMP types other than echo/echo reply
+ - does not handle protocols other than ICMP, UDP, and TCP
+ - assumes the handset has its own (routed) /64 ipv6 subnet
+ - assumes the /120 or /128 ipv6 subnet it generates can use the nat64 gateway
+ - assumes the nat64 gateway has the ipv4 address in the last 32 bits of the ipv6 address (that it uses a /96 plat subnet)
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..261eeb9
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/MODULE_LICENSE_APACHE2 b/MODULE_LICENSE_APACHE2
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/MODULE_LICENSE_APACHE2
diff --git a/NOTICE b/NOTICE
new file mode 100644
index 0000000..5943b54
--- /dev/null
+++ b/NOTICE
@@ -0,0 +1,189 @@
+ Copyright (c) 2010-2012, Daniel Drown
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
diff --git a/checksum.c b/checksum.c
new file mode 100644
index 0000000..14b7113
--- /dev/null
+++ b/checksum.c
@@ -0,0 +1,113 @@
+/*
+ * Copyright 2011 Daniel Drown
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * checksum.c - ipv4/ipv6 checksum calculation
+ */
+#include <netinet/in.h>
+#include <netinet/ip.h>
+#include <netinet/ip_icmp.h>
+#include <netinet/udp.h>
+#include <netinet/tcp.h>
+#include <netinet/ip6.h>
+#include <netinet/icmp6.h>
+#include <linux/icmp.h>
+
+#include "checksum.h"
+
+/* function: ip_checksum_add
+ * adds data to a checksum
+ * current_sum - the current checksum (or 0 to start a new checksum)
+ * data - the data to add to the checksum
+ * len - length of data
+ */
+uint32_t ip_checksum_add(uint32_t current_sum, const void *data, int len) {
+ uint32_t checksum = current_sum;
+ int left = len;
+ const uint16_t *data_16 = data;
+
+ while(left > 1) {
+ checksum += *data_16;
+ data_16++;
+ left -= 2;
+ }
+ if(left) {
+ checksum += *(uint8_t *)data_16;
+ }
+
+ return checksum;
+}
+
+/* function: ip_checksum_finish
+ * close the checksum
+ * temp_sum - sum from ip_checksum_add
+ */
+uint16_t ip_checksum_finish(uint32_t temp_sum) {
+ while(temp_sum > 0xffff)
+ temp_sum = (temp_sum >> 16) + (temp_sum & 0xFFFF);
+
+ temp_sum = (~temp_sum) & 0xffff;
+
+ return temp_sum;
+}
+
+/* function: ip_checksum
+ * combined ip_checksum_add and ip_checksum_finish
+ * data - data to checksum
+ * len - length of data
+ */
+uint16_t ip_checksum(const void *data, int len) {
+ uint32_t temp_sum;
+
+ temp_sum = ip_checksum_add(0,data,len);
+ return ip_checksum_finish(temp_sum);
+}
+
+/* function: ipv6_pseudo_header_checksum
+ * calculate the pseudo header checksum for use in tcp/udp/icmp headers
+ * current_sum - the current checksum or 0 to start a new checksum
+ * ip6 - the ipv6 header
+ */
+uint32_t ipv6_pseudo_header_checksum(uint32_t current_sum, const struct ip6_hdr *ip6) {
+ uint32_t checksum_len, checksum_next;
+
+ checksum_len = htonl(ntohs(ip6->ip6_plen));
+ checksum_next = htonl(ip6->ip6_nxt);
+
+ current_sum = ip_checksum_add(current_sum,&(ip6->ip6_src),sizeof(struct in6_addr));
+ current_sum = ip_checksum_add(current_sum,&(ip6->ip6_dst),sizeof(struct in6_addr));
+ current_sum = ip_checksum_add(current_sum,&checksum_len,sizeof(checksum_len));
+ current_sum = ip_checksum_add(current_sum,&checksum_next,sizeof(checksum_next));
+
+ return current_sum;
+}
+
+/* function: ipv4_pseudo_header_checksum
+ * calculate the pseudo header checksum for use in tcp/udp headers
+ * current_sum - the current checksum or 0 to start a new checksum
+ * ip - the ipv4 header
+ */
+uint32_t ipv4_pseudo_header_checksum(uint32_t current_sum, const struct iphdr *ip) {
+ uint16_t temp_protocol, temp_length;
+
+ temp_protocol = htons(ip->protocol);
+ temp_length = htons(ntohs(ip->tot_len) - ip->ihl*4);
+
+ current_sum = ip_checksum_add(current_sum, &(ip->saddr), sizeof(uint32_t));
+ current_sum = ip_checksum_add(current_sum, &(ip->daddr), sizeof(uint32_t));
+ current_sum = ip_checksum_add(current_sum, &temp_protocol, sizeof(uint16_t));
+ current_sum = ip_checksum_add(current_sum, &temp_length, sizeof(uint16_t));
+
+ return current_sum;
+}
diff --git a/checksum.h b/checksum.h
new file mode 100644
index 0000000..c8346a0
--- /dev/null
+++ b/checksum.h
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2011 Daniel Drown
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * checksum.h - checksum functions
+ */
+#ifndef __CHECKSUM_H__
+#define __CHECKSUM_H__
+
+uint32_t ip_checksum_add(uint32_t current_sum, const void *data, int len);
+uint16_t ip_checksum_finish(uint32_t temp_sum);
+uint16_t ip_checksum(const void *data, int len);
+
+uint32_t ipv6_pseudo_header_checksum(uint32_t current_sum, const struct ip6_hdr *ip6);
+uint32_t ipv4_pseudo_header_checksum(uint32_t current_sum, const struct iphdr *ip);
+
+#endif /* __CHECKSUM_H__ */
diff --git a/clatd.c b/clatd.c
new file mode 100644
index 0000000..17a3548
--- /dev/null
+++ b/clatd.c
@@ -0,0 +1,522 @@
+/*
+ * Copyright 2012 Daniel Drown
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * clatd.c - tun interface setup and main event loop
+ */
+#include <poll.h>
+#include <signal.h>
+#include <time.h>
+#include <stdio.h>
+#include <sys/types.h>
+#include <sys/ioctl.h>
+#include <sys/stat.h>
+#include <string.h>
+#include <errno.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <arpa/inet.h>
+#include <fcntl.h>
+
+#include <netinet/in.h>
+#include <netinet/ip.h>
+#include <netinet/ip_icmp.h>
+#include <netinet/udp.h>
+#include <netinet/tcp.h>
+#include <netinet/ip6.h>
+#include <netinet/icmp6.h>
+#include <linux/icmp.h>
+
+#include <linux/capability.h>
+#include <linux/prctl.h>
+#include <linux/if.h>
+#include <linux/if_tun.h>
+#include <linux/if_ether.h>
+
+#include <private/android_filesystem_config.h>
+
+#include "ipv4.h"
+#include "ipv6.h"
+#include "clatd.h"
+#include "config.h"
+#include "logging.h"
+#include "setif.h"
+#include "setroute.h"
+#include "mtu.h"
+#include "getaddr.h"
+#include "dump.h"
+
+#define DEVICENAME6 "clat"
+#define DEVICENAME4 "clat4"
+
+int forwarding_fd = -1;
+volatile sig_atomic_t running = 1;
+
+struct tun_data {
+ char device6[IFNAMSIZ], device4[IFNAMSIZ];
+ int fd6, fd4;
+};
+
+/* function: set_forwarding
+ * enables/disables ipv6 forwarding
+ */
+void set_forwarding(int fd, const char *setting) {
+ /* we have to forward packets from the WAN to the tun interface */
+ if(write(fd, setting, strlen(setting)) < 0) {
+ logmsg(ANDROID_LOG_FATAL,"set_forwarding(%s) failed: %s", setting, strerror(errno));
+ exit(1);
+ }
+}
+
+/* function: set_accept_ra
+ * accepts IPv6 RAs on all interfaces, even when forwarding is on
+ */
+void set_accept_ra() {
+ int fd, i;
+ const char *interface_names[] = {"wlan0","default",NULL};
+ const char ipv6_sysctl[] = "/proc/sys/net/ipv6/conf/";
+ const char accept_ra[] = "/accept_ra";
+
+ for(i = 0; interface_names[i]; i++) {
+ ssize_t sysctl_path_len = strlen(ipv6_sysctl)+strlen(interface_names[i])+strlen(accept_ra)+1;
+ char *sysctl_path = malloc(sysctl_path_len);
+ if(!sysctl_path) {
+ logmsg(ANDROID_LOG_FATAL,"set_accept_ra: malloc failed");
+ exit(1);
+ }
+ snprintf(sysctl_path, sysctl_path_len, "%s%s%s", ipv6_sysctl, interface_names[i], accept_ra);
+
+ fd = open(sysctl_path, O_RDWR);
+ free(sysctl_path);
+ if(fd < 0) {
+ continue;
+ }
+ if(write(fd, "2\n", 2) < 0) {
+ logmsg(ANDROID_LOG_WARN,"write to (%s)accept_ra failed: %s",interface_names[i],strerror(errno));
+ }
+ close(fd);
+ }
+}
+
+/* function: got_sigterm
+ * signal handler: mark it time to clean up
+ */
+void got_sigterm(int signal) {
+ running = 0;
+}
+
+/* function: tun_open
+ * tries to open the tunnel device
+ */
+int tun_open() {
+ int fd;
+
+ fd = open("/dev/tun", O_RDWR);
+ if(fd < 0) {
+ fd = open("/dev/net/tun", O_RDWR);
+ }
+
+ return fd;
+}
+
+/* function: tun_alloc
+ * creates a tun interface and names it
+ * dev - the name for the new tun device
+ */
+int tun_alloc(char *dev, int fd) {
+ struct ifreq ifr;
+ int err;
+
+ memset(&ifr, 0, sizeof(ifr));
+
+ ifr.ifr_flags = IFF_TUN;
+ if( *dev ) {
+ strncpy(ifr.ifr_name, dev, IFNAMSIZ);
+ ifr.ifr_name[IFNAMSIZ-1] = '\0';
+ }
+
+ if( (err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0 ){
+ close(fd);
+ return err;
+ }
+ strcpy(dev, ifr.ifr_name);
+ return 0;
+}
+
+/* function: deconfigure_tun_ipv6
+ * removes the ipv6 route
+ * tunnel - tun device data
+ */
+void deconfigure_tun_ipv6(const struct tun_data *tunnel) {
+ int status;
+
+ status = if_route(tunnel->device6, AF_INET6, &Global_Clatd_Config.ipv6_local_subnet,
+ 128, NULL, 1, 0, ROUTE_DELETE);
+ if(status < 0) {
+ logmsg(ANDROID_LOG_WARN,"deconfigure_tun_ipv6/if_route(6) failed: %s",strerror(-status));
+ }
+}
+
+/* function: configure_tun_ipv6
+ * configures the ipv6 route
+ * note: routes a /128 out of the (assumed routed to us) /64 to the CLAT interface
+ * tunnel - tun device data
+ */
+void configure_tun_ipv6(const struct tun_data *tunnel) {
+ struct in6_addr local_nat64_prefix_6;
+ int status;
+
+ status = if_route(tunnel->device6, AF_INET6, &Global_Clatd_Config.ipv6_local_subnet,
+ 128, NULL, 1, 0, ROUTE_CREATE);
+ if(status < 0) {
+ logmsg(ANDROID_LOG_FATAL,"configure_tun_ipv6/if_route(6) failed: %s",strerror(-status));
+ exit(1);
+ }
+}
+
+/* function: interface_poll
+ * polls the uplink network interface for address changes
+ * tunnel - tun device data
+ */
+void interface_poll(const struct tun_data *tunnel) {
+ union anyip *interface_ip;
+
+ interface_ip = getinterface_ip(Global_Clatd_Config.default_pdp_interface, AF_INET6);
+ if(!interface_ip) {
+ logmsg(ANDROID_LOG_WARN,"unable to find an ipv6 ip on interface %s",Global_Clatd_Config.default_pdp_interface);
+ return;
+ }
+
+ config_generate_local_ipv6_subnet(&interface_ip->ip6);
+
+ if(!IN6_ARE_ADDR_EQUAL(&interface_ip->ip6, &Global_Clatd_Config.ipv6_local_subnet)) {
+ char from_addr[INET6_ADDRSTRLEN], to_addr[INET6_ADDRSTRLEN];
+ inet_ntop(AF_INET6, &Global_Clatd_Config.ipv6_local_subnet, from_addr, sizeof(from_addr));
+ inet_ntop(AF_INET6, &interface_ip->ip6, to_addr, sizeof(to_addr));
+ logmsg(ANDROID_LOG_WARN, "clat subnet changed from %s to %s", from_addr, to_addr);
+
+ // remove old route
+ deconfigure_tun_ipv6(tunnel);
+
+ // add new route, start translating packets to the new prefix
+ memcpy(&Global_Clatd_Config.ipv6_local_subnet, &interface_ip->ip6, sizeof(struct in6_addr));
+ configure_tun_ipv6(tunnel);
+ }
+
+ free(interface_ip);
+}
+
+/* function: configure_tun_ip
+ * configures the ipv4 and ipv6 addresses on the tunnel interface
+ * tunnel - tun device data
+ */
+void configure_tun_ip(const struct tun_data *tunnel) {
+ struct in_addr default_4;
+ int status;
+
+ default_4.s_addr = INADDR_ANY;
+
+ if((status = if_up(tunnel->device6, Global_Clatd_Config.mtu)) < 0) {
+ logmsg(ANDROID_LOG_FATAL,"configure_tun_ip/if_up(6) failed: %s",strerror(-status));
+ exit(1);
+ }
+ if((status = if_up(tunnel->device4, Global_Clatd_Config.ipv4mtu)) < 0) {
+ logmsg(ANDROID_LOG_FATAL,"configure_tun_ip/if_up(4) failed: %s",strerror(-status));
+ exit(1);
+ }
+ status = add_address(tunnel->device4, AF_INET, &Global_Clatd_Config.ipv4_local_subnet,
+ 32, &Global_Clatd_Config.ipv4_local_subnet);
+ if(status < 0) {
+ logmsg(ANDROID_LOG_FATAL,"configure_tun_ip/if_address(4) failed: %s",strerror(-status));
+ exit(1);
+ }
+
+ configure_tun_ipv6(tunnel);
+
+ /* setup default ipv4 route */
+ status = if_route(tunnel->device4, AF_INET, &default_4, 0, NULL, 1, 0, ROUTE_REPLACE);
+ if(status < 0) {
+ logmsg(ANDROID_LOG_FATAL,"configure_tun_ip/if_route failed: %s",strerror(-status));
+ exit(1);
+ }
+}
+
+/* function: drop_root
+ * drops root privs but keeps the needed capability
+ */
+void drop_root() {
+ gid_t groups[] = { AID_INET };
+ if(setgroups(sizeof(groups)/sizeof(groups[0]), groups) < 0) {
+ logmsg(ANDROID_LOG_FATAL,"drop_root/setgroups failed: %s",strerror(errno));
+ exit(1);
+ }
+
+ prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
+
+ if(setgid(AID_CLAT) < 0) {
+ logmsg(ANDROID_LOG_FATAL,"drop_root/setgid failed: %s",strerror(errno));
+ exit(1);
+ }
+ if(setuid(AID_CLAT) < 0) {
+ logmsg(ANDROID_LOG_FATAL,"drop_root/setuid failed: %s",strerror(errno));
+ exit(1);
+ }
+
+ struct __user_cap_header_struct header;
+ struct __user_cap_data_struct cap;
+ memset(&header, 0, sizeof(header));
+ memset(&cap, 0, sizeof(cap));
+
+ header.version = _LINUX_CAPABILITY_VERSION;
+ header.pid = 0; // 0 = change myself
+ cap.effective = cap.permitted = (1 << CAP_NET_ADMIN);
+
+ if(capset(&header, &cap) < 0) {
+ logmsg(ANDROID_LOG_FATAL,"drop_root/capset failed: %s",strerror(errno));
+ exit(1);
+ }
+}
+
+/* function: configure_interface
+ * reads the configuration and applies it to the interface
+ * uplink_interface - network interface to use to reach the ipv6 internet
+ * plat_prefix - PLAT prefix to use
+ * tunnel - tun device data
+ */
+void configure_interface(const char *uplink_interface, const char *plat_prefix, struct tun_data *tunnel) {
+ int error;
+
+ if(!read_config("/system/etc/clatd.conf", uplink_interface, plat_prefix)) {
+ logmsg(ANDROID_LOG_FATAL,"read_config failed");
+ exit(1);
+ }
+
+ if(Global_Clatd_Config.mtu > MAXMTU) {
+ logmsg(ANDROID_LOG_WARN,"Max MTU is %d, requested %d", MAXMTU, Global_Clatd_Config.mtu);
+ Global_Clatd_Config.mtu = MAXMTU;
+ }
+ if(Global_Clatd_Config.mtu <= 0) {
+ Global_Clatd_Config.mtu = getifmtu(Global_Clatd_Config.default_pdp_interface);
+ logmsg(ANDROID_LOG_WARN,"ifmtu=%d",Global_Clatd_Config.mtu);
+ }
+ if(Global_Clatd_Config.mtu < 1280) {
+ logmsg(ANDROID_LOG_WARN,"mtu too small = %d", Global_Clatd_Config.mtu);
+ Global_Clatd_Config.mtu = 1280;
+ }
+
+ if(Global_Clatd_Config.ipv4mtu <= 0 || (Global_Clatd_Config.ipv4mtu > Global_Clatd_Config.mtu - 20)) {
+ Global_Clatd_Config.ipv4mtu = Global_Clatd_Config.mtu-20;
+ logmsg(ANDROID_LOG_WARN,"ipv4mtu now set to = %d",Global_Clatd_Config.ipv4mtu);
+ }
+
+ error = tun_alloc(tunnel->device6, tunnel->fd6);
+ if(error < 0) {
+ logmsg(ANDROID_LOG_FATAL,"tun_alloc failed: %s",strerror(errno));
+ exit(1);
+ }
+
+ error = tun_alloc(tunnel->device4, tunnel->fd4);
+ if(error < 0) {
+ logmsg(ANDROID_LOG_FATAL,"tun_alloc/4 failed: %s",strerror(errno));
+ exit(1);
+ }
+
+ configure_tun_ip(tunnel);
+}
+
+/* function: packet_handler
+ * takes a tun header and a packet and sends it down the stack
+ * tunnel - tun device data
+ * tun_header - tun header
+ * packet - packet
+ * packetsize - size of packet
+ */
+void packet_handler(const struct tun_data *tunnel, struct tun_pi *tun_header, const char *packet, size_t packetsize) {
+ tun_header->proto = ntohs(tun_header->proto);
+
+ if(tun_header->flags != 0) {
+ logmsg(ANDROID_LOG_WARN,"packet_handler: unexpected flags = %d", tun_header->flags);
+ }
+
+ if(tun_header->proto == ETH_P_IP) {
+ ip_packet(tunnel->fd6,packet,packetsize);
+ } else if(tun_header->proto == ETH_P_IPV6) {
+ ipv6_packet(tunnel->fd4,packet,packetsize);
+ } else {
+ logmsg(ANDROID_LOG_WARN,"packet_handler: unknown packet type = %x",tun_header->proto);
+ }
+}
+
+/* function: read_packet
+ * reads a packet from the tunnel fd and passes it down the stack
+ * active_fd - tun file descriptor marked ready for reading
+ * tunnel - tun device data
+ */
+void read_packet(int active_fd, const struct tun_data *tunnel) {
+ ssize_t readlen;
+ char packet[PACKETLEN];
+
+ // in case something ignores the packet length
+ memset(packet, 0, PACKETLEN);
+
+ readlen = read(active_fd,packet,PACKETLEN);
+
+ if(readlen < 0) {
+ logmsg(ANDROID_LOG_WARN,"read_packet/read error: %s", strerror(errno));
+ return;
+ } else if(readlen == 0) {
+ logmsg(ANDROID_LOG_WARN,"read_packet/tun interface removed");
+ running = 0;
+ } else {
+ struct tun_pi tun_header;
+ ssize_t header_size = sizeof(struct tun_pi);
+
+ if(readlen < header_size) {
+ logmsg(ANDROID_LOG_WARN,"read_packet/short read: got %ld bytes", readlen);
+ return;
+ }
+
+ memcpy(&tun_header, packet, header_size);
+
+ packet_handler(tunnel, &tun_header, packet+header_size, readlen-header_size);
+ }
+}
+
+/* function: event_loop
+ * reads packets from the tun network interface and passes them down the stack
+ * tunnel - tun device data
+ */
+void event_loop(const struct tun_data *tunnel) {
+ time_t last_interface_poll;
+ struct pollfd wait_fd[2];
+
+ // start the poll timer
+ last_interface_poll = time(NULL);
+
+ wait_fd[0].fd = tunnel->fd6;
+ wait_fd[0].events = POLLIN;
+ wait_fd[0].revents = 0;
+ wait_fd[1].fd = tunnel->fd4;
+ wait_fd[1].events = POLLIN;
+ wait_fd[1].revents = 0;
+
+ while(running) {
+ if(poll(wait_fd, 2, NO_TRAFFIC_INTERFACE_POLL_FREQUENCY*1000) == -1) {
+ if(errno != EINTR) {
+ logmsg(ANDROID_LOG_WARN,"event_loop/poll returned an error: %s",strerror(errno));
+ }
+ } else {
+ int i;
+ for(i = 0; i < 2; i++) {
+ if((wait_fd[i].revents & POLLIN) != 0) {
+ read_packet(wait_fd[i].fd,tunnel);
+ }
+ }
+ }
+
+ time_t now = time(NULL);
+ if(last_interface_poll < (now - INTERFACE_POLL_FREQUENCY)) {
+ interface_poll(tunnel);
+ last_interface_poll = now;
+ }
+ }
+}
+
+/* function: print_help
+ * in case the user is running this on the command line
+ */
+void print_help() {
+ printf("android-clat arguments:\n");
+ printf("-i [uplink interface]\n");
+ printf("-p [plat prefix]\n");
+}
+
+/* function: main
+ * allocate and setup the tun device, then run the event loop
+ */
+int main(int argc, char **argv) {
+ struct tun_data tunnel;
+ int opt;
+ char *uplink_interface = NULL, *plat_prefix = NULL;
+
+ strcpy(tunnel.device6, DEVICENAME6);
+ strcpy(tunnel.device4, DEVICENAME4);
+
+ while((opt = getopt(argc, argv, "i:p:h")) != -1) {
+ switch(opt) {
+ case 'i':
+ uplink_interface = optarg;
+ break;
+ case 'p':
+ plat_prefix = optarg;
+ break;
+ case 'h':
+ default:
+ print_help();
+ exit(1);
+ break;
+ }
+ }
+
+ if(uplink_interface == NULL) {
+ logmsg(ANDROID_LOG_FATAL,"clatd called without an interface");
+ printf("I need an interface\n");
+ exit(1);
+ }
+
+ // open the tunnel device before dropping privs
+ tunnel.fd6 = tun_open();
+ if(tunnel.fd6 < 0) {
+ logmsg(ANDROID_LOG_FATAL,"tun_open failed: %s",strerror(errno));
+ exit(1);
+ }
+
+ tunnel.fd4 = tun_open();
+ if(tunnel.fd4 < 0) {
+ logmsg(ANDROID_LOG_FATAL,"tun_open4 failed: %s",strerror(errno));
+ exit(1);
+ }
+
+ // open the forwarding configuration before dropping privs
+ forwarding_fd = open("/proc/sys/net/ipv6/conf/all/forwarding", O_RDWR);
+ if(forwarding_fd < 0) {
+ logmsg(ANDROID_LOG_FATAL,"open /proc/sys/net/ipv6/conf/all/forwarding failed: %s",strerror(errno));
+ exit(1);
+ }
+
+ // forwarding slows down IPv6 config while transitioning to wifi
+ // forwarding also removes default routes learned from a RA
+ set_accept_ra();
+
+ // run under a regular user
+ drop_root();
+
+ if(signal(SIGTERM, got_sigterm) == SIG_ERR) {
+ logmsg(ANDROID_LOG_FATAL, "sigterm handler failed: %s", strerror(errno));
+ exit(1);
+ }
+
+ configure_interface(uplink_interface, plat_prefix, &tunnel);
+
+ // turning on forwarding in linux has a side effect of calling rt6_purge_dflt_routers
+ // workaround: turn the RA-learned default route into a static route
+ set_default_ipv6_route(uplink_interface);
+ set_forwarding(forwarding_fd,"1\n");
+
+ event_loop(&tunnel); // event_loop returns if someone sets the tun interface down manually
+
+ set_forwarding(forwarding_fd,"0\n");
+
+ return 0;
+}
diff --git a/clatd.conf b/clatd.conf
new file mode 100644
index 0000000..e6336d7
--- /dev/null
+++ b/clatd.conf
@@ -0,0 +1,15 @@
+# host ID to use as the source of CLAT traffic
+# this is a /128 taken out of the /64 routed to the phone
+ipv6_host_id ::200:5E10:0:0
+
+# ipv4 subnet for the local traffic to use. This is a /32 host address
+ipv4_local_subnet 192.168.255.1
+
+# get the plat_subnet from dns lookups (requires DNS64)
+plat_from_dns64 yes
+# hostname to use to lookup plat subnet. must contain only A records
+plat_from_dns64_hostname ipv4.google.com
+
+# plat subnet to send ipv4 traffic to. This is a /96 subnet.
+# This setting only makes sense with: plat_from_dns64 no
+#plat_subnet 2001:db8:1:2:3:4::
diff --git a/clatd.h b/clatd.h
new file mode 100644
index 0000000..00a4094
--- /dev/null
+++ b/clatd.h
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2011 Daniel Drown
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * clatd.h - main system definitions
+ */
+#ifndef __CLATD_H__
+#define __CLATD_H__
+
+#include <linux/if_tun.h>
+
+#define MAXMTU 1500
+#define PACKETLEN (MAXMTU+sizeof(struct tun_pi))
+
+// how frequently (in seconds) to poll for an address change while traffic is passing
+#define INTERFACE_POLL_FREQUENCY 30
+
+// how frequently (in seconds) to poll for an address change while there is no traffic
+#define NO_TRAFFIC_INTERFACE_POLL_FREQUENCY 90
+
+#endif /* __CLATD_H__ */
diff --git a/config.c b/config.c
new file mode 100644
index 0000000..e7ec80e
--- /dev/null
+++ b/config.c
@@ -0,0 +1,302 @@
+/*
+ * Copyright 2011 Daniel Drown
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * config.c - configuration settings
+ */
+
+#include <string.h>
+#include <stdlib.h>
+#include <arpa/inet.h>
+#include <stdio.h>
+#include <limits.h>
+#include <errno.h>
+#include <unistd.h>
+
+#include <cutils/config_utils.h>
+
+#include "config.h"
+#include "dns64.h"
+#include "logging.h"
+#include "getaddr.h"
+#include "clatd.h"
+#include "setroute.h"
+
+struct clat_config Global_Clatd_Config;
+
+/* function: config_item_str
+ * locates the config item and returns the pointer to a string, or NULL on failure. Caller frees pointer
+ * root - parsed configuration
+ * item_name - name of config item to locate
+ * defaultvar - value to use if config item isn't present
+ */
+char *config_item_str(cnode *root, const char *item_name, const char *defaultvar) {
+ const char *tmp;
+
+ if(!(tmp = config_str(root, item_name, defaultvar))) {
+ logmsg(ANDROID_LOG_FATAL,"%s config item needed",item_name);
+ return NULL;
+ }
+ return strdup(tmp);
+}
+
+/* function: config_item_int16_t
+ * locates the config item, parses the integer, and returns the pointer ret_val_ptr, or NULL on failure
+ * root - parsed configuration
+ * item_name - name of config item to locate
+ * defaultvar - value to use if config item isn't present
+ * ret_val_ptr - pointer for return value storage
+ */
+int16_t *config_item_int16_t(cnode *root, const char *item_name, const char *defaultvar, int16_t *ret_val_ptr) {
+ const char *tmp;
+ char *endptr;
+ long int conf_int;
+
+ if(!(tmp = config_str(root, item_name, defaultvar))) {
+ logmsg(ANDROID_LOG_FATAL,"%s config item needed",item_name);
+ return NULL;
+ }
+
+ errno = 0;
+ conf_int = strtol(tmp,&endptr,10);
+ if(errno > 0) {
+ logmsg(ANDROID_LOG_FATAL,"%s config item is not numeric: %s (error=%s)",item_name,tmp,strerror(errno));
+ return NULL;
+ }
+ if(endptr == tmp || *tmp == '\0') {
+ logmsg(ANDROID_LOG_FATAL,"%s config item is not numeric: %s",item_name,tmp);
+ return NULL;
+ }
+ if(*endptr != '\0') {
+ logmsg(ANDROID_LOG_FATAL,"%s config item contains non-numeric characters: %s",item_name,endptr);
+ return NULL;
+ }
+ if(conf_int > INT16_MAX || conf_int < INT16_MIN) {
+ logmsg(ANDROID_LOG_FATAL,"%s config item is too big/small: %d",item_name,conf_int);
+ return NULL;
+ }
+ *ret_val_ptr = conf_int;
+ return ret_val_ptr;
+}
+
+/* function: config_item_ip
+ * locates the config item, parses the ipv4 address, and returns the pointer ret_val_ptr, or NULL on failure
+ * root - parsed configuration
+ * item_name - name of config item to locate
+ * defaultvar - value to use if config item isn't present
+ * ret_val_ptr - pointer for return value storage
+ */
+struct in_addr *config_item_ip(cnode *root, const char *item_name, const char *defaultvar, struct in_addr *ret_val_ptr) {
+ const char *tmp;
+ int status;
+
+ if(!(tmp = config_str(root, item_name, defaultvar))) {
+ logmsg(ANDROID_LOG_FATAL,"%s config item needed",item_name);
+ return NULL;
+ }
+
+ status = inet_pton(AF_INET, tmp, ret_val_ptr);
+ if(status <= 0) {
+ logmsg(ANDROID_LOG_FATAL,"invalid IPv4 address specified for %s: %s", item_name, tmp);
+ return NULL;
+ }
+
+ return ret_val_ptr;
+}
+
+/* function: config_item_ip6
+ * locates the config item, parses the ipv6 address, and returns the pointer ret_val_ptr, or NULL on failure
+ * root - parsed configuration
+ * item_name - name of config item to locate
+ * defaultvar - value to use if config item isn't present
+ * ret_val_ptr - pointer for return value storage
+ */
+struct in6_addr *config_item_ip6(cnode *root, const char *item_name, const char *defaultvar, struct in6_addr *ret_val_ptr) {
+ const char *tmp;
+ int status;
+
+ if(!(tmp = config_str(root, item_name, defaultvar))) {
+ logmsg(ANDROID_LOG_FATAL,"%s config item needed",item_name);
+ return NULL;
+ }
+
+ status = inet_pton(AF_INET6, tmp, ret_val_ptr);
+ if(status <= 0) {
+ logmsg(ANDROID_LOG_FATAL,"invalid IPv6 address specified for %s: %s", item_name, tmp);
+ return NULL;
+ }
+
+ return ret_val_ptr;
+}
+
+/* function: free_config
+ * frees the memory used by the global config variable
+ */
+void free_config() {
+ if(Global_Clatd_Config.plat_from_dns64_hostname) {
+ free(Global_Clatd_Config.plat_from_dns64_hostname);
+ Global_Clatd_Config.plat_from_dns64_hostname = NULL;
+ }
+}
+
+/* function: dns64_detection
+ * does dns lookups to set the plat subnet or exits on failure, waits forever for a dns response with a query backoff timer
+ */
+void dns64_detection() {
+ int i, backoff_sleep, status;
+ struct in6_addr tmp_ptr;
+
+ backoff_sleep = 1;
+
+ while(1) {
+ status = plat_prefix(Global_Clatd_Config.plat_from_dns64_hostname,&tmp_ptr);
+ if(status > 0) {
+ memcpy(&Global_Clatd_Config.plat_subnet, &tmp_ptr, sizeof(struct in6_addr));
+ return;
+ }
+ if(status < 0) {
+ logmsg(ANDROID_LOG_FATAL, "dns64_detection/no dns64, giving up\n");
+ exit(1);
+ }
+ logmsg(ANDROID_LOG_WARN, "dns64_detection failed, sleeping for %d seconds", backoff_sleep);
+ sleep(backoff_sleep);
+ if(backoff_sleep >= 120) {
+ backoff_sleep = 120;
+ } else {
+ backoff_sleep *= 2;
+ }
+ }
+}
+
+
+/* function: config_generate_local_ipv6_subnet
+ * generates the local ipv6 subnet when given the interface ip
+ * requires config.ipv6_host_id
+ * interface_ip - in: interface ip, out: local ipv6 host address
+ */
+void config_generate_local_ipv6_subnet(struct in6_addr *interface_ip) {
+ int i;
+
+ for(i = 2; i < 4; i++) {
+ interface_ip->s6_addr32[i] = Global_Clatd_Config.ipv6_host_id.s6_addr32[i];
+ }
+}
+
+/* function: subnet_from_interface
+ * finds the ipv6 subnet configured on the specified interface
+ * root - parsed configuration
+ * interface - network interface name
+ */
+int subnet_from_interface(cnode *root, const char *interface) {
+ union anyip *interface_ip;
+
+ if(!config_item_ip6(root, "ipv6_host_id", "::200:5E10:0:0", &Global_Clatd_Config.ipv6_host_id))
+ return 0;
+
+ interface_ip = getinterface_ip(interface, AF_INET6);
+ if(!interface_ip) {
+ logmsg(ANDROID_LOG_FATAL,"unable to find an ipv6 ip on interface %s",interface);
+ return 0;
+ }
+
+ memcpy(&Global_Clatd_Config.ipv6_local_subnet, &interface_ip->ip6, sizeof(struct in6_addr));
+ free(interface_ip);
+
+ config_generate_local_ipv6_subnet(&Global_Clatd_Config.ipv6_local_subnet);
+
+ return 1;
+}
+
+/* function: read_config
+ * reads the config file and parses it into the global variable Global_Clatd_Config. returns 0 on failure, 1 on success
+ * file - filename to parse
+ * uplink_interface - interface to use to reach the internet and supplier of address space
+ * plat_prefix - (optional) plat prefix to use, otherwise follow config file
+ */
+int read_config(const char *file, const char *uplink_interface, const char *plat_prefix) {
+ cnode *root = config_node("", "");
+ void *tmp_ptr = NULL;
+
+ if(!root) {
+ logmsg(ANDROID_LOG_FATAL,"out of memory");
+ return 0;
+ }
+
+ memset(&Global_Clatd_Config, '\0', sizeof(Global_Clatd_Config));
+
+ config_load_file(root, file);
+ if(root->first_child == NULL) {
+ logmsg(ANDROID_LOG_FATAL,"Could not read config file %s", file);
+ goto failed;
+ }
+
+ strncpy(Global_Clatd_Config.default_pdp_interface, uplink_interface, sizeof(Global_Clatd_Config.default_pdp_interface));
+
+ if(!subnet_from_interface(root,Global_Clatd_Config.default_pdp_interface))
+ goto failed;
+
+ if(!config_item_int16_t(root, "mtu", "-1", &Global_Clatd_Config.mtu))
+ goto failed;
+
+ if(!config_item_int16_t(root, "ipv4mtu", "-1", &Global_Clatd_Config.ipv4mtu))
+ goto failed;
+
+ if(!config_item_ip(root, "ipv4_local_subnet", DEFAULT_IPV4_LOCAL_SUBNET, &Global_Clatd_Config.ipv4_local_subnet))
+ goto failed;
+
+ if(plat_prefix) { // plat subnet is coming from the command line
+ if(inet_pton(AF_INET6, plat_prefix, &Global_Clatd_Config.plat_subnet) <= 0) {
+ logmsg(ANDROID_LOG_FATAL,"invalid IPv6 address specified for plat prefix: %s", plat_prefix);
+ goto failed;
+ }
+ } else {
+ tmp_ptr = (void *)config_item_str(root, "plat_from_dns64", "yes");
+ if(!tmp_ptr || strcmp(tmp_ptr, "no") == 0) {
+ free(tmp_ptr);
+
+ if(!config_item_ip6(root, "plat_subnet", NULL, &Global_Clatd_Config.plat_subnet)) {
+ logmsg(ANDROID_LOG_FATAL, "plat_from_dns64 disabled, but no plat_subnet specified");
+ goto failed;
+ }
+ } else {
+ free(tmp_ptr);
+
+ if(!(Global_Clatd_Config.plat_from_dns64_hostname = config_item_str(root, "plat_from_dns64_hostname", DEFAULT_DNS64_DETECTION_HOSTNAME)))
+ goto failed;
+ dns64_detection();
+ }
+ }
+
+
+ return 1;
+
+failed:
+ free(root);
+ free_config();
+ return 0;
+}
+
+/* function; dump_config
+ * prints the current config
+ */
+void dump_config() {
+ char charbuffer[INET6_ADDRSTRLEN];
+
+ logmsg(ANDROID_LOG_DEBUG,"mtu = %d",Global_Clatd_Config.mtu);
+ logmsg(ANDROID_LOG_DEBUG,"ipv4mtu = %d",Global_Clatd_Config.ipv4mtu);
+ logmsg(ANDROID_LOG_DEBUG,"ipv6_local_subnet = %s",inet_ntop(AF_INET6, &Global_Clatd_Config.ipv6_local_subnet, charbuffer, sizeof(charbuffer)));
+ logmsg(ANDROID_LOG_DEBUG,"ipv4_local_subnet = %s",inet_ntop(AF_INET, &Global_Clatd_Config.ipv4_local_subnet, charbuffer, sizeof(charbuffer)));
+ logmsg(ANDROID_LOG_DEBUG,"plat_subnet = %s",inet_ntop(AF_INET6, &Global_Clatd_Config.plat_subnet, charbuffer, sizeof(charbuffer)));
+ logmsg(ANDROID_LOG_DEBUG,"default_pdp_interface = %s",Global_Clatd_Config.default_pdp_interface);
+}
diff --git a/config.h b/config.h
new file mode 100644
index 0000000..a83cbec
--- /dev/null
+++ b/config.h
@@ -0,0 +1,42 @@
+/*
+ * Copyright 2011 Daniel Drown
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * config.h - configuration settings
+ */
+#ifndef __CONFIG_H__
+#define __CONFIG_H__
+
+#include <netinet/in.h>
+#include <sys/system_properties.h>
+
+#define DEFAULT_IPV4_LOCAL_SUBNET "192.168.255.1"
+#define DEFAULT_DNS64_DETECTION_HOSTNAME "ipv4.google.com"
+
+struct clat_config {
+ int16_t mtu, ipv4mtu;
+ struct in6_addr ipv6_local_subnet;
+ struct in6_addr ipv6_host_id;
+ struct in_addr ipv4_local_subnet;
+ struct in6_addr plat_subnet;
+ char default_pdp_interface[PROP_VALUE_MAX];
+ char *plat_from_dns64_hostname;
+};
+
+extern struct clat_config Global_Clatd_Config;
+
+int read_config(const char *file, const char *uplink_interface, const char *plat_prefix);
+void config_generate_local_ipv6_subnet(struct in6_addr *interface_ip);
+
+#endif /* __CONFIG_H__ */
diff --git a/debug.h b/debug.h
new file mode 100644
index 0000000..ba4971b
--- /dev/null
+++ b/debug.h
@@ -0,0 +1,24 @@
+/*
+ * Copyright 2011 Daniel Drown
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * debug.h - debug settings
+ */
+#ifndef __DEBUG_H__
+#define __DEBUG_H__
+
+// set to 1 to enable debug logging
+#define CLAT_DEBUG 0
+
+#endif /* __DEBUG_H__ */
diff --git a/dns64.c b/dns64.c
new file mode 100644
index 0000000..ab662c7
--- /dev/null
+++ b/dns64.c
@@ -0,0 +1,91 @@
+/*
+ * Copyright 2011 Daniel Drown
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * dns64.c - find the nat64 prefix with a dns64 lookup
+ */
+
+#include <sys/socket.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <netdb.h>
+#include <strings.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+#include "dns64.h"
+#include "logging.h"
+
+/* function: plat_prefix
+ * looks up an ipv4-only hostname and looks for a nat64 /96 prefix, returns 1 on success, 0 on temporary failure, -1 on permanent failure
+ * ipv4_name - name to lookup
+ * prefix - the plat /96 prefix
+ */
+int plat_prefix(const char *ipv4_name, struct in6_addr *prefix) {
+ struct addrinfo hints, *result, *p;
+ int status, plat_addr_set, ipv4_records, ipv6_records;
+ struct in6_addr plat_addr, this_plat_addr;
+ struct sockaddr_in6 *this_addr;
+
+ result = NULL;
+ plat_addr_set = 0;
+ ipv4_records = ipv6_records = 0;
+
+ bzero(&hints, sizeof(hints));
+ hints.ai_family = AF_UNSPEC;
+ status = getaddrinfo(ipv4_name, NULL, &hints, &result);
+ if(status != 0) {
+ logmsg(ANDROID_LOG_ERROR,"plat_prefix/dns(%s) status = %d/%s\n", ipv4_name, status, gai_strerror(status));
+ return 0;
+ }
+
+ for(p = result; p; p = p->ai_next) {
+ if(p->ai_family == AF_INET) {
+ ipv4_records++;
+ continue;
+ }
+ if(p->ai_family != AF_INET6) {
+ logmsg(ANDROID_LOG_WARN,"plat_prefix/unexpected address family: %d\n", p->ai_family);
+ continue;
+ }
+ ipv6_records++;
+ this_addr = (struct sockaddr_in6 *)p->ai_addr;
+ this_plat_addr = this_addr->sin6_addr;
+ this_plat_addr.s6_addr32[3] = 0;
+
+ if(!plat_addr_set) {
+ plat_addr = this_plat_addr;
+ plat_addr_set = 1;
+ continue;
+ }
+
+ if(!IN6_ARE_ADDR_EQUAL(&plat_addr, &this_plat_addr)) {
+ char plat_addr_str[INET6_ADDRSTRLEN], this_plat_addr_str[INET6_ADDRSTRLEN];
+ logmsg(ANDROID_LOG_ERROR,"plat_prefix/two different plat addrs = %s,%s",
+ inet_ntop(AF_INET6, &plat_addr, plat_addr_str, sizeof(plat_addr_str)),
+ inet_ntop(AF_INET6, &this_plat_addr, this_plat_addr_str, sizeof(this_plat_addr_str))
+ );
+ }
+ }
+ if(result != NULL) {
+ freeaddrinfo(result);
+ }
+ if(ipv4_records > 0 && ipv6_records == 0) {
+ logmsg(ANDROID_LOG_WARN,"plat_prefix/no dns64 detected\n");
+ return -1;
+ }
+ *prefix = plat_addr;
+ return 1;
+}
diff --git a/dns64.h b/dns64.h
new file mode 100644
index 0000000..f295e50
--- /dev/null
+++ b/dns64.h
@@ -0,0 +1,23 @@
+/*
+ * Copyright 2011 Daniel Drown
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * dns64.h - find the nat64 prefix with a dns64 lookup
+ */
+#ifndef __DNS64_H__
+#define __DNS64_H__
+
+int plat_prefix(const char *ipv4_name, struct in6_addr *prefix);
+
+#endif
diff --git a/dump.c b/dump.c
new file mode 100644
index 0000000..3e4a6cc
--- /dev/null
+++ b/dump.c
@@ -0,0 +1,225 @@
+/*
+ * Copyright 2011 Daniel Drown
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * dump.c - print various headers for debugging
+ */
+#include <stdio.h>
+#include <stdint.h>
+
+#include <arpa/inet.h>
+#include <netinet/in.h>
+#include <netinet/ip.h>
+#include <netinet/ip_icmp.h>
+#include <netinet/udp.h>
+#include <netinet/tcp.h>
+#include <netinet/ip6.h>
+#include <netinet/icmp6.h>
+#include <linux/icmp.h>
+
+#include "checksum.h"
+#include "clatd.h"
+#include "logging.h"
+
+/* print ip header */
+void dump_ip(struct iphdr *header) {
+ u_int16_t frag_flags;
+ char addrstr[INET6_ADDRSTRLEN];
+
+ frag_flags = ntohs(header->frag_off);
+
+ printf("IP packet\n");
+ printf("header_len = %x\n",header->ihl);
+ printf("version = %x\n",header->version);
+ printf("tos = %x\n",header->tos);
+ printf("tot_len = %x\n",ntohs(header->tot_len));
+ printf("id = %x\n",ntohs(header->id));
+ printf("frag: ");
+ if(frag_flags & IP_RF) {
+ printf("(RF) ");
+ }
+ if(frag_flags & IP_DF) {
+ printf("DF ");
+ }
+ if(frag_flags & IP_MF) {
+ printf("MF ");
+ }
+ printf("offset = %x\n",frag_flags & IP_OFFMASK);
+ printf("ttl = %x\n",header->ttl);
+ printf("protocol = %x\n",header->protocol);
+ printf("checksum = %x\n",ntohs(header->check));
+ inet_ntop(AF_INET, &header->saddr, addrstr, sizeof(addrstr));
+ printf("saddr = %s\n",addrstr);
+ inet_ntop(AF_INET, &header->daddr, addrstr, sizeof(addrstr));
+ printf("daddr = %s\n",addrstr);
+}
+
+/* print ip6 header */
+void dump_ip6(struct ip6_hdr *header) {
+ char addrstr[INET6_ADDRSTRLEN];
+
+ printf("ipv6\n");
+ printf("version = %x\n",header->ip6_vfc >> 4);
+ printf("traffic class = %x\n",header->ip6_flow >> 20);
+ printf("flow label = %x\n",ntohl(header->ip6_flow & 0x000fffff));
+ printf("payload len = %x\n",ntohs(header->ip6_plen));
+ printf("next header = %x\n",header->ip6_nxt);
+ printf("hop limit = %x\n",header->ip6_hlim);
+
+ inet_ntop(AF_INET6, &header->ip6_src, addrstr, sizeof(addrstr));
+ printf("source = %s\n",addrstr);
+
+ inet_ntop(AF_INET6, &header->ip6_dst, addrstr, sizeof(addrstr));
+ printf("dest = %s\n",addrstr);
+}
+
+/* print icmp header */
+void dump_icmp(struct icmphdr *icmp) {
+ printf("ICMP\n");
+
+ printf("icmp.type = %x ",icmp->type);
+ if(icmp->type == ICMP_ECHOREPLY) {
+ printf("echo reply");
+ } else if(icmp->type == ICMP_ECHO) {
+ printf("echo request");
+ } else {
+ printf("other");
+ }
+ printf("\n");
+ printf("icmp.code = %x\n",icmp->code);
+ printf("icmp.checksum = %x\n",ntohs(icmp->checksum));
+ if(icmp->type == ICMP_ECHOREPLY || icmp->type == ICMP_ECHO) {
+ printf("icmp.un.echo.id = %x\n",ntohs(icmp->un.echo.id));
+ printf("icmp.un.echo.sequence = %x\n",ntohs(icmp->un.echo.sequence));
+ }
+}
+
+/* print icmp6 header */
+void dump_icmp6(struct icmp6_hdr *icmp6) {
+ printf("ICMP6\n");
+ printf("type = %x",icmp6->icmp6_type);
+ if(icmp6->icmp6_type == ICMP6_ECHO_REQUEST) {
+ printf("(echo request)");
+ } else if(icmp6->icmp6_type == ICMP6_ECHO_REPLY) {
+ printf("(echo reply)");
+ }
+ printf("\n");
+ printf("code = %x\n",icmp6->icmp6_code);
+
+ printf("checksum = %x\n",icmp6->icmp6_cksum);
+
+ if((icmp6->icmp6_type == ICMP6_ECHO_REQUEST) || (icmp6->icmp6_type == ICMP6_ECHO_REPLY)) {
+ printf("icmp6_id = %x\n",icmp6->icmp6_id);
+ printf("icmp6_seq = %x\n",icmp6->icmp6_seq);
+ }
+}
+
+/* print udp header */
+void dump_udp_generic(const struct udphdr *udp, uint32_t temp_checksum, const char *payload, size_t payload_size) {
+ uint16_t my_checksum;
+
+ temp_checksum = ip_checksum_add(temp_checksum, udp, sizeof(struct udphdr));
+ temp_checksum = ip_checksum_add(temp_checksum, payload, payload_size);
+ my_checksum = ip_checksum_finish(temp_checksum);
+
+ printf("UDP\n");
+ printf("source = %x\n",ntohs(udp->source));
+ printf("dest = %x\n",ntohs(udp->dest));
+ printf("len = %x\n",ntohs(udp->len));
+ printf("check = %x (mine %x)\n",udp->check,my_checksum);
+}
+
+/* print ipv4/udp header */
+void dump_udp(const struct udphdr *udp, const struct iphdr *ip, const char *payload, size_t payload_size) {
+ uint32_t temp_checksum;
+ temp_checksum = ipv4_pseudo_header_checksum(0, ip);
+ dump_udp_generic(udp, temp_checksum, payload, payload_size);
+}
+
+/* print ipv6/udp header */
+void dump_udp6(const struct udphdr *udp, const struct ip6_hdr *ip6, const char *payload, size_t payload_size) {
+ uint32_t temp_checksum;
+ temp_checksum = ipv6_pseudo_header_checksum(0, ip6);
+ dump_udp_generic(udp, temp_checksum, payload, payload_size);
+}
+
+/* print tcp header */
+void dump_tcp_generic(const struct tcphdr *tcp, const char *options, size_t options_size, uint32_t temp_checksum, const char *payload, size_t payload_size) {
+ uint16_t my_checksum;
+
+ temp_checksum = ip_checksum_add(temp_checksum, tcp, sizeof(struct tcphdr));
+ if(options) {
+ temp_checksum = ip_checksum_add(temp_checksum, options, options_size);
+ }
+ temp_checksum = ip_checksum_add(temp_checksum, payload, payload_size);
+ my_checksum = ip_checksum_finish(temp_checksum);
+
+ printf("TCP\n");
+ printf("source = %x\n",ntohs(tcp->source));
+ printf("dest = %x\n",ntohs(tcp->dest));
+ printf("seq = %x\n",ntohl(tcp->seq));
+ printf("ack = %x\n",ntohl(tcp->ack_seq));
+ printf("d_off = %x\n",tcp->doff);
+ printf("res1 = %x\n",tcp->res1);
+#ifdef __BIONIC__
+ printf("CWR = %x\n",tcp->cwr);
+ printf("ECE = %x\n",tcp->ece);
+#else
+ printf("CWR/ECE = %x\n",tcp->res2);
+#endif
+ printf("urg = %x ack = %x psh = %x rst = %x syn = %x fin = %x\n",
+ tcp->urg, tcp->ack, tcp->psh, tcp->rst, tcp->syn, tcp->fin);
+ printf("window = %x\n",ntohs(tcp->window));
+ printf("check = %x [mine %x]\n",tcp->check,my_checksum);
+ printf("urgent = %x\n",tcp->urg_ptr);
+
+ if(options) {
+ size_t i;
+
+ printf("options: ");
+ for(i=0; i<options_size; i++) {
+ printf("%x ",*(options+i));
+ }
+ printf("\n");
+ }
+}
+
+/* print ipv4/tcp header */
+void dump_tcp(const struct tcphdr *tcp, const struct iphdr *ip, const char *payload, size_t payload_size, const char *options, size_t options_size) {
+ uint32_t temp_checksum;
+
+ temp_checksum = ipv4_pseudo_header_checksum(0, ip);
+ dump_tcp_generic(tcp, options, options_size, temp_checksum, payload, payload_size);
+}
+
+/* print ipv6/tcp header */
+void dump_tcp6(const struct tcphdr *tcp, const struct ip6_hdr *ip6, const char *payload, size_t payload_size, const char *options, size_t options_size) {
+ uint32_t temp_checksum;
+
+ temp_checksum = ipv6_pseudo_header_checksum(0, ip6);
+ dump_tcp_generic(tcp, options, options_size, temp_checksum, payload, payload_size);
+}
+
+/* generic hex dump */
+void logcat_hexdump(const char *info, const char *data, size_t len) {
+ char output[PACKETLEN*2+1];
+ size_t i;
+
+ for(i = 0; i < len && i < PACKETLEN; i++) {
+ snprintf(output + i*2, 3, "%02x", (uint8_t)data[i]);
+ }
+ output[len*2+2] = '\0';
+
+ logmsg(ANDROID_LOG_WARN,"info %s len %d data %s", info, len, output);
+}
diff --git a/dump.h b/dump.h
new file mode 100644
index 0000000..6ca44bd
--- /dev/null
+++ b/dump.h
@@ -0,0 +1,33 @@
+/*
+ * Copyright 2011 Daniel Drown
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * dump.h - debug functions
+ */
+#ifndef __DUMP_H__
+#define __DUMP_H__
+
+void dump_ip(struct iphdr *header);
+void dump_icmp(struct icmphdr *icmp);
+void dump_udp(const struct udphdr *udp, const struct iphdr *ip, const char *payload, size_t payload_size);
+void dump_tcp(const struct tcphdr *tcp, const struct iphdr *ip, const char *payload, size_t payload_size, const char *options, size_t options_size);
+
+void dump_ip6(struct ip6_hdr *header);
+void dump_icmp6(struct icmp6_hdr *icmp6);
+void dump_udp6(const struct udphdr *udp, const struct ip6_hdr *ip6, const char *payload, size_t payload_size);
+void dump_tcp6(const struct tcphdr *tcp, const struct ip6_hdr *ip6, const char *payload, size_t payload_size, const char *options, size_t options_size);
+
+void logcat_hexdump(const char *info, const char *data, size_t len);
+
+#endif /* __DUMP_H__ */
diff --git a/getaddr.c b/getaddr.c
new file mode 100644
index 0000000..fb761f0
--- /dev/null
+++ b/getaddr.c
@@ -0,0 +1,137 @@
+/*
+ * Copyright 2012 Daniel Drown
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * getaddr.c - get a locally configured address
+ */
+#include <netinet/in.h>
+#include <strings.h>
+#include <string.h>
+#include <net/if.h>
+
+#include <linux/rtnetlink.h>
+#include <netlink/handlers.h>
+#include <netlink/msg.h>
+
+#include "getaddr.h"
+#include "netlink_msg.h"
+#include "logging.h"
+
+// shared state between getinterface_ip and getaddr_cb
+struct target {
+ int family;
+ unsigned int ifindex;
+ union anyip ip;
+ int foundip;
+};
+
+/* function: getaddr_cb
+ * callback for getinterface_ip
+ * msg - netlink message
+ * data - (struct target) info for which address we're looking for
+ */
+static int getaddr_cb(struct nl_msg *msg, void *data) {
+ struct ifaddrmsg *ifa_p;
+ struct rtattr *rta_p;
+ int rta_len;
+ struct target *targ_p = (struct target *)data;
+
+ ifa_p = (struct ifaddrmsg *)nlmsg_data(nlmsg_hdr(msg));
+ rta_p = (struct rtattr *)IFA_RTA(ifa_p);
+
+ if(ifa_p->ifa_index != targ_p->ifindex)
+ return NL_OK;
+
+ if(ifa_p->ifa_scope != RT_SCOPE_UNIVERSE)
+ return NL_OK;
+
+ rta_len = RTM_PAYLOAD(nlmsg_hdr(msg));
+ for (; RTA_OK(rta_p, rta_len); rta_p = RTA_NEXT(rta_p, rta_len)) {
+ switch(rta_p->rta_type) {
+ case IFA_ADDRESS:
+ if((targ_p->family == AF_INET6) && !(ifa_p->ifa_flags & IFA_F_SECONDARY)) {
+ memcpy(&targ_p->ip.ip6, RTA_DATA(rta_p), rta_p->rta_len - sizeof(struct rtattr));
+ targ_p->foundip = 1;
+ return NL_OK;
+ }
+ break;
+ case IFA_LOCAL:
+ if(targ_p->family == AF_INET) {
+ memcpy(&targ_p->ip.ip4, RTA_DATA(rta_p), rta_p->rta_len - sizeof(struct rtattr));
+ targ_p->foundip = 1;
+ return NL_OK;
+ }
+ break;
+ }
+ }
+
+ return NL_OK;
+}
+
+/* function: error_handler
+ * error callback for getinterface_ip
+ * nla - source of the error message
+ * err - netlink message
+ * arg - (struct target) info for which address we're looking for
+ */
+static int error_handler(struct sockaddr_nl *nla, struct nlmsgerr *err, void *arg) {
+ return NL_OK;
+}
+
+/* function: getinterface_ip
+ * finds the first global non-privacy IP of the given family for the given interface, or returns NULL. caller frees pointer
+ * interface - interface to look for
+ * family - family
+ */
+union anyip *getinterface_ip(const char *interface, int family) {
+ struct ifaddrmsg ifa;
+ struct nl_cb *callbacks = NULL;
+ struct target targ;
+ union anyip *retval = NULL;
+
+ targ.family = family;
+ targ.foundip = 0;
+ targ.ifindex = if_nametoindex(interface);
+ if(targ.ifindex == 0) {
+ return NULL; // interface not found
+ }
+
+ memset(&ifa, 0, sizeof(ifa));
+ ifa.ifa_family = targ.family;
+
+ callbacks = nl_cb_alloc(NL_CB_DEFAULT);
+ if(!callbacks) {
+ goto cleanup;
+ }
+ nl_cb_set(callbacks, NL_CB_VALID, NL_CB_CUSTOM, getaddr_cb, &targ);
+ nl_cb_err(callbacks, NL_CB_CUSTOM, error_handler, &targ);
+
+ // sends message and waits for a response
+ send_ifaddrmsg(RTM_GETADDR, NLM_F_REQUEST | NLM_F_ROOT, &ifa, callbacks);
+
+ if(targ.foundip) {
+ retval = malloc(sizeof(union anyip));
+ if(!retval) {
+ logmsg(ANDROID_LOG_FATAL,"getinterface_ip/out of memory");
+ goto cleanup;
+ }
+ memcpy(retval, &targ.ip, sizeof(union anyip));
+ }
+
+cleanup:
+ if(callbacks)
+ nl_cb_put(callbacks);
+
+ return retval;
+}
diff --git a/getaddr.h b/getaddr.h
new file mode 100644
index 0000000..5718e62
--- /dev/null
+++ b/getaddr.h
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2011 Daniel Drown
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * getaddr.h - get a locally configured address
+ */
+#ifndef __GETADDR_H__
+#define __GETADDR_H__
+
+union anyip {
+ struct in6_addr ip6;
+ struct in_addr ip4;
+};
+
+union anyip *getinterface_ip(const char *interface, int family);
+
+#endif
diff --git a/getroute.c b/getroute.c
new file mode 100644
index 0000000..5f9475e
--- /dev/null
+++ b/getroute.c
@@ -0,0 +1,143 @@
+/*
+ * Copyright 2012 Daniel Drown
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * getroute.c - get an ip route
+ */
+#include <string.h>
+#include <errno.h>
+
+#include <sys/socket.h>
+#include <linux/netlink.h>
+#include <linux/rtnetlink.h>
+#include <arpa/inet.h>
+
+#include <netlink/handlers.h>
+#include <netlink/msg.h>
+
+#include "getroute.h"
+#include "netlink_callbacks.h"
+#include "netlink_msg.h"
+
+/* function: get_default_route_cb
+ * finds the default route with the request family and out interface and saves the gateway
+ * msg - netlink message
+ * data - (struct default_route_data) requested filters and response storage
+ */
+static int get_default_route_cb(struct nl_msg *msg, void *data) {
+ struct rtmsg *rt_p;
+ struct rtattr *rta_p;
+ int rta_len;
+ struct default_route_data *default_route = data;
+ union anyip *this_gateway = NULL;
+ ssize_t this_gateway_size;
+ int this_interface_id = -1;
+
+ if(default_route->reply_found_route) { // we already found our route
+ return NL_OK;
+ }
+
+ rt_p = (struct rtmsg *)nlmsg_data(nlmsg_hdr(msg));
+ if(rt_p->rtm_dst_len != 0) { // not a default route
+ return NL_OK;
+ }
+ if((rt_p->rtm_family != default_route->request_family) || (rt_p->rtm_table != RT_TABLE_MAIN)) { // not a route we care about
+ return NL_OK;
+ }
+
+ rta_p = (struct rtattr *)RTM_RTA(rt_p);
+ rta_len = RTM_PAYLOAD(nlmsg_hdr(msg));
+ for(; RTA_OK(rta_p, rta_len); rta_p = RTA_NEXT(rta_p, rta_len)) {
+ switch(rta_p->rta_type) {
+ case RTA_GATEWAY:
+ this_gateway = RTA_DATA(rta_p);
+ this_gateway_size = RTA_PAYLOAD(rta_p);
+ break;
+ case RTA_OIF:
+ this_interface_id = *(int *)RTA_DATA(rta_p);
+ break;
+ default:
+ break;
+ }
+ }
+
+ if(this_interface_id == default_route->request_interface_id) {
+ default_route->reply_found_route = 1;
+ if(this_gateway != NULL) {
+ memcpy(&default_route->reply_gateway, this_gateway, this_gateway_size);
+ default_route->reply_has_gateway = 1;
+ } else {
+ default_route->reply_has_gateway = 0;
+ }
+ }
+ return NL_OK;
+}
+
+/* function: error_handler
+ * error callback for get_default_route
+ * nla - where the message came from
+ * err - netlink message
+ * arg - (int *) storage for the error number
+ */
+static int error_handler(struct sockaddr_nl *nla, struct nlmsgerr *err, void *arg) {
+ int *retval = arg;
+ if(err->error < 0) { // error_handler called even on no error (NLMSG_ERROR reply type used)
+ *retval = err->error;
+ }
+ return NL_OK;
+}
+
+/* function: get_default_route
+ * finds the first default route with the given family and interface, returns the gateway (if it exists) in the struct
+ * default_route - requested family and interface, and response storage
+ */
+int get_default_route(struct default_route_data *default_route) {
+ struct rtmsg msg;
+ struct nl_cb *callbacks = NULL;
+ struct nl_msg *nlmsg = NULL;
+ int retval = 0;
+
+ default_route->reply_has_gateway = 0;
+ default_route->reply_found_route = 0;
+
+ memset(&msg,'\0',sizeof(msg));
+ msg.rtm_family = default_route->request_family;
+ msg.rtm_table = RT_TABLE_MAIN;
+ msg.rtm_protocol = RTPROT_KERNEL;
+ msg.rtm_scope = RT_SCOPE_UNIVERSE;
+
+ callbacks = nl_cb_alloc(NL_CB_DEFAULT);
+ if(!callbacks) {
+ retval = -ENOMEM;
+ goto cleanup;
+ }
+ // get_default_route_cb sets the response fields in default_route
+ nl_cb_set(callbacks, NL_CB_VALID, NL_CB_CUSTOM, get_default_route_cb, default_route);
+ nl_cb_err(callbacks, NL_CB_CUSTOM, error_handler, &retval);
+
+ nlmsg = nlmsg_alloc_rtmsg(RTM_GETROUTE, NLM_F_REQUEST | NLM_F_ROOT, &msg);
+ if(!nlmsg) {
+ retval = -ENOMEM;
+ goto cleanup;
+ }
+ send_netlink_msg(nlmsg, callbacks);
+
+cleanup:
+ if(callbacks)
+ nl_cb_put(callbacks);
+ if(nlmsg)
+ nlmsg_free(nlmsg);
+
+ return retval;
+}
diff --git a/getroute.h b/getroute.h
new file mode 100644
index 0000000..e7b8670
--- /dev/null
+++ b/getroute.h
@@ -0,0 +1,35 @@
+/*
+ * Copyright 2012 Daniel Drown
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * getroute.h - get an ip route
+ */
+#ifndef __GETROUTE_H__
+#define __GETROUTE_H__
+
+// for union anyip
+#include "getaddr.h"
+
+struct default_route_data {
+ int request_interface_id;
+ int request_family;
+
+ union anyip reply_gateway;
+ int reply_has_gateway;
+ int reply_found_route;
+};
+
+int get_default_route(struct default_route_data *default_route);
+
+#endif
diff --git a/ipv4.c b/ipv4.c
new file mode 100644
index 0000000..784f10c
--- /dev/null
+++ b/ipv4.c
@@ -0,0 +1,187 @@
+/*
+ * Copyright 2011 Daniel Drown
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ipv4.c - takes ipv4 packets, finds their headers, and then calls translation functions on them
+ */
+#include <string.h>
+
+#include <netinet/in.h>
+#include <netinet/ip.h>
+#include <netinet/ip_icmp.h>
+#include <netinet/udp.h>
+#include <netinet/tcp.h>
+#include <netinet/ip6.h>
+#include <netinet/icmp6.h>
+#include <linux/icmp.h>
+
+#include "translate.h"
+#include "checksum.h"
+#include "ipv4.h"
+#include "logging.h"
+#include "debug.h"
+
+/* function: icmp_packet
+ * takes an icmp packet and sets it up for translation
+ * fd - tun interface fd
+ * packet - ip payload
+ * len - size of ip payload
+ * ip - ip header
+ */
+void icmp_packet(int fd, const char *packet, size_t len, struct iphdr *ip) {
+ struct icmphdr icmp;
+ const char *payload;
+ size_t payload_size;
+
+ if(len < sizeof(icmp)) {
+ logmsg_dbg(ANDROID_LOG_ERROR,"icmp_packet/(too small)");
+ return;
+ }
+
+ memcpy(&icmp, packet, sizeof(icmp));
+ payload = packet + sizeof(icmp);
+ payload_size = len - sizeof(icmp);
+
+ icmp_to_icmp6(fd,ip,&icmp,payload,payload_size);
+}
+
+/* function: tcp_packet
+ * takes a tcp packet and sets it up for translation
+ * fd - tun interface fd
+ * packet - ip payload
+ * len - size of ip payload
+ * ip - ip header
+ */
+void tcp_packet(int fd, const char *packet, size_t len, struct iphdr *ip) {
+ struct tcphdr tcp;
+ const char *payload;
+ const char *options;
+ size_t payload_size, options_size;
+
+ if(len < sizeof(tcp)) {
+ logmsg_dbg(ANDROID_LOG_ERROR,"tcp_packet/(too small)");
+ return;
+ }
+
+ memcpy(&tcp, packet, sizeof(tcp));
+
+ if(tcp.doff < 5) {
+ logmsg_dbg(ANDROID_LOG_ERROR,"tcp_packet/tcp header length set to less than 5: %x",tcp.doff);
+ return;
+ }
+
+ if((size_t)tcp.doff*4 > len) {
+ logmsg_dbg(ANDROID_LOG_ERROR,"tcp_packet/tcp header length set too large: %x",tcp.doff);
+ return;
+ }
+
+ if(tcp.doff > 5) {
+ options = packet + sizeof(tcp);
+ options_size = tcp.doff*4 - sizeof(tcp);
+ } else {
+ options = NULL;
+ options_size = 0;
+ }
+
+ payload = packet + tcp.doff*4;
+ payload_size = len - tcp.doff*4;
+
+ tcp_to_tcp6(fd,ip,&tcp,payload,payload_size,options,options_size);
+}
+
+/* function: udp_packet
+ * takes a udp packet and sets it up for translation
+ * fd - tun interface fd
+ * packet - ip payload
+ * len - size of ip payload
+ * ip - ip header
+ */
+void udp_packet(int fd, const char *packet, size_t len, const struct iphdr *ip) {
+ struct udphdr udp;
+ const char *payload;
+ size_t payload_size;
+
+ if(len < sizeof(udp)) {
+ logmsg_dbg(ANDROID_LOG_ERROR,"udp_packet/(too small)");
+ return;
+ }
+
+ memcpy(&udp, packet, sizeof(udp));
+ payload = packet + sizeof(udp);
+ payload_size = len - sizeof(udp);
+
+ udp_to_udp6(fd,ip,&udp,payload,payload_size);
+}
+
+/* function: ip_packet
+ * takes an ip packet and hands it off to the layer 4 protocol function
+ * fd - tun interface fd
+ * packet - packet data
+ * len - size of packet
+ */
+void ip_packet(int fd, const char *packet, size_t len) {
+ struct iphdr header;
+ uint16_t frag_flags;
+ const char *next_header;
+ size_t len_left;
+
+ if(len < sizeof(header)) {
+ logmsg_dbg(ANDROID_LOG_ERROR,"ip_packet/too short for an ip header");
+ return;
+ }
+
+ memcpy(&header, packet, sizeof(header));
+
+ frag_flags = ntohs(header.frag_off);
+ if(frag_flags & IP_MF) { // this could theoretically be supported, but isn't
+ logmsg_dbg(ANDROID_LOG_ERROR,"ip_packet/more fragments set, dropping");
+ return;
+ }
+
+ if(header.ihl < 5) {
+ logmsg_dbg(ANDROID_LOG_ERROR,"ip_packet/ip header length set to less than 5: %x",header.ihl);
+ return;
+ }
+
+ if((size_t)header.ihl*4 > len) { // ip header length larger than entire packet
+ logmsg_dbg(ANDROID_LOG_ERROR,"ip_packet/ip header length set too large: %x",header.ihl);
+ return;
+ }
+
+ if(header.version != 4) {
+ logmsg_dbg(ANDROID_LOG_ERROR,"ip_packet/ip header version not 4: %x",header.version);
+ return;
+ }
+
+ /* rfc6145 - If any IPv4 options are present in the IPv4 packet, they MUST be
+ * ignored and the packet translated normally; there is no attempt to
+ * translate the options.
+ */
+
+ next_header = packet + header.ihl*4;
+ len_left = len - header.ihl*4;
+
+ if(header.protocol == IPPROTO_ICMP) {
+ icmp_packet(fd,next_header,len_left,&header);
+ } else if(header.protocol == IPPROTO_TCP) {
+ tcp_packet(fd,next_header,len_left,&header);
+ } else if(header.protocol == IPPROTO_UDP) {
+ udp_packet(fd,next_header,len_left,&header);
+ } else {
+#if CLAT_DEBUG
+ logmsg_dbg(ANDROID_LOG_ERROR,"ip_packet/unknown protocol: %x",header.protocol);
+ logcat_hexdump("ipv4/protocol", packet, len);
+#endif
+ }
+}
diff --git a/ipv4.h b/ipv4.h
new file mode 100644
index 0000000..eef3f0c
--- /dev/null
+++ b/ipv4.h
@@ -0,0 +1,23 @@
+/*
+ * Copyright 2011 Daniel Drown
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ipv4.h - takes an ipv4 packet and hands it off to the proper translate function
+ */
+#ifndef __IPV4_H__
+#define __IPV4_H__
+
+void ip_packet(int fd, const char *packet, size_t len);
+
+#endif /* __IPV4_H__ */
diff --git a/ipv6.c b/ipv6.c
new file mode 100644
index 0000000..8fc36a4
--- /dev/null
+++ b/ipv6.c
@@ -0,0 +1,194 @@
+/*
+ * Copyright 2011 Daniel Drown
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ipv6.c - takes ipv6 packets, finds their headers, and then calls translation functions on them
+ */
+#include <string.h>
+
+#include <netinet/in.h>
+#include <netinet/ip.h>
+#include <netinet/ip_icmp.h>
+#include <netinet/udp.h>
+#include <netinet/tcp.h>
+#include <netinet/ip6.h>
+#include <netinet/icmp6.h>
+#include <linux/icmp.h>
+
+#include "translate.h"
+#include "checksum.h"
+#include "ipv6.h"
+#include "logging.h"
+#include "dump.h"
+#include "config.h"
+#include "debug.h"
+
+/* function: icmp6_packet
+ * takes an icmp6 packet and sets it up for translation
+ * fd - tun interface fd
+ * packet - ip payload
+ * len - size of ip payload
+ * ip6 - ip6 header
+ */
+void icmp6_packet(int fd, const char *packet, size_t len, struct ip6_hdr *ip6) {
+ struct icmp6_hdr icmp6;
+ const char *payload;
+ size_t payload_size;
+
+ if(len < sizeof(icmp6)) {
+ logmsg_dbg(ANDROID_LOG_ERROR,"icmp6_packet/(too small)");
+ return;
+ }
+
+ memcpy(&icmp6, packet, sizeof(icmp6));
+ payload = packet + sizeof(icmp6);
+ payload_size = len - sizeof(icmp6);
+
+ icmp6_to_icmp(fd, ip6, &icmp6, payload, payload_size);
+}
+
+/* function: tcp6_packet
+ * takes a tcp packet and sets it up for translation
+ * fd - tun interface fd
+ * packet - ip payload
+ * len - size of ip payload
+ * ip6 - ip6 header
+ */
+void tcp6_packet(int fd, const char *packet, size_t len, struct ip6_hdr *ip6) {
+ struct tcphdr tcp;
+ const char *payload;
+ const char *options;
+ size_t payload_size, options_size;
+
+ if(len < sizeof(tcp)) {
+ logmsg_dbg(ANDROID_LOG_ERROR,"tcp6_packet/(too small)");
+ return;
+ }
+
+ memcpy(&tcp, packet, sizeof(tcp));
+
+ if(tcp.doff < 5) {
+ logmsg_dbg(ANDROID_LOG_ERROR,"tcp6_packet/tcp header length set to less than 5: %x",tcp.doff);
+ return;
+ }
+
+ if((size_t)tcp.doff*4 > len) {
+ logmsg_dbg(ANDROID_LOG_ERROR,"tcp6_packet/tcp header length set too large: %x",tcp.doff);
+ return;
+ }
+
+ if(tcp.doff > 5) {
+ options = packet + sizeof(tcp);
+ options_size = tcp.doff*4 - sizeof(tcp);
+ } else {
+ options = NULL;
+ options_size = 0;
+ }
+
+ payload = packet + tcp.doff*4;
+ payload_size = len - tcp.doff*4;
+
+ tcp6_to_tcp(fd,ip6,&tcp,payload,payload_size,options,options_size);
+}
+
+/* function: udp6_packet
+ * takes a udp packet and sets it up for translation
+ * fd - tun interface fd
+ * packet - ip payload
+ * len - size of ip payload
+ * ip6 - ip6 header
+ */
+void udp6_packet(int fd, const char *packet, size_t len, struct ip6_hdr *ip6) {
+ struct udphdr udp;
+ const char *payload;
+ size_t payload_size;
+
+ if(len < sizeof(udp)) {
+ logmsg_dbg(ANDROID_LOG_ERROR,"udp6_packet/(too small)");
+ return;
+ }
+
+ memcpy(&udp, packet, sizeof(udp));
+ payload = packet + sizeof(udp);
+ payload_size = len - sizeof(udp);
+
+ udp6_to_udp(fd,ip6,&udp,payload,payload_size);
+}
+
+/* function: log_bad_address
+ * logs a bad address to android's log buffer if debugging is turned on
+ * fmt - printf-style format, use %s to place the address
+ * badaddr - the bad address in question
+ */
+void log_bad_address(const char *fmt, const struct in6_addr *badaddr) {
+#if CLAT_DEBUG
+ char badaddr_str[INET6_ADDRSTRLEN];
+
+ inet_ntop(AF_INET6, badaddr, badaddr_str, sizeof(badaddr_str));
+ logmsg_dbg(ANDROID_LOG_ERROR,fmt,badaddr_str);
+#endif
+}
+
+/* function: ipv6_packet
+ * takes an ipv6 packet and hands it off to the layer 4 protocol function
+ * fd - tun interface fd
+ * packet - packet data
+ * len - size of packet
+ */
+void ipv6_packet(int fd, const char *packet, size_t len) {
+ struct ip6_hdr header;
+ const char *next_header;
+ size_t len_left;
+ int i;
+
+ if(len < sizeof(header)) {
+ logmsg_dbg(ANDROID_LOG_ERROR,"ipv6_packet/too short for an ip6 header");
+ return;
+ }
+
+ memcpy(&header, packet, sizeof(header));
+
+ next_header = packet + sizeof(header);
+ len_left = len - sizeof(header);
+
+ if(IN6_IS_ADDR_MULTICAST(&header.ip6_dst)) {
+ log_bad_address("ipv6_packet/multicast %s", &header.ip6_dst);
+ return; // silently ignore
+ }
+
+ for(i = 0; i < 3; i++) {
+ if(header.ip6_src.s6_addr32[i] != Global_Clatd_Config.plat_subnet.s6_addr32[i]) {
+ log_bad_address("ipv6_packet/wrong source address: %s", &header.ip6_src);
+ return;
+ }
+ }
+ if(!IN6_ARE_ADDR_EQUAL(&header.ip6_dst, &Global_Clatd_Config.ipv6_local_subnet)) {
+ log_bad_address("ipv6_packet/wrong destination address: %s", &header.ip6_dst);
+ return;
+ }
+
+ // does not support IPv6 extension headers, this will drop any packet with them
+ if(header.ip6_nxt == IPPROTO_ICMPV6) {
+ icmp6_packet(fd,next_header,len_left,&header);
+ } else if(header.ip6_nxt == IPPROTO_TCP) {
+ tcp6_packet(fd,next_header,len_left,&header);
+ } else if(header.ip6_nxt == IPPROTO_UDP) {
+ udp6_packet(fd,next_header,len_left,&header);
+ } else {
+#if CLAT_DEBUG
+ logmsg(ANDROID_LOG_ERROR,"ipv6_packet/unknown next header type: %x",header.ip6_nxt);
+ logcat_hexdump("ipv6/nxthdr", packet, len);
+#endif
+ }
+}
diff --git a/ipv6.h b/ipv6.h
new file mode 100644
index 0000000..b898ad9
--- /dev/null
+++ b/ipv6.h
@@ -0,0 +1,23 @@
+/*
+ * Copyright 2011 Daniel Drown
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ipv6.h - takes an ipv6 packet and hands it off to the proper translate function
+ */
+#ifndef __IPV6_H__
+#define __IPV6_H__
+
+void ipv6_packet(int fd, const char *packet, size_t len);
+
+#endif /* __IPV6_H__ */
diff --git a/logging.c b/logging.c
new file mode 100644
index 0000000..f2f3d50
--- /dev/null
+++ b/logging.c
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2011 Daniel Drown
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * logging.c - print a log message
+ */
+
+#include <stdarg.h>
+#include <android/log.h>
+
+#include "logging.h"
+#include "debug.h"
+
+/* function: logmsg
+ * prints a log message to android's log buffer
+ * prio - the log message priority
+ * fmt - printf format specifier
+ * ... - printf format arguments
+ */
+void logmsg(int prio, const char *fmt, ...) {
+ va_list ap;
+
+ va_start(ap, fmt);
+ __android_log_vprint(prio, "clatd", fmt, ap);
+ va_end(ap);
+}
+
+/* function: logmsg_dbg
+ * prints a log message to android's log buffer if CLAT_DEBUG is set
+ * prio - the log message priority
+ * fmt - printf format specifier
+ * ... - printf format arguments
+ */
+void logmsg_dbg(int prio, const char *fmt, ...) {
+#if CLAT_DEBUG
+ va_list ap;
+
+ va_start(ap, fmt);
+ __android_log_vprint(prio, "clatd", fmt, ap);
+ va_end(ap);
+#endif
+}
diff --git a/logging.h b/logging.h
new file mode 100644
index 0000000..1f4b6b6
--- /dev/null
+++ b/logging.h
@@ -0,0 +1,27 @@
+/*
+ * Copyright 2011 Daniel Drown
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * logging.h - print a log message
+ */
+
+#ifndef __LOGGING_H__
+#define __LOGGING_H__
+// for the priorities
+#include <android/log.h>
+
+void logmsg(int prio, const char *fmt, ...);
+void logmsg_dbg(int prio, const char *fmt, ...);
+
+#endif
diff --git a/mtu.c b/mtu.c
new file mode 100644
index 0000000..975bf0e
--- /dev/null
+++ b/mtu.c
@@ -0,0 +1,46 @@
+/*
+ * Copyright 2011 Daniel Drown
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * mtu.c - get interface mtu
+ */
+
+#include <string.h>
+#include <stdlib.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/ioctl.h>
+#include <net/if.h>
+
+#include "mtu.h"
+
+/* function: getifmtu
+ * returns the interface mtu or -1 on failure
+ * ifname - interface name
+ */
+int getifmtu(const char *ifname) {
+ int fd;
+ struct ifreq if_mtu;
+
+ fd = socket(AF_INET, SOCK_STREAM, 0);
+ if(fd < 0) {
+ return -1;
+ }
+ strncpy(if_mtu.ifr_name, ifname, IFNAMSIZ);
+ if_mtu.ifr_name[IFNAMSIZ - 1] = '\0';
+ if(ioctl(fd, SIOCGIFMTU, &if_mtu) < 0) {
+ return -1;
+ }
+ return if_mtu.ifr_mtu;
+}
diff --git a/mtu.h b/mtu.h
new file mode 100644
index 0000000..c330c24
--- /dev/null
+++ b/mtu.h
@@ -0,0 +1,24 @@
+/*
+ * Copyright 2011 Daniel Drown
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * mtu.c - get interface mtu
+ */
+
+#ifndef __MTU_H__
+#define __MTU_H__
+
+int getifmtu(const char *ifname);
+
+#endif
diff --git a/netlink_callbacks.c b/netlink_callbacks.c
new file mode 100644
index 0000000..5e0f34e
--- /dev/null
+++ b/netlink_callbacks.c
@@ -0,0 +1,66 @@
+/*
+ * Copyright 2012 Daniel Drown <dan-android@drown.org>
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * netlink_callbacks.c - generic callbacks for netlink responses
+ */
+#include <netinet/in.h>
+#include <net/if.h>
+
+#include <linux/rtnetlink.h>
+#include <netlink/handlers.h>
+#include <netlink/msg.h>
+
+/* function: ack_handler
+ * generic netlink callback for ack messages
+ * msg - netlink message
+ * data - pointer to an int, stores the success code
+ */
+static int ack_handler(struct nl_msg *msg, void *data) {
+ int *retval = data;
+ *retval = 0;
+ return NL_OK;
+}
+
+/* function: error_handler
+ * generic netlink callback for error messages
+ * nla - error source
+ * err - netlink error message
+ * arg - pointer to an int, stores the error code
+ */
+static int error_handler(struct sockaddr_nl *nla, struct nlmsgerr *err, void *arg) {
+ int *retval = arg;
+ if(err->error < 0) {
+ *retval = err->error;
+ } else {
+ *retval = 0; // NLMSG_ERROR used as reply type on no error
+ }
+ return NL_OK;
+}
+
+/* function: alloc_ack_callbacks
+ * allocates a set of netlink callbacks. returns NULL on failure. callbacks will modify retval with <0 meaning failure
+ * retval - shared state between caller and callback functions
+ */
+struct nl_cb *alloc_ack_callbacks(int *retval) {
+ struct nl_cb *callbacks;
+
+ callbacks = nl_cb_alloc(NL_CB_DEFAULT);
+ if(!callbacks) {
+ return NULL;
+ }
+ nl_cb_set(callbacks, NL_CB_ACK, NL_CB_CUSTOM, ack_handler, retval);
+ nl_cb_err(callbacks, NL_CB_CUSTOM, error_handler, retval);
+ return callbacks;
+}
diff --git a/netlink_callbacks.h b/netlink_callbacks.h
new file mode 100644
index 0000000..298ad3e
--- /dev/null
+++ b/netlink_callbacks.h
@@ -0,0 +1,24 @@
+/*
+ * Copyright 2012 Daniel Drown <dan-android@drown.org>
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * netlink_callbacks.h - callbacks for netlink responses
+ */
+
+#ifndef __NETLINK_CALLBACKS_H__
+#define __NETLINK_CALLBACKS_H__
+
+struct nl_cb *alloc_ack_callbacks(int *retval);
+
+#endif
diff --git a/netlink_msg.c b/netlink_msg.c
new file mode 100644
index 0000000..7363028
--- /dev/null
+++ b/netlink_msg.c
@@ -0,0 +1,168 @@
+/*
+ * Copyright 2012 Daniel Drown
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * netlink_msg.c - send an ifaddrmsg/ifinfomsg/rtmsg via netlink
+ */
+
+#include <netinet/in.h>
+#include <linux/netlink.h>
+#include <linux/rtnetlink.h>
+#include <string.h>
+#include <errno.h>
+
+#include <netlink-types.h>
+#include <netlink/socket.h>
+#include <netlink/netlink.h>
+#include <netlink/msg.h>
+
+#include "netlink_msg.h"
+#include "netlink_callbacks.h"
+
+/* function: family_size
+ * returns the size of the address structure for the given family, or 0 on error
+ * family - AF_INET or AF_INET6
+ */
+size_t inet_family_size(int family) {
+ if(family == AF_INET) {
+ return sizeof(struct in_addr);
+ } else if(family == AF_INET6) {
+ return sizeof(struct in6_addr);
+ } else {
+ return 0;
+ }
+}
+
+/* function: nlmsg_alloc_generic
+ * allocates a netlink message with the given struct inside of it. returns NULL on failure
+ * type - netlink message type
+ * flags - netlink message flags
+ * payload_struct - pointer to a struct to add to netlink message
+ * payload_len - bytelength of structure
+ */
+struct nl_msg *nlmsg_alloc_generic(uint16_t type, uint16_t flags, void *payload_struct, size_t payload_len) {
+ struct nl_msg *msg;
+
+ msg = nlmsg_alloc();
+ if(!msg) {
+ return NULL;
+ }
+
+ if ((sizeof(struct nl_msg) + payload_len) > msg->nm_size) {
+ nlmsg_free(msg);
+ return NULL;
+ }
+
+ msg->nm_nlh->nlmsg_len = NLMSG_LENGTH(payload_len);
+ msg->nm_nlh->nlmsg_flags = flags;
+ msg->nm_nlh->nlmsg_type = type;
+
+ memcpy(nlmsg_data(msg->nm_nlh), payload_struct, payload_len);
+
+ return msg;
+}
+
+/* function: nlmsg_alloc_ifaddr
+ * allocates a netlink message with a struct ifaddrmsg inside of it. returns NULL on failure
+ * type - netlink message type
+ * flags - netlink message flags
+ * ifa - ifaddrmsg to copy into the new netlink message
+ */
+struct nl_msg *nlmsg_alloc_ifaddr(uint16_t type, uint16_t flags, struct ifaddrmsg *ifa) {
+ return nlmsg_alloc_generic(type, flags, ifa, sizeof(*ifa));
+}
+
+/* function: nlmsg_alloc_ifinfo
+ * allocates a netlink message with a struct ifinfomsg inside of it. returns NULL on failure
+ * type - netlink message type
+ * flags - netlink message flags
+ * ifi - ifinfomsg to copy into the new netlink message
+ */
+struct nl_msg *nlmsg_alloc_ifinfo(uint16_t type, uint16_t flags, struct ifinfomsg *ifi) {
+ return nlmsg_alloc_generic(type, flags, ifi, sizeof(*ifi));
+}
+
+/* function: nlmsg_alloc_rtmsg
+ * allocates a netlink message with a struct rtmsg inside of it. returns NULL on failure
+ * type - netlink message type
+ * flags - netlink message flags
+ * rt - rtmsg to copy into the new netlink message
+ */
+struct nl_msg *nlmsg_alloc_rtmsg(uint16_t type, uint16_t flags, struct rtmsg *rt) {
+ return nlmsg_alloc_generic(type, flags, rt, sizeof(*rt));
+}
+
+/* function: send_netlink_msg
+ * sends a netlink message, reads a response, and hands the response(s) to the callbacks
+ * msg - netlink message to send
+ * callbacks - callbacks to use on responses
+ */
+void send_netlink_msg(struct nl_msg *msg, struct nl_cb *callbacks) {
+ struct nl_sock *nl_sk;
+
+ nl_sk = nl_socket_alloc();
+ if(!nl_sk)
+ goto cleanup;
+
+ if(nl_connect(nl_sk, NETLINK_ROUTE) != 0)
+ goto cleanup;
+
+ if(nl_send_auto_complete(nl_sk, msg) < 0)
+ goto cleanup;
+
+ nl_recvmsgs(nl_sk, callbacks);
+
+cleanup:
+ if(nl_sk)
+ nl_socket_free(nl_sk);
+}
+
+/* function: send_ifaddrmsg
+ * sends a netlink/ifaddrmsg message and hands the responses to the callbacks
+ * type - netlink message type
+ * flags - netlink message flags
+ * ifa - ifaddrmsg to send
+ * callbacks - callbacks to use with the responses
+ */
+void send_ifaddrmsg(uint16_t type, uint16_t flags, struct ifaddrmsg *ifa, struct nl_cb *callbacks) {
+ struct nl_msg *msg = NULL;
+
+ msg = nlmsg_alloc_ifaddr(type, flags, ifa);
+ if(!msg)
+ return;
+
+ send_netlink_msg(msg, callbacks);
+
+ nlmsg_free(msg);
+}
+
+/* function: netlink_sendrecv
+ * send a nl_msg and return an int status - only supports OK/ERROR responses
+ * msg - msg to send
+ */
+int netlink_sendrecv(struct nl_msg *msg) {
+ struct nl_cb *callbacks = NULL;
+ int retval = -EIO;
+
+ callbacks = alloc_ack_callbacks(&retval);
+ if(!callbacks) {
+ return -ENOMEM;
+ }
+
+ send_netlink_msg(msg, callbacks);
+
+ nl_cb_put(callbacks);
+
+ return retval;
+}
diff --git a/netlink_msg.h b/netlink_msg.h
new file mode 100644
index 0000000..bc85b2d
--- /dev/null
+++ b/netlink_msg.h
@@ -0,0 +1,29 @@
+/*
+ * Copyright 2012 Daniel Drown
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * netlink_msg.h - send an ifaddrmsg/ifinfomsg via netlink
+ */
+#ifndef __NETLINK_IFMSG_H__
+#define __NETLINK_IFMSG_H__
+
+size_t inet_family_size(int family);
+struct nl_msg *nlmsg_alloc_ifaddr(uint16_t type, uint16_t flags, struct ifaddrmsg *ifa);
+struct nl_msg *nlmsg_alloc_ifinfo(uint16_t type, uint16_t flags, struct ifinfomsg *ifi);
+struct nl_msg *nlmsg_alloc_rtmsg(uint16_t type, uint16_t flags, struct rtmsg *rt);
+void send_netlink_msg(struct nl_msg *msg, struct nl_cb *callbacks);
+void send_ifaddrmsg(uint16_t type, uint16_t flags, struct ifaddrmsg *ifa, struct nl_cb *callbacks);
+int netlink_sendrecv(struct nl_msg *msg);
+
+#endif
diff --git a/setif.c b/setif.c
new file mode 100644
index 0000000..5ee00bc
--- /dev/null
+++ b/setif.c
@@ -0,0 +1,129 @@
+/*
+ * Copyright 2012 Daniel Drown <dan-android@drown.org>
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * setif.c - network interface configuration
+ */
+#include <errno.h>
+#include <netinet/in.h>
+#include <net/if.h>
+
+#include <linux/rtnetlink.h>
+#include <netlink/handlers.h>
+#include <netlink/msg.h>
+
+#include "netlink_msg.h"
+
+/* function: add_address
+ * adds an IP address to/from an interface, returns 0 on success and <0 on failure
+ * ifname - name of interface to change
+ * family - address family (AF_INET, AF_INET6)
+ * address - pointer to a struct in_addr or in6_addr
+ * prefixlen - bitlength of network (example: 24 for AF_INET's 255.255.255.0)
+ * broadcast - broadcast address (only for AF_INET, ignored for AF_INET6)
+ */
+int add_address(const char *ifname, int family, const void *address, int prefixlen, const void *broadcast) {
+ int retval;
+ size_t addr_size;
+ struct ifaddrmsg ifa;
+ struct nl_msg *msg = NULL;
+
+ addr_size = inet_family_size(family);
+ if(addr_size == 0) {
+ retval = -EAFNOSUPPORT;
+ goto cleanup;
+ }
+
+ memset(&ifa, 0, sizeof(ifa));
+ if (!(ifa.ifa_index = if_nametoindex(ifname))) {
+ retval = -ENODEV;
+ goto cleanup;
+ }
+ ifa.ifa_family = family;
+ ifa.ifa_prefixlen = prefixlen;
+ ifa.ifa_scope = RT_SCOPE_UNIVERSE;
+
+ msg = nlmsg_alloc_ifaddr(RTM_NEWADDR, NLM_F_ACK | NLM_F_REQUEST | NLM_F_CREATE | NLM_F_REPLACE, &ifa);
+ if(!msg) {
+ retval = -ENOMEM;
+ goto cleanup;
+ }
+
+ if(nla_put(msg, IFA_LOCAL, addr_size, address) < 0) {
+ retval = -ENOMEM;
+ goto cleanup;
+ }
+ if(family == AF_INET6) {
+ // AF_INET6 gets IFA_LOCAL + IFA_ADDRESS
+ if(nla_put(msg, IFA_ADDRESS, addr_size, address) < 0) {
+ retval = -ENOMEM;
+ goto cleanup;
+ }
+ } else if(family == AF_INET) {
+ // AF_INET gets IFA_LOCAL + IFA_BROADCAST
+ if(nla_put(msg, IFA_BROADCAST, addr_size, broadcast) < 0) {
+ retval = -ENOMEM;
+ goto cleanup;
+ }
+ } else {
+ retval = -EAFNOSUPPORT;
+ goto cleanup;
+ }
+
+ retval = netlink_sendrecv(msg);
+
+cleanup:
+ if(msg)
+ nlmsg_free(msg);
+
+ return retval;
+}
+
+/* function: if_up
+ * sets interface link state to up and sets mtu, returns 0 on success and <0 on failure
+ * ifname - interface name to change
+ * mtu - new mtu
+ */
+int if_up(const char *ifname, int mtu) {
+ int retval = -1;
+ struct ifinfomsg ifi;
+ struct nl_msg *msg = NULL;
+
+ memset(&ifi, 0, sizeof(ifi));
+ if (!(ifi.ifi_index = if_nametoindex(ifname))) {
+ retval = -ENODEV;
+ goto cleanup;
+ }
+ ifi.ifi_change = IFF_UP;
+ ifi.ifi_flags = IFF_UP;
+
+ msg = nlmsg_alloc_ifinfo(RTM_SETLINK, NLM_F_ACK | NLM_F_REQUEST | NLM_F_ROOT, &ifi);
+ if(!msg) {
+ retval = -ENOMEM;
+ goto cleanup;
+ }
+
+ if(nla_put(msg, IFLA_MTU, 4, &mtu) < 0) {
+ retval = -ENOMEM;
+ goto cleanup;
+ }
+
+ retval = netlink_sendrecv(msg);
+
+cleanup:
+ if(msg)
+ nlmsg_free(msg);
+
+ return retval;
+}
diff --git a/setif.h b/setif.h
new file mode 100644
index 0000000..7f83f73
--- /dev/null
+++ b/setif.h
@@ -0,0 +1,24 @@
+/*
+ * Copyright 2012 Daniel Drown
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * setif.h - network interface configuration
+ */
+#ifndef __SETIF_H__
+#define __SETIF_H__
+
+int add_address(const char *ifname, int family, const void *address, int cidr, const void *broadcast);
+int if_up(const char *ifname, int mtu);
+
+#endif
diff --git a/setroute.c b/setroute.c
new file mode 100644
index 0000000..3edfe39
--- /dev/null
+++ b/setroute.c
@@ -0,0 +1,186 @@
+/*
+ * Copyright 2012 Daniel Drown <dan-android@drown.org>
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * setroute.c - network route configuration
+ */
+#include <errno.h>
+#include <netinet/in.h>
+#include <net/if.h>
+
+#include <linux/netlink.h>
+#include <linux/rtnetlink.h>
+#include <netlink/handlers.h>
+#include <netlink/msg.h>
+#include <netlink-types.h>
+
+#include "netlink_msg.h"
+#include "setroute.h"
+#include "logging.h"
+#include "getroute.h"
+
+/* function: if_route
+ * create/replace/delete a route
+ * ifname - name of the outbound interface
+ * family - AF_INET or AF_INET6
+ * destination - pointer to a struct in_addr or in6_addr for the destination network
+ * prefixlen - bitlength of the network address (example: 24 for AF_INET's 255.255.255.0)
+ * gateway - pointer to a struct in_addr or in6_addr for the gateway to use or NULL for an interface route
+ * metric - route metric (lower is better)
+ * mtu - route-specific mtu or 0 for the interface mtu
+ * change_type - ROUTE_DELETE, ROUTE_REPLACE, or ROUTE_CREATE
+ */
+int if_route(const char *ifname, int family, const void *destination, int prefixlen, const void *gateway, int metric, int mtu, int change_type) {
+ int retval;
+ struct nl_msg *msg = NULL;
+ struct rtmsg rt;
+ uint16_t type, flags = 0;
+ size_t addr_size;
+ uint32_t ifindex;
+
+ addr_size = inet_family_size(family);
+ if(addr_size == 0) {
+ retval = -EAFNOSUPPORT;
+ goto cleanup;
+ }
+
+ if (!(ifindex = if_nametoindex(ifname))) {
+ retval = -ENODEV;
+ goto cleanup;
+ }
+
+ memset(&rt, 0, sizeof(rt));
+ rt.rtm_family = family;
+ rt.rtm_table = RT_TABLE_MAIN;
+ rt.rtm_dst_len = prefixlen;
+ switch(change_type) {
+ case ROUTE_DELETE:
+ rt.rtm_scope = RT_SCOPE_NOWHERE;
+ type = RTM_DELROUTE;
+ break;
+
+ case ROUTE_REPLACE:
+ flags = NLM_F_REPLACE;
+ case ROUTE_CREATE:
+ type = RTM_NEWROUTE;
+ flags |= NLM_F_CREATE;
+ if(gateway == NULL) {
+ rt.rtm_scope = RT_SCOPE_LINK;
+ } else {
+ rt.rtm_scope = RT_SCOPE_UNIVERSE;
+ }
+ rt.rtm_type = RTN_UNICAST;
+ //RTPROT_STATIC = from administrator's configuration
+ //RTPROT_BOOT = from an automatic process
+ rt.rtm_protocol = RTPROT_BOOT;
+ break;
+
+ default:
+ retval = -EINVAL;
+ goto cleanup;
+ }
+
+ flags |= NLM_F_REQUEST | NLM_F_ACK;
+
+ msg = nlmsg_alloc_rtmsg(type, flags, &rt);
+ if(!msg) {
+ retval = -ENOMEM;
+ goto cleanup;
+ }
+
+ if(nla_put(msg, RTA_DST, addr_size, destination) < 0) {
+ retval = -ENOMEM;
+ goto cleanup;
+ }
+ if(gateway != NULL)
+ if(nla_put(msg, RTA_GATEWAY, addr_size, gateway) < 0) {
+ retval = -ENOMEM;
+ goto cleanup;
+ }
+ if(nla_put(msg, RTA_OIF, 4, &ifindex) < 0) {
+ retval = -ENOMEM;
+ goto cleanup;
+ }
+ if(nla_put(msg, RTA_PRIORITY, 4, &metric) < 0) {
+ retval = -ENOMEM;
+ goto cleanup;
+ }
+ if(mtu > 0 && change_type != ROUTE_DELETE) {
+ // MTU is inside an RTA_METRICS nested message
+ struct nlattr *metrics = nla_nest_start(msg, RTA_METRICS);
+ if(metrics == NULL) {
+ retval = -ENOMEM;
+ goto cleanup;
+ }
+
+ if(nla_put(msg, RTAX_MTU, 4, &mtu) < 0) {
+ retval = -ENOMEM;
+ goto cleanup;
+ }
+
+ nla_nest_end(msg, metrics);
+ }
+
+ retval = netlink_sendrecv(msg);
+
+cleanup:
+ if(msg)
+ nlmsg_free(msg);
+
+ return retval;
+}
+
+/* function: set_default_ipv6_route
+ * copies the default route on an interface (turns an RA route into a static
+ * route), which is needed to keep the route when forwarding is turned on
+ * device - interface to be the default route
+ */
+void set_default_ipv6_route(const char *device) {
+ struct in6_addr default_6 = IN6ADDR_ANY_INIT;
+ struct default_route_data default_route;
+ int status;
+ void *gateway = NULL;
+
+ memset(&default_route, '\0', sizeof(default_route));
+ default_route.request_family = AF_INET6;
+ default_route.request_interface_id = if_nametoindex(device);
+ if(default_route.request_interface_id == 0) {
+ logmsg(ANDROID_LOG_FATAL, "set_default_ipv6_route failed: no interface %s found", device);
+ exit(1);
+ }
+
+ status = get_default_route(&default_route);
+ if(status < 0) {
+ logmsg(ANDROID_LOG_FATAL, "set_default_ipv6_route/get_default_route failed: returned %d", status);
+ exit(1);
+ }
+
+ if(!default_route.reply_found_route) {
+ logmsg(ANDROID_LOG_FATAL, "set_default_ipv6_route/get_default_route failed: no default route found for %s", device);
+ exit(1);
+ }
+
+ if(default_route.reply_has_gateway) {
+ gateway = &default_route.reply_gateway.ip6;
+ }
+
+ if((status = if_route(device, AF_INET6, &default_6, 0, gateway, 1, 0, ROUTE_REPLACE)) < 0) {
+ if(status == -EEXIST) {
+ logmsg(ANDROID_LOG_WARN,"set_default_ipv6_route/if_route failed due to the route already existing");
+ } else {
+ logmsg(ANDROID_LOG_FATAL,"set_default_ipv6_route/if_route failed: %s",strerror(-status));
+ exit(1);
+ }
+ }
+}
diff --git a/setroute.h b/setroute.h
new file mode 100644
index 0000000..d0e7d79
--- /dev/null
+++ b/setroute.h
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2012 Daniel Drown <dan-android@drown.org>
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * setroute.h - network route configuration
+ */
+
+#ifndef __SETROUTE_H__
+#define __SETROUTE_H__
+
+#define ROUTE_DELETE 0
+#define ROUTE_REPLACE 1
+#define ROUTE_CREATE 2
+int if_route(const char *ifname, int family, const void *destination, int cidr, const void *gateway, int metric, int mtu, int change_type);
+void set_default_ipv6_route(const char *device);
+
+#endif
diff --git a/translate.c b/translate.c
new file mode 100644
index 0000000..cdaca14
--- /dev/null
+++ b/translate.c
@@ -0,0 +1,404 @@
+/*
+ * Copyright 2011 Daniel Drown
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * translate.c - CLAT functions / partial implementation of rfc6145
+ */
+#include <string.h>
+#include <sys/uio.h>
+
+#include <netinet/in.h>
+#include <netinet/ip.h>
+#include <netinet/ip_icmp.h>
+#include <netinet/udp.h>
+#include <netinet/tcp.h>
+#include <netinet/ip6.h>
+#include <netinet/icmp6.h>
+#include <linux/icmp.h>
+
+#include "checksum.h"
+#include "clatd.h"
+#include "config.h"
+#include "logging.h"
+#include "debug.h"
+
+/* function: fill_tun_header
+ * fill in the header for the tun fd
+ * tun_header - tunnel header, already allocated
+ * proto - ethernet protocol id: ETH_P_IP(ipv4) or ETH_P_IPV6(ipv6)
+ */
+void fill_tun_header(struct tun_pi *tun_header, uint16_t proto) {
+ tun_header->flags = 0;
+ tun_header->proto = htons(proto);
+}
+
+/* function: ipv6_src_to_ipv4_src
+ * return the corresponding ipv4 address for the given ipv6 address
+ * sourceaddr - ipv6 source address
+ */
+uint32_t ipv6_src_to_ipv4_src(const struct in6_addr *sourceaddr) {
+ // assumes a /96 plat subnet
+ return sourceaddr->s6_addr32[3];
+}
+
+/* function: fill_ip_header
+ * generating an ipv4 header from an ipv6 header (called by the layer 4 protocol-specific functions)
+ * ip_targ - (ipv4) target packet header, source addr: original ipv4 addr, dest addr: local subnet addr
+ * payload_len - length of other data inside packet
+ * protocol - protocol number (tcp, udp, etc)
+ * old_header - (ipv6) source packet header, source addr: nat64 prefix, dest addr: local subnet prefix
+ */
+void fill_ip_header(struct iphdr *ip_targ, uint16_t payload_len, uint8_t protocol, const struct ip6_hdr *old_header) {
+ memset(ip_targ, 0, sizeof(ip_targ));
+
+ ip_targ->ihl = 5;
+ ip_targ->version = 4;
+ ip_targ->tos = 0;
+ ip_targ->tot_len = htons(sizeof(struct iphdr) + payload_len);
+ ip_targ->id = 0;
+ ip_targ->frag_off = htons(IP_DF);
+ ip_targ->ttl = old_header->ip6_hlim;
+ ip_targ->protocol = protocol;
+ ip_targ->check = 0;
+
+ ip_targ->saddr = ipv6_src_to_ipv4_src(&old_header->ip6_src);
+ ip_targ->daddr = Global_Clatd_Config.ipv4_local_subnet.s_addr;
+
+ ip_targ->check = ip_checksum(ip_targ, sizeof(struct iphdr));
+}
+
+/* function: ipv4_dst_to_ipv6_dst
+ * return the corresponding ipv6 address for the given ipv4 address
+ * destination - ipv4 destination address (network byte order)
+ */
+struct in6_addr ipv4_dst_to_ipv6_dst(uint32_t destination) {
+ struct in6_addr v6_destination;
+
+ // assumes a /96 plat subnet
+ v6_destination = Global_Clatd_Config.plat_subnet;
+ v6_destination.s6_addr32[3] = destination;
+
+ return v6_destination;
+}
+
+/* function: fill_ip6_header
+ * generating an ipv6 header from an ipv4 header (called by the layer 4 protocol-specific functions)
+ * ip6 - (ipv6) target packet header, source addr: local subnet prefix, dest addr: nat64 prefix
+ * payload_len - length of other data inside packet
+ * protocol - protocol number (tcp, udp, etc)
+ * old_header - (ipv4) source packet header, source addr: local subnet addr, dest addr: internet's ipv4 addr
+ */
+void fill_ip6_header(struct ip6_hdr *ip6, uint16_t payload_len, uint8_t protocol, const struct iphdr *old_header) {
+ memset(ip6, 0, sizeof(struct ip6_hdr));
+
+ ip6->ip6_vfc = 6 << 4;
+ ip6->ip6_plen = htons(payload_len);
+ ip6->ip6_nxt = protocol;
+ ip6->ip6_hlim = old_header->ttl;
+
+ ip6->ip6_src = Global_Clatd_Config.ipv6_local_subnet;
+ ip6->ip6_dst = ipv4_dst_to_ipv6_dst(old_header->daddr);
+}
+
+/* function: icmp_to_icmp6
+ * translate ipv4 icmp to ipv6 icmp (only currently supports echo/echo reply)
+ * fd - tun interface fd
+ * ip - source packet ipv4 header
+ * icmp - source packet icmp header
+ * payload - icmp payload
+ * payload_size - size of payload
+ */
+void icmp_to_icmp6(int fd, const struct iphdr *ip, const struct icmphdr *icmp, const char *payload, size_t payload_size) {
+ struct ip6_hdr ip6_targ;
+ struct icmp6_hdr icmp6_targ;
+ struct iovec io_targ[4];
+ struct tun_pi tun_header;
+ uint32_t checksum_temp;
+
+ if((icmp->type != ICMP_ECHO) && (icmp->type != ICMP_ECHOREPLY)) {
+ logmsg_dbg(ANDROID_LOG_WARN,"icmp_to_icmp6/unhandled icmp type: 0x%x",icmp->type);
+ return;
+ }
+
+ fill_tun_header(&tun_header,ETH_P_IPV6);
+
+ fill_ip6_header(&ip6_targ,payload_size + sizeof(icmp6_targ),IPPROTO_ICMPV6,ip);
+
+ memset(&icmp6_targ, 0, sizeof(icmp6_targ));
+ icmp6_targ.icmp6_type = (icmp->type == ICMP_ECHO) ? ICMP6_ECHO_REQUEST : ICMP6_ECHO_REPLY;
+ icmp6_targ.icmp6_code = 0;
+ icmp6_targ.icmp6_cksum = 0;
+ icmp6_targ.icmp6_id = icmp->un.echo.id;
+ icmp6_targ.icmp6_seq = icmp->un.echo.sequence;
+
+ checksum_temp = ipv6_pseudo_header_checksum(0,&ip6_targ);
+ checksum_temp = ip_checksum_add(checksum_temp, &icmp6_targ, sizeof(icmp6_targ));
+ checksum_temp = ip_checksum_add(checksum_temp, payload, payload_size);
+ icmp6_targ.icmp6_cksum = ip_checksum_finish(checksum_temp);
+
+ io_targ[0].iov_base = &tun_header;
+ io_targ[0].iov_len = sizeof(tun_header);
+ io_targ[1].iov_base = &ip6_targ;
+ io_targ[1].iov_len = sizeof(ip6_targ);
+ io_targ[2].iov_base = &icmp6_targ;
+ io_targ[2].iov_len = sizeof(icmp6_targ);
+ io_targ[3].iov_base = (char *)payload;
+ io_targ[3].iov_len = payload_size;
+
+ writev(fd, io_targ, 4);
+}
+
+/* function: icmp6_to_icmp
+ * translate ipv6 icmp to ipv4 icmp (only currently supports echo/echo reply)
+ * fd - tun interface fd
+ * ip6 - source packet ipv6 header
+ * icmp6 - source packet icmp6 header
+ * payload - icmp6 payload
+ * payload_size - size of payload
+ */
+void icmp6_to_icmp(int fd, const struct ip6_hdr *ip6, const struct icmp6_hdr *icmp6, const char *payload, size_t payload_size) {
+ struct iphdr ip_targ;
+ struct icmphdr icmp_targ;
+ struct iovec io_targ[4];
+ struct tun_pi tun_header;
+ uint32_t temp_icmp_checksum;
+
+ if((icmp6->icmp6_type != ICMP6_ECHO_REQUEST) && (icmp6->icmp6_type != ICMP6_ECHO_REPLY)) {
+ logmsg_dbg(ANDROID_LOG_WARN,"icmp6_to_icmp/unhandled icmp6 type: 0x%x",icmp6->icmp6_type);
+ return;
+ }
+
+ memset(&icmp_targ, 0, sizeof(icmp_targ));
+
+ fill_tun_header(&tun_header,ETH_P_IP);
+ fill_ip_header(&ip_targ,sizeof(icmp_targ) + payload_size, IPPROTO_ICMP, ip6);
+
+ icmp_targ.type = (icmp6->icmp6_type == ICMP6_ECHO_REQUEST) ? ICMP_ECHO : ICMP_ECHOREPLY;
+ icmp_targ.code = 0x0;
+ icmp_targ.checksum = 0;
+ icmp_targ.un.echo.id = icmp6->icmp6_id;
+ icmp_targ.un.echo.sequence = icmp6->icmp6_seq;
+
+ temp_icmp_checksum = ip_checksum_add(0, &icmp_targ, sizeof(icmp_targ));
+ temp_icmp_checksum = ip_checksum_add(temp_icmp_checksum, (void *)payload, payload_size);
+ icmp_targ.checksum = ip_checksum_finish(temp_icmp_checksum);
+
+ io_targ[0].iov_base = &tun_header;
+ io_targ[0].iov_len = sizeof(tun_header);
+ io_targ[1].iov_base = &ip_targ;
+ io_targ[1].iov_len = sizeof(ip_targ);
+ io_targ[2].iov_base = &icmp_targ;
+ io_targ[2].iov_len = sizeof(icmp_targ);
+ io_targ[3].iov_base = (char *)payload;
+ io_targ[3].iov_len = payload_size;
+
+ writev(fd, io_targ, 4);
+}
+
+/* function: udp_translate
+ * common between ipv4/ipv6 - setup checksum and send udp packet
+ * fd - tun interface fd
+ * udp - source packet udp header
+ * payload - udp payload
+ * payload_size - size of payload
+ * io_targ - iovec with tun and ipv4/ipv6 header (see below)
+ * array position 0 - tun header
+ * array position 1 - ipv4/ipv6 header
+ * array position 2 - empty (will be udp header)
+ * array position 3 - empty (will be payload)
+ * checksum - partial checksum covering ipv4/ipv6 header
+ */
+void udp_translate(int fd, const struct udphdr *udp, const char *payload, size_t payload_size, struct iovec *io_targ, uint32_t checksum) {
+ struct udphdr udp_targ;
+
+ memcpy(&udp_targ, udp, sizeof(udp_targ));
+ udp_targ.check = 0; // reset checksum, to be calculated
+
+ checksum = ip_checksum_add(checksum, &udp_targ, sizeof(struct udphdr));
+ checksum = ip_checksum_add(checksum, payload, payload_size);
+ udp_targ.check = ip_checksum_finish(checksum);
+
+ io_targ[2].iov_base = &udp_targ;
+ io_targ[2].iov_len = sizeof(udp_targ);
+ io_targ[3].iov_base = (char *)payload;
+ io_targ[3].iov_len = payload_size;
+
+ writev(fd, io_targ, 4);
+}
+
+/* function: udp_to_udp6
+ * translate ipv4 udp to ipv6 udp
+ * fd - tun interface fd
+ * ip - source packet ipv4 header
+ * udp - source packet udp header
+ * payload - udp payload
+ * payload_size - size of payload
+ */
+void udp_to_udp6(int fd, const struct iphdr *ip, const struct udphdr *udp, const char *payload, size_t payload_size) {
+ struct ip6_hdr ip6_targ;
+ struct iovec io_targ[4];
+ struct tun_pi tun_header;
+ uint32_t checksum;
+
+ fill_tun_header(&tun_header,ETH_P_IPV6);
+
+ fill_ip6_header(&ip6_targ,payload_size + sizeof(struct udphdr),IPPROTO_UDP,ip);
+
+ checksum = ipv6_pseudo_header_checksum(0, &ip6_targ);
+
+ io_targ[0].iov_base = &tun_header;
+ io_targ[0].iov_len = sizeof(tun_header);
+ io_targ[1].iov_base = &ip6_targ;
+ io_targ[1].iov_len = sizeof(ip6_targ);
+
+ udp_translate(fd,udp,payload,payload_size,io_targ,checksum);
+}
+
+/* function: udp6_to_udp
+ * translate ipv6 udp to ipv4 udp
+ * fd - tun interface fd
+ * ip6 - source packet ipv6 header
+ * udp - source packet udp header
+ * payload - udp payload
+ * payload_size - size of payload
+ */
+void udp6_to_udp(int fd, const struct ip6_hdr *ip6, const struct udphdr *udp, const char *payload, size_t payload_size) {
+ struct iphdr ip_targ;
+ struct iovec io_targ[4];
+ struct tun_pi tun_header;
+ uint32_t checksum;
+
+ fill_tun_header(&tun_header,ETH_P_IP);
+
+ fill_ip_header(&ip_targ,payload_size + sizeof(struct udphdr),IPPROTO_UDP,ip6);
+
+ checksum = ipv4_pseudo_header_checksum(0, &ip_targ);
+
+ io_targ[0].iov_base = &tun_header;
+ io_targ[0].iov_len = sizeof(tun_header);
+ io_targ[1].iov_base = &ip_targ;
+ io_targ[1].iov_len = sizeof(ip_targ);
+
+ udp_translate(fd,udp,payload,payload_size,io_targ,checksum);
+}
+
+/* function: tcp_translate
+ * common between ipv4/ipv6 - setup checksum and send tcp packet
+ * fd - tun interface fd
+ * tcp - source packet tcp header
+ * payload - tcp payload
+ * payload_size - size of payload
+ * io_targ - iovec with tun and ipv4/ipv6 header (see below)
+ * array position 0 - tun header
+ * array position 1 - ipv4/ipv6 header
+ * array position 2 - empty (will be tcp header)
+ * array position 3 - empty (will be tcp options or payload)
+ * array position 4 - empty (can be payload)
+ * checksum - partial checksum covering ipv4/ipv6 header
+ * options - pointer to tcp option buffer
+ * options_size - size of tcp option buffer
+ *
+ * TODO: mss rewrite
+ * TODO: hosts without pmtu discovery - non DF packets will rely on fragmentation (unimplemented)
+ */
+void tcp_translate(int fd, const struct tcphdr *tcp, const char *payload, size_t payload_size, struct iovec *io_targ, uint32_t checksum, const char *options, size_t options_size) {
+ struct tcphdr tcp_targ;
+ int targ_index = 2;
+
+ memcpy(&tcp_targ, tcp, sizeof(tcp_targ));
+ tcp_targ.check = 0;
+
+ checksum = ip_checksum_add(checksum, &tcp_targ, sizeof(tcp_targ));
+ if(options) {
+ checksum = ip_checksum_add(checksum, options, options_size);
+ }
+ checksum = ip_checksum_add(checksum, payload, payload_size);
+ tcp_targ.check = ip_checksum_finish(checksum);
+
+ io_targ[targ_index].iov_base = &tcp_targ;
+ io_targ[targ_index].iov_len = sizeof(tcp_targ);
+ targ_index++;
+
+ if(options) {
+ io_targ[targ_index].iov_base = (char *)options;
+ io_targ[targ_index].iov_len = options_size;
+ targ_index++;
+ }
+
+ io_targ[targ_index].iov_base = (char *)payload;
+ io_targ[targ_index].iov_len = payload_size;
+ targ_index++;
+
+ writev(fd, io_targ, targ_index);
+}
+
+/* function: tcp_to_tcp6
+ * translate ipv4 tcp to ipv6 tcp
+ * fd - tun interface fd
+ * ip - source packet ipv4 header
+ * tcp - source packet tcp header
+ * payload - tcp payload
+ * payload_size - size of payload
+ * options - tcp options
+ * options_size - size of options
+ */
+void tcp_to_tcp6(int fd,const struct iphdr *ip, const struct tcphdr *tcp, const char *payload, size_t payload_size, const char *options, size_t options_size) {
+ struct ip6_hdr ip6_targ;
+ struct iovec io_targ[5];
+ struct tun_pi tun_header;
+ uint32_t checksum;
+
+ fill_tun_header(&tun_header,ETH_P_IPV6);
+
+ fill_ip6_header(&ip6_targ,payload_size+options_size+sizeof(struct tcphdr),IPPROTO_TCP,ip);
+
+ checksum = ipv6_pseudo_header_checksum(0, &ip6_targ);
+
+ io_targ[0].iov_base = &tun_header;
+ io_targ[0].iov_len = sizeof(tun_header);
+ io_targ[1].iov_base = &ip6_targ;
+ io_targ[1].iov_len = sizeof(ip6_targ);
+
+ tcp_translate(fd,tcp,payload,payload_size,io_targ,checksum,options,options_size);
+}
+
+/* function: tcp6_to_tcp
+ * translate ipv6 tcp to ipv4 tcp
+ * fd - tun interface fd
+ * ip6 - source packet ipv6 header
+ * tcp - source packet tcp header
+ * payload - tcp payload
+ * payload_size - size of payload
+ * options - tcp options
+ * options_size - size of options
+ */
+void tcp6_to_tcp(int fd,const struct ip6_hdr *ip6, const struct tcphdr *tcp, const char *payload, size_t payload_size, const char *options, size_t options_size) {
+ struct iphdr ip_targ;
+ struct iovec io_targ[5];
+ struct tun_pi tun_header;
+ uint32_t checksum;
+
+ fill_tun_header(&tun_header,ETH_P_IP);
+
+ fill_ip_header(&ip_targ,payload_size+options_size+sizeof(struct tcphdr),IPPROTO_TCP,ip6);
+
+ checksum = ipv4_pseudo_header_checksum(0, &ip_targ);
+
+ io_targ[0].iov_base = &tun_header;
+ io_targ[0].iov_len = sizeof(tun_header);
+ io_targ[1].iov_base = &ip_targ;
+ io_targ[1].iov_len = sizeof(ip_targ);
+
+ tcp_translate(fd,tcp,payload,payload_size,io_targ,checksum,options,options_size);
+}
diff --git a/translate.h b/translate.h
new file mode 100644
index 0000000..6fc3c79
--- /dev/null
+++ b/translate.h
@@ -0,0 +1,30 @@
+/*
+ * Copyright 2011 Daniel Drown
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * translate.h - translate from one version of ip to another
+ */
+#ifndef __TRANSLATE_H__
+#define __TRANSLATE_H__
+
+void icmp_to_icmp6(int fd, const struct iphdr *ip, const struct icmphdr *icmp, const char *payload, size_t payload_size);
+void icmp6_to_icmp(int fd, const struct ip6_hdr *ip6, const struct icmp6_hdr *icmp6, const char *payload, size_t payload_size);
+
+void udp_to_udp6(int fd, const struct iphdr *ip, const struct udphdr *udp, const char *payload, size_t payload_size);
+void udp6_to_udp(int fd, const struct ip6_hdr *ip6, const struct udphdr *udp, const char *payload, size_t payload_size);
+
+void tcp_to_tcp6(int fd,const struct iphdr *ip, const struct tcphdr *tcp, const char *payload, size_t payload_size, const char *options, size_t options_size);
+void tcp6_to_tcp(int fd,const struct ip6_hdr *ip6, const struct tcphdr *tcp, const char *payload, size_t payload_size, const char *options, size_t options_size);
+
+#endif /* __TRANSLATE_H__ */