├── .gitignore ├── build.gradle.kts ├── gradle.properties ├── gradle ├── libs.versions.toml └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── module ├── .gitignore ├── build.gradle.kts ├── src │ └── main │ │ ├── AndroidManifest.xml │ │ └── cpp │ │ ├── CMakeLists.txt │ │ ├── hook.cpp │ │ ├── socket_utils.cpp │ │ ├── socket_utils.h │ │ ├── utils.h │ │ └── zygisk_next_api.h └── template │ ├── META-INF │ └── com │ │ └── google │ │ └── android │ │ ├── update-binary │ │ └── updater-script │ ├── customize.sh │ ├── module.prop │ ├── post-fs-data.sh │ ├── sepolicy.rule │ ├── service.sh │ ├── verify.sh │ └── zn_modules.txt └── settings.gradle.kts /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea 5 | .DS_Store 6 | /build 7 | /captures 8 | .externalNativeBuild 9 | .cxx 10 | local.properties 11 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | import com.android.build.gradle.AppExtension 2 | import java.io.ByteArrayOutputStream 3 | 4 | plugins { 5 | alias(libs.plugins.agp.app) apply false 6 | } 7 | 8 | fun String.execute(currentWorkingDir: File = file("./")): String { 9 | val byteOut = ByteArrayOutputStream() 10 | project.exec { 11 | workingDir = currentWorkingDir 12 | commandLine = split("\\s".toRegex()) 13 | standardOutput = byteOut 14 | } 15 | return String(byteOut.toByteArray()).trim() 16 | } 17 | 18 | val gitCommitCount = "git rev-list HEAD --count".execute().toInt() 19 | val gitCommitHash = "git rev-parse --verify --short HEAD".execute() 20 | 21 | // also the soname 22 | val moduleId by extra("hostsredirect") 23 | val moduleName by extra("Hosts Redirect") 24 | val verName by extra("v1") 25 | val verCode by extra(gitCommitCount) 26 | val commitHash by extra(gitCommitHash) 27 | val abiList by extra(listOf("arm64-v8a")) 28 | 29 | val androidMinSdkVersion by extra(29) 30 | val androidTargetSdkVersion by extra(35) 31 | val androidCompileSdkVersion by extra(35) 32 | val androidBuildToolsVersion by extra("35.0.0") 33 | val androidCompileNdkVersion by extra("27.1.12297006") 34 | val androidSourceCompatibility by extra(JavaVersion.VERSION_21) 35 | val androidTargetCompatibility by extra(JavaVersion.VERSION_21) 36 | 37 | tasks.register("Delete", Delete::class) { 38 | delete(rootProject.buildDir) 39 | } 40 | 41 | fun Project.configureBaseExtension() { 42 | extensions.findByType(AppExtension::class)?.run { 43 | namespace = "io.github.aviraxp.hostsredirect" 44 | compileSdkVersion(androidCompileSdkVersion) 45 | ndkVersion = androidCompileNdkVersion 46 | buildToolsVersion = androidBuildToolsVersion 47 | 48 | defaultConfig { 49 | minSdk = androidMinSdkVersion 50 | } 51 | 52 | compileOptions { 53 | sourceCompatibility = androidSourceCompatibility 54 | targetCompatibility = androidTargetCompatibility 55 | } 56 | } 57 | 58 | } 59 | 60 | subprojects { 61 | plugins.withId("com.android.application") { 62 | configureBaseExtension() 63 | } 64 | plugins.withType(JavaPlugin::class.java) { 65 | extensions.configure(JavaPluginExtension::class.java) { 66 | sourceCompatibility = androidSourceCompatibility 67 | targetCompatibility = androidTargetCompatibility 68 | } 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | # AndroidX package structure to make it clearer which packages are bundled with the 15 | # Android operating system, and which are packaged with your app"s APK 16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 17 | android.useAndroidX=true 18 | # Automatically convert third-party libraries to use AndroidX 19 | android.enableJetifier=true 20 | -------------------------------------------------------------------------------- /gradle/libs.versions.toml: -------------------------------------------------------------------------------- 1 | [versions] 2 | agp = "8.8.0" 3 | 4 | [plugins] 5 | agp-app = { id = "com.android.application", version.ref = "agp" } 6 | 7 | [libraries] 8 | cxx = { module = "org.lsposed.libcxx:libcxx", version = "27.0.12077973" } 9 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aviraxp/ZN-hostsredirect/b2c5030afe92a61a6664f2d13266fa7548ca74b4/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sun Dec 31 12:28:57 CST 2023 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-bin.zip 5 | zipStoreBase=GRADLE_USER_HOME 6 | zipStorePath=wrapper/dists 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # 4 | # Copyright 2015 the original author or authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | ## 21 | ## Gradle start up script for UN*X 22 | ## 23 | ############################################################################## 24 | 25 | # Attempt to set APP_HOME 26 | # Resolve links: $0 may be a link 27 | PRG="$0" 28 | # Need this for relative symlinks. 29 | while [ -h "$PRG" ] ; do 30 | ls=`ls -ld "$PRG"` 31 | link=`expr "$ls" : '.*-> \(.*\)$'` 32 | if expr "$link" : '/.*' > /dev/null; then 33 | PRG="$link" 34 | else 35 | PRG=`dirname "$PRG"`"/$link" 36 | fi 37 | done 38 | SAVED="`pwd`" 39 | cd "`dirname \"$PRG\"`/" >/dev/null 40 | APP_HOME="`pwd -P`" 41 | cd "$SAVED" >/dev/null 42 | 43 | APP_NAME="Gradle" 44 | APP_BASE_NAME=`basename "$0"` 45 | 46 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 47 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 48 | 49 | # Use the maximum available, or set MAX_FD != -1 to use that value. 50 | MAX_FD="maximum" 51 | 52 | warn () { 53 | echo "$*" 54 | } 55 | 56 | die () { 57 | echo 58 | echo "$*" 59 | echo 60 | exit 1 61 | } 62 | 63 | # OS specific support (must be 'true' or 'false'). 64 | cygwin=false 65 | msys=false 66 | darwin=false 67 | nonstop=false 68 | case "`uname`" in 69 | CYGWIN* ) 70 | cygwin=true 71 | ;; 72 | Darwin* ) 73 | darwin=true 74 | ;; 75 | MINGW* ) 76 | msys=true 77 | ;; 78 | NONSTOP* ) 79 | nonstop=true 80 | ;; 81 | esac 82 | 83 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 84 | 85 | 86 | # Determine the Java command to use to start the JVM. 87 | if [ -n "$JAVA_HOME" ] ; then 88 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 89 | # IBM's JDK on AIX uses strange locations for the executables 90 | JAVACMD="$JAVA_HOME/jre/sh/java" 91 | else 92 | JAVACMD="$JAVA_HOME/bin/java" 93 | fi 94 | if [ ! -x "$JAVACMD" ] ; then 95 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 96 | 97 | Please set the JAVA_HOME variable in your environment to match the 98 | location of your Java installation." 99 | fi 100 | else 101 | JAVACMD="java" 102 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 103 | 104 | Please set the JAVA_HOME variable in your environment to match the 105 | location of your Java installation." 106 | fi 107 | 108 | # Increase the maximum file descriptors if we can. 109 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 110 | MAX_FD_LIMIT=`ulimit -H -n` 111 | if [ $? -eq 0 ] ; then 112 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 113 | MAX_FD="$MAX_FD_LIMIT" 114 | fi 115 | ulimit -n $MAX_FD 116 | if [ $? -ne 0 ] ; then 117 | warn "Could not set maximum file descriptor limit: $MAX_FD" 118 | fi 119 | else 120 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 121 | fi 122 | fi 123 | 124 | # For Darwin, add options to specify how the application appears in the dock 125 | if $darwin; then 126 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 127 | fi 128 | 129 | # For Cygwin or MSYS, switch paths to Windows format before running java 130 | if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then 131 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 132 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 133 | 134 | JAVACMD=`cygpath --unix "$JAVACMD"` 135 | 136 | # We build the pattern for arguments to be converted via cygpath 137 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 138 | SEP="" 139 | for dir in $ROOTDIRSRAW ; do 140 | ROOTDIRS="$ROOTDIRS$SEP$dir" 141 | SEP="|" 142 | done 143 | OURCYGPATTERN="(^($ROOTDIRS))" 144 | # Add a user-defined pattern to the cygpath arguments 145 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 146 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 147 | fi 148 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 149 | i=0 150 | for arg in "$@" ; do 151 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 152 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 153 | 154 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 155 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 156 | else 157 | eval `echo args$i`="\"$arg\"" 158 | fi 159 | i=`expr $i + 1` 160 | done 161 | case $i in 162 | 0) set -- ;; 163 | 1) set -- "$args0" ;; 164 | 2) set -- "$args0" "$args1" ;; 165 | 3) set -- "$args0" "$args1" "$args2" ;; 166 | 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 167 | 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 168 | 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 169 | 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 170 | 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 171 | 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 172 | esac 173 | fi 174 | 175 | # Escape application args 176 | save () { 177 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 178 | echo " " 179 | } 180 | APP_ARGS=`save "$@"` 181 | 182 | # Collect all arguments for the java command, following the shell quoting and substitution rules 183 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 184 | 185 | exec "$JAVACMD" "$@" 186 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /module/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | /libs 3 | /obj 4 | /release 5 | -------------------------------------------------------------------------------- /module/build.gradle.kts: -------------------------------------------------------------------------------- 1 | import android.databinding.tool.ext.capitalizeUS 2 | import org.apache.tools.ant.filters.FixCrLfFilter 3 | import org.apache.tools.ant.filters.ReplaceTokens 4 | import java.security.MessageDigest 5 | 6 | plugins { 7 | alias(libs.plugins.agp.app) 8 | } 9 | 10 | val moduleId: String by rootProject.extra 11 | val moduleName: String by rootProject.extra 12 | val verCode: Int by rootProject.extra 13 | val verName: String by rootProject.extra 14 | val commitHash: String by rootProject.extra 15 | val abiList: List by rootProject.extra 16 | val androidMinSdkVersion: Int by rootProject.extra 17 | 18 | android { 19 | buildFeatures { 20 | prefab = true 21 | } 22 | defaultConfig { 23 | ndk { 24 | abiFilters.addAll(abiList) 25 | } 26 | externalNativeBuild { 27 | cmake { 28 | cppFlags("-std=c++20") 29 | arguments( 30 | "-DANDROID_STL=none", 31 | "-DMODULE_NAME=$moduleId" 32 | ) 33 | } 34 | } 35 | } 36 | externalNativeBuild { 37 | /* 38 | ndkBuild { 39 | path("src/main/cpp/Android.mk") 40 | } 41 | */ 42 | cmake { 43 | path("src/main/cpp/CMakeLists.txt") 44 | } 45 | } 46 | } 47 | 48 | val abiMap = mapOf( 49 | "arm64-v8a" to "arm64", 50 | "armeabi-v7a" to "arm", 51 | "x86" to "x86", 52 | "x86_64" to "x64" 53 | ) 54 | 55 | androidComponents.onVariants { variant -> 56 | afterEvaluate { 57 | val variantLowered = variant.name.lowercase() 58 | val variantCapped = variant.name.capitalizeUS() 59 | val buildTypeLowered = variant.buildType?.lowercase() 60 | val supportedAbis = abiList.joinToString(" ") { 61 | abiMap[it] ?: error("unsupported abi $it") 62 | } 63 | 64 | val moduleDir = layout.buildDirectory.file("outputs/module/$variantLowered") 65 | val zipFileName = 66 | "$moduleName-$verName-$verCode-$commitHash-$buildTypeLowered.zip".replace(' ', '-') 67 | 68 | val prepareModuleFilesTask = task("prepareModuleFiles$variantCapped") { 69 | group = "module" 70 | dependsOn("assemble$variantCapped") 71 | into(moduleDir) 72 | from(rootProject.layout.projectDirectory.file("README.md")) 73 | from(layout.projectDirectory.file("template")) { 74 | exclude("module.prop", "customize.sh", "post-fs-data.sh", "service.sh", "zn_modules.txt") 75 | filter("eol" to FixCrLfFilter.CrLf.newInstance("lf")) 76 | } 77 | from(layout.projectDirectory.file("template")) { 78 | include("module.prop", "zn_modules.txt") 79 | expand( 80 | "moduleId" to moduleId, 81 | "moduleName" to moduleName, 82 | "versionName" to "$verName ($verCode-$commitHash-$variantLowered)", 83 | "versionCode" to verCode 84 | ) 85 | } 86 | from(layout.projectDirectory.file("template")) { 87 | include("customize.sh", "post-fs-data.sh", "service.sh") 88 | val tokens = mapOf( 89 | "DEBUG" to if (buildTypeLowered == "debug") "true" else "false", 90 | "SONAME" to moduleId, 91 | "SUPPORTED_ABIS" to supportedAbis, 92 | "MIN_SDK" to androidMinSdkVersion.toString() 93 | ) 94 | filter("tokens" to tokens) 95 | filter("eol" to FixCrLfFilter.CrLf.newInstance("lf")) 96 | } 97 | abiList.forEach { abi -> 98 | val arch = abiMap[abi] 99 | from(layout.buildDirectory.file("intermediates/stripped_native_libs/$variantLowered/strip${variantCapped}DebugSymbols/out/lib/$abi")) { 100 | into("lib/$arch") 101 | } 102 | } 103 | 104 | doLast { 105 | fileTree(moduleDir).visit { 106 | if (isDirectory) return@visit 107 | val md = MessageDigest.getInstance("SHA-256") 108 | file.forEachBlock(4096) { bytes, size -> 109 | md.update(bytes, 0, size) 110 | } 111 | file(file.path + ".sha256").writeText( 112 | org.apache.commons.codec.binary.Hex.encodeHexString( 113 | md.digest() 114 | ) 115 | ) 116 | } 117 | } 118 | } 119 | 120 | val zipTask = task("zip$variantCapped") { 121 | group = "module" 122 | dependsOn(prepareModuleFilesTask) 123 | archiveFileName.set(zipFileName) 124 | destinationDirectory.set(layout.projectDirectory.file("release").asFile) 125 | from(moduleDir) 126 | } 127 | 128 | val pushTask = task("push$variantCapped") { 129 | group = "module" 130 | dependsOn(zipTask) 131 | commandLine("adb", "push", zipTask.outputs.files.singleFile.path, "/data/local/tmp") 132 | } 133 | 134 | val installKsuTask = task("installKsu$variantCapped") { 135 | group = "module" 136 | dependsOn(pushTask) 137 | commandLine( 138 | "adb", "shell", "su", "-c", 139 | "/data/adb/ksud module install /data/local/tmp/$zipFileName" 140 | ) 141 | } 142 | 143 | val installMagiskTask = task("installMagisk$variantCapped") { 144 | group = "module" 145 | dependsOn(pushTask) 146 | commandLine( 147 | "adb", 148 | "shell", 149 | "su", 150 | "-M", 151 | "-c", 152 | "magisk --install-module /data/local/tmp/$zipFileName" 153 | ) 154 | } 155 | 156 | task("installKsuAndReboot$variantCapped") { 157 | group = "module" 158 | dependsOn(installKsuTask) 159 | commandLine("adb", "reboot") 160 | } 161 | 162 | task("installMagiskAndReboot$variantCapped") { 163 | group = "module" 164 | dependsOn(installMagiskTask) 165 | commandLine("adb", "reboot") 166 | } 167 | } 168 | } 169 | 170 | dependencies { 171 | implementation(libs.cxx) 172 | } 173 | -------------------------------------------------------------------------------- /module/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /module/src/main/cpp/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.22.1) 2 | project(hostsredirect) 3 | 4 | set(CXX_FLAGS "${CXX_FLAGS} -fno-exceptions -fno-rtti -fvisibility=hidden -fvisibility-inlines-hidden") 5 | 6 | set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CXX_FLAGS}") 7 | 8 | find_package(cxx REQUIRED CONFIG) 9 | link_libraries(cxx::cxx) 10 | 11 | add_library(${MODULE_NAME} SHARED hook.cpp socket_utils.cpp) 12 | target_link_libraries(${MODULE_NAME} log) 13 | -------------------------------------------------------------------------------- /module/src/main/cpp/hook.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include "zygisk_next_api.h" 9 | #include "socket_utils.h" 10 | 11 | #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, "hostsredirect", __VA_ARGS__) 12 | #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, "hostsredirect", __VA_ARGS__) 13 | #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, "hostsredirect", __VA_ARGS__) 14 | 15 | static ZygiskNextAPI api_table; 16 | void* handle; 17 | 18 | // backup of old __openat function 19 | static int (*old_openat)(int fd, const char* pathname, int flag, int mode) = nullptr; 20 | // our replacement for __openat function 21 | static int my_openat(int fd, const char* pathname, int flag, int mode) { 22 | // https://android.googlesource.com/platform/system/netd/+/55864199479074e8fb3d285220280ccda270fe7d 23 | // https://github.com/LineageOS/android_system_netd/commit/f92bf2804098512142cc8d7934ed9d5031b0532c 24 | if (strcmp(pathname, "/system/etc/hosts") != 0) { 25 | return old_openat(fd, pathname, flag, mode); 26 | } 27 | 28 | auto cp_fd = api_table.connectCompanion(handle); 29 | if (cp_fd < 0) { 30 | return old_openat(fd, pathname, flag, mode); 31 | } 32 | 33 | auto file_fd = socket_utils::recv_fd(cp_fd); 34 | close(cp_fd); 35 | 36 | if (file_fd < 0) { 37 | return old_openat(fd, pathname, flag, mode); 38 | } 39 | 40 | return file_fd; 41 | } 42 | 43 | // this function will be called after all of the main executable's needed libraries are loaded 44 | // and before the entry of the main executable called 45 | void onModuleLoaded(void* self_handle, const struct ZygiskNextAPI* api) { 46 | // You need to copy the api table if you want to use it after this callback finished 47 | memcpy(&api_table, api, sizeof(struct ZygiskNextAPI)); 48 | handle = self_handle; 49 | 50 | auto resolver = api_table.newSymbolResolver("libc.so", nullptr); 51 | if (!resolver) { 52 | LOGE("create resolver failed"); 53 | return; 54 | } 55 | 56 | size_t sz; 57 | auto addr = api_table.symbolLookup(resolver, "__openat", false, &sz); 58 | 59 | api_table.freeSymbolResolver(resolver); 60 | 61 | if (addr == nullptr) { 62 | LOGE("failed to find __openat"); 63 | return; 64 | } 65 | 66 | // inline hook netd's openat function 67 | if (api_table.inlineHook(addr, (void *) my_openat, (void**) &old_openat) == ZN_SUCCESS) { 68 | LOGI("inline hook success %p", old_openat); 69 | } else { 70 | LOGE("inline hook failed"); 71 | } 72 | } 73 | 74 | // declaration of the zygisk next module 75 | __attribute__((visibility("default"), unused)) 76 | struct ZygiskNextModule zn_module = { 77 | .target_api_version = ZYGISK_NEXT_API_VERSION_1, 78 | .onModuleLoaded = onModuleLoaded, 79 | }; 80 | 81 | static void onCompanionLoaded() { 82 | LOGI("companion loaded"); 83 | } 84 | 85 | static void onModuleConnected(int fd) { 86 | auto hosts = "/data/adb/hostsredirect/hosts"; 87 | struct stat st{}; 88 | if (stat(hosts, &st) < 0) { 89 | LOGD("no hosts file found"); 90 | close(fd); 91 | return; 92 | } 93 | 94 | // netd needs to access hosts file socket 95 | auto system_file = "u:object_r:system_file:s0"; 96 | syscall(__NR_setxattr, hosts, XATTR_NAME_SELINUX, system_file, strlen(system_file) + 1, 0); 97 | 98 | auto hosts_fd = open(hosts, O_RDONLY | O_CLOEXEC); 99 | if (hosts_fd < 0) { 100 | LOGD("failed to open hosts file"); 101 | close(fd); 102 | return; 103 | } 104 | socket_utils::send_fd(fd, hosts_fd); 105 | close(hosts_fd); 106 | // need to be closed unconditionally 107 | close(fd); 108 | } 109 | 110 | __attribute__((visibility("default"), unused)) 111 | struct ZygiskNextCompanionModule zn_companion_module = { 112 | .target_api_version = ZYGISK_NEXT_API_VERSION_1, 113 | .onCompanionLoaded = onCompanionLoaded, 114 | .onModuleConnected = onModuleConnected, 115 | }; 116 | -------------------------------------------------------------------------------- /module/src/main/cpp/socket_utils.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #include "utils.h" 8 | #include "socket_utils.h" 9 | 10 | namespace socket_utils { 11 | constexpr auto kMaxStringSize = 4096; 12 | 13 | bool get_client_cred(int fd, sock_cred &cred) { 14 | socklen_t len = sizeof(ucred); 15 | if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &cred, &len) != 0) { 16 | return false; 17 | } 18 | char buf[4096]; 19 | len = sizeof(buf); 20 | if (getsockopt(fd, SOL_SOCKET, SO_PEERSEC, buf, &len) != 0) { 21 | len = 0; 22 | } 23 | buf[len] = '\0'; 24 | cred.context = buf; 25 | return true; 26 | } 27 | 28 | ssize_t xread(int fd, void* buf, size_t count) { 29 | size_t read_sz = 0; 30 | ssize_t ret; 31 | do { 32 | ret = read(fd, (std::byte*) buf + read_sz, count - read_sz); 33 | if (ret < 0) { 34 | if (errno == EINTR) continue; 35 | return ret; 36 | } 37 | read_sz += ret; 38 | } while (read_sz != count && ret != 0); 39 | if (read_sz != count) { 40 | errno = EIO; 41 | } 42 | return read_sz; 43 | } 44 | 45 | size_t xwrite(int fd, const void* buf, size_t count) { 46 | size_t write_sz = 0; 47 | ssize_t ret; 48 | do { 49 | ret = write(fd, (std::byte*) buf + write_sz, count - write_sz); 50 | if (ret < 0) { 51 | if (errno == EINTR) continue; 52 | return write_sz; 53 | } 54 | write_sz += ret; 55 | } while (write_sz != count && ret != 0); 56 | if (write_sz != count) { 57 | errno = EIO; 58 | } 59 | return write_sz; 60 | } 61 | 62 | ssize_t xrecvmsg(int sockfd, struct msghdr* msg, int flags) { 63 | int rec = recvmsg(sockfd, msg, flags); 64 | return rec; 65 | } 66 | 67 | ssize_t xsendmsg(int sockfd, struct msghdr* msg, int flags) { 68 | int rec = sendmsg(sockfd, msg, flags); 69 | return rec; 70 | } 71 | 72 | template 73 | inline T read_exact_or(int fd, T fail) { 74 | T res; 75 | return sizeof(T) == xread(fd, &res, sizeof(T)) ? res : fail; 76 | } 77 | 78 | template 79 | inline bool write_exact(int fd, T val) { 80 | return sizeof(T) == xwrite(fd, &val, sizeof(T)); 81 | } 82 | 83 | uint8_t read_u8(int fd) { 84 | return read_exact_or(fd, -1); 85 | } 86 | 87 | uint32_t read_u32(int fd) { 88 | return read_exact_or(fd, -1); 89 | } 90 | 91 | int32_t read_i32(int fd) { 92 | return read_exact_or(fd, -1); 93 | } 94 | 95 | std::string read_string(int fd) { 96 | auto len = read_i32(fd); 97 | if (len > kMaxStringSize) { 98 | errno = E2BIG; 99 | return ""; 100 | } else if (len <= 0) return ""; 101 | char buf[len + 1]; 102 | buf[len] = '\0'; 103 | xread(fd, buf, len); 104 | return buf; 105 | } 106 | 107 | bool write_u8(int fd, uint8_t val) { 108 | return write_exact(fd, val); 109 | } 110 | 111 | bool write_u32(int fd, uint32_t val) { 112 | return write_exact(fd, val); 113 | } 114 | 115 | bool write_u64(int fd, uint64_t val) { 116 | return write_exact(fd, val); 117 | } 118 | 119 | bool write_i32(int fd, int32_t val) { 120 | return write_exact(fd, val); 121 | } 122 | 123 | bool write_string(int fd, std::string_view str) { 124 | if (str.size() > kMaxStringSize) { 125 | errno = E2BIG; 126 | return write_i32(fd, 0); 127 | } 128 | return write_i32(fd, str.size()) && (str.empty() || str.size() == xwrite(fd, str.data(), str.size())); 129 | } 130 | 131 | bool set_sockcreate_con(const char* con) { 132 | auto sz = static_cast(strlen(con) + 1); 133 | UniqueFd fd = open("/proc/thread-self/attr/sockcreate", O_WRONLY | O_CLOEXEC); 134 | if (fd == -1 || write(fd, con, sz) != sz) { 135 | char buf[128]; 136 | snprintf(buf, sizeof(buf), "/proc/%d/attr/sockcreate", gettid()); 137 | fd = open(buf, O_WRONLY | O_CLOEXEC); 138 | if (fd == -1 || write(fd, con, sz) != sz) { 139 | return false; 140 | } 141 | } 142 | return true; 143 | } 144 | 145 | static int send_fds(int sockfd, void *cmsgbuf, size_t bufsz, const int *fds, int cnt) { 146 | iovec iov = { 147 | .iov_base = &cnt, 148 | .iov_len = sizeof(cnt), 149 | }; 150 | msghdr msg = { 151 | .msg_iov = &iov, 152 | .msg_iovlen = 1, 153 | }; 154 | 155 | if (cnt) { 156 | msg.msg_control = cmsgbuf; 157 | msg.msg_controllen = bufsz; 158 | cmsghdr *cmsg = CMSG_FIRSTHDR(&msg); 159 | cmsg->cmsg_len = CMSG_LEN(sizeof(int) * cnt); 160 | cmsg->cmsg_level = SOL_SOCKET; 161 | cmsg->cmsg_type = SCM_RIGHTS; 162 | 163 | memcpy(CMSG_DATA(cmsg), fds, sizeof(int) * cnt); 164 | } 165 | 166 | return xsendmsg(sockfd, &msg, 0); 167 | } 168 | 169 | int send_fds(int sockfd, const int *fds, int cnt) { 170 | if (cnt == 0) { 171 | return send_fds(sockfd, nullptr, 0, nullptr, 0); 172 | } 173 | std::vector cmsgbuf; 174 | cmsgbuf.resize(CMSG_SPACE(sizeof(int) * cnt)); 175 | return send_fds(sockfd, cmsgbuf.data(), cmsgbuf.size(), fds, cnt); 176 | } 177 | 178 | int send_fd(int sockfd, int fd) { 179 | if (fd < 0) { 180 | return send_fds(sockfd, nullptr, 0, nullptr, 0); 181 | } 182 | char cmsgbuf[CMSG_SPACE(sizeof(int))]; 183 | return send_fds(sockfd, cmsgbuf, sizeof(cmsgbuf), &fd, 1); 184 | } 185 | 186 | static void *recv_fds(int sockfd, char *cmsgbuf, size_t bufsz, int cnt) { 187 | iovec iov = { 188 | .iov_base = &cnt, 189 | .iov_len = sizeof(cnt), 190 | }; 191 | msghdr msg = { 192 | .msg_iov = &iov, 193 | .msg_iovlen = 1, 194 | .msg_control = cmsgbuf, 195 | .msg_controllen = bufsz 196 | }; 197 | 198 | xrecvmsg(sockfd, &msg, MSG_WAITALL); 199 | if (msg.msg_controllen != bufsz) { 200 | return nullptr; 201 | } 202 | 203 | cmsghdr *cmsg = CMSG_FIRSTHDR(&msg); 204 | if (cmsg == nullptr) { 205 | return nullptr; 206 | } 207 | if (cmsg->cmsg_len != CMSG_LEN(sizeof(int) * cnt)) { 208 | return nullptr; 209 | } 210 | if (cmsg->cmsg_level != SOL_SOCKET) { 211 | return nullptr; 212 | } 213 | if (cmsg->cmsg_type != SCM_RIGHTS) { 214 | return nullptr; 215 | } 216 | 217 | return CMSG_DATA(cmsg); 218 | } 219 | 220 | std::vector recv_fds(int sockfd) { 221 | std::vector results; 222 | 223 | // Peek fd count to allocate proper buffer 224 | int cnt; 225 | recv(sockfd, &cnt, sizeof(cnt), MSG_PEEK); 226 | if (cnt == 0) { 227 | // Consume data 228 | recv(sockfd, &cnt, sizeof(cnt), MSG_WAITALL); 229 | return results; 230 | } 231 | 232 | std::vector cmsgbuf; 233 | cmsgbuf.resize(CMSG_SPACE(sizeof(int) * cnt)); 234 | 235 | void *data = recv_fds(sockfd, cmsgbuf.data(), cmsgbuf.size(), cnt); 236 | if (data == nullptr) 237 | return results; 238 | 239 | results.resize(cnt); 240 | memcpy(results.data(), data, sizeof(int) * cnt); 241 | 242 | return results; 243 | } 244 | 245 | int recv_fd(int sockfd) { 246 | // Peek fd count 247 | int cnt; 248 | recv(sockfd, &cnt, sizeof(cnt), MSG_PEEK); 249 | if (cnt == 0) { 250 | // Consume data 251 | recv(sockfd, &cnt, sizeof(cnt), MSG_WAITALL); 252 | return -1; 253 | } 254 | 255 | char cmsgbuf[CMSG_SPACE(sizeof(int))]; 256 | 257 | void *data = recv_fds(sockfd, cmsgbuf, sizeof(cmsgbuf), 1); 258 | if (data == nullptr) 259 | return -1; 260 | 261 | int result; 262 | memcpy(&result, data, sizeof(int)); 263 | return result; 264 | } 265 | 266 | bool check_unix_socket(int fd, bool block) { 267 | // Make sure the socket is still valid 268 | pollfd pfd = { fd, POLLIN, 0 }; 269 | TEMP_FAILURE_RETRY(poll(&pfd, 1, block ? -1 : 0)); 270 | if ((pfd.revents & ~POLLIN) != 0) { 271 | // Any revent means error 272 | close(fd); 273 | return false; 274 | } 275 | return true; 276 | } 277 | 278 | bool clear_cloexec(int fd) { 279 | auto flags = fcntl(fd, F_GETFD); 280 | if (flags == -1) { 281 | return false; 282 | } 283 | if (fcntl(fd, F_SETFD, flags & ~FD_CLOEXEC) == -1) { 284 | return false; 285 | } 286 | return true; 287 | } 288 | } -------------------------------------------------------------------------------- /module/src/main/cpp/socket_utils.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | 5 | #include 6 | #include 7 | #include 8 | 9 | namespace socket_utils { 10 | struct sock_cred : ucred { 11 | std::string context; 12 | }; 13 | 14 | bool get_client_cred(int fd, sock_cred &cred); 15 | 16 | uint8_t read_u8(int fd); 17 | uint32_t read_u32(int fd); 18 | int32_t read_i32(int fd); 19 | std::string read_string(int fd); 20 | 21 | bool write_u8(int fd, uint8_t val); 22 | bool write_u32(int fd, uint32_t val); 23 | bool write_u64(int fd, uint64_t val); 24 | bool write_i32(int fd, int32_t val); 25 | bool write_string(int fd, std::string_view str); 26 | 27 | bool set_sockcreate_con(const char* con); 28 | 29 | int send_fds(int sockfd, const int *fds, int cnt); 30 | int send_fd(int sockfd, int fd); 31 | 32 | std::vector recv_fds(int sockfd); 33 | int recv_fd(int sockfd); 34 | 35 | bool check_unix_socket(int fd, bool block); 36 | 37 | bool clear_cloexec(int fd); 38 | } 39 | -------------------------------------------------------------------------------- /module/src/main/cpp/utils.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #if defined(__LP64__) 8 | # define LP_SELECT(lp32, lp64) lp64 9 | #else 10 | # define LP_SELECT(lp32, lp64) lp32 11 | #endif 12 | 13 | class UniqueFd { 14 | using Fd = int; 15 | public: 16 | UniqueFd() = default; 17 | 18 | inline UniqueFd(Fd fd) : fd_(fd) {} 19 | 20 | inline ~UniqueFd() { if (fd_ >= 0) close(fd_); } 21 | 22 | // Disallow copy 23 | inline UniqueFd(const UniqueFd&) = delete; 24 | 25 | inline UniqueFd& operator=(const UniqueFd&) = delete; 26 | 27 | // Allow move 28 | inline UniqueFd(UniqueFd&& other) { std::swap(fd_, other.fd_); } 29 | 30 | inline UniqueFd& operator=(UniqueFd&& other) { 31 | std::swap(fd_, other.fd_); 32 | return *this; 33 | } 34 | 35 | inline void drop() { 36 | close(fd_); 37 | fd_ = -1; 38 | } 39 | 40 | inline int into_fd() { 41 | int r = -1; 42 | std::swap(r, fd_); 43 | return r; 44 | } 45 | 46 | inline int as_fd() { 47 | return fd_; 48 | } 49 | 50 | // Implict cast to Fd 51 | inline operator const Fd&() const { return fd_; } 52 | 53 | private: 54 | Fd fd_ = -1; 55 | }; 56 | -------------------------------------------------------------------------------- /module/src/main/cpp/zygisk_next_api.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #ifdef __cplusplus 6 | extern "C" { 7 | #endif 8 | 9 | #define ZYGISK_NEXT_API_VERSION_1 3 10 | 11 | #define ZN_SUCCESS 0 12 | #define ZN_FAILED 1 13 | 14 | struct ZnSymbolResolver; 15 | 16 | struct ZygiskNextAPI { 17 | // Hook API 18 | 19 | // Do plt hook at symbol specified by the param `symbol` of library specified by the param `base_addr` 20 | // The plt address of `symbol` in the library will be replaced with hook_handler, and 21 | // its original value will be put to the address specified by `origianl` (can be null). 22 | // You can use this api to do caller-oriented hook 23 | // If you want to unhook, please call this function with hook_handler = original 24 | // If hook succeed, returns ZN_SUCCESS, otherwise ZN_FAILED 25 | int (*pltHook)(void* base_addr, const char* symbol, void* hook_handler, void** original); 26 | 27 | // Do inline hook at the address specified by `target`, replace it with a new function specified 28 | // by `addr`, and the param `original` receives the address of original function. 29 | // You can use this api to achieve a global hook in current process. 30 | // In the current implementation , an address can only hook once, so the module can't hook an 31 | // address which is already hooked by an another module, except that the module unhooked it. 32 | // If hooking succeed, returns ZN_SUCCESS, otherwise ZN_FAILED 33 | int (*inlineHook)(void* target, void* addr, void** original); 34 | 35 | // Unhook the address which is formerly hooked. 36 | // If hook succeed, returns ZN_SUCCESS, otherwise ZN_FAILED 37 | int (*inlineUnhook)(void* target); 38 | 39 | // Symbol Resolver API 40 | 41 | // Obtain a new ZnSymbolResolver object 42 | // `path` is required, which specifies the path of library to resolve. It can be an absolute path 43 | // or just the file name of library, e.g. /system/lib64/libc.so or libc.so . 44 | // If `base_addr` is non-zero, it will be used as the base address of the library. 45 | // Otherwise, Zygisk Next will try to find out the base address of the specified library in this process. 46 | // If succeed, it returns a valid pointer to the symbol resolver, otherwise nullptr is returned. 47 | struct ZnSymbolResolver* (*newSymbolResolver)(const char* path, void* base_addr); 48 | 49 | // Release the ZnSymbolResolver object pointed by `resolver`. 50 | void (*freeSymbolResolver)(struct ZnSymbolResolver* resolver); 51 | 52 | // Retrieve the base address of the library of the resolver image in the process. 53 | void* (*getBaseAddress)(struct ZnSymbolResolver* resolver); 54 | 55 | // Lookup the address of symbol by name or prefix (if `prefix` is true) 56 | // If the symbol exists, the function returns its address, otherwise returns nullptr. 57 | // If `size` is not nullptr, the size of the symbol will be put to *size . 58 | // In the current implementation, gnu_debugdata resolution is supported. 59 | void* (*symbolLookup)(struct ZnSymbolResolver* resolver, const char* name, bool prefix, size_t* size); 60 | 61 | // Walk through the symbol table of the library, the callback will receive the name, the address, 62 | // and the size of each symbol. Returning false in the callback means stop the walking. 63 | void (*forEachSymbols)(struct ZnSymbolResolver* resolver, 64 | bool (*callback)(const char* name, void* addr, size_t size, void* data), 65 | void* data); 66 | 67 | // Companion API 68 | 69 | // Create a unix sock stream connection to your declared companion process. 70 | // The value of `handle` is the `self_handle` which you've received from onModuleLoaded. 71 | // On success, it returns the file descriptor refer to the socket, otherwise -1 is returned. 72 | // Please close this file descriptor by yourself. 73 | int (*connectCompanion)(void* handle); 74 | }; 75 | 76 | // Callbacks of an injected library 77 | struct ZygiskNextModule { 78 | // Please fill this with the target version of your module, e.g. ZYGISK_NEXT_API_VERSION_1 79 | int target_api_version; 80 | 81 | // This callback will be called after all needed library of the main executable are loaded, 82 | // and before the entry (i.e. `main`) of the main executable is called. 83 | void (*onModuleLoaded)(void* self_handle, const struct ZygiskNextAPI* api); 84 | }; 85 | 86 | // Callbacks of a companion library 87 | struct ZygiskNextCompanionModule { 88 | int target_api_version; 89 | 90 | void (*onCompanionLoaded)(); 91 | 92 | // This callback will be called when your Zygisk Next module is trying to establish a connection 93 | // with your companion module, i.e. `connectCompanion` is called. 94 | // The `fd` param will be a unix sock stream file descriptor. 95 | // Please close this file descriptor after use by yourself. 96 | void (*onModuleConnected)(int fd); 97 | }; 98 | 99 | // Please define your `zn_module` in your source file. 100 | extern __attribute__((visibility("default"), unused)) struct ZygiskNextModule zn_module; 101 | extern __attribute__((visibility("default"), unused)) struct ZygiskNextCompanionModule zn_companion_module; 102 | 103 | #ifdef __cplusplus 104 | } 105 | #endif 106 | -------------------------------------------------------------------------------- /module/template/META-INF/com/google/android/update-binary: -------------------------------------------------------------------------------- 1 | #!/sbin/sh 2 | 3 | ################# 4 | # Initialization 5 | ################# 6 | 7 | umask 022 8 | 9 | # echo before loading util_functions 10 | ui_print() { echo "$1"; } 11 | 12 | require_new_magisk() { 13 | ui_print "*******************************" 14 | ui_print " Please install Magisk v20.4+! " 15 | ui_print "*******************************" 16 | exit 1 17 | } 18 | 19 | ######################### 20 | # Load util_functions.sh 21 | ######################### 22 | 23 | OUTFD=$2 24 | ZIPFILE=$3 25 | 26 | mount /data 2>/dev/null 27 | 28 | [ -f /data/adb/magisk/util_functions.sh ] || require_new_magisk 29 | . /data/adb/magisk/util_functions.sh 30 | [ $MAGISK_VER_CODE -lt 20400 ] && require_new_magisk 31 | 32 | install_module 33 | exit 0 34 | -------------------------------------------------------------------------------- /module/template/META-INF/com/google/android/updater-script: -------------------------------------------------------------------------------- 1 | #MAGISK 2 | -------------------------------------------------------------------------------- /module/template/customize.sh: -------------------------------------------------------------------------------- 1 | # shellcheck disable=SC2034 2 | SKIPUNZIP=1 3 | 4 | DEBUG=@DEBUG@ 5 | SONAME=@SONAME@ 6 | SUPPORTED_ABIS="@SUPPORTED_ABIS@" 7 | MIN_SDK=@MIN_SDK@ 8 | 9 | if [ "$BOOTMODE" ] && [ "$KSU" ]; then 10 | ui_print "- Installing from KernelSU app" 11 | ui_print "- KernelSU version: $KSU_KERNEL_VER_CODE (kernel) + $KSU_VER_CODE (ksud)" 12 | if [ "$(which magisk)" ]; then 13 | ui_print "*********************************************************" 14 | ui_print "! Multiple root implementation is NOT supported!" 15 | ui_print "! Please uninstall Magisk before installing $SONAME" 16 | abort "*********************************************************" 17 | fi 18 | elif [ "$BOOTMODE" ] && [ "$MAGISK_VER_CODE" ]; then 19 | ui_print "- Installing from Magisk app" 20 | else 21 | ui_print "*********************************************************" 22 | ui_print "! Install from recovery is not supported" 23 | ui_print "! Please install from KernelSU or Magisk app" 24 | abort "*********************************************************" 25 | fi 26 | 27 | VERSION=$(grep_prop version "${TMPDIR}/module.prop") 28 | ui_print "- Installing $SONAME $VERSION" 29 | 30 | # check architecture 31 | support=false 32 | for abi in $SUPPORTED_ABIS 33 | do 34 | if [ "$ARCH" == "$abi" ]; then 35 | support=true 36 | fi 37 | done 38 | if [ "$support" == "false" ]; then 39 | abort "! Unsupported platform: $ARCH" 40 | else 41 | ui_print "- Device platform: $ARCH" 42 | fi 43 | 44 | # check android 45 | if [ "$API" -lt $MIN_SDK ]; then 46 | ui_print "! Unsupported sdk: $API" 47 | abort "! Minimal supported sdk is $MIN_SDK" 48 | else 49 | ui_print "- Device sdk: $API" 50 | fi 51 | 52 | ui_print "- Extracting verify.sh" 53 | unzip -o "$ZIPFILE" 'verify.sh' -d "$TMPDIR" >&2 54 | if [ ! -f "$TMPDIR/verify.sh" ]; then 55 | ui_print "*********************************************************" 56 | ui_print "! Unable to extract verify.sh!" 57 | ui_print "! This zip may be corrupted, please try downloading again" 58 | abort "*********************************************************" 59 | fi 60 | . "$TMPDIR/verify.sh" 61 | extract "$ZIPFILE" 'customize.sh' "$TMPDIR/.vunzip" 62 | extract "$ZIPFILE" 'verify.sh' "$TMPDIR/.vunzip" 63 | extract "$ZIPFILE" 'sepolicy.rule' "$TMPDIR" 64 | 65 | ui_print "- Extracting module files" 66 | extract "$ZIPFILE" 'module.prop' "$MODPATH" 67 | extract "$ZIPFILE" 'post-fs-data.sh' "$MODPATH" 68 | extract "$ZIPFILE" 'service.sh' "$MODPATH" 69 | extract "$ZIPFILE" 'zn_modules.txt' "$MODPATH" 70 | mv "$TMPDIR/sepolicy.rule" "$MODPATH" 71 | 72 | mkdir "$MODPATH/lib" 73 | 74 | ui_print "- Extracting $ARCH libraries" 75 | extract "$ZIPFILE" "lib/$ARCH/lib$SONAME.so" "$MODPATH/lib" true 76 | -------------------------------------------------------------------------------- /module/template/module.prop: -------------------------------------------------------------------------------- 1 | id=${moduleId} 2 | name=${moduleName} 3 | version=${versionName} 4 | versionCode=${versionCode} 5 | author=aviraxp 6 | description=Redirect hosts file to /data/adb/hostsredirect/hosts by injecting netd 7 | #updateJson= 8 | -------------------------------------------------------------------------------- /module/template/post-fs-data.sh: -------------------------------------------------------------------------------- 1 | MODDIR=${0%/*} 2 | 3 | dir="/data/adb/hostsredirect" 4 | 5 | [ ! -d "$dir" ] && mkdir -p "$dir" 6 | -------------------------------------------------------------------------------- /module/template/sepolicy.rule: -------------------------------------------------------------------------------- 1 | allow netd netd process execmem 2 | -------------------------------------------------------------------------------- /module/template/service.sh: -------------------------------------------------------------------------------- 1 | DEBUG=@DEBUG@ 2 | 3 | MODDIR=${0%/*} 4 | -------------------------------------------------------------------------------- /module/template/verify.sh: -------------------------------------------------------------------------------- 1 | TMPDIR_FOR_VERIFY="$TMPDIR/.vunzip" 2 | mkdir "$TMPDIR_FOR_VERIFY" 3 | 4 | abort_verify() { 5 | ui_print "*********************************************************" 6 | ui_print "! $1" 7 | ui_print "! This zip may be corrupted, please try downloading again" 8 | abort "*********************************************************" 9 | } 10 | 11 | # extract 12 | extract() { 13 | zip=$1 14 | file=$2 15 | dir=$3 16 | junk_paths=$4 17 | [ -z "$junk_paths" ] && junk_paths=false 18 | opts="-o" 19 | [ $junk_paths = true ] && opts="-oj" 20 | 21 | file_path="" 22 | hash_path="" 23 | if [ $junk_paths = true ]; then 24 | file_path="$dir/$(basename "$file")" 25 | hash_path="$TMPDIR_FOR_VERIFY/$(basename "$file").sha256" 26 | else 27 | file_path="$dir/$file" 28 | hash_path="$TMPDIR_FOR_VERIFY/$file.sha256" 29 | fi 30 | 31 | unzip $opts "$zip" "$file" -d "$dir" >&2 32 | [ -f "$file_path" ] || abort_verify "$file not exists" 33 | 34 | unzip $opts "$zip" "$file.sha256" -d "$TMPDIR_FOR_VERIFY" >&2 35 | [ -f "$hash_path" ] || abort_verify "$file.sha256 not exists" 36 | 37 | (echo "$(cat "$hash_path") $file_path" | sha256sum -c -s -) || abort_verify "Failed to verify $file" 38 | ui_print "- Verified $file" >&1 39 | } 40 | 41 | file="META-INF/com/google/android/update-binary" 42 | file_path="$TMPDIR_FOR_VERIFY/$file" 43 | hash_path="$file_path.sha256" 44 | unzip -o "$ZIPFILE" "META-INF/com/google/android/*" -d "$TMPDIR_FOR_VERIFY" >&2 45 | [ -f "$file_path" ] || abort_verify "$file not exists" 46 | if [ -f "$hash_path" ]; then 47 | (echo "$(cat "$hash_path") $file_path" | sha256sum -c -s -) || abort_verify "Failed to verify $file" 48 | ui_print "- Verified $file" >&1 49 | else 50 | ui_print "- Download from Magisk app" 51 | fi 52 | -------------------------------------------------------------------------------- /module/template/zn_modules.txt: -------------------------------------------------------------------------------- 1 | name=netd companion lib/lib${moduleId}.so -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | google() 4 | mavenCentral() 5 | gradlePluginPortal() 6 | } 7 | } 8 | 9 | dependencyResolutionManagement { 10 | repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) 11 | repositories { 12 | google() 13 | mavenCentral() 14 | } 15 | } 16 | 17 | rootProject.name = "hostsredirect" 18 | include( 19 | ":module" 20 | ) 21 | --------------------------------------------------------------------------------