From c4378784ae2caec57634f9f04bcb3dcddc673f36 Mon Sep 17 00:00:00 2001 From: Rick Lei Date: Wed, 14 Jan 2015 22:11:43 +0800 Subject: Add Android 4.1+ support. See doc/README-Android.md for build HOWTO. * Update CMake files to work with android-cmake * Use unix domain socket for communicating with Android GUI * May also run standalone but requires rooted Android device --- COPYRIGHT | 4 + cmake/UseDoxygen.cmake | 14 ++- cmake/config.cmake | 4 +- cmake/deps.cmake | 9 +- doc/README-Android.md | 23 +++++ doc/build-fastd-android.sh | 145 ++++++++++++++++++++++++++++++ src/CMakeLists.txt | 1 + src/android_ctrl_sock.c | 218 +++++++++++++++++++++++++++++++++++++++++++++ src/compat.h | 2 +- src/config.c | 10 +++ src/cpuid.h | 2 +- src/fastd.c | 24 +++-- src/fastd.h | 18 ++++ src/options.c | 11 +++ src/options.def.h | 5 ++ src/poll.c | 2 +- src/send.c | 9 ++ src/socket.c | 7 ++ src/tuntap.c | 50 +++++++++-- 19 files changed, 536 insertions(+), 22 deletions(-) create mode 100644 doc/README-Android.md create mode 100755 doc/build-fastd-android.sh create mode 100644 src/android_ctrl_sock.c diff --git a/COPYRIGHT b/COPYRIGHT index 901d74d..95182c7 100644 --- a/COPYRIGHT +++ b/COPYRIGHT @@ -1,6 +1,10 @@ Copyright (c) 2012-2014, Matthias Schiffer All rights reserved. +Contributors: +Copyright (c) 2014-2015, Haofeng "Rick" Lei +All rights reserved. + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: diff --git a/cmake/UseDoxygen.cmake b/cmake/UseDoxygen.cmake index ae7c8d7..66978fc 100644 --- a/cmake/UseDoxygen.cmake +++ b/cmake/UseDoxygen.cmake @@ -57,13 +57,25 @@ macro(usedoxygen_set_default name value type docstring) endif() endmacro() -find_package(Doxygen) +if(ANDROID) + find_host_package(Doxygen) +else(ANDROID) + find_package(Doxygen) +endif(ANDROID) if(DOXYGEN_FOUND) + if(ANDROID) + # android-cmake doesn't provide a find_host_file and here's the workaround + set(_save_root_path ${CMAKE_FIND_ROOT_PATH}) + set(CMAKE_FIND_ROOT_PATH) + endif(ANDROID) find_file(DOXYFILE_IN "Doxyfile.in" PATHS "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_ROOT}/Modules/" NO_DEFAULT_PATH DOC "Path to the doxygen configuration template file") + if(ANDROID) + set(CMAKE_FIND_ROOT_PATH $_save_root_path) + endif(ANDROID) set(DOXYFILE "${CMAKE_CURRENT_BINARY_DIR}/Doxyfile") include(FindPackageHandleStandardArgs) find_package_handle_standard_args(DOXYFILE_IN DEFAULT_MSG "DOXYFILE_IN") diff --git a/cmake/config.cmake b/cmake/config.cmake index 8aa6549..e6b70a2 100644 --- a/cmake/config.cmake +++ b/cmake/config.cmake @@ -34,9 +34,9 @@ set(ENABLE_OPENSSL FALSE CACHE BOOL "Enable crypto implementations using OpenSSL set(ENABLE_LTO FALSE CACHE BOOL "Enable link-time optimization") -if(LINUX) +if(LINUX AND NOT ANDROID) set(ENABLE_SYSTEMD TRUE CACHE BOOL "Enable systemd support") -endif(LINUX) +endif(LINUX AND NOT ANDROID) set(WITH_CMDLINE_USER TRUE CACHE BOOL "Include support for setting user/group related options on the command line") set(WITH_CMDLINE_LOGGING TRUE CACHE BOOL "Include support for setting logging related options on the command line") diff --git a/cmake/deps.cmake b/cmake/deps.cmake index 7f48854..0d06bee 100644 --- a/cmake/deps.cmake +++ b/cmake/deps.cmake @@ -4,9 +4,14 @@ if(NOT DARWIN) set(PTHREAD_LDFLAGS -pthread) endif(NOT DARWIN) +if(ANDROID) + find_host_package(BISON 2.5 REQUIRED) + find_host_package(PkgConfig REQUIRED) +else(ANDROID) + find_package(BISON 2.5 REQUIRED) + find_package(PkgConfig REQUIRED) +endif(ANDROID) -find_package(BISON 2.5 REQUIRED) -find_package(PkgConfig REQUIRED) pkg_check_modules(UECC REQUIRED libuecc>=3) diff --git a/doc/README-Android.md b/doc/README-Android.md new file mode 100644 index 0000000..975a679 --- /dev/null +++ b/doc/README-Android.md @@ -0,0 +1,23 @@ +fastd for Android +================= + +Runtime Requirements +-------------------- +* Android 4.1+ +* x86 / ARMv7a + * NEON optimiazation is planned but not currently required + * Not tested with x86\_64 or AArch64 but should work too + +How to Build +------------ +* Android NDK r10d+ (r10c or older versions won't work) + * make sure ANDROID\_NDK\_HOME is set +* Ubuntu 12.04+ + * `sudo apt-get install build-essential automake bison cmake libtool pkg-config` + * For Ubuntu **12.04**: cmake 2.8.7 won't work; get a newer version from https://launchpad.net/~kalakris/+archive/ubuntu/cmake +* or Mac OS X 10.10+ (older versions should work too) + * Homebrew + * `brew install automake libtool cmake bison` + +Then run `doc/build-fastd-android.sh` from `fastd-android` folder. Be warned the script is not perfect; you may need to look into it should anything go wrong. + diff --git a/doc/build-fastd-android.sh b/doc/build-fastd-android.sh new file mode 100755 index 0000000..145f9c4 --- /dev/null +++ b/doc/build-fastd-android.sh @@ -0,0 +1,145 @@ +# Helper script for building fastd-android and its dependencies +#!/bin/bash + +if [ x${PWD##*/} == xdoc ]; then + echo "Warning: it seems you're currently in the doc/ folder. This script needs to run under the top folder of fastd source code." + echo "See README-Android.md for more info." + exit 1 +fi + +echo "This script downloads and builds dependencies for fastd-android, as well as fastd-android itself." +echo "Make sure you have these packages installed:" +echo " * Android NDK r10d or newer" +echo " * for Debian/Ubuntu: sudo apt-get install curl build-eseentials automake bison cmake git libtool pkg-config" +echo " - Ubuntu 12.04 users need to grab cmake 2.8.9 or newer. See README-Android.md for more info." +echo " * for Mac OS X: brew install automake libtool cmake bison" +echo "Hit ctrl-c now if you don't have all needed stuff yet." +read + +SODIUM_VER=1.0.1 +UECC_VER=4 +LIBSODIUM_PATH=libsodium-${SODIUM_VER} +LIBUECC_PATH=libuecc-${UECC_VER} +ANDROID_NATIVE_LEVEL=16 + +if [ x$ANDROID_NDK_HOME == x ]; then + echo "Set ANDROID_NDK_HOME first"; exit 1; +fi + +if [ ! -d "build" ]; then + mkdir build +fi + +pushd build > /dev/null +WORK_DIR=${PWD} + +if [ -d "${LIBSODIUM_PATH}" ]; then + echo "It seems you already have libsodium downloaded."; +else + echo "Downloading libsodium ${SODIUM_VER}..." + curl -L https://github.com/jedisct1/libsodium/releases/download/${SODIUM_VER}/libsodium-${SODIUM_VER}.tar.gz | tar zxf - || exit 1 +fi + +pushd ${LIBSODIUM_PATH} > /dev/null +if [ ! -f "dist-build/android-armv7.sh" ]; then + echo "Patching libsodium build scripts..." + sed -i.bak 's/--enable-minimal//' dist-build/android-build.sh + sed -e 's/-mthumb -marm -march=armv6/-march=armv7-a -mfloat-abi=softfp -mfpu=vfpv3-d16/' dist-build/android-arm.sh > dist-build/android-armv7.sh + chmod +x dist-build/android-armv7.sh +fi +if [ ! -d "libsodium-android-arm" ]; then + dist-build/android-armv7.sh || exit 2 + # for static link using cmake + rm libsodium-android-arm/lib/libsodium.so +fi +if [ ! -d "libsodium-android-x86" ]; then + dist-build/android-x86.sh || exit 2 + # for static link using cmake + rm libsodium-android-x86/lib/libsodium.so +fi +popd > /dev/null + +if [ -d "android-cmake" ]; then + echo "It seems you already have android-cmake downloaded."; +else + echo "Downloading android-cmake" + git clone https://github.com/taka-no-me/android-cmake.git; +fi +CMAKE_TOOLCHAIN=${WORK_DIR}/android-cmake/android.toolchain.cmake +ANDROID_CMAKE="cmake -DCMAKE_TOOLCHAIN_FILE=${CMAKE_TOOLCHAIN}" +echo ">> android-cmake ready." + +CMAKE_COMMON_DEFS="-DCMAKE_BUILD_TYPE=Release -DANDROID_NDK=${ANDROID_NDK_HOME} -DANDROID_NATIVE_API_LEVEL=${ANDROID_NATIVE_LEVEL}" + +if [ -d "${LIBUECC_PATH}" ]; then + echo "It seems you already have libuecc downloaded."; +else + curl -k -L https://projects.universe-factory.net/attachments/download/71/libuecc-${UECC_VER}.tar.xz | tar Jxf - || exit 4 +fi +for ARCH in arm x86; do + BUILD_DIR=libuecc-${ARCH} + if [ ! -d "${BUILD_DIR}" ]; then + mkdir ${BUILD_DIR} && pushd ${BUILD_DIR} > /dev/null + if [ ${ARCH} == arm ]; then + _USE_ABI="armeabi-v7a" + else + _USE_ABI=${ARCH} + fi + ${ANDROID_CMAKE} -DANDROID_ABI="$_USE_ABI" ${CMAKE_COMMON_DEFS} -DCMAKE_INSTALL_PREFIX=`pwd`/output ../${LIBUECC_PATH} || exit 5 + make && make install || exit 6 + # for static link using cmake + rm output/lib/libuecc.so* + popd > /dev/null; + echo ">> libuecc ${ARCH} built." + fi +done + +if [ ! -d "pkgconfig" ]; then + mkdir pkgconfig + for ARCH in arm x86; do + mkdir pkgconfig/${ARCH} + cp libuecc-${ARCH}/output/lib/pkgconfig/libuecc.pc pkgconfig/${ARCH} + cp ${LIBSODIUM_PATH}/libsodium-android-${ARCH}/lib/pkgconfig/libsodium.pc pkgconfig/${ARCH} + done + echo ">> pkgconfig files prepared." +fi + +# detect HomeBrew installed bison for OS X +HOMEBREW_BISON_PATH=`find /usr/local/Cellar/bison -name bin` +if [ x${HOMEBREW_BISON_PATH} != x ]; then + USE_PATH=${HOMEBREW_BISON_PATH}:$PATH +else + USE_PATH=$PATH +fi + +FASTD_ANDROID_DEFS="-DWITH_CAPABILITIES=OFF -DWITH_STATUS_SOCKET=OFF -DWITH_CIPHER_AES128_CTR=FALSE -DWITH_METHOD_XSALSA20_POLY1305=FALSE -DWITH_METHOD_GENERIC_POLY1305=FALSE -DWITH_CMDLINE_COMMANDS=FALSE" + +for ARCH in arm x86; do + BUILD_DIR=fastd-${ARCH} + if [ ! -d "BUILD_DIR" ]; then + mkdir ${BUILD_DIR} + fi + pushd ${BUILD_DIR} > /dev/null + if [ ! -f "Makefile" ]; then + if [ ${ARCH} == arm ]; then + _USE_ABI="armeabi-v7a" + ADD_DEFS="-DWITH_CIPHER_SALSA2012_NACL=TRUE -DWITH_CIPHER_SALSA20_NACL=TRUE" + else + _USE_ABI=${ARCH} + ADD_DEFS="-DWITH_CIPHER_SALSA2012_NACL=FALSE -DWITH_CIPHER_SALSA20_NACL=FALSE" + fi + + PATH=${USE_PATH} PKG_CONFIG_LIBDIR=../pkgconfig/${ARCH} \ + ${ANDROID_CMAKE} \ + -DANDROID_ABI="$_USE_ABI" ${CMAKE_COMMON_DEFS} \ + ${FASTD_ANDROID_DEFS} \ + ${ADD_DEFS} -DEXECUTABLE_OUTPUT_PATH=`pwd` \ + ../.. || exit 7 + fi + + make && echo ">> fastd ${ARCH} build ready in build/${BUILD_DIR}" + popd > /dev/null +done + +popd > /dev/null + diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 978d8e9..e7dd5d1 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -18,6 +18,7 @@ configure_file(${CMAKE_CURRENT_SOURCE_DIR}/fastd_config.h.in ${CMAKE_CURRENT_BIN BISON_TARGET(fastd_config_parse config.y ${CMAKE_CURRENT_BINARY_DIR}/config.yy.c) add_executable(fastd + android_ctrl_sock.c async.c capabilities.c config.c diff --git a/src/android_ctrl_sock.c b/src/android_ctrl_sock.c new file mode 100644 index 0000000..c681755 --- /dev/null +++ b/src/android_ctrl_sock.c @@ -0,0 +1,218 @@ +/*************************************************************************** + * libancillary - black magic on Unix domain sockets + * (C) Nicolas George + ***************************************************************************/ + +/* + * fastd Android port + * Copyright (c) 2014-2015, Haofeng "Rick" Lei + * All rights reserved. + */ + +/* + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO + * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* libancillary code from: + * http://www.normalesup.org/~george/comp/libancillary/ + * with minor indent/style adjusts to fit fastd project + */ +/* vim: set noexpandtab ts=8 sw=8 sts=8 */ + +/** + \file + + Android specific methods for communicating with GUI +*/ + +#ifdef __ANDROID__ + +#include +#include +#include +#include + +#include "fastd.h" + +/** declare a work buffer for sending/receiving \e n handles */ +#define ANCIL_FD_BUFFER(n) \ + struct { \ + struct cmsghdr h; \ + int fd[n]; \ + } + +/** receive \e n_fds handles from unix domain socket \e sock and store in \e fds */ +static int ancil_recv_fds_with_buffer(int sock, int *fds, unsigned n_fds, void *buffer) { + struct msghdr msghdr; + char nothing; + struct iovec nothing_ptr; + struct cmsghdr *cmsg; + int i; + + nothing_ptr.iov_base = ¬hing; + nothing_ptr.iov_len = 1; + msghdr.msg_name = NULL; + msghdr.msg_namelen = 0; + msghdr.msg_iov = ¬hing_ptr; + msghdr.msg_iovlen = 1; + msghdr.msg_flags = 0; + msghdr.msg_control = buffer; + msghdr.msg_controllen = sizeof(struct cmsghdr) + sizeof(int) * n_fds; + cmsg = CMSG_FIRSTHDR(&msghdr); + cmsg->cmsg_len = msghdr.msg_controllen; + cmsg->cmsg_level = SOL_SOCKET; + cmsg->cmsg_type = SCM_RIGHTS; + for (i = 0; i < n_fds; i++) { + ((int *)CMSG_DATA(cmsg))[i] = -1; + } + + if (recvmsg(sock, &msghdr, 0) < 0) { + return(-1); + } + for (i = 0; i < n_fds; i++) { + fds[i] = ((int *)CMSG_DATA(cmsg))[i]; + } + n_fds = (cmsg->cmsg_len - sizeof(struct cmsghdr)) / sizeof(int); + return n_fds; +} + +/** shortcut for receiving only one \e fd from \e sock */ +static int ancil_recv_fd(int sock, int *fd) { + ANCIL_FD_BUFFER(1) buffer; + + return ancil_recv_fds_with_buffer(sock, fd, 1, &buffer) == 1 ? 0 : -1; +} + +/** send \e n_fds handles in \e fds to unix domain socket \e sock */ +static int ancil_send_fds_with_buffer(int sock, const int *fds, unsigned n_fds, void *buffer) { + struct msghdr msghdr; + char nothing = '!'; + struct iovec nothing_ptr; + struct cmsghdr *cmsg; + int i; + + nothing_ptr.iov_base = ¬hing; + nothing_ptr.iov_len = 1; + msghdr.msg_name = NULL; + msghdr.msg_namelen = 0; + msghdr.msg_iov = ¬hing_ptr; + msghdr.msg_iovlen = 1; + msghdr.msg_flags = 0; + msghdr.msg_control = buffer; + msghdr.msg_controllen = sizeof(struct cmsghdr) + sizeof(int) * n_fds; + cmsg = CMSG_FIRSTHDR(&msghdr); + cmsg->cmsg_len = msghdr.msg_controllen; + cmsg->cmsg_level = SOL_SOCKET; + cmsg->cmsg_type = SCM_RIGHTS; + for (i = 0; i < n_fds; i++) { + ((int *)CMSG_DATA(cmsg))[i] = fds[i]; + } + return sendmsg(sock, &msghdr, 0) >= 0 ? 0 : -1; +} + +/** shortcut for sending only one \e fd to \e sock */ +static int ancil_send_fd(int sock, int fd) +{ + ANCIL_FD_BUFFER(1) buffer; + + return ancil_send_fds_with_buffer(sock, &fd, 1, &buffer); +} + +/* + * libancillary end + */ + + +/** name of unix domain socket for communication with Android FastdVpnService */ +#define CTRL_SOCK_NAME "fastd_tun_sock" + +/** message sent by Android FastdVpnService to indicate successful protection of socket */ +#define PROTECT_OK 'X' + +/** message sent by Android FastdVpnService when protecting socket failed */ +#define PROTECT_ERROR 'E' + +/** establish the unix domain socket with Android GUI */ +static void init_ctrl_sock(void) { + /* Must keep consistent with FastdVpnService */ + struct sockaddr_un addr; + + if ((ctx.android_ctrl_sock_fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { + exit_errno("could not create unix domain socket"); + } + + memset(&addr, 0, sizeof(addr)); + addr.sun_family = AF_UNIX; + addr.sun_path[0] = 0; /* Linux's abstract unix domain socket name */ + strncpy(addr.sun_path + 1, CTRL_SOCK_NAME, sizeof(addr.sun_path) - 2); + int socklen = offsetof(struct sockaddr_un, sun_path) + strlen(CTRL_SOCK_NAME) + 1; + + if (connect(ctx.android_ctrl_sock_fd, (struct sockaddr*)&addr, socklen) == -1) { + exit_errno("could not connect to Android LocalServerSocket"); + } +} + +/** receive TUN fd from Android GUI; this is the only way to open TUN device on non-rooted Android */ +int fastd_android_receive_tunfd(void) { + init_ctrl_sock(); + + int handle; + if (ancil_recv_fd(ctx.android_ctrl_sock_fd, &handle)) { + exit_errno("could not receive TUN handle from Android"); + } else { + pr_debug("received fd: %u", handle); + } + + return handle; +} + +/** send fastd pid to Android GUI for later signal sending (HUP, TERM etc) */ +void fastd_android_send_pid(void) { + char pid[20]; + snprintf(pid, sizeof(pid), "%u", (unsigned)getpid()); + if (write(ctx.android_ctrl_sock_fd, pid, strlen(pid)) != strlen(pid)) { + exit_errno("send pid"); + } +} + +/** report \e fd to Android GUI to be protected (i.e. not to be routed via TUN) */ +bool fastd_android_protect_socket(int fd) { + if (!conf.android_integration) { + /* rooted/non-GUI mode */ + return true; + } + + pr_debug("sending fd to protect"); + if (ancil_send_fd(ctx.android_ctrl_sock_fd, fd) == -1) { + exit_errno("could not send handle to Android for protecting"); + } + + char buf[20]; + if (read(ctx.android_ctrl_sock_fd, buf, sizeof(buf)) == -1) { + exit_errno("read ack"); + } + return buf[0] == PROTECT_OK; +} + +#endif /* __ANDROID__ */ + diff --git a/src/compat.h b/src/compat.h index c73a340..411c6bb 100644 --- a/src/compat.h +++ b/src/compat.h @@ -94,7 +94,7 @@ struct ethhdr { /** Replacement function for *BSD systems not supporting get_current_dir_name() */ static inline char *get_current_dir_name(void) { -#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__APPLE__) +#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__APPLE__) || defined(__ANDROID__) return getcwd(NULL, 0); diff --git a/src/config.c b/src/config.c index 7a0cb4e..1c74026 100644 --- a/src/config.c +++ b/src/config.c @@ -2,6 +2,10 @@ Copyright (c) 2012-2014, Matthias Schiffer All rights reserved. + Android port contributor: + Copyright (c) 2014-2015, Haofeng "Rick" Lei + All rights reserved. + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -382,6 +386,11 @@ static void configure_user(void) { conf.uid = getuid(); conf.gid = getgid(); +#ifdef __ANDROID__ + if (conf.user || conf.group) { + exit_error("config error: setting user/group is not supported on Android"); + } +#else if (conf.user) { struct passwd pwd, *pwdr; size_t bufspace = 1024; @@ -441,6 +450,7 @@ static void configure_user(void) { conf.groups[i] = groups[i]; } } +#endif } /** Initializes global configuration that depends on the configured methods */ diff --git a/src/cpuid.h b/src/cpuid.h index 9382156..671be87 100644 --- a/src/cpuid.h +++ b/src/cpuid.h @@ -50,7 +50,7 @@ static inline uint64_t fastd_cpuid(void) { unsigned eax, ebx, ecx, edx; - __asm__("cpuid" : "=a" (eax), "=b" (ebx), "=c" (ecx), "=d" (edx) : "a" (1)); + __asm__ __volatile__ ("mov %%ebx, %%edi;" "cpuid;" "xchgl %%ebx, %%edi;" : "=a" (eax), "=D" (ebx), "=c" (ecx), "=d" (edx) : "a" (1)); return ((uint64_t)ecx) << 32 | edx; } diff --git a/src/fastd.c b/src/fastd.c index 43dacc7..1b2eb33 100644 --- a/src/fastd.c +++ b/src/fastd.c @@ -2,6 +2,10 @@ Copyright (c) 2012-2014, Matthias Schiffer All rights reserved. + Android port contributor: + Copyright (c) 2014-2015, Haofeng "Rick" Lei + All rights reserved. + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -246,6 +250,12 @@ static inline void write_pid(void) { if (!conf.pid_file) return; +#ifdef __ANDROID__ + if (conf.android_integration) { + pr_warn("fastd doesn't support pid file in GUI integration mode on Android"); + return; + } +#endif uid_t uid = geteuid(); gid_t gid = getegid(); @@ -256,17 +266,17 @@ static inline void write_pid(void) { pr_debug_errno("seteuid"); } - int fd = open(conf.pid_file, O_WRONLY|O_CREAT|O_TRUNC, 0666); - if (fd < 0) { - pr_error_errno("can't write PID file: open"); + FILE *f = fopen(conf.pid_file, "w"); + if (f == NULL) { + pr_error_errno("can't write PID file: fopen"); goto end; } - if (dprintf(fd, "%u", (unsigned)getpid()) < 0) - pr_error_errno("can't write PID file: dprintf"); + if (fprintf(f, "%u", (unsigned)getpid()) < 0) + pr_error_errno("can't write PID file: fprintf"); - if (close(fd) < 0) - pr_warn_errno("close"); + if (fclose(f) < 0) + pr_warn_errno("fclose"); end: if (seteuid(uid) < 0) diff --git a/src/fastd.h b/src/fastd.h index 6e4cda6..3d62053 100644 --- a/src/fastd.h +++ b/src/fastd.h @@ -2,6 +2,10 @@ Copyright (c) 2012-2014, Matthias Schiffer All rights reserved. + Android port contributor: + Copyright (c) 2014-2015, Haofeng "Rick" Lei + All rights reserved. + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -239,6 +243,10 @@ struct fastd_config { char *status_socket; /**< The path of the status socket */ #endif +#ifdef __ANDROID__ + bool android_integration; /**< Enable Android GUI integration features */ +#endif + bool daemon; /**< Set to make fastd fork to the background after initialization */ char *pid_file; /**< A filename to write fastd's PID to */ @@ -296,6 +304,10 @@ struct fastd_context { int tunfd; /**< The file descriptor of the tunnel interface */ +#ifdef __ANDROID__ + int android_ctrl_sock_fd; /**< The unix domain socket for communicating with Android GUI */ +#endif + size_t n_socks; /**< The number of sockets in socks */ fastd_socket_t *socks; /**< Array of all sockets */ @@ -337,6 +349,12 @@ fastd_socket_t * fastd_socket_open(fastd_peer_t *peer, int af); void fastd_socket_close(fastd_socket_t *sock); void fastd_socket_error(fastd_socket_t *sock); +#ifdef __ANDROID__ +int fastd_android_receive_tunfd(void); +void fastd_android_send_pid(void); +bool fastd_android_protect_socket(int fd); +#endif + void fastd_resolve_peer(fastd_peer_t *peer, fastd_remote_t *remote); void fastd_tuntap_open(void); diff --git a/src/options.c b/src/options.c index b54c086..f8a358e 100644 --- a/src/options.c +++ b/src/options.c @@ -2,6 +2,10 @@ Copyright (c) 2012-2014, Matthias Schiffer All rights reserved. + Android port contributor: + Copyright (c) 2014-2015, Haofeng "Rick" Lei + All rights reserved. + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -325,6 +329,13 @@ static void option_forward(void) { #endif +#ifdef __ANDROID__ +/** Handles the --android-integration option */ +static void option_android_integration(void) { + conf.android_integration = true; +} +#endif + #ifdef WITH_CMDLINE_COMMANDS /** Handles the --on-pre-up option */ diff --git a/src/options.def.h b/src/options.def.h index 9ea0476..6d0efca 100644 --- a/src/options.def.h +++ b/src/options.def.h @@ -38,6 +38,11 @@ OPTION(option_forward, "--forward", "Enables forwarding of packets between peers SEPARATOR; #endif +#ifdef __ANDROID__ +OPTION(option_android_integration, "--android-integration", "Enable integration with Android GUI"); +SEPARATOR; +#endif + #ifdef WITH_CMDLINE_COMMANDS OPTION_ARG(option_on_pre_up, "--on-pre-up", "", "Sets a shell command to execute before interface creation"); OPTION_ARG(option_on_up, "--on-up", "", "Sets a shell command to execute after interface creation"); diff --git a/src/poll.c b/src/poll.c index 549d097..d4da8f1 100644 --- a/src/poll.c +++ b/src/poll.c @@ -81,7 +81,7 @@ static inline int epoll_wait_unblocked(int epfd, struct epoll_event *events, int void fastd_poll_init(void) { - ctx.epoll_fd = epoll_create1(0); + ctx.epoll_fd = epoll_create(1); if (ctx.epoll_fd < 0) exit_errno("epoll_create1"); diff --git a/src/send.c b/src/send.c index 8b9aae7..6e425c6 100644 --- a/src/send.c +++ b/src/send.c @@ -2,6 +2,10 @@ Copyright (c) 2012-2014, Matthias Schiffer All rights reserved. + Android port contributor: + Copyright (c) 2014-2015, Haofeng "Rick" Lei + All rights reserved. + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -38,6 +42,11 @@ /** Adds packet info to ancillary control messages */ static inline void add_pktinfo(struct msghdr *msg, const fastd_peer_address_t *local_addr) { +#ifdef __ANDROID__ + /* PKTINFO will mess with Android VpnService.protect(socket) */ + if (conf.android_integration) + return; +#endif if (!local_addr) return; diff --git a/src/socket.c b/src/socket.c index e72ec94..5e33010 100644 --- a/src/socket.c +++ b/src/socket.c @@ -152,6 +152,13 @@ static int bind_socket(const fastd_bind_address_t *addr, bool warn) { goto error; } +#ifdef __ANDROID__ + if (!fastd_android_protect_socket(fd)) { + pr_error("error protecting socket"); + goto error; + } +#endif + return fd; error: diff --git a/src/tuntap.c b/src/tuntap.c index e35858e..2656486 100644 --- a/src/tuntap.c +++ b/src/tuntap.c @@ -2,6 +2,10 @@ Copyright (c) 2012-2014, Matthias Schiffer All rights reserved. + Android port contributor: + Copyright (c) 2014-2015, Haofeng "Rick" Lei + All rights reserved. + Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -35,7 +39,6 @@ #include #include - #ifdef __linux__ #include @@ -60,16 +63,15 @@ static const bool multiaf_tun = false; static const bool multiaf_tun = true; #endif +#ifdef __linux__ -#if defined(__linux__) +/** Opens the TUN/TAP device helper shared by Android and Linux targets */ +static void tuntap_open_linux(const char * dev_name) { + pr_debug("initializing tun/tap device..."); -/** Opens the TUN/TAP device */ -void fastd_tuntap_open(void) { struct ifreq ifr = {}; - pr_debug("initializing tun/tap device..."); - - if ((ctx.tunfd = open("/dev/net/tun", O_RDWR|O_NONBLOCK)) < 0) + if ((ctx.tunfd = open(dev_name, O_RDWR|O_NONBLOCK)) < 0) exit_errno("could not open tun/tap device file"); if (conf.ifname) @@ -115,6 +117,40 @@ void fastd_tuntap_open(void) { pr_debug("tun/tap device initialized."); } +#endif + +#if defined(__ANDROID__) + +/** Opens the TUN/TAP device */ +void fastd_tuntap_open(void) { + pr_debug("initializing tun device..."); + + if (conf.android_integration) { + if (conf.mode != MODE_TUN) { + exit_error("Non root Android supports only TUN mode"); + } + + pr_debug("using android TUN fd"); + ctx.tunfd = fastd_android_receive_tunfd(); + + fastd_android_send_pid(); + + fastd_poll_set_fd_tuntap(); + + pr_debug("tun device initialized."); + } else { + /* this requires root on Android */ + tuntap_open_linux("/dev/tun"); + } +} + +#elif defined(__linux__) + +/** Opens the TUN/TAP device */ +void fastd_tuntap_open(void) { + tuntap_open_linux("/dev/net/tun"); +} + #elif defined(__FreeBSD__) || defined(__OpenBSD__) /** Sets the MTU of the TUN/TAP device */ -- cgit v1.2.3