diff --git a/Lite_version/SKRoot-Lite-(2026-3-8).apk b/Lite_version/SKRoot-Lite-(2026-3-8).apk new file mode 100644 index 00000000..5b22c440 Binary files /dev/null and b/Lite_version/SKRoot-Lite-(2026-3-8).apk differ diff --git a/Lite_version/patch_kernel_root(2026-3-11).exe b/Lite_version/patch_kernel_root(2026-3-11).exe new file mode 100644 index 00000000..e6b8c0b3 Binary files /dev/null and b/Lite_version/patch_kernel_root(2026-3-11).exe differ diff --git a/Lite_version/src/PermissionManager/.gitignore b/Lite_version/src/PermissionManager/.gitignore new file mode 100644 index 00000000..a3d88905 --- /dev/null +++ b/Lite_version/src/PermissionManager/.gitignore @@ -0,0 +1,16 @@ +*.iml +.idea +.gradle +/local.properties +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +.DS_Store +/build +/captures +.externalNativeBuild +.cxx +local.properties diff --git a/Lite_version/src/PermissionManager/app/.gitignore b/Lite_version/src/PermissionManager/app/.gitignore new file mode 100644 index 00000000..42afabfd --- /dev/null +++ b/Lite_version/src/PermissionManager/app/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/Lite_version/src/PermissionManager/app/build.gradle b/Lite_version/src/PermissionManager/app/build.gradle new file mode 100644 index 00000000..be525d13 --- /dev/null +++ b/Lite_version/src/PermissionManager/app/build.gradle @@ -0,0 +1,53 @@ +plugins { + id 'com.android.application' +} + +android { + compileSdk 31 + + defaultConfig { + applicationId "com.linux.permissionmanager" + minSdk 26 + targetSdk 31 + versionCode 1 + versionName "2026-3-8" + + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + externalNativeBuild { + cmake { + cppFlags '-std=c++17' + abiFilters "arm64-v8a" + } + } + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + externalNativeBuild { + cmake { + path file('src/main/cpp/CMakeLists.txt') + version '3.18.1' + } + } + buildFeatures { + viewBinding true + } +} + +dependencies { + + implementation 'androidx.appcompat:appcompat:1.4.1' + implementation 'com.google.android.material:material:1.5.0' + implementation 'androidx.constraintlayout:constraintlayout:2.1.3' + testImplementation 'junit:junit:4.13.2' + androidTestImplementation 'androidx.test.ext:junit:1.1.3' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' +} \ No newline at end of file diff --git a/Lite_version/src/PermissionManager/app/proguard-rules.pro b/Lite_version/src/PermissionManager/app/proguard-rules.pro new file mode 100644 index 00000000..481bb434 --- /dev/null +++ b/Lite_version/src/PermissionManager/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile \ No newline at end of file diff --git a/Lite_version/src/PermissionManager/app/src/androidTest/java/com/linux/permissionmanager/ExampleInstrumentedTest.java b/Lite_version/src/PermissionManager/app/src/androidTest/java/com/linux/permissionmanager/ExampleInstrumentedTest.java new file mode 100644 index 00000000..e63884ad --- /dev/null +++ b/Lite_version/src/PermissionManager/app/src/androidTest/java/com/linux/permissionmanager/ExampleInstrumentedTest.java @@ -0,0 +1,26 @@ +package com.linux.permissionmanager; + +import android.content.Context; + +import androidx.test.platform.app.InstrumentationRegistry; +import androidx.test.ext.junit.runners.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import static org.junit.Assert.*; + +/** + * Instrumented test, which will execute on an Android device. + * + * @see Testing documentation + */ +@RunWith(AndroidJUnit4.class) +public class ExampleInstrumentedTest { + @Test + public void useAppContext() { + // Context of the app under test. + Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); + assertEquals("com.linux.permissionmanager", appContext.getPackageName()); + } +} \ No newline at end of file diff --git a/Lite_version/src/PermissionManager/app/src/main/AndroidManifest.xml b/Lite_version/src/PermissionManager/app/src/main/AndroidManifest.xml new file mode 100644 index 00000000..ac7de7ed --- /dev/null +++ b/Lite_version/src/PermissionManager/app/src/main/AndroidManifest.xml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Lite_version/src/PermissionManager/app/src/main/cpp/CMakeLists.txt b/Lite_version/src/PermissionManager/app/src/main/cpp/CMakeLists.txt new file mode 100644 index 00000000..8bdb5531 --- /dev/null +++ b/Lite_version/src/PermissionManager/app/src/main/cpp/CMakeLists.txt @@ -0,0 +1,59 @@ +# For more information about using CMake with Android Studio, read the +# documentation: https://d.android.com/studio/projects/add-native-code.html + +# Sets the minimum version of CMake required to build the native library. + +cmake_minimum_required(VERSION 3.18.1) + +# Declares and names the project. + +project("permissionmanager") + +set(OTHER_SRC + "${CMAKE_CURRENT_SOURCE_DIR}/cJSON.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/native-lib.cpp" + ) +# Creates and names a library, sets it as either STATIC +# or SHARED, and provides the relative paths to its source code. +# You can define multiple libraries, and CMake builds them for you. +# Gradle automatically packages shared libraries with your APK. + +add_library( # Sets the name of the library. + permissionmanager + + # Sets the library as a shared library. + SHARED + + # Provides a relative path to your source file(s). + ${OTHER_SRC}) + +# Searches for a specified prebuilt library and stores the path as a +# variable. Because CMake includes system libraries in the search path by +# default, you only need to specify the name of the public NDK library +# you want to add. CMake verifies that the library exists before +# completing its build. + +find_library( # Sets the name of the path variable. + log-lib + + # Specifies the name of the NDK library that + # you want CMake to locate. + log) + +# Specifies libraries CMake should link to your target library. You +# can link multiple libraries, such as libraries you define in this +# build script, prebuilt third-party libraries, or system libraries. + +target_include_directories( + permissionmanager + PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/../../../../../testRoot/ +) + +target_link_libraries( # Specifies the target library. + permissionmanager + + # Links the target library to the log library + # included in the NDK. + ${CMAKE_CURRENT_SOURCE_DIR}/../../../../../testRoot/kernel_root_kit/lib/libkernel_root_kit_static.a + ${log-lib}) \ No newline at end of file diff --git a/Lite_version/src/PermissionManager/app/src/main/cpp/cJSON.cpp b/Lite_version/src/PermissionManager/app/src/main/cpp/cJSON.cpp new file mode 100644 index 00000000..faa3e297 --- /dev/null +++ b/Lite_version/src/PermissionManager/app/src/main/cpp/cJSON.cpp @@ -0,0 +1,3129 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +/* cJSON */ +/* JSON parser in C. */ + +/* disable warnings about old C89 functions in MSVC */ +#if !defined(_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) +#define _CRT_SECURE_NO_DEPRECATE +#endif + +#ifdef __GNUC__ +#pragma GCC visibility push(default) +#endif +#if defined(_MSC_VER) +#pragma warning (push) +/* disable warning about single line comments in system headers */ +#pragma warning (disable : 4001) +#endif + +#include +#include +#include +#include +#include +#include +#include + +#ifdef ENABLE_LOCALES +#include +#endif + +#if defined(_MSC_VER) +#pragma warning (pop) +#endif +#ifdef __GNUC__ +#pragma GCC visibility pop +#endif + +#include "cJSON.h" + +/* define our own boolean type */ +#ifdef true +#undef true +#endif +#define true ((cJSON_bool)1) + +#ifdef false +#undef false +#endif +#define false ((cJSON_bool)0) + +/* define isnan and isinf for ANSI C, if in C99 or above, isnan and isinf has been defined in math.h */ +#ifndef isinf +#define isinf(d) (isnan((d - d)) && !isnan(d)) +#endif +#ifndef isnan +#define isnan(d) (d != d) +#endif + +#ifndef NAN +#ifdef _WIN32 +#define NAN sqrt(-1.0) +#else +#define NAN 0.0/0.0 +#endif +#endif + +typedef struct { + const unsigned char *json; + size_t position; +} error; +static error global_error = { NULL, 0 }; + +CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void) +{ + return (const char*) (global_error.json + global_error.position); +} + +CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item) +{ + if (!cJSON_IsString(item)) + { + return NULL; + } + + return item->valuestring; +} + +CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item) +{ + if (!cJSON_IsNumber(item)) + { + return (double) NAN; + } + + return item->valuedouble; +} + +/* This is a safeguard to prevent copy-pasters from using incompatible C and header files */ +#if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 7) || (CJSON_VERSION_PATCH != 16) + #error cJSON.h and cJSON.c have different versions. Make sure that both have the same. +#endif + +CJSON_PUBLIC(const char*) cJSON_Version(void) +{ + static char version[15]; + sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH); + + return version; +} + +/* Case insensitive string comparison, doesn't consider two NULL pointers equal though */ +static int case_insensitive_strcmp(const unsigned char *string1, const unsigned char *string2) +{ + if ((string1 == NULL) || (string2 == NULL)) + { + return 1; + } + + if (string1 == string2) + { + return 0; + } + + for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++) + { + if (*string1 == '\0') + { + return 0; + } + } + + return tolower(*string1) - tolower(*string2); +} + +typedef struct internal_hooks +{ + void *(CJSON_CDECL *allocate)(size_t size); + void (CJSON_CDECL *deallocate)(void *pointer); + void *(CJSON_CDECL *reallocate)(void *pointer, size_t size); +} internal_hooks; + +#if defined(_MSC_VER) +/* work around MSVC error C2322: '...' address of dllimport '...' is not static */ +static void * CJSON_CDECL internal_malloc(size_t size) +{ + return malloc(size); +} +static void CJSON_CDECL internal_free(void *pointer) +{ + free(pointer); +} +static void * CJSON_CDECL internal_realloc(void *pointer, size_t size) +{ + return realloc(pointer, size); +} +#else +#define internal_malloc malloc +#define internal_free free +#define internal_realloc realloc +#endif + +/* strlen of character literals resolved at compile time */ +#define static_strlen(string_literal) (sizeof(string_literal) - sizeof("")) + +static internal_hooks global_hooks = { internal_malloc, internal_free, internal_realloc }; + +static unsigned char* cJSON_strdup(const unsigned char* string, const internal_hooks * const hooks) +{ + size_t length = 0; + unsigned char *copy = NULL; + + if (string == NULL) + { + return NULL; + } + + length = strlen((const char*)string) + sizeof(""); + copy = (unsigned char*)hooks->allocate(length); + if (copy == NULL) + { + return NULL; + } + memcpy(copy, string, length); + + return copy; +} + +CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks) +{ + if (hooks == NULL) + { + /* Reset hooks */ + global_hooks.allocate = malloc; + global_hooks.deallocate = free; + global_hooks.reallocate = realloc; + return; + } + + global_hooks.allocate = malloc; + if (hooks->malloc_fn != NULL) + { + global_hooks.allocate = hooks->malloc_fn; + } + + global_hooks.deallocate = free; + if (hooks->free_fn != NULL) + { + global_hooks.deallocate = hooks->free_fn; + } + + /* use realloc only if both free and malloc are used */ + global_hooks.reallocate = NULL; + if ((global_hooks.allocate == malloc) && (global_hooks.deallocate == free)) + { + global_hooks.reallocate = realloc; + } +} + +/* Internal constructor. */ +static cJSON *cJSON_New_Item(const internal_hooks * const hooks) +{ + cJSON* node = (cJSON*)hooks->allocate(sizeof(cJSON)); + if (node) + { + memset(node, '\0', sizeof(cJSON)); + } + + return node; +} + +/* Delete a cJSON structure. */ +CJSON_PUBLIC(void) cJSON_Delete(cJSON *item) +{ + cJSON *next = NULL; + while (item != NULL) + { + next = item->next; + if (!(item->type & cJSON_IsReference) && (item->child != NULL)) + { + cJSON_Delete(item->child); + } + if (!(item->type & cJSON_IsReference) && (item->valuestring != NULL)) + { + global_hooks.deallocate(item->valuestring); + } + if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) + { + global_hooks.deallocate(item->string); + } + global_hooks.deallocate(item); + item = next; + } +} + +/* get the decimal point character of the current locale */ +static unsigned char get_decimal_point(void) +{ +#ifdef ENABLE_LOCALES + struct lconv *lconv = localeconv(); + return (unsigned char) lconv->decimal_point[0]; +#else + return '.'; +#endif +} + +typedef struct +{ + const unsigned char *content; + size_t length; + size_t offset; + size_t depth; /* How deeply nested (in arrays/objects) is the input at the current offset. */ + internal_hooks hooks; +} parse_buffer; + +/* check if the given size is left to read in a given parse buffer (starting with 1) */ +#define can_read(buffer, size) ((buffer != NULL) && (((buffer)->offset + size) <= (buffer)->length)) +/* check if the buffer can be accessed at the given index (starting with 0) */ +#define can_access_at_index(buffer, index) ((buffer != NULL) && (((buffer)->offset + index) < (buffer)->length)) +#define cannot_access_at_index(buffer, index) (!can_access_at_index(buffer, index)) +/* get a pointer to the buffer at the position */ +#define buffer_at_offset(buffer) ((buffer)->content + (buffer)->offset) + +/* Parse the input text to generate a number, and populate the result into item. */ +static cJSON_bool parse_number(cJSON * const item, parse_buffer * const input_buffer) +{ + double number = 0; + unsigned char *after_end = NULL; + unsigned char number_c_string[64]; + unsigned char decimal_point = get_decimal_point(); + size_t i = 0; + + if ((input_buffer == NULL) || (input_buffer->content == NULL)) + { + return false; + } + + /* copy the number into a temporary buffer and replace '.' with the decimal point + * of the current locale (for strtod) + * This also takes care of '\0' not necessarily being available for marking the end of the input */ + for (i = 0; (i < (sizeof(number_c_string) - 1)) && can_access_at_index(input_buffer, i); i++) + { + switch (buffer_at_offset(input_buffer)[i]) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case '+': + case '-': + case 'e': + case 'E': + number_c_string[i] = buffer_at_offset(input_buffer)[i]; + break; + + case '.': + number_c_string[i] = decimal_point; + break; + + default: + goto loop_end; + } + } +loop_end: + number_c_string[i] = '\0'; + + number = strtod((const char*)number_c_string, (char**)&after_end); + if (number_c_string == after_end) + { + return false; /* parse_error */ + } + + item->valuedouble = number; + + /* use saturation in case of overflow */ + if (number >= INT_MAX) + { + item->valueint = INT_MAX; + } + else if (number <= (double)INT_MIN) + { + item->valueint = INT_MIN; + } + else + { + item->valueint = (int)number; + } + + item->type = cJSON_Number; + + input_buffer->offset += (size_t)(after_end - number_c_string); + return true; +} + +/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */ +CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number) +{ + if (number >= INT_MAX) + { + object->valueint = INT_MAX; + } + else if (number <= (double)INT_MIN) + { + object->valueint = INT_MIN; + } + else + { + object->valueint = (int)number; + } + + return object->valuedouble = number; +} + +CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring) +{ + char *copy = NULL; + /* if object's type is not cJSON_String or is cJSON_IsReference, it should not set valuestring */ + if ((object == NULL) || !(object->type & cJSON_String) || (object->type & cJSON_IsReference)) + { + return NULL; + } + /* return NULL if the object is corrupted */ + if (object->valuestring == NULL) + { + return NULL; + } + if (strlen(valuestring) <= strlen(object->valuestring)) + { + strcpy(object->valuestring, valuestring); + return object->valuestring; + } + copy = (char*) cJSON_strdup((const unsigned char*)valuestring, &global_hooks); + if (copy == NULL) + { + return NULL; + } + if (object->valuestring != NULL) + { + cJSON_free(object->valuestring); + } + object->valuestring = copy; + + return copy; +} + +typedef struct +{ + unsigned char *buffer; + size_t length; + size_t offset; + size_t depth; /* current nesting depth (for formatted printing) */ + cJSON_bool noalloc; + cJSON_bool format; /* is this print a formatted print */ + internal_hooks hooks; +} printbuffer; + +/* realloc printbuffer if necessary to have at least "needed" bytes more */ +static unsigned char* ensure(printbuffer * const p, size_t needed) +{ + unsigned char *newbuffer = NULL; + size_t newsize = 0; + + if ((p == NULL) || (p->buffer == NULL)) + { + return NULL; + } + + if ((p->length > 0) && (p->offset >= p->length)) + { + /* make sure that offset is valid */ + return NULL; + } + + if (needed > INT_MAX) + { + /* sizes bigger than INT_MAX are currently not supported */ + return NULL; + } + + needed += p->offset + 1; + if (needed <= p->length) + { + return p->buffer + p->offset; + } + + if (p->noalloc) { + return NULL; + } + + /* calculate new buffer size */ + if (needed > (INT_MAX / 2)) + { + /* overflow of int, use INT_MAX if possible */ + if (needed <= INT_MAX) + { + newsize = INT_MAX; + } + else + { + return NULL; + } + } + else + { + newsize = needed * 2; + } + + if (p->hooks.reallocate != NULL) + { + /* reallocate with realloc if available */ + newbuffer = (unsigned char*)p->hooks.reallocate(p->buffer, newsize); + if (newbuffer == NULL) + { + p->hooks.deallocate(p->buffer); + p->length = 0; + p->buffer = NULL; + + return NULL; + } + } + else + { + /* otherwise reallocate manually */ + newbuffer = (unsigned char*)p->hooks.allocate(newsize); + if (!newbuffer) + { + p->hooks.deallocate(p->buffer); + p->length = 0; + p->buffer = NULL; + + return NULL; + } + + memcpy(newbuffer, p->buffer, p->offset + 1); + p->hooks.deallocate(p->buffer); + } + p->length = newsize; + p->buffer = newbuffer; + + return newbuffer + p->offset; +} + +/* calculate the new length of the string in a printbuffer and update the offset */ +static void update_offset(printbuffer * const buffer) +{ + const unsigned char *buffer_pointer = NULL; + if ((buffer == NULL) || (buffer->buffer == NULL)) + { + return; + } + buffer_pointer = buffer->buffer + buffer->offset; + + buffer->offset += strlen((const char*)buffer_pointer); +} + +/* securely comparison of floating-point variables */ +static cJSON_bool compare_double(double a, double b) +{ + double maxVal = fabs(a) > fabs(b) ? fabs(a) : fabs(b); + return (fabs(a - b) <= maxVal * DBL_EPSILON); +} + +/* Render the number nicely from the given item into a string. */ +static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + double d = item->valuedouble; + int length = 0; + size_t i = 0; + unsigned char number_buffer[26] = {0}; /* temporary buffer to print the number into */ + unsigned char decimal_point = get_decimal_point(); + double test = 0.0; + + if (output_buffer == NULL) + { + return false; + } + + /* This checks for NaN and Infinity */ + if (isnan(d) || isinf(d)) + { + length = sprintf((char*)number_buffer, "null"); + } + else if(d == (double)item->valueint) + { + length = sprintf((char*)number_buffer, "%d", item->valueint); + } + else + { + /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */ + length = sprintf((char*)number_buffer, "%1.15g", d); + + /* Check whether the original double can be recovered */ + if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || !compare_double((double)test, d)) + { + /* If not, print with 17 decimal places of precision */ + length = sprintf((char*)number_buffer, "%1.17g", d); + } + } + + /* sprintf failed or buffer overrun occurred */ + if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1))) + { + return false; + } + + /* reserve appropriate space in the output */ + output_pointer = ensure(output_buffer, (size_t)length + sizeof("")); + if (output_pointer == NULL) + { + return false; + } + + /* copy the printed number to the output and replace locale + * dependent decimal point with '.' */ + for (i = 0; i < ((size_t)length); i++) + { + if (number_buffer[i] == decimal_point) + { + output_pointer[i] = '.'; + continue; + } + + output_pointer[i] = number_buffer[i]; + } + output_pointer[i] = '\0'; + + output_buffer->offset += (size_t)length; + + return true; +} + +/* parse 4 digit hexadecimal number */ +static unsigned parse_hex4(const unsigned char * const input) +{ + unsigned int h = 0; + size_t i = 0; + + for (i = 0; i < 4; i++) + { + /* parse digit */ + if ((input[i] >= '0') && (input[i] <= '9')) + { + h += (unsigned int) input[i] - '0'; + } + else if ((input[i] >= 'A') && (input[i] <= 'F')) + { + h += (unsigned int) 10 + input[i] - 'A'; + } + else if ((input[i] >= 'a') && (input[i] <= 'f')) + { + h += (unsigned int) 10 + input[i] - 'a'; + } + else /* invalid */ + { + return 0; + } + + if (i < 3) + { + /* shift left to make place for the next nibble */ + h = h << 4; + } + } + + return h; +} + +/* converts a UTF-16 literal to UTF-8 + * A literal can be one or two sequences of the form \uXXXX */ +static unsigned char utf16_literal_to_utf8(const unsigned char * const input_pointer, const unsigned char * const input_end, unsigned char **output_pointer) +{ + long unsigned int codepoint = 0; + unsigned int first_code = 0; + const unsigned char *first_sequence = input_pointer; + unsigned char utf8_length = 0; + unsigned char utf8_position = 0; + unsigned char sequence_length = 0; + unsigned char first_byte_mark = 0; + + if ((input_end - first_sequence) < 6) + { + /* input ends unexpectedly */ + goto fail; + } + + /* get the first utf16 sequence */ + first_code = parse_hex4(first_sequence + 2); + + /* check that the code is valid */ + if (((first_code >= 0xDC00) && (first_code <= 0xDFFF))) + { + goto fail; + } + + /* UTF16 surrogate pair */ + if ((first_code >= 0xD800) && (first_code <= 0xDBFF)) + { + const unsigned char *second_sequence = first_sequence + 6; + unsigned int second_code = 0; + sequence_length = 12; /* \uXXXX\uXXXX */ + + if ((input_end - second_sequence) < 6) + { + /* input ends unexpectedly */ + goto fail; + } + + if ((second_sequence[0] != '\\') || (second_sequence[1] != 'u')) + { + /* missing second half of the surrogate pair */ + goto fail; + } + + /* get the second utf16 sequence */ + second_code = parse_hex4(second_sequence + 2); + /* check that the code is valid */ + if ((second_code < 0xDC00) || (second_code > 0xDFFF)) + { + /* invalid second half of the surrogate pair */ + goto fail; + } + + + /* calculate the unicode codepoint from the surrogate pair */ + codepoint = 0x10000 + (((first_code & 0x3FF) << 10) | (second_code & 0x3FF)); + } + else + { + sequence_length = 6; /* \uXXXX */ + codepoint = first_code; + } + + /* encode as UTF-8 + * takes at maximum 4 bytes to encode: + * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */ + if (codepoint < 0x80) + { + /* normal ascii, encoding 0xxxxxxx */ + utf8_length = 1; + } + else if (codepoint < 0x800) + { + /* two bytes, encoding 110xxxxx 10xxxxxx */ + utf8_length = 2; + first_byte_mark = 0xC0; /* 11000000 */ + } + else if (codepoint < 0x10000) + { + /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */ + utf8_length = 3; + first_byte_mark = 0xE0; /* 11100000 */ + } + else if (codepoint <= 0x10FFFF) + { + /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */ + utf8_length = 4; + first_byte_mark = 0xF0; /* 11110000 */ + } + else + { + /* invalid unicode codepoint */ + goto fail; + } + + /* encode as utf8 */ + for (utf8_position = (unsigned char)(utf8_length - 1); utf8_position > 0; utf8_position--) + { + /* 10xxxxxx */ + (*output_pointer)[utf8_position] = (unsigned char)((codepoint | 0x80) & 0xBF); + codepoint >>= 6; + } + /* encode first byte */ + if (utf8_length > 1) + { + (*output_pointer)[0] = (unsigned char)((codepoint | first_byte_mark) & 0xFF); + } + else + { + (*output_pointer)[0] = (unsigned char)(codepoint & 0x7F); + } + + *output_pointer += utf8_length; + + return sequence_length; + +fail: + return 0; +} + +/* Parse the input text into an unescaped cinput, and populate item. */ +static cJSON_bool parse_string(cJSON * const item, parse_buffer * const input_buffer) +{ + const unsigned char *input_pointer = buffer_at_offset(input_buffer) + 1; + const unsigned char *input_end = buffer_at_offset(input_buffer) + 1; + unsigned char *output_pointer = NULL; + unsigned char *output = NULL; + + /* not a string */ + if (buffer_at_offset(input_buffer)[0] != '\"') + { + goto fail; + } + + { + /* calculate approximate size of the output (overestimate) */ + size_t allocation_length = 0; + size_t skipped_bytes = 0; + while (((size_t)(input_end - input_buffer->content) < input_buffer->length) && (*input_end != '\"')) + { + /* is escape sequence */ + if (input_end[0] == '\\') + { + if ((size_t)(input_end + 1 - input_buffer->content) >= input_buffer->length) + { + /* prevent buffer overflow when last input character is a backslash */ + goto fail; + } + skipped_bytes++; + input_end++; + } + input_end++; + } + if (((size_t)(input_end - input_buffer->content) >= input_buffer->length) || (*input_end != '\"')) + { + goto fail; /* string ended unexpectedly */ + } + + /* This is at most how much we need for the output */ + allocation_length = (size_t) (input_end - buffer_at_offset(input_buffer)) - skipped_bytes; + output = (unsigned char*)input_buffer->hooks.allocate(allocation_length + sizeof("")); + if (output == NULL) + { + goto fail; /* allocation failure */ + } + } + + output_pointer = output; + /* loop through the string literal */ + while (input_pointer < input_end) + { + if (*input_pointer != '\\') + { + *output_pointer++ = *input_pointer++; + } + /* escape sequence */ + else + { + unsigned char sequence_length = 2; + if ((input_end - input_pointer) < 1) + { + goto fail; + } + + switch (input_pointer[1]) + { + case 'b': + *output_pointer++ = '\b'; + break; + case 'f': + *output_pointer++ = '\f'; + break; + case 'n': + *output_pointer++ = '\n'; + break; + case 'r': + *output_pointer++ = '\r'; + break; + case 't': + *output_pointer++ = '\t'; + break; + case '\"': + case '\\': + case '/': + *output_pointer++ = input_pointer[1]; + break; + + /* UTF-16 literal */ + case 'u': + sequence_length = utf16_literal_to_utf8(input_pointer, input_end, &output_pointer); + if (sequence_length == 0) + { + /* failed to convert UTF16-literal to UTF-8 */ + goto fail; + } + break; + + default: + goto fail; + } + input_pointer += sequence_length; + } + } + + /* zero terminate the output */ + *output_pointer = '\0'; + + item->type = cJSON_String; + item->valuestring = (char*)output; + + input_buffer->offset = (size_t) (input_end - input_buffer->content); + input_buffer->offset++; + + return true; + +fail: + if (output != NULL) + { + input_buffer->hooks.deallocate(output); + } + + if (input_pointer != NULL) + { + input_buffer->offset = (size_t)(input_pointer - input_buffer->content); + } + + return false; +} + +/* Render the cstring provided to an escaped version that can be printed. */ +static cJSON_bool print_string_ptr(const unsigned char * const input, printbuffer * const output_buffer) +{ + const unsigned char *input_pointer = NULL; + unsigned char *output = NULL; + unsigned char *output_pointer = NULL; + size_t output_length = 0; + /* numbers of additional characters needed for escaping */ + size_t escape_characters = 0; + + if (output_buffer == NULL) + { + return false; + } + + /* empty string */ + if (input == NULL) + { + output = ensure(output_buffer, sizeof("\"\"")); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "\"\""); + + return true; + } + + /* set "flag" to 1 if something needs to be escaped */ + for (input_pointer = input; *input_pointer; input_pointer++) + { + switch (*input_pointer) + { + case '\"': + case '\\': + case '\b': + case '\f': + case '\n': + case '\r': + case '\t': + /* one character escape sequence */ + escape_characters++; + break; + default: + if (*input_pointer < 32) + { + /* UTF-16 escape sequence uXXXX */ + escape_characters += 5; + } + break; + } + } + output_length = (size_t)(input_pointer - input) + escape_characters; + + output = ensure(output_buffer, output_length + sizeof("\"\"")); + if (output == NULL) + { + return false; + } + + /* no characters have to be escaped */ + if (escape_characters == 0) + { + output[0] = '\"'; + memcpy(output + 1, input, output_length); + output[output_length + 1] = '\"'; + output[output_length + 2] = '\0'; + + return true; + } + + output[0] = '\"'; + output_pointer = output + 1; + /* copy the string */ + for (input_pointer = input; *input_pointer != '\0'; (void)input_pointer++, output_pointer++) + { + if ((*input_pointer > 31) && (*input_pointer != '\"') && (*input_pointer != '\\')) + { + /* normal character, copy */ + *output_pointer = *input_pointer; + } + else + { + /* character needs to be escaped */ + *output_pointer++ = '\\'; + switch (*input_pointer) + { + case '\\': + *output_pointer = '\\'; + break; + case '\"': + *output_pointer = '\"'; + break; + case '\b': + *output_pointer = 'b'; + break; + case '\f': + *output_pointer = 'f'; + break; + case '\n': + *output_pointer = 'n'; + break; + case '\r': + *output_pointer = 'r'; + break; + case '\t': + *output_pointer = 't'; + break; + default: + /* escape and print as unicode codepoint */ + sprintf((char*)output_pointer, "u%04x", *input_pointer); + output_pointer += 4; + break; + } + } + } + output[output_length + 1] = '\"'; + output[output_length + 2] = '\0'; + + return true; +} + +/* Invoke print_string_ptr (which is useful) on an item. */ +static cJSON_bool print_string(const cJSON * const item, printbuffer * const p) +{ + return print_string_ptr((unsigned char*)item->valuestring, p); +} + +/* Predeclare these prototypes. */ +static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer); +static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer); +static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer); + +/* Utility to jump whitespace and cr/lf */ +static parse_buffer *buffer_skip_whitespace(parse_buffer * const buffer) +{ + if ((buffer == NULL) || (buffer->content == NULL)) + { + return NULL; + } + + if (cannot_access_at_index(buffer, 0)) + { + return buffer; + } + + while (can_access_at_index(buffer, 0) && (buffer_at_offset(buffer)[0] <= 32)) + { + buffer->offset++; + } + + if (buffer->offset == buffer->length) + { + buffer->offset--; + } + + return buffer; +} + +/* skip the UTF-8 BOM (byte order mark) if it is at the beginning of a buffer */ +static parse_buffer *skip_utf8_bom(parse_buffer * const buffer) +{ + if ((buffer == NULL) || (buffer->content == NULL) || (buffer->offset != 0)) + { + return NULL; + } + + if (can_access_at_index(buffer, 4) && (strncmp((const char*)buffer_at_offset(buffer), "\xEF\xBB\xBF", 3) == 0)) + { + buffer->offset += 3; + } + + return buffer; +} + +CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated) +{ + size_t buffer_length; + + if (NULL == value) + { + return NULL; + } + + /* Adding null character size due to require_null_terminated. */ + buffer_length = strlen(value) + sizeof(""); + + return cJSON_ParseWithLengthOpts(value, buffer_length, return_parse_end, require_null_terminated); +} + +/* Parse an object - create a new root, and populate. */ +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated) +{ + parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } }; + cJSON *item = NULL; + + /* reset error position */ + global_error.json = NULL; + global_error.position = 0; + + if (value == NULL || 0 == buffer_length) + { + goto fail; + } + + buffer.content = (const unsigned char*)value; + buffer.length = buffer_length; + buffer.offset = 0; + buffer.hooks = global_hooks; + + item = cJSON_New_Item(&global_hooks); + if (item == NULL) /* memory fail */ + { + goto fail; + } + + if (!parse_value(item, buffer_skip_whitespace(skip_utf8_bom(&buffer)))) + { + /* parse failure. ep is set. */ + goto fail; + } + + /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */ + if (require_null_terminated) + { + buffer_skip_whitespace(&buffer); + if ((buffer.offset >= buffer.length) || buffer_at_offset(&buffer)[0] != '\0') + { + goto fail; + } + } + if (return_parse_end) + { + *return_parse_end = (const char*)buffer_at_offset(&buffer); + } + + return item; + +fail: + if (item != NULL) + { + cJSON_Delete(item); + } + + if (value != NULL) + { + error local_error; + local_error.json = (const unsigned char*)value; + local_error.position = 0; + + if (buffer.offset < buffer.length) + { + local_error.position = buffer.offset; + } + else if (buffer.length > 0) + { + local_error.position = buffer.length - 1; + } + + if (return_parse_end != NULL) + { + *return_parse_end = (const char*)local_error.json + local_error.position; + } + + global_error = local_error; + } + + return NULL; +} + +/* Default options for cJSON_Parse */ +CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value) +{ + return cJSON_ParseWithOpts(value, 0, 0); +} + +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length) +{ + return cJSON_ParseWithLengthOpts(value, buffer_length, 0, 0); +} + +#define cjson_min(a, b) (((a) < (b)) ? (a) : (b)) + +static unsigned char *print(const cJSON * const item, cJSON_bool format, const internal_hooks * const hooks) +{ + static const size_t default_buffer_size = 256; + printbuffer buffer[1]; + unsigned char *printed = NULL; + + memset(buffer, 0, sizeof(buffer)); + + /* create buffer */ + buffer->buffer = (unsigned char*) hooks->allocate(default_buffer_size); + buffer->length = default_buffer_size; + buffer->format = format; + buffer->hooks = *hooks; + if (buffer->buffer == NULL) + { + goto fail; + } + + /* print the value */ + if (!print_value(item, buffer)) + { + goto fail; + } + update_offset(buffer); + + /* check if reallocate is available */ + if (hooks->reallocate != NULL) + { + printed = (unsigned char*) hooks->reallocate(buffer->buffer, buffer->offset + 1); + if (printed == NULL) { + goto fail; + } + buffer->buffer = NULL; + } + else /* otherwise copy the JSON over to a new buffer */ + { + printed = (unsigned char*) hooks->allocate(buffer->offset + 1); + if (printed == NULL) + { + goto fail; + } + memcpy(printed, buffer->buffer, cjson_min(buffer->length, buffer->offset + 1)); + printed[buffer->offset] = '\0'; /* just to be sure */ + + /* free the buffer */ + hooks->deallocate(buffer->buffer); + } + + return printed; + +fail: + if (buffer->buffer != NULL) + { + hooks->deallocate(buffer->buffer); + } + + if (printed != NULL) + { + hooks->deallocate(printed); + } + + return NULL; +} + +/* Render a cJSON item/entity/structure to text. */ +CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item) +{ + return (char*)print(item, true, &global_hooks); +} + +CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item) +{ + return (char*)print(item, false, &global_hooks); +} + +CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt) +{ + printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; + + if (prebuffer < 0) + { + return NULL; + } + + p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer); + if (!p.buffer) + { + return NULL; + } + + p.length = (size_t)prebuffer; + p.offset = 0; + p.noalloc = false; + p.format = fmt; + p.hooks = global_hooks; + + if (!print_value(item, &p)) + { + global_hooks.deallocate(p.buffer); + return NULL; + } + + return (char*)p.buffer; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format) +{ + printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; + + if ((length < 0) || (buffer == NULL)) + { + return false; + } + + p.buffer = (unsigned char*)buffer; + p.length = (size_t)length; + p.offset = 0; + p.noalloc = true; + p.format = format; + p.hooks = global_hooks; + + return print_value(item, &p); +} + +/* Parser core - when encountering text, process appropriately. */ +static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer) +{ + if ((input_buffer == NULL) || (input_buffer->content == NULL)) + { + return false; /* no input */ + } + + /* parse the different types of values */ + /* null */ + if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "null", 4) == 0)) + { + item->type = cJSON_NULL; + input_buffer->offset += 4; + return true; + } + /* false */ + if (can_read(input_buffer, 5) && (strncmp((const char*)buffer_at_offset(input_buffer), "false", 5) == 0)) + { + item->type = cJSON_False; + input_buffer->offset += 5; + return true; + } + /* true */ + if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "true", 4) == 0)) + { + item->type = cJSON_True; + item->valueint = 1; + input_buffer->offset += 4; + return true; + } + /* string */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '\"')) + { + return parse_string(item, input_buffer); + } + /* number */ + if (can_access_at_index(input_buffer, 0) && ((buffer_at_offset(input_buffer)[0] == '-') || ((buffer_at_offset(input_buffer)[0] >= '0') && (buffer_at_offset(input_buffer)[0] <= '9')))) + { + return parse_number(item, input_buffer); + } + /* array */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '[')) + { + return parse_array(item, input_buffer); + } + /* object */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '{')) + { + return parse_object(item, input_buffer); + } + + return false; +} + +/* Render a value to text. */ +static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output = NULL; + + if ((item == NULL) || (output_buffer == NULL)) + { + return false; + } + + switch ((item->type) & 0xFF) + { + case cJSON_NULL: + output = ensure(output_buffer, 5); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "null"); + return true; + + case cJSON_False: + output = ensure(output_buffer, 6); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "false"); + return true; + + case cJSON_True: + output = ensure(output_buffer, 5); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "true"); + return true; + + case cJSON_Number: + return print_number(item, output_buffer); + + case cJSON_Raw: + { + size_t raw_length = 0; + if (item->valuestring == NULL) + { + return false; + } + + raw_length = strlen(item->valuestring) + sizeof(""); + output = ensure(output_buffer, raw_length); + if (output == NULL) + { + return false; + } + memcpy(output, item->valuestring, raw_length); + return true; + } + + case cJSON_String: + return print_string(item, output_buffer); + + case cJSON_Array: + return print_array(item, output_buffer); + + case cJSON_Object: + return print_object(item, output_buffer); + + default: + return false; + } +} + +/* Build an array from input text. */ +static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer) +{ + cJSON *head = NULL; /* head of the linked list */ + cJSON *current_item = NULL; + + if (input_buffer->depth >= CJSON_NESTING_LIMIT) + { + return false; /* to deeply nested */ + } + input_buffer->depth++; + + if (buffer_at_offset(input_buffer)[0] != '[') + { + /* not an array */ + goto fail; + } + + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ']')) + { + /* empty array */ + goto success; + } + + /* check if we skipped to the end of the buffer */ + if (cannot_access_at_index(input_buffer, 0)) + { + input_buffer->offset--; + goto fail; + } + + /* step back to character in front of the first element */ + input_buffer->offset--; + /* loop through the comma separated array elements */ + do + { + /* allocate next item */ + cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); + if (new_item == NULL) + { + goto fail; /* allocation failure */ + } + + /* attach next item to list */ + if (head == NULL) + { + /* start the linked list */ + current_item = head = new_item; + } + else + { + /* add to the end and advance */ + current_item->next = new_item; + new_item->prev = current_item; + current_item = new_item; + } + + /* parse next value */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_value(current_item, input_buffer)) + { + goto fail; /* failed to parse value */ + } + buffer_skip_whitespace(input_buffer); + } + while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ',')); + + if (cannot_access_at_index(input_buffer, 0) || buffer_at_offset(input_buffer)[0] != ']') + { + goto fail; /* expected end of array */ + } + +success: + input_buffer->depth--; + + if (head != NULL) { + head->prev = current_item; + } + + item->type = cJSON_Array; + item->child = head; + + input_buffer->offset++; + + return true; + +fail: + if (head != NULL) + { + cJSON_Delete(head); + } + + return false; +} + +/* Render an array to text */ +static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + size_t length = 0; + cJSON *current_element = item->child; + + if (output_buffer == NULL) + { + return false; + } + + /* Compose the output array. */ + /* opening square bracket */ + output_pointer = ensure(output_buffer, 1); + if (output_pointer == NULL) + { + return false; + } + + *output_pointer = '['; + output_buffer->offset++; + output_buffer->depth++; + + while (current_element != NULL) + { + if (!print_value(current_element, output_buffer)) + { + return false; + } + update_offset(output_buffer); + if (current_element->next) + { + length = (size_t) (output_buffer->format ? 2 : 1); + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ','; + if(output_buffer->format) + { + *output_pointer++ = ' '; + } + *output_pointer = '\0'; + output_buffer->offset += length; + } + current_element = current_element->next; + } + + output_pointer = ensure(output_buffer, 2); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ']'; + *output_pointer = '\0'; + output_buffer->depth--; + + return true; +} + +/* Build an object from the text. */ +static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer) +{ + cJSON *head = NULL; /* linked list head */ + cJSON *current_item = NULL; + + if (input_buffer->depth >= CJSON_NESTING_LIMIT) + { + return false; /* to deeply nested */ + } + input_buffer->depth++; + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '{')) + { + goto fail; /* not an object */ + } + + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '}')) + { + goto success; /* empty object */ + } + + /* check if we skipped to the end of the buffer */ + if (cannot_access_at_index(input_buffer, 0)) + { + input_buffer->offset--; + goto fail; + } + + /* step back to character in front of the first element */ + input_buffer->offset--; + /* loop through the comma separated array elements */ + do + { + /* allocate next item */ + cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); + if (new_item == NULL) + { + goto fail; /* allocation failure */ + } + + /* attach next item to list */ + if (head == NULL) + { + /* start the linked list */ + current_item = head = new_item; + } + else + { + /* add to the end and advance */ + current_item->next = new_item; + new_item->prev = current_item; + current_item = new_item; + } + + /* parse the name of the child */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_string(current_item, input_buffer)) + { + goto fail; /* failed to parse name */ + } + buffer_skip_whitespace(input_buffer); + + /* swap valuestring and string, because we parsed the name */ + current_item->string = current_item->valuestring; + current_item->valuestring = NULL; + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != ':')) + { + goto fail; /* invalid object */ + } + + /* parse the value */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_value(current_item, input_buffer)) + { + goto fail; /* failed to parse value */ + } + buffer_skip_whitespace(input_buffer); + } + while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ',')); + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '}')) + { + goto fail; /* expected end of object */ + } + +success: + input_buffer->depth--; + + if (head != NULL) { + head->prev = current_item; + } + + item->type = cJSON_Object; + item->child = head; + + input_buffer->offset++; + return true; + +fail: + if (head != NULL) + { + cJSON_Delete(head); + } + + return false; +} + +/* Render an object to text. */ +static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + size_t length = 0; + cJSON *current_item = item->child; + + if (output_buffer == NULL) + { + return false; + } + + /* Compose the output: */ + length = (size_t) (output_buffer->format ? 2 : 1); /* fmt: {\n */ + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + + *output_pointer++ = '{'; + output_buffer->depth++; + if (output_buffer->format) + { + *output_pointer++ = '\n'; + } + output_buffer->offset += length; + + while (current_item) + { + if (output_buffer->format) + { + size_t i; + output_pointer = ensure(output_buffer, output_buffer->depth); + if (output_pointer == NULL) + { + return false; + } + for (i = 0; i < output_buffer->depth; i++) + { + *output_pointer++ = '\t'; + } + output_buffer->offset += output_buffer->depth; + } + + /* print key */ + if (!print_string_ptr((unsigned char*)current_item->string, output_buffer)) + { + return false; + } + update_offset(output_buffer); + + length = (size_t) (output_buffer->format ? 2 : 1); + output_pointer = ensure(output_buffer, length); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ':'; + if (output_buffer->format) + { + *output_pointer++ = '\t'; + } + output_buffer->offset += length; + + /* print value */ + if (!print_value(current_item, output_buffer)) + { + return false; + } + update_offset(output_buffer); + + /* print comma if not last */ + length = ((size_t)(output_buffer->format ? 1 : 0) + (size_t)(current_item->next ? 1 : 0)); + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + if (current_item->next) + { + *output_pointer++ = ','; + } + + if (output_buffer->format) + { + *output_pointer++ = '\n'; + } + *output_pointer = '\0'; + output_buffer->offset += length; + + current_item = current_item->next; + } + + output_pointer = ensure(output_buffer, output_buffer->format ? (output_buffer->depth + 1) : 2); + if (output_pointer == NULL) + { + return false; + } + if (output_buffer->format) + { + size_t i; + for (i = 0; i < (output_buffer->depth - 1); i++) + { + *output_pointer++ = '\t'; + } + } + *output_pointer++ = '}'; + *output_pointer = '\0'; + output_buffer->depth--; + + return true; +} + +/* Get Array size/item / object item. */ +CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array) +{ + cJSON *child = NULL; + size_t size = 0; + + if (array == NULL) + { + return 0; + } + + child = array->child; + + while(child != NULL) + { + size++; + child = child->next; + } + + /* FIXME: Can overflow here. Cannot be fixed without breaking the API */ + + return (int)size; +} + +static cJSON* get_array_item(const cJSON *array, size_t index) +{ + cJSON *current_child = NULL; + + if (array == NULL) + { + return NULL; + } + + current_child = array->child; + while ((current_child != NULL) && (index > 0)) + { + index--; + current_child = current_child->next; + } + + return current_child; +} + +CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index) +{ + if (index < 0) + { + return NULL; + } + + return get_array_item(array, (size_t)index); +} + +static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive) +{ + cJSON *current_element = NULL; + + if ((object == NULL) || (name == NULL)) + { + return NULL; + } + + current_element = object->child; + if (case_sensitive) + { + while ((current_element != NULL) && (current_element->string != NULL) && (strcmp(name, current_element->string) != 0)) + { + current_element = current_element->next; + } + } + else + { + while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0)) + { + current_element = current_element->next; + } + } + + if ((current_element == NULL) || (current_element->string == NULL)) { + return NULL; + } + + return current_element; +} + +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string) +{ + return get_object_item(object, string, false); +} + +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string) +{ + return get_object_item(object, string, true); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string) +{ + return cJSON_GetObjectItem(object, string) ? 1 : 0; +} + +/* Utility for array list handling. */ +static void suffix_object(cJSON *prev, cJSON *item) +{ + prev->next = item; + item->prev = prev; +} + +/* Utility for handling references. */ +static cJSON *create_reference(const cJSON *item, const internal_hooks * const hooks) +{ + cJSON *reference = NULL; + if (item == NULL) + { + return NULL; + } + + reference = cJSON_New_Item(hooks); + if (reference == NULL) + { + return NULL; + } + + memcpy(reference, item, sizeof(cJSON)); + reference->string = NULL; + reference->type |= cJSON_IsReference; + reference->next = reference->prev = NULL; + return reference; +} + +static cJSON_bool add_item_to_array(cJSON *array, cJSON *item) +{ + cJSON *child = NULL; + + if ((item == NULL) || (array == NULL) || (array == item)) + { + return false; + } + + child = array->child; + /* + * To find the last item in array quickly, we use prev in array + */ + if (child == NULL) + { + /* list is empty, start new one */ + array->child = item; + item->prev = item; + item->next = NULL; + } + else + { + /* append to the end */ + if (child->prev) + { + suffix_object(child->prev, item); + array->child->prev = item; + } + } + + return true; +} + +/* Add item to array/object. */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item) +{ + return add_item_to_array(array, item); +} + +#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) + #pragma GCC diagnostic push +#endif +#ifdef __GNUC__ +#pragma GCC diagnostic ignored "-Wcast-qual" +#endif +/* helper function to cast away const */ +static void* cast_away_const(const void* string) +{ + return (void*)string; +} +#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) + #pragma GCC diagnostic pop +#endif + + +static cJSON_bool add_item_to_object(cJSON * const object, const char * const string, cJSON * const item, const internal_hooks * const hooks, const cJSON_bool constant_key) +{ + char *new_key = NULL; + int new_type = cJSON_Invalid; + + if ((object == NULL) || (string == NULL) || (item == NULL) || (object == item)) + { + return false; + } + + if (constant_key) + { + new_key = (char*)cast_away_const(string); + new_type = item->type | cJSON_StringIsConst; + } + else + { + new_key = (char*)cJSON_strdup((const unsigned char*)string, hooks); + if (new_key == NULL) + { + return false; + } + + new_type = item->type & ~cJSON_StringIsConst; + } + + if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) + { + hooks->deallocate(item->string); + } + + item->string = new_key; + item->type = new_type; + + return add_item_to_array(object, item); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item) +{ + return add_item_to_object(object, string, item, &global_hooks, false); +} + +/* Add an item to an object with constant string as key */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item) +{ + return add_item_to_object(object, string, item, &global_hooks, true); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) +{ + if (array == NULL) + { + return false; + } + + return add_item_to_array(array, create_reference(item, &global_hooks)); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item) +{ + if ((object == NULL) || (string == NULL)) + { + return false; + } + + return add_item_to_object(object, string, create_reference(item, &global_hooks), &global_hooks, false); +} + +CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name) +{ + cJSON *null = cJSON_CreateNull(); + if (add_item_to_object(object, name, null, &global_hooks, false)) + { + return null; + } + + cJSON_Delete(null); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name) +{ + cJSON *true_item = cJSON_CreateTrue(); + if (add_item_to_object(object, name, true_item, &global_hooks, false)) + { + return true_item; + } + + cJSON_Delete(true_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name) +{ + cJSON *false_item = cJSON_CreateFalse(); + if (add_item_to_object(object, name, false_item, &global_hooks, false)) + { + return false_item; + } + + cJSON_Delete(false_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean) +{ + cJSON *bool_item = cJSON_CreateBool(boolean); + if (add_item_to_object(object, name, bool_item, &global_hooks, false)) + { + return bool_item; + } + + cJSON_Delete(bool_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number) +{ + cJSON *number_item = cJSON_CreateNumber(number); + if (add_item_to_object(object, name, number_item, &global_hooks, false)) + { + return number_item; + } + + cJSON_Delete(number_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string) +{ + cJSON *string_item = cJSON_CreateString(string); + if (add_item_to_object(object, name, string_item, &global_hooks, false)) + { + return string_item; + } + + cJSON_Delete(string_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw) +{ + cJSON *raw_item = cJSON_CreateRaw(raw); + if (add_item_to_object(object, name, raw_item, &global_hooks, false)) + { + return raw_item; + } + + cJSON_Delete(raw_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name) +{ + cJSON *object_item = cJSON_CreateObject(); + if (add_item_to_object(object, name, object_item, &global_hooks, false)) + { + return object_item; + } + + cJSON_Delete(object_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name) +{ + cJSON *array = cJSON_CreateArray(); + if (add_item_to_object(object, name, array, &global_hooks, false)) + { + return array; + } + + cJSON_Delete(array); + return NULL; +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item) +{ + if ((parent == NULL) || (item == NULL)) + { + return NULL; + } + + if (item != parent->child) + { + /* not the first element */ + item->prev->next = item->next; + } + if (item->next != NULL) + { + /* not the last element */ + item->next->prev = item->prev; + } + + if (item == parent->child) + { + /* first element */ + parent->child = item->next; + } + else if (item->next == NULL) + { + /* last element */ + parent->child->prev = item->prev; + } + + /* make sure the detached item doesn't point anywhere anymore */ + item->prev = NULL; + item->next = NULL; + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which) +{ + if (which < 0) + { + return NULL; + } + + return cJSON_DetachItemViaPointer(array, get_array_item(array, (size_t)which)); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which) +{ + cJSON_Delete(cJSON_DetachItemFromArray(array, which)); +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string) +{ + cJSON *to_detach = cJSON_GetObjectItem(object, string); + + return cJSON_DetachItemViaPointer(object, to_detach); +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string) +{ + cJSON *to_detach = cJSON_GetObjectItemCaseSensitive(object, string); + + return cJSON_DetachItemViaPointer(object, to_detach); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string) +{ + cJSON_Delete(cJSON_DetachItemFromObject(object, string)); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string) +{ + cJSON_Delete(cJSON_DetachItemFromObjectCaseSensitive(object, string)); +} + +/* Replace array/object items with new ones. */ +CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem) +{ + cJSON *after_inserted = NULL; + + if (which < 0 || newitem == NULL) + { + return false; + } + + after_inserted = get_array_item(array, (size_t)which); + if (after_inserted == NULL) + { + return add_item_to_array(array, newitem); + } + + if (after_inserted != array->child && newitem->prev == NULL) { + /* return false if after_inserted is a corrupted array item */ + return false; + } + + newitem->next = after_inserted; + newitem->prev = after_inserted->prev; + after_inserted->prev = newitem; + if (after_inserted == array->child) + { + array->child = newitem; + } + else + { + newitem->prev->next = newitem; + } + return true; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement) +{ + if ((parent == NULL) || (parent->child == NULL) || (replacement == NULL) || (item == NULL)) + { + return false; + } + + if (replacement == item) + { + return true; + } + + replacement->next = item->next; + replacement->prev = item->prev; + + if (replacement->next != NULL) + { + replacement->next->prev = replacement; + } + if (parent->child == item) + { + if (parent->child->prev == parent->child) + { + replacement->prev = replacement; + } + parent->child = replacement; + } + else + { /* + * To find the last item in array quickly, we use prev in array. + * We can't modify the last item's next pointer where this item was the parent's child + */ + if (replacement->prev != NULL) + { + replacement->prev->next = replacement; + } + if (replacement->next == NULL) + { + parent->child->prev = replacement; + } + } + + item->next = NULL; + item->prev = NULL; + cJSON_Delete(item); + + return true; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem) +{ + if (which < 0) + { + return false; + } + + return cJSON_ReplaceItemViaPointer(array, get_array_item(array, (size_t)which), newitem); +} + +static cJSON_bool replace_item_in_object(cJSON *object, const char *string, cJSON *replacement, cJSON_bool case_sensitive) +{ + if ((replacement == NULL) || (string == NULL)) + { + return false; + } + + /* replace the name in the replacement */ + if (!(replacement->type & cJSON_StringIsConst) && (replacement->string != NULL)) + { + cJSON_free(replacement->string); + } + replacement->string = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks); + if (replacement->string == NULL) + { + return false; + } + + replacement->type &= ~cJSON_StringIsConst; + + return cJSON_ReplaceItemViaPointer(object, get_object_item(object, string, case_sensitive), replacement); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem) +{ + return replace_item_in_object(object, string, newitem, false); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, cJSON *newitem) +{ + return replace_item_in_object(object, string, newitem, true); +} + +/* Create basic types: */ +CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_NULL; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_True; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_False; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = boolean ? cJSON_True : cJSON_False; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_Number; + item->valuedouble = num; + + /* use saturation in case of overflow */ + if (num >= INT_MAX) + { + item->valueint = INT_MAX; + } + else if (num <= (double)INT_MIN) + { + item->valueint = INT_MIN; + } + else + { + item->valueint = (int)num; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_String; + item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks); + if(!item->valuestring) + { + cJSON_Delete(item); + return NULL; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) + { + item->type = cJSON_String | cJSON_IsReference; + item->valuestring = (char*)cast_away_const(string); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) { + item->type = cJSON_Object | cJSON_IsReference; + item->child = (cJSON*)cast_away_const(child); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child) { + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) { + item->type = cJSON_Array | cJSON_IsReference; + item->child = (cJSON*)cast_away_const(child); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_Raw; + item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks); + if(!item->valuestring) + { + cJSON_Delete(item); + return NULL; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type=cJSON_Array; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item) + { + item->type = cJSON_Object; + } + + return item; +} + +/* Create Arrays: */ +CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for(i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber(numbers[i]); + if (!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for(i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber((double)numbers[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for(i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber(numbers[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (strings == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for (i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateString(strings[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p,n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +/* Duplication */ +CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse) +{ + cJSON *newitem = NULL; + cJSON *child = NULL; + cJSON *next = NULL; + cJSON *newchild = NULL; + + /* Bail on bad ptr */ + if (!item) + { + goto fail; + } + /* Create new item */ + newitem = cJSON_New_Item(&global_hooks); + if (!newitem) + { + goto fail; + } + /* Copy over all vars */ + newitem->type = item->type & (~cJSON_IsReference); + newitem->valueint = item->valueint; + newitem->valuedouble = item->valuedouble; + if (item->valuestring) + { + newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks); + if (!newitem->valuestring) + { + goto fail; + } + } + if (item->string) + { + newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks); + if (!newitem->string) + { + goto fail; + } + } + /* If non-recursive, then we're done! */ + if (!recurse) + { + return newitem; + } + /* Walk the ->next chain for the child. */ + child = item->child; + while (child != NULL) + { + newchild = cJSON_Duplicate(child, true); /* Duplicate (with recurse) each item in the ->next chain */ + if (!newchild) + { + goto fail; + } + if (next != NULL) + { + /* If newitem->child already set, then crosswire ->prev and ->next and move on */ + next->next = newchild; + newchild->prev = next; + next = newchild; + } + else + { + /* Set newitem->child and move to it */ + newitem->child = newchild; + next = newchild; + } + child = child->next; + } + if (newitem && newitem->child) + { + newitem->child->prev = newchild; + } + + return newitem; + +fail: + if (newitem != NULL) + { + cJSON_Delete(newitem); + } + + return NULL; +} + +static void skip_oneline_comment(char **input) +{ + *input += static_strlen("//"); + + for (; (*input)[0] != '\0'; ++(*input)) + { + if ((*input)[0] == '\n') { + *input += static_strlen("\n"); + return; + } + } +} + +static void skip_multiline_comment(char **input) +{ + *input += static_strlen("/*"); + + for (; (*input)[0] != '\0'; ++(*input)) + { + if (((*input)[0] == '*') && ((*input)[1] == '/')) + { + *input += static_strlen("*/"); + return; + } + } +} + +static void minify_string(char **input, char **output) { + (*output)[0] = (*input)[0]; + *input += static_strlen("\""); + *output += static_strlen("\""); + + + for (; (*input)[0] != '\0'; (void)++(*input), ++(*output)) { + (*output)[0] = (*input)[0]; + + if ((*input)[0] == '\"') { + (*output)[0] = '\"'; + *input += static_strlen("\""); + *output += static_strlen("\""); + return; + } else if (((*input)[0] == '\\') && ((*input)[1] == '\"')) { + (*output)[1] = (*input)[1]; + *input += static_strlen("\""); + *output += static_strlen("\""); + } + } +} + +CJSON_PUBLIC(void) cJSON_Minify(char *json) +{ + char *into = json; + + if (json == NULL) + { + return; + } + + while (json[0] != '\0') + { + switch (json[0]) + { + case ' ': + case '\t': + case '\r': + case '\n': + json++; + break; + + case '/': + if (json[1] == '/') + { + skip_oneline_comment(&json); + } + else if (json[1] == '*') + { + skip_multiline_comment(&json); + } else { + json++; + } + break; + + case '\"': + minify_string(&json, (char**)&into); + break; + + default: + into[0] = json[0]; + json++; + into++; + } + } + + /* and null-terminate. */ + *into = '\0'; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Invalid; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_False; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xff) == cJSON_True; +} + + +CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & (cJSON_True | cJSON_False)) != 0; +} +CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_NULL; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Number; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_String; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Array; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Object; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Raw; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive) +{ + if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF))) + { + return false; + } + + /* check if type is valid */ + switch (a->type & 0xFF) + { + case cJSON_False: + case cJSON_True: + case cJSON_NULL: + case cJSON_Number: + case cJSON_String: + case cJSON_Raw: + case cJSON_Array: + case cJSON_Object: + break; + + default: + return false; + } + + /* identical objects are equal */ + if (a == b) + { + return true; + } + + switch (a->type & 0xFF) + { + /* in these cases and equal type is enough */ + case cJSON_False: + case cJSON_True: + case cJSON_NULL: + return true; + + case cJSON_Number: + if (compare_double(a->valuedouble, b->valuedouble)) + { + return true; + } + return false; + + case cJSON_String: + case cJSON_Raw: + if ((a->valuestring == NULL) || (b->valuestring == NULL)) + { + return false; + } + if (strcmp(a->valuestring, b->valuestring) == 0) + { + return true; + } + + return false; + + case cJSON_Array: + { + cJSON *a_element = a->child; + cJSON *b_element = b->child; + + for (; (a_element != NULL) && (b_element != NULL);) + { + if (!cJSON_Compare(a_element, b_element, case_sensitive)) + { + return false; + } + + a_element = a_element->next; + b_element = b_element->next; + } + + /* one of the arrays is longer than the other */ + if (a_element != b_element) { + return false; + } + + return true; + } + + case cJSON_Object: + { + cJSON *a_element = NULL; + cJSON *b_element = NULL; + cJSON_ArrayForEach(a_element, a) + { + /* TODO This has O(n^2) runtime, which is horrible! */ + b_element = get_object_item(b, a_element->string, case_sensitive); + if (b_element == NULL) + { + return false; + } + + if (!cJSON_Compare(a_element, b_element, case_sensitive)) + { + return false; + } + } + + /* doing this twice, once on a and b to prevent true comparison if a subset of b + * TODO: Do this the proper way, this is just a fix for now */ + cJSON_ArrayForEach(b_element, b) + { + a_element = get_object_item(a, b_element->string, case_sensitive); + if (a_element == NULL) + { + return false; + } + + if (!cJSON_Compare(b_element, a_element, case_sensitive)) + { + return false; + } + } + + return true; + } + + default: + return false; + } +} + +CJSON_PUBLIC(void *) cJSON_malloc(size_t size) +{ + return global_hooks.allocate(size); +} + +CJSON_PUBLIC(void) cJSON_free(void *object) +{ + global_hooks.deallocate(object); +} diff --git a/Lite_version/src/PermissionManager/app/src/main/cpp/cJSON.h b/Lite_version/src/PermissionManager/app/src/main/cpp/cJSON.h new file mode 100644 index 00000000..2628d763 --- /dev/null +++ b/Lite_version/src/PermissionManager/app/src/main/cpp/cJSON.h @@ -0,0 +1,300 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#ifndef cJSON__h +#define cJSON__h + +#ifdef __cplusplus +extern "C" +{ +#endif + +#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32)) +#define __WINDOWS__ +#endif + +#ifdef __WINDOWS__ + +/* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention. For windows you have 3 define options: + +CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols +CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default) +CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol + +For *nix builds that support visibility attribute, you can define similar behavior by + +setting default visibility to hidden by adding +-fvisibility=hidden (for gcc) +or +-xldscope=hidden (for sun cc) +to CFLAGS + +then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does + +*/ + +#define CJSON_CDECL __cdecl +#define CJSON_STDCALL __stdcall + +/* export symbols by default, this is necessary for copy pasting the C and header file */ +#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS) +#define CJSON_EXPORT_SYMBOLS +#endif + +#if defined(CJSON_HIDE_SYMBOLS) +#define CJSON_PUBLIC(type) type CJSON_STDCALL +#elif defined(CJSON_EXPORT_SYMBOLS) +#define CJSON_PUBLIC(type) __declspec(dllexport) type CJSON_STDCALL +#elif defined(CJSON_IMPORT_SYMBOLS) +#define CJSON_PUBLIC(type) __declspec(dllimport) type CJSON_STDCALL +#endif +#else /* !__WINDOWS__ */ +#define CJSON_CDECL +#define CJSON_STDCALL + +#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY) +#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type +#else +#define CJSON_PUBLIC(type) type +#endif +#endif + +/* project version */ +#define CJSON_VERSION_MAJOR 1 +#define CJSON_VERSION_MINOR 7 +#define CJSON_VERSION_PATCH 16 + +#include + +/* cJSON Types: */ +#define cJSON_Invalid (0) +#define cJSON_False (1 << 0) +#define cJSON_True (1 << 1) +#define cJSON_NULL (1 << 2) +#define cJSON_Number (1 << 3) +#define cJSON_String (1 << 4) +#define cJSON_Array (1 << 5) +#define cJSON_Object (1 << 6) +#define cJSON_Raw (1 << 7) /* raw json */ + +#define cJSON_IsReference 256 +#define cJSON_StringIsConst 512 + +/* The cJSON structure: */ +typedef struct cJSON +{ + /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */ + struct cJSON *next; + struct cJSON *prev; + /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */ + struct cJSON *child; + + /* The type of the item, as above. */ + int type; + + /* The item's string, if type==cJSON_String and type == cJSON_Raw */ + char *valuestring; + /* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */ + int valueint; + /* The item's number, if type==cJSON_Number */ + double valuedouble; + + /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */ + char *string; +} cJSON; + +typedef struct cJSON_Hooks +{ + /* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */ + void *(CJSON_CDECL *malloc_fn)(size_t sz); + void (CJSON_CDECL *free_fn)(void *ptr); +} cJSON_Hooks; + +typedef int cJSON_bool; + +/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them. + * This is to prevent stack overflows. */ +#ifndef CJSON_NESTING_LIMIT +#define CJSON_NESTING_LIMIT 1000 +#endif + +/* returns the version of cJSON as a string */ +CJSON_PUBLIC(const char*) cJSON_Version(void); + +/* Supply malloc, realloc and free functions to cJSON */ +CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks); + +/* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */ +/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */ +CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value); +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length); +/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */ +/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */ +CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated); +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated); + +/* Render a cJSON entity to text for transfer/storage. */ +CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item); +/* Render a cJSON entity to text for transfer/storage without any formatting. */ +CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item); +/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */ +CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt); +/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */ +/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */ +CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format); +/* Delete a cJSON entity and all subentities. */ +CJSON_PUBLIC(void) cJSON_Delete(cJSON *item); + +/* Returns the number of items in an array (or object). */ +CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array); +/* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */ +CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index); +/* Get item "string" from object. Case insensitive. */ +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string); +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string); +CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string); +/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */ +CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void); + +/* Check item type and return its value */ +CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item); +CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item); + +/* These functions check the type of an item */ +CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item); + +/* These calls create a cJSON item of the appropriate type. */ +CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean); +CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num); +CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string); +/* raw json */ +CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw); +CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void); + +/* Create a string where valuestring references a string so + * it will not be freed by cJSON_Delete */ +CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string); +/* Create an object/array that only references it's elements so + * they will not be freed by cJSON_Delete */ +CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child); +CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child); + +/* These utilities create an Array of count items. + * The parameter count cannot be greater than the number of elements in the number array, otherwise array access will be out of bounds.*/ +CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count); + +/* Append item to the specified array/object. */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item); +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item); +/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object. + * WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before + * writing to `item->string` */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item); +/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item); +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item); + +/* Remove/Detach items from Arrays/Objects. */ +CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which); +CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string); +CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string); +CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string); + +/* Update array items. */ +CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */ +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement); +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem); +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem); +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem); + +/* Duplicate a cJSON item */ +CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse); +/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will + * need to be released. With recurse!=0, it will duplicate any children connected to the item. + * The item->next and ->prev pointers are always zero on return from Duplicate. */ +/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal. + * case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */ +CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive); + +/* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from strings. + * The input pointer json cannot point to a read-only address area, such as a string constant, + * but should point to a readable and writable address area. */ +CJSON_PUBLIC(void) cJSON_Minify(char *json); + +/* Helper functions for creating and adding items to an object at the same time. + * They return the added item or NULL on failure. */ +CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean); +CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number); +CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string); +CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw); +CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name); + +/* When assigning an integer value, it needs to be propagated to valuedouble too. */ +#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number)) +/* helper for the cJSON_SetNumberValue macro */ +CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number); +#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number)) +/* Change the valuestring of a cJSON_String object, only takes effect when type of object is cJSON_String */ +CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring); + +/* If the object is not a boolean type this does nothing and returns cJSON_Invalid else it returns the new type*/ +#define cJSON_SetBoolValue(object, boolValue) ( \ + (object != NULL && ((object)->type & (cJSON_False|cJSON_True))) ? \ + (object)->type=((object)->type &(~(cJSON_False|cJSON_True)))|((boolValue)?cJSON_True:cJSON_False) : \ + cJSON_Invalid\ +) + +/* Macro for iterating over an array or object */ +#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next) + +/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */ +CJSON_PUBLIC(void *) cJSON_malloc(size_t size); +CJSON_PUBLIC(void) cJSON_free(void *object); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/Lite_version/src/PermissionManager/app/src/main/cpp/native-lib.cpp b/Lite_version/src/PermissionManager/app/src/main/cpp/native-lib.cpp new file mode 100644 index 00000000..218aea17 --- /dev/null +++ b/Lite_version/src/PermissionManager/app/src/main/cpp/native-lib.cpp @@ -0,0 +1,280 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "kernel_root_kit/include/rootkit_umbrella.h" +#include "urlEncodeUtils.h" +#include "cJSON.h" +using namespace std; + +std::string g_last_su_file_path; + +static string jstringToStr(JNIEnv* env, jstring jstring1) { + const char *str1 = env->GetStringUTFChars(jstring1, 0); + string s = str1; + env->ReleaseStringUTFChars(jstring1, str1); + return s; +} + +static string urlEncodeToStr(string str) { + size_t len = str.length(); + size_t max_encoded_len = 3 * len + 1; + std::vector buf(max_encoded_len); + url_encode(const_cast(str.c_str()), (char*)buf.data()); + return (char*)buf.data(); +} + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_testRoot( + JNIEnv* env, + jclass /* this */, + jstring rootKey) { + string strRootKey = jstringToStr(env, rootKey); + + std::string result = kernel_root::get_root_test_report(strRootKey.c_str()); + return env->NewStringUTF(result.c_str()); +} + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_runRootCmd( + JNIEnv* env, + jclass /* this */, + jstring rootKey, + jstring cmd) { + string strRootKey = jstringToStr(env, rootKey); + string strCmd = jstringToStr(env, cmd); + + string result; + KRootErr err = kernel_root::run_root_cmd(strRootKey.c_str(), strCmd.c_str(), result); + stringstream sstr; + sstr << "run_root_cmd " << to_string(err).c_str() << ", result:" << result; + return env->NewStringUTF(sstr.str().c_str()); +} + + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_rootExecProcessCmd( + JNIEnv* env, + jclass /* this */, + jstring rootKey, + jstring cmd) { + string strRootKey = jstringToStr(env, rootKey); + string strCmd = jstringToStr(env, cmd); + + KRootErr err = kernel_root::root_exec_process(strRootKey.c_str(), strCmd.c_str()); + + stringstream sstr; + sstr << "root_exec_process " << to_string(err).c_str(); + return env->NewStringUTF(sstr.str().c_str()); +} + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_installSu( + JNIEnv* env, + jclass /* this */, + jstring rootKey) { + string strRootKey = jstringToStr(env, rootKey); + + //安装su工具套件 + std::string su_hide_full_path; + KRootErr err = kernel_root::install_su(strRootKey.c_str(), su_hide_full_path); + + stringstream sstr; + sstr << "install su " << to_string(err).c_str() << ", su_hide_full_path:" << su_hide_full_path << std::endl; + g_last_su_file_path = su_hide_full_path; + if (is_ok(err)) sstr << "install_su done."<< std::endl; + return env->NewStringUTF(sstr.str().c_str()); +} + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_getLastSuFilePath( + JNIEnv* env, + jclass /* this */) { + return env->NewStringUTF(g_last_su_file_path.c_str()); +} + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_uninstallSu( + JNIEnv* env, + jclass /* this */, + jstring rootKey) { + string strRootKey = jstringToStr(env, rootKey); + + stringstream sstr; + + KRootErr err = kernel_root::uninstall_su(strRootKey.c_str()); + sstr << "uninstall_su " << to_string(err).c_str() << std::endl; + if (is_failed(err)) return env->NewStringUTF(sstr.str().c_str()); + g_last_su_file_path.clear(); + sstr << "uninstall_su done."; + return env->NewStringUTF(sstr.str().c_str()); +} + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_autoSuEnvInject( + JNIEnv* env, + jclass /* this */, + jstring rootKey, + jstring targetProcessCmdline) { + + if(g_last_su_file_path.empty()) return env->NewStringUTF("【错误】请先安装部署su"); + string strRootKey = jstringToStr(env, rootKey); + string strTargetProcessCmdline = jstringToStr(env, targetProcessCmdline); + + stringstream sstr; + + //杀光所有历史进程 + std::set out; + KRootErr err = kernel_root::find_all_cmdline_process(strRootKey.c_str(), strTargetProcessCmdline.c_str(), out); + sstr << "find_all_cmdline_process " << to_string(err).c_str() << ", cnt:"<NewStringUTF(sstr.str().c_str()); + std::string kill_cmd; + for (pid_t t : out) { + err = kernel_root::kill_process(strRootKey.c_str(), t); + sstr << "kill_ret " << to_string(err).c_str() << std::endl; + if (is_failed(err)) return env->NewStringUTF(sstr.str().c_str()); + } + pid_t pid; + err = kernel_root::wait_and_find_cmdline_process(strRootKey.c_str(), strTargetProcessCmdline.c_str(), 60*1000, pid); + std::string su_dir_path = is_ok(err) ? (std::filesystem::path(g_last_su_file_path).parent_path().string() + "/") : ""; + sstr << "auto_su_env_inject("<< to_string(err).c_str() <<", " << su_dir_path <<")" << std::endl; + if (is_failed(err)) return env->NewStringUTF(sstr.str().c_str()); + err = kernel_root::inject_process_env64_PATH_wrapper(strRootKey.c_str(), pid, su_dir_path.c_str()); + sstr << "auto_su_env_inject ret val:" << to_string(err).c_str() << std::endl; + if (is_failed(err)) return env->NewStringUTF(sstr.str().c_str()); + sstr << "auto_su_env_inject done."; + return env->NewStringUTF(sstr.str().c_str()); +} + + + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_getAllCmdlineProcess( + JNIEnv* env, + jclass /* this */, + jstring rootKey) { + string strRootKey = jstringToStr(env, rootKey); + + std::stringstream ss; + std::map pid_map; + KRootErr err = kernel_root::get_all_cmdline_process(strRootKey.c_str(), pid_map); + if (is_failed(err)) { + ss << "get_all_cmdline_process " << to_string(err).c_str() << std::endl; + return env->NewStringUTF(ss.str().c_str()); + } + cJSON *root = cJSON_CreateArray(); + for (auto &iter : pid_map) { + cJSON *item = cJSON_CreateObject(); + string encodeName = urlEncodeToStr(iter.second); + cJSON_AddNumberToObject(item, "pid", iter.first); + cJSON_AddStringToObject(item, "name", encodeName.c_str()); + cJSON_AddItemToArray(root, item); + } + ss << cJSON_Print(root); + cJSON_Delete(root); + return env->NewStringUTF(ss.str().c_str()); +} + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_parasitePrecheckApp( + JNIEnv* env, + jclass /* this */, + jstring rootKey, + jstring targetProcessCmdline) { + string strRootKey = jstringToStr(env, rootKey); + string strTargetProcessCmdline = jstringToStr(env, targetProcessCmdline); + + stringstream sstr; + std::set test_pid; + KRootErr err = kernel_root::find_all_cmdline_process(strRootKey.c_str(), strTargetProcessCmdline.c_str(), test_pid); + if (is_failed(err)) { + sstr << "find_all_cmdline_process " << to_string(err).c_str() << ", cnt:"<< test_pid.size() << std::endl; + return env->NewStringUTF(sstr.str().c_str()); + } + if (test_pid.size() == 0) { + sstr << "目标进程不存在" << std::endl; + return env->NewStringUTF(sstr.str().c_str()); + } + + std::map dynlibPathList; + err = kernel_root::parasite_precheck_app(strRootKey.c_str(), strTargetProcessCmdline.c_str(), dynlibPathList); + if (is_failed(err)) { + sstr << "parasite_precheck_app ret val:" << to_string(err).c_str() << std::endl; + if(err == KRootErr::ERR_EXIST_32BIT) sstr << "此目标APP为32位应用,无法寄生" << std::endl; + return env->NewStringUTF(sstr.str().c_str()); + } + + if (!dynlibPathList.size()) { + sstr << "无法检测到目标APP的JNI环境,目标APP暂不可被寄生;您可重新运行目标APP后重试;或将APP进行手动加固(加壳),因为加固(加壳)APP后,APP会被产生JNI环境,方可寄生!" << std::endl; + return env->NewStringUTF(sstr.str().c_str()); + } + + cJSON *root = cJSON_CreateArray(); + for (auto &iter : dynlibPathList) { + cJSON *item = cJSON_CreateObject(); + string encodeName = urlEncodeToStr(iter.first); + cJSON_AddStringToObject(item, "name", encodeName.c_str()); + cJSON_AddNumberToObject(item, "status", iter.second); + cJSON_AddItemToArray(root, item); + } + sstr << cJSON_Print(root); + cJSON_Delete(root); + return env->NewStringUTF(sstr.str().c_str()); + +} + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_parasiteImplantApp( + JNIEnv* env, + jclass /* this */, + jstring rootKey, + jstring targetProcessCmdline, + jstring targetSoFullPath) { + string strRootKey = jstringToStr(env, rootKey); + string strTargetProcessCmdline = jstringToStr(env, targetProcessCmdline); + string strTargetSoFullPath = jstringToStr(env, targetSoFullPath); + + stringstream sstr; + KRootErr err = kernel_root::parasite_implant_app(strRootKey.c_str(), strTargetProcessCmdline.c_str(), strTargetSoFullPath.c_str()); + if (is_failed(err)) { + sstr << "parasite_implant_app " << to_string(err).c_str() << std::endl; + return env->NewStringUTF(sstr.str().c_str()); + } + sstr << "parasite_implant_app done."; + return env->NewStringUTF(sstr.str().c_str()); + +} + + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_parasiteImplantSuEnv( + JNIEnv* env, + jclass /* this */, + jstring rootKey, + jstring targetProcessCmdline, + jstring targetSoFullPath) { + if(g_last_su_file_path.empty()) { + return env->NewStringUTF("【错误】请先安装部署su"); + } + string strRootKey = jstringToStr(env, rootKey); + string strTargetProcessCmdline = jstringToStr(env, targetProcessCmdline); + string strTargetSoFullPath = jstringToStr(env, targetSoFullPath); + + std::string su_dir_path = std::filesystem::path(g_last_su_file_path).parent_path().string() + "/"; + + stringstream sstr; + KRootErr err = kernel_root::parasite_implant_su_env(strRootKey.c_str(), strTargetProcessCmdline.c_str(), strTargetSoFullPath.c_str(), su_dir_path.c_str()); + if (is_failed(err)) { + sstr << "parasite_implant_su_env " << to_string(err).c_str() << std::endl; + return env->NewStringUTF(sstr.str().c_str()); + } + sstr << "parasite_implant_su_env done."; + return env->NewStringUTF(sstr.str().c_str()); + +} diff --git a/Lite_version/src/PermissionManager/app/src/main/cpp/urlEncodeUtils.h b/Lite_version/src/PermissionManager/app/src/main/cpp/urlEncodeUtils.h new file mode 100644 index 00000000..0d1482f7 --- /dev/null +++ b/Lite_version/src/PermissionManager/app/src/main/cpp/urlEncodeUtils.h @@ -0,0 +1,74 @@ +#ifndef URL_ENCODE_UTILS_H_ +#define URL_ENCODE_UTILS_H_ +#include +#include + +static inline char to_hex(char code) { + static char hex[] = "0123456789ABCDEF"; + return hex[code & 15]; +} +static inline char from_hex(char ch) { + return isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10; +} + +/* +//使用例子 +int main() { + char str[] = "你好,世界"; + char encoded_str[256]; + url_encode(str, encoded_str); + printf("Encoded URL: %s\n", encoded_str); + return 0; +} +*/ +static void url_encode(char *str, char *encoded_str) { + char *pstr = str, *buf = encoded_str; + while (*pstr) { + unsigned char c = *pstr; + if (c <= 0x7F) { // ASCII + if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') { + *buf++ = c; + } else if (c == ' ') { + *buf++ = '+'; + } else { + *buf++ = '%', *buf++ = to_hex(c >> 4), *buf++ = to_hex(c & 15); + } + } else { // Non-ASCII + while (c) { + *buf++ = '%', *buf++ = to_hex(c >> 4), *buf++ = to_hex(c & 15); + c = *(++pstr); + } + continue; + } + pstr++; + } + *buf = '\0'; +} +/* +//使用例子 +int main() { + char url[] = "%E4%BD%A0%E5%A5%BD%EF%BC%8C%E4%B8%96%E7%95%8C"; // "你好,世界"的URL编码 + char decoded_str[256]; + url_decode(url, decoded_str); + printf("Decoded URL: %s\n", decoded_str); + return 0; +} +*/ +static void url_decode(char *str, char *decoded_str) { + char *pstr = str, *buf = decoded_str; + while (*pstr) { + if (*pstr == '%') { + if (pstr[1] && pstr[2]) { + *buf++ = from_hex(pstr[1]) << 4 | from_hex(pstr[2]); + pstr += 2; + } + } else if (*pstr == '+') { + *buf++ = ' '; + } else { + *buf++ = *pstr; + } + pstr++; + } + *buf = '\0'; +} +#endif \ No newline at end of file diff --git a/Lite_version/src/PermissionManager/app/src/main/ic_launcher-playstore.png b/Lite_version/src/PermissionManager/app/src/main/ic_launcher-playstore.png new file mode 100644 index 00000000..c8e58bd5 Binary files /dev/null and b/Lite_version/src/PermissionManager/app/src/main/ic_launcher-playstore.png differ diff --git a/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/AppSettings.java b/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/AppSettings.java new file mode 100644 index 00000000..c065f5e7 --- /dev/null +++ b/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/AppSettings.java @@ -0,0 +1,69 @@ +package com.linux.permissionmanager; + +import android.content.Context; +import android.content.SharedPreferences; + +import java.util.Collections; +import java.util.Set; + +public class AppSettings { + private static SharedPreferences preferences; + + public static void init(Context context) { + if (preferences == null) { + preferences = context.getSharedPreferences("AppSettings", Context.MODE_PRIVATE); + } + } + + public static void setBoolean(String key, boolean value) { + preferences.edit().putBoolean(key, value).apply(); + } + + public static boolean getBoolean(String key, boolean defaultValue) { + try { + return preferences.getBoolean(key, defaultValue); + } catch (Exception e) { + e.printStackTrace(); + } + return defaultValue; + } + + public static void setString(String key, String value) { + preferences.edit().putString(key, value).apply(); + } + + public static String getString(String key, String defaultValue) { + try { + return preferences.getString(key, defaultValue); + } catch (Exception e) { + e.printStackTrace(); + } + return defaultValue; + } + + public static void setInt(String key, int value) { + preferences.edit().putInt(key, value).apply(); + } + + public static int getInt(String key, int defaultValue) { + try { + return preferences.getInt(key, defaultValue); + } catch (Exception e) { + e.printStackTrace(); + } + return defaultValue; + } + + public static void setStringSet(String key, Set value) { + preferences.edit().putStringSet(key, value).apply(); + } + + public static Set getStringSet(String key, Set defaultValue) { + try { + return preferences.getStringSet(key, defaultValue); + } catch (Exception e) { + e.printStackTrace(); + } + return defaultValue != null ? defaultValue : Collections.emptySet(); + } +} diff --git a/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/MainActivity.java b/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/MainActivity.java new file mode 100644 index 00000000..3a31fba8 --- /dev/null +++ b/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/MainActivity.java @@ -0,0 +1,419 @@ +package com.linux.permissionmanager; + +import android.app.AlertDialog; +import android.app.ProgressDialog; +import android.content.DialogInterface; +import android.graphics.Paint; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.view.View; +import android.widget.Button; +import android.widget.CheckBox; +import android.widget.EditText; +import android.widget.TextView; +import android.widget.Toast; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; + +import com.linux.permissionmanager.bridge.NativeBridge; +import com.linux.permissionmanager.helper.SelectAppDlg; +import com.linux.permissionmanager.helper.SelectFileDlg; +import com.linux.permissionmanager.model.SelectAppItem; +import com.linux.permissionmanager.model.SelectFileItem; +import com.linux.permissionmanager.utils.ClipboardUtils; +import com.linux.permissionmanager.utils.DialogUtils; +import com.linux.permissionmanager.utils.GetAppListPermissionHelper; +import com.linux.permissionmanager.utils.UrlIntentUtils; + +import org.json.JSONArray; +import org.json.JSONObject; + +import java.net.URLDecoder; +import java.util.HashMap; +import java.util.Map; + +public class MainActivity extends AppCompatActivity implements View.OnClickListener { + private String rootKey = ""; + private String lastInputCmd = "id"; + private String lastInputRootExecPath = ""; + private ProgressDialog m_loadingDlg = null; + + private EditText console_edit; + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_main); + AppSettings.init(this); + + rootKey = AppSettings.getString("rootKey", rootKey); + lastInputCmd = AppSettings.getString("lastInputCmd", lastInputCmd); + lastInputRootExecPath = AppSettings.getString("lastInputRootExecPath", lastInputRootExecPath); + checkGetAppListPermission(); + showInputRootKeyDlg(); + + Button test_root_btn = findViewById(R.id.test_root_btn); + Button run_root_cmd_btn = findViewById(R.id.run_root_cmd_btn); + Button root_exec_process_btn = findViewById(R.id.root_exec_process_btn); + Button su_env_install_btn = findViewById(R.id.su_env_install_btn); + Button su_env_inject_btn = findViewById(R.id.su_env_inject_btn); + Button clean_su_btn = findViewById(R.id.clean_su_btn); + Button implant_app_btn = findViewById(R.id.implant_app_btn); + Button copy_info_btn = findViewById(R.id.copy_info_btn); + Button clean_info_btn = findViewById(R.id.clean_info_btn); + console_edit = findViewById(R.id.console_edit); + + test_root_btn.setOnClickListener(this); + run_root_cmd_btn.setOnClickListener(this); + root_exec_process_btn.setOnClickListener(this); + su_env_install_btn.setOnClickListener(this); + su_env_inject_btn.setOnClickListener(this); + clean_su_btn.setOnClickListener(this); + implant_app_btn.setOnClickListener(this); + copy_info_btn.setOnClickListener(this); + clean_info_btn.setOnClickListener(this); + initLink(); + } + + @Override + public void onClick(View v) { + switch (v.getId()) { + case R.id.test_root_btn: + appendConsoleMsg(NativeBridge.testRoot(rootKey)); + break; + case R.id.run_root_cmd_btn: + showInputRootCmdDlg(); + break; + case R.id.root_exec_process_btn: + showInputRootExecProcessPathDlg(); + break; + case R.id.su_env_install_btn: + onClickSuEnvInstallBtn(); + break; + case R.id.su_env_inject_btn: + showSelectSuInjectModeDlg(); + break; + case R.id.clean_su_btn: + onClickSuEnvUninstallBtn(); + break; + case R.id.implant_app_btn: + onClickImplantAppBtn(); + break; + case R.id.copy_info_btn: + copyConsoleMsg(); + break; + case R.id.clean_info_btn: + cleanConsoleMsg(); + break; + default: + break; + } + } + + private void initLink() { + TextView link_tv = findViewById(R.id.link_tv); + link_tv.setText("https://github.com/abcz316/SKRoot-linuxKernelRoot"); + link_tv.setOnClickListener(v -> { UrlIntentUtils.openUrl(this, link_tv.getText().toString()); }); + link_tv.getPaint().setFlags(link_tv.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); + } + + private void showSkrootStatus() { + appendConsoleMsg("版本:" + BuildConfig.VERSION_NAME); + } + + public void showInputRootKeyDlg() { + Handler inputCallback = new Handler() { + @Override + public void handleMessage(@NonNull Message msg) { + String text = (String)msg.obj; + rootKey = text; + AppSettings.setString("rootKey", rootKey); + showSkrootStatus(); + super.handleMessage(msg); + } + }; + DialogUtils.showInputDlg(this, rootKey,"请输入ROOT权限的KEY", null, inputCallback, null); + } + private void checkGetAppListPermission() { + if(GetAppListPermissionHelper.getPermissions(this)) return; + DialogUtils.showCustomDialog(this,"权限申请","请授予读取APP列表权限,再重新打开",null,"确定", (dialog, which) -> { + dialog.dismiss(); + finish(); + },null, null + ); + } + + public void showInputRootCmdDlg() { + Handler inputCallback = new Handler() { + @Override + public void handleMessage(@NonNull Message msg) { + String text = (String)msg.obj; + lastInputCmd = text; + AppSettings.setString("lastInputCmd", lastInputCmd); + appendConsoleMsg(text + "\n" + NativeBridge.runRootCmd(rootKey, text)); + super.handleMessage(msg); + } + }; + DialogUtils.showInputDlg(this, lastInputCmd, "请输入ROOT命令", null, inputCallback, null); + } + + public void showInputRootExecProcessPathDlg() { + Handler inputCallback = new Handler() { + @Override + public void handleMessage(@NonNull Message msg) { + String text = (String)msg.obj; + + lastInputRootExecPath = text; + AppSettings.setString("lastInputRootExecPath", lastInputRootExecPath); + appendConsoleMsg(text + "\n" + NativeBridge.rootExecProcessCmd(rootKey, text)); + super.handleMessage(msg); + } + }; + Handler helperCallback = new Handler() { + @Override + public void handleMessage(@NonNull Message msg) { + DialogUtils.showMsgDlg(MainActivity.this,"帮助", "请将JNI可执行文件放入/data内任意目录并且赋予777权限,如/data/app/com.xx,然后输入文件路径,即可直接执行,如:\n/data/com.xx/aaa\n", null); + super.handleMessage(msg); + } + }; + DialogUtils.showInputDlg(this, lastInputRootExecPath, "请输入Linux可运行文件的位置", "指导", inputCallback, helperCallback); + DialogUtils.showMsgDlg(this,"提示", "本功能是以ROOT身份直接运行程序,可避免产生su、sh等多余驻留后台进程,能最大程度上避免侦测", null); + } + + public void onClickSuEnvInstallBtn() { + String insRet = NativeBridge.installSu(rootKey); + appendConsoleMsg(insRet); + if(insRet.indexOf("install_su done.") != -1) { + String suFilePath = NativeBridge.getLastSuFilePath(); + appendConsoleMsg("last_su_file_path:" + suFilePath); + DialogUtils.showMsgDlg(this,"温馨提示","安装部署su成功,su路径已复制到剪贴板。", null); + ClipboardUtils.copyText(this, suFilePath); + appendConsoleMsg("安装部署su成功,su路径已复制到剪贴板"); + } + } + + public void onClickSuEnvUninstallBtn() { + appendConsoleMsg(NativeBridge.uninstallSu(rootKey)); + ClipboardUtils.copyText(this, ""); + } + + private void suTempInject() { + Handler selectInjectSuAppCallback = new Handler() { + @Override + public void handleMessage(@NonNull Message msg) { + SelectAppItem app = (SelectAppItem) msg.obj; + if (m_loadingDlg == null) { + m_loadingDlg = new ProgressDialog(MainActivity.this); + m_loadingDlg.setCancelable(false); + } + m_loadingDlg.setTitle(""); + m_loadingDlg.setMessage("请现在手动启动APP [" + app.getShowName(MainActivity.this) + "]"); + m_loadingDlg.show(); + startSuTempInjectThread(app); + super.handleMessage(msg); + } + }; + SelectAppDlg.showSelectAppDlg(MainActivity.this, rootKey, selectInjectSuAppCallback); + } + + private void startSuTempInjectThread(SelectAppItem app) { + new Thread() { + public void run() { + String autoSuEnvInjectRet = NativeBridge.autoSuEnvInject(rootKey, app.getPackageName()); + runOnUiThread(new Runnable() { + public void run() { + appendConsoleMsg(autoSuEnvInjectRet); + m_loadingDlg.cancel(); + + if(autoSuEnvInjectRet.indexOf("auto_su_env_inject done.") != -1) { + DialogUtils.showMsgDlg(MainActivity.this, "提示","已授予ROOT权限至APP [" + app.getShowName(MainActivity.this) + "]", + app.getDrawable(MainActivity.this)); + } + } + }); + } + }.start(); + } + + private void suForeverInject() { + Handler selectImplantSuEnvCallback = new Handler() { + @Override + public void handleMessage(@NonNull Message msg) { + SelectAppItem app = (SelectAppItem) msg.obj; + if (m_loadingDlg == null) { + m_loadingDlg = new ProgressDialog(MainActivity.this); + m_loadingDlg.setCancelable(false); + } + m_loadingDlg.setTitle(""); + m_loadingDlg.setMessage("请现在手动启动APP [" + app.getShowName(MainActivity.this) + "]"); + m_loadingDlg.show(); + startSuForeverInjectThread(app); + super.handleMessage(msg); + } + }; + View view = SelectAppDlg.showSelectAppDlg(MainActivity.this, rootKey, selectImplantSuEnvCallback); + CheckBox show_system_app_ckbox = view.findViewById(R.id.show_system_app_ckbox); + CheckBox show_thirty_app_ckbox = view.findViewById(R.id.show_thirty_app_ckbox); + CheckBox show_running_app_ckbox = view.findViewById(R.id.show_running_app_ckbox); + show_system_app_ckbox.setChecked(false); + show_system_app_ckbox.setEnabled(false); + show_thirty_app_ckbox.setChecked(true); + show_thirty_app_ckbox.setEnabled(false); + show_running_app_ckbox.setChecked(true); + show_running_app_ckbox.setEnabled(false); + } + + private void startSuForeverInjectThread(SelectAppItem app) { + new Thread() { + public void run() { + String parasitePrecheckAppRet = NativeBridge.parasitePrecheckApp(rootKey, app.getPackageName()); + runOnUiThread(new Runnable() { + public void run() { + m_loadingDlg.cancel(); + Map fileList = parseSoFullPathInfo(parasitePrecheckAppRet); + if (fileList.size() == 0 && !parasitePrecheckAppRet.isEmpty()) { + appendConsoleMsg(parasitePrecheckAppRet); + return; + } + Handler selectFileCallback = new Handler() { + @Override + public void handleMessage(@NonNull Message msg) { + SelectFileItem fileItem = (SelectFileItem) msg.obj; + String parasiteImplantSuEnvRet = NativeBridge.parasiteImplantSuEnv(rootKey, app.getPackageName(), fileItem.getFilePath()); + appendConsoleMsg(parasiteImplantSuEnvRet); + if(parasiteImplantSuEnvRet.indexOf("parasite_implant_su_env done.")!= -1) { + DialogUtils.showMsgDlg(MainActivity.this, "提示","已永久寄生su环境至APP [" + app.getShowName(MainActivity.this) + "]", + app.getDrawable(MainActivity.this)); + } + super.handleMessage(msg); + } + }; + SelectFileDlg.showSelectFileDlg(MainActivity.this, fileList, selectFileCallback); + } + }); + } + }.start(); + } + + public void showSelectSuInjectModeDlg() { + final String[] items = {"临时授权su", "永久授权su"}; + AlertDialog.Builder builder = new AlertDialog.Builder(this); + builder.setTitle("请选择一个选项"); + builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + if(which == 0) suTempInject(); + else if(which == 1) suForeverInject(); + } + }); + builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } + }); + AlertDialog dialog = builder.create(); + dialog.show(); + } + + + private void onClickImplantAppBtn() { + Handler selectImplantAppCallback = new Handler() { + @Override + public void handleMessage(@NonNull Message msg) { + SelectAppItem app = (SelectAppItem) msg.obj; + if (m_loadingDlg == null) { + m_loadingDlg = new ProgressDialog(MainActivity.this); + m_loadingDlg.setCancelable(false); + } + m_loadingDlg.setTitle(""); + m_loadingDlg.setMessage("请现在手动启动APP [" + app.getShowName(MainActivity.this) + "]"); + m_loadingDlg.show(); + startImplantAppThread(app); + super.handleMessage(msg); + } + }; + View view = SelectAppDlg.showSelectAppDlg(MainActivity.this, rootKey, selectImplantAppCallback); + CheckBox show_system_app_ckbox = view.findViewById(R.id.show_system_app_ckbox); + CheckBox show_thirty_app_ckbox = view.findViewById(R.id.show_thirty_app_ckbox); + CheckBox show_running_app_ckbox = view.findViewById(R.id.show_running_app_ckbox); + show_system_app_ckbox.setChecked(false); + show_system_app_ckbox.setEnabled(false); + show_thirty_app_ckbox.setChecked(true); + show_thirty_app_ckbox.setEnabled(false); + show_running_app_ckbox.setChecked(true); + show_running_app_ckbox.setEnabled(false); + } + + private void startImplantAppThread(SelectAppItem app) { + new Thread() { + public void run() { + String parasitePrecheckAppRet = NativeBridge.parasitePrecheckApp(rootKey, app.getPackageName()); + runOnUiThread(new Runnable() { + public void run() { + m_loadingDlg.cancel(); + Map fileList = parseSoFullPathInfo(parasitePrecheckAppRet); + if (fileList.size() == 0 && !parasitePrecheckAppRet.isEmpty()) { + appendConsoleMsg(parasitePrecheckAppRet); + return; + } + Handler selectFileCallback = new Handler() { + @Override + public void handleMessage(@NonNull Message msg) { + SelectFileItem fileItem = (SelectFileItem) msg.obj; + String parasiteImplantAppRet = NativeBridge.parasiteImplantApp(rootKey, app.getPackageName(), fileItem.getFilePath()); + appendConsoleMsg(parasiteImplantAppRet); + if(parasiteImplantAppRet.indexOf("parasite_implant_app done.")!= -1) { + DialogUtils.showMsgDlg(MainActivity.this, "提示", + "已经寄生到APP [" + app.getShowName(MainActivity.this) + "]", + app.getDrawable(MainActivity.this)); + } + super.handleMessage(msg); + } + }; + SelectFileDlg.showSelectFileDlg(MainActivity.this, fileList, selectFileCallback); + } + }); + } + }.start(); + } + + private void appendConsoleMsg(String msg) { + StringBuffer txt = new StringBuffer(); + txt.append(console_edit.getText().toString()); + if (txt.length() != 0) txt.append("\n"); + txt.append(msg); + txt.append("\n"); + console_edit.setText(txt.toString()); + console_edit.setSelection(txt.length()); + } + + public void copyConsoleMsg() { + ClipboardUtils.copyText(this, console_edit.getText().toString()); + Toast.makeText(this, "复制成功", Toast.LENGTH_SHORT).show(); + } + + public void cleanConsoleMsg() { + console_edit.setText(""); + } + + private Map parseSoFullPathInfo(String jsonStr) { + Map soPathMap = new HashMap<>(); + try { + JSONArray jsonArray = new JSONArray(jsonStr); + for (int i = 0; i < jsonArray.length(); i++) { + JSONObject jsonObject = jsonArray.getJSONObject(i); + String name = URLDecoder.decode(jsonObject.getString("name"), "UTF-8"); + int n = jsonObject.getInt("status"); + SelectFileDlg.FileStatus status = SelectFileDlg.FileStatus.Unknown; + status = n == 1 ? SelectFileDlg.FileStatus.Running : status; + status = n == 2 ? SelectFileDlg.FileStatus.NotRunning : status; + soPathMap.put(name, status); + } + } catch (Exception e) { + e.printStackTrace(); + } + return soPathMap; + } + +} \ No newline at end of file diff --git a/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/adapter/SelectAppAdapter.java b/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/adapter/SelectAppAdapter.java new file mode 100644 index 00000000..7af6f333 --- /dev/null +++ b/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/adapter/SelectAppAdapter.java @@ -0,0 +1,102 @@ +package com.linux.permissionmanager.adapter; + +import android.graphics.Color; +import android.graphics.drawable.Drawable; +import android.text.SpannableStringBuilder; +import android.text.Spanned; +import android.text.style.ForegroundColorSpan; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ImageView; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.recyclerview.widget.RecyclerView; + +import com.linux.permissionmanager.model.SelectAppItem; +import com.linux.permissionmanager.R; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class SelectAppAdapter extends RecyclerView.Adapter { + public interface OnAppSelectedListener { + void onAppSelected(@NonNull SelectAppItem item); + } + + private final int itemLayoutId; + private final List items = new ArrayList<>(); + @NonNull private final OnAppSelectedListener listener; + + public SelectAppAdapter(int itemLayoutId, @NonNull List initialItems, @NonNull OnAppSelectedListener listener) { + this.itemLayoutId = itemLayoutId; + this.listener = listener; + setData(initialItems); + } + + public void setData(@Nullable List newList) { + items.clear(); + if (newList != null) items.addAll(newList); + notifyDataSetChanged(); + } + + @NonNull + public List getData() { + return Collections.unmodifiableList(items); + } + + @NonNull + @Override + public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { + View v = LayoutInflater.from(parent.getContext()).inflate(itemLayoutId, parent, false); + return new ViewHolder(v); + } + + @Override + public void onBindViewHolder(@NonNull ViewHolder holder, int position) { + SelectAppItem item = items.get(position); + + Drawable icon = item.getDrawable(holder.itemView.getContext()); + String showName = item.getShowName(holder.itemView.getContext()); + String packageName = item.getPackageName(); + + holder.icon.setImageDrawable(icon); + holder.name.setText(buildColoredTitle(showName, packageName)); + holder.pkg.setText(packageName); + holder.itemView.setOnClickListener(v -> listener.onAppSelected(item)); + } + + @Override + public int getItemCount() { + return items.size(); + } + + private CharSequence buildColoredTitle(String showName, String packageName) { + SpannableStringBuilder ssb = new SpannableStringBuilder(); + + int startName = ssb.length(); + ssb.append(showName); + ssb.setSpan(new ForegroundColorSpan(Color.parseColor("#88CC88")), startName, ssb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + ssb.append(" "); + int startPkg = ssb.length(); + ssb.append("(").append(packageName).append(")"); + ssb.setSpan(new ForegroundColorSpan(Color.parseColor("#88CCCC")), startPkg, ssb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + return ssb; + } + + static class ViewHolder extends RecyclerView.ViewHolder { + final ImageView icon; + final TextView name; + final TextView pkg; + + ViewHolder(@NonNull View itemView) { + super(itemView); + icon = itemView.findViewById(R.id.select_app_icon); + name = itemView.findViewById(R.id.select_app_text); + pkg = itemView.findViewById(R.id.select_package_name); + } + } +} diff --git a/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/adapter/SelectFileAdapter.java b/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/adapter/SelectFileAdapter.java new file mode 100644 index 00000000..464daf44 --- /dev/null +++ b/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/adapter/SelectFileAdapter.java @@ -0,0 +1,93 @@ +package com.linux.permissionmanager.adapter; + +import android.graphics.Color; +import android.text.SpannableStringBuilder; +import android.text.Spanned; +import android.text.style.ForegroundColorSpan; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.TextView; + +import androidx.annotation.ColorInt; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.recyclerview.widget.RecyclerView; + +import com.linux.permissionmanager.model.SelectFileItem; +import com.linux.permissionmanager.R; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +public class SelectFileAdapter extends RecyclerView.Adapter { + + public interface OnFileSelectedListener { + void onFileSelected(@NonNull SelectFileItem item); + } + private final int itemLayoutId; + private final List items = new ArrayList<>(); + @NonNull private final OnFileSelectedListener listener; + + public SelectFileAdapter(int itemLayoutId, @NonNull List initialItems, @NonNull OnFileSelectedListener listener) { + this.itemLayoutId = itemLayoutId; + this.listener = listener; + setData(initialItems); + } + + public void setData(@Nullable List newList) { + items.clear(); + if (newList != null) items.addAll(newList); + notifyDataSetChanged(); + } + + @NonNull + public List getData() { + return Collections.unmodifiableList(items); + } + + @NonNull + @Override + public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { + View v = LayoutInflater.from(parent.getContext()).inflate(itemLayoutId, parent, false); + return new ViewHolder(v); + } + + @Override + public void onBindViewHolder(@NonNull ViewHolder holder, int position) { + SelectFileItem item = items.get(position); + + String fileName = item.getFileName(); + String fileDesc = item.getFileDesc(); + + Color fileDescColor = item.getFileDescColor(); + @ColorInt int descColor = fileDescColor.toArgb(); + + holder.name.setText(buildColoredText(fileName, 0xFF88CC88)); + holder.desc.setText(buildColoredText(fileDesc, descColor)); + + holder.itemView.setOnClickListener(v -> listener.onFileSelected(item)); + } + + @Override + public int getItemCount() { + return items.size(); + } + + private CharSequence buildColoredText(String text, @ColorInt int color) { + SpannableStringBuilder ssb = new SpannableStringBuilder(text); + ssb.setSpan(new ForegroundColorSpan(color), 0, ssb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + return ssb; + } + + static class ViewHolder extends RecyclerView.ViewHolder { + final TextView name; + final TextView desc; + + ViewHolder(@NonNull View itemView) { + super(itemView); + name = itemView.findViewById(R.id.select_file_name); + desc = itemView.findViewById(R.id.select_file_desc); + } + } +} \ No newline at end of file diff --git a/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/bridge/NativeBridge.java b/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/bridge/NativeBridge.java new file mode 100644 index 00000000..94dcf69f --- /dev/null +++ b/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/bridge/NativeBridge.java @@ -0,0 +1,30 @@ +package com.linux.permissionmanager.bridge; + +public class NativeBridge { + static { + System.loadLibrary("permissionmanager"); + } + + public static native String testRoot(String rootKey); + + public static native String runRootCmd(String rootKey, String cmd); + + public static native String rootExecProcessCmd(String rootKey, String cmd); + + public static native String installSu(String rootKey); + + public static native String getLastSuFilePath(); + + public static native String uninstallSu(String rootKey); + + public static native String autoSuEnvInject(String rootKey, String targetProcessCmdline); + + public static native String getAllCmdlineProcess(String rootKey); + + public static native String parasitePrecheckApp(String rootKey, String targetProcessCmdline); + + public static native String parasiteImplantApp(String rootKey, String targetProcessCmdline, String targetSoFullPath); + + public static native String parasiteImplantSuEnv(String rootKey, String targetProcessCmdline, String targetSoFullPath); + +} diff --git a/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/helper/SelectAppDlg.java b/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/helper/SelectAppDlg.java new file mode 100644 index 00000000..f0c8ccf8 --- /dev/null +++ b/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/helper/SelectAppDlg.java @@ -0,0 +1,184 @@ +package com.linux.permissionmanager.helper; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageInfo; +import android.graphics.drawable.ColorDrawable; +import android.os.Handler; +import android.os.Message; +import android.text.Editable; +import android.text.TextWatcher; +import android.view.Gravity; +import android.view.View; +import android.view.ViewGroup; +import android.widget.CheckBox; +import android.widget.CompoundButton; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.PopupWindow; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import com.linux.permissionmanager.R; +import com.linux.permissionmanager.adapter.SelectAppAdapter; +import com.linux.permissionmanager.bridge.NativeBridge; +import com.linux.permissionmanager.model.SelectAppItem; +import com.linux.permissionmanager.utils.ScreenInfoUtils; + +import org.json.JSONArray; +import org.json.JSONObject; + +import java.net.URLDecoder; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class SelectAppDlg { + public static View showSelectAppDlg(Activity activity, String rootKey, Handler selectAppCallback) { + final PopupWindow popupWindow = new PopupWindow(activity); + View view = View.inflate(activity, R.layout.select_app_wnd, null); + popupWindow.setContentView(view); + popupWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT); + popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT); + popupWindow.setBackgroundDrawable(new ColorDrawable(0x9B000000)); + popupWindow.setOutsideTouchable(true); + popupWindow.setFocusable(true); + popupWindow.setTouchable(true); + //全屏 + View parent = View.inflate(activity, R.layout.activity_main, null); + popupWindow.showAtLocation(parent, Gravity.NO_GRAVITY, 0, 0); + popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() { + @Override + public void onDismiss() {} + }); + final int screenWidth = ScreenInfoUtils.getRealWidth(activity); + final int screenHeight = ScreenInfoUtils.getRealHeight(activity); + + final double centerWidth = ((double) screenWidth) * 0.80; + final double centerHeight = ((double) screenHeight) * 0.90; + + LinearLayout center_layout = (LinearLayout) view.findViewById(R.id.center_layout); + ViewGroup.LayoutParams lp = center_layout.getLayoutParams(); + lp.width = (int) centerWidth; + lp.height = (int) centerHeight; + center_layout.setLayoutParams(lp); + + // 外层容器:点到阴影就关闭弹窗 + View outside = view.findViewById(R.id.popup_outside_container); + outside.setOnClickListener(v -> popupWindow.dismiss()); + // 中间内容区域:消费点击,不往外传(防止点内容也被当成点阴影) + center_layout.setOnClickListener(v -> { + // 什么都不做,只是阻止事件传到 outside + }); + + List appList = new ArrayList<>(); + List packages = activity.getPackageManager().getInstalledPackages(0); + + for (int i = 0; i < packages.size(); i++) { + PackageInfo packageInfo = packages.get(i); + String packageName = packageInfo.applicationInfo.packageName; + if(packageName.equals(activity.getPackageName())) continue; + appList.add(new SelectAppItem(packageInfo)); + } + + SelectAppAdapter adapter = new SelectAppAdapter(R.layout.select_app_recycler_item, appList, + item -> { + popupWindow.dismiss(); + Message msg = new Message(); msg.obj = item; + selectAppCallback.sendMessage(msg); + } + ); + RecyclerView select_app_recycler_view = (RecyclerView) view.findViewById(R.id.select_app_recycler_view); + LinearLayoutManager linearLayoutManager = new LinearLayoutManager(activity); + linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); + select_app_recycler_view.setLayoutManager(linearLayoutManager); + select_app_recycler_view.setAdapter(adapter); + + // 获取正在运行的APP + String runningApp = NativeBridge.getAllCmdlineProcess(rootKey); + Map processMap = parseProcessInfo(runningApp); + TextView clear_search_btn = view.findViewById(R.id.clear_search_btn); + EditText search_edit = view.findViewById(R.id.search_edit); + CheckBox show_system_app_ckbox = view.findViewById(R.id.show_system_app_ckbox); + CheckBox show_thirty_app_ckbox = view.findViewById(R.id.show_thirty_app_ckbox); + CheckBox show_running_app_ckbox = view.findViewById(R.id.show_running_app_ckbox); + show_system_app_ckbox.setEnabled(true); + show_thirty_app_ckbox.setEnabled(true); + show_running_app_ckbox.setEnabled(true); + Map finalProcessMap = processMap; + @SuppressLint("HandlerLeak") Handler updateAppListFunc = new Handler() { + @Override + public void handleMessage(@NonNull Message msg) { + List newAppList = new ArrayList<>(); + String filterText = search_edit.getText().toString(); + for(SelectAppItem item : appList) { + PackageInfo pack = item.getPackageInfo(); + if(!show_system_app_ckbox.isChecked()) { + if ((pack.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) continue; //系统应用 + } + if(!show_thirty_app_ckbox.isChecked()) { + if ((pack.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) continue; // 第三方应用 + } + if (show_running_app_ckbox.isChecked()) { + boolean isFound = finalProcessMap.values().stream().anyMatch(value -> value.contains(item.getPackageName())); + if (!isFound) continue; + } + if(item.getPackageName().indexOf(filterText) != -1 || item.getShowName(activity).indexOf(filterText) != -1) newAppList.add(item); + } + adapter.setData(newAppList); + super.handleMessage(msg); + } + }; + search_edit.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) {} + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + clear_search_btn.setVisibility(s.toString().length() > 0 ? View.VISIBLE : View.GONE); + updateAppListFunc.sendMessage(new Message()); + } + @Override + public void afterTextChanged(Editable s) {} + }); + clear_search_btn.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { search_edit.setText(""); } + }); + + show_system_app_ckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { + @Override + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { updateAppListFunc.sendMessage(new Message()); } + }); + show_thirty_app_ckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { + @Override + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { updateAppListFunc.sendMessage(new Message()); } + }); + show_running_app_ckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { + @Override + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { updateAppListFunc.sendMessage(new Message()); } + }); + updateAppListFunc.sendMessage(new Message()); + return view; + } + + private static Map parseProcessInfo(String jsonStr) { + Map processMap = new HashMap<>(); + try { + JSONArray jsonArray = new JSONArray(jsonStr); + for (int i = 0; i < jsonArray.length(); i++) { + JSONObject jsonObject = jsonArray.getJSONObject(i); + int pid = jsonObject.getInt("pid"); + String encodedValue = jsonObject.getString("name"); + String name = URLDecoder.decode(encodedValue, "UTF-8"); + processMap.put(pid, name); + } + } catch (Exception e) { e.printStackTrace(); } + return processMap; + } +} diff --git a/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/helper/SelectFileDlg.java b/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/helper/SelectFileDlg.java new file mode 100644 index 00000000..95b19602 --- /dev/null +++ b/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/helper/SelectFileDlg.java @@ -0,0 +1,151 @@ +package com.linux.permissionmanager.helper; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.graphics.Color; +import android.graphics.drawable.ColorDrawable; +import android.os.Handler; +import android.os.Message; +import android.text.Editable; +import android.text.TextWatcher; +import android.view.Gravity; +import android.view.View; +import android.view.ViewGroup; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.PopupWindow; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import com.linux.permissionmanager.R; +import com.linux.permissionmanager.adapter.SelectAppAdapter; +import com.linux.permissionmanager.adapter.SelectFileAdapter; +import com.linux.permissionmanager.model.SelectFileItem; +import com.linux.permissionmanager.utils.ScreenInfoUtils; + +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class SelectFileDlg { + + private static String[] RECOMMEND_FILES = {"libc++_shared.so"}; + + public enum FileStatus { + Unknown, + Running, + NotRunning, + }; + public static View showSelectFileDlg(Activity activity, Map filePath, Handler selectFileCallback) { + final PopupWindow popupWindow = new PopupWindow(activity); + View view = View.inflate(activity, R.layout.select_file_wnd, null); + popupWindow.setContentView(view); + popupWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT); + popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT); + popupWindow.setBackgroundDrawable(new ColorDrawable(0x9B000000)); + popupWindow.setOutsideTouchable(true); + popupWindow.setFocusable(true); + popupWindow.setTouchable(true); + + //全屏 + View parent = View.inflate(activity, R.layout.activity_main, null); + popupWindow.showAtLocation(parent, Gravity.NO_GRAVITY, 0, 0); + popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() { + @Override + public void onDismiss() {} + }); + final int screenWidth = ScreenInfoUtils.getRealWidth(activity); + final int screenHeight = ScreenInfoUtils.getRealHeight(activity); + final double centerWidth = ((double) screenWidth) * 0.80; + final double centerHeight = ((double) screenHeight) * 0.90; + LinearLayout center_layout = (LinearLayout) view.findViewById(R.id.center_layout); + ViewGroup.LayoutParams lp = center_layout.getLayoutParams(); + lp.width = (int) centerWidth; + lp.height = (int) centerHeight; + center_layout.setLayoutParams(lp); + // 外层容器:点到阴影就关闭弹窗 + View outside = view.findViewById(R.id.popup_outside_container); + outside.setOnClickListener(v -> popupWindow.dismiss()); + // 中间内容区域:消费点击,不往外传(防止点内容也被当成点阴影) + center_layout.setOnClickListener(v -> { + // 什么都不做,只是阻止事件传到 outside + }); + + List fileList = new ArrayList<>(); + for (Map.Entry entry : filePath.entrySet()) { + String strFilePath = entry.getKey(); + FileStatus status = entry.getValue(); + if(status != FileStatus.Running) continue; + String strFileDesc = checkIsRecommendFile(strFilePath) ? "(推荐,正在运行)" : "(正在运行)"; + fileList.add(new SelectFileItem(strFilePath, strFileDesc, Color.valueOf(0xFFFFFFFF))); + } + for (Map.Entry entry : filePath.entrySet()) { + String strFilePath = entry.getKey(); + FileStatus status = entry.getValue(); + if(status != FileStatus.NotRunning) continue; + String strFileDesc ="(未运行)"; + fileList.add(new SelectFileItem(strFilePath, strFileDesc, Color.valueOf(Color.GRAY))); + } + SelectFileAdapter adapter = new SelectFileAdapter(R.layout.select_file_recycler_item, fileList, + item -> { + popupWindow.dismiss(); + Message msg = new Message(); msg.obj = item; + selectFileCallback.sendMessage(msg); + } + ); + RecyclerView select_file_recycler_view = (RecyclerView) view.findViewById(R.id.select_file_recycler_view); + LinearLayoutManager linearLayoutManager = new LinearLayoutManager(activity); + linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); + select_file_recycler_view.setLayoutManager(linearLayoutManager); + select_file_recycler_view.setAdapter(adapter); + TextView clear_search_btn = view.findViewById(R.id.clear_search_btn); + EditText search_edit = view.findViewById(R.id.search_edit); + @SuppressLint("HandlerLeak") Handler updateFileListFunc = new Handler() { + @Override + public void handleMessage(@NonNull Message msg) { + List newFileList = new ArrayList<>(); + String filterText = search_edit.getText().toString(); + for(SelectFileItem item : fileList) { + String fileName = item.getFileName(); + if(fileName.indexOf(filterText) != -1) newFileList.add(item); + } + adapter.setData(newFileList); + super.handleMessage(msg); + } + }; + search_edit.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) {} + + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + clear_search_btn.setVisibility(s.toString().length() > 0 ? View.VISIBLE : View.GONE); + updateFileListFunc.sendMessage(new Message()); + } + + @Override + public void afterTextChanged(Editable s) {} + }); + clear_search_btn.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { search_edit.setText(""); } + }); + updateFileListFunc.sendMessage(new Message()); + return view; + } + + private static boolean checkIsRecommendFile(String filePath) { + Path path = Paths.get(filePath); + String fileName = path.getFileName().toString(); + for (String recommendFile : RECOMMEND_FILES) { + if (recommendFile.equals(fileName)) return true; + } + return false; + } + +} diff --git a/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/model/SelectAppItem.java b/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/model/SelectAppItem.java new file mode 100644 index 00000000..205dc4e9 --- /dev/null +++ b/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/model/SelectAppItem.java @@ -0,0 +1,31 @@ +package com.linux.permissionmanager.model; + +import android.content.Context; +import android.content.pm.PackageInfo; +import android.graphics.drawable.Drawable; + +public class SelectAppItem { + private PackageInfo packageInfo; + + public SelectAppItem(PackageInfo packageInfo){ + this.packageInfo = packageInfo; + } + + public PackageInfo getPackageInfo() { + return packageInfo; + } + + public String getShowName(Context ctx) { + String showName = this.packageInfo.applicationInfo.loadLabel(ctx.getPackageManager()).toString(); + return showName; + } + public String getPackageName() { + String packageName = this.packageInfo.applicationInfo.packageName; + return packageName; + } + public Drawable getDrawable(Context ctx) { + Drawable icon = this.packageInfo.applicationInfo.loadIcon(ctx.getPackageManager()); + return icon; + } + +} diff --git a/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/model/SelectFileItem.java b/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/model/SelectFileItem.java new file mode 100644 index 00000000..be366ef8 --- /dev/null +++ b/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/model/SelectFileItem.java @@ -0,0 +1,34 @@ +package com.linux.permissionmanager.model; + +import android.graphics.Color; + +import java.nio.file.Path; +import java.nio.file.Paths; + +public class SelectFileItem { + private String filePath; + private String fileDesc; + private Color fileDescColor; + + public SelectFileItem(String filePath, String fileDesc, Color fileDescColor){ + this.filePath = filePath; + this.fileDesc = fileDesc; + this.fileDescColor = fileDescColor; + } + + public String getFilePath() { + return this.filePath; + } + + public String getFileName() { + Path path = Paths.get(filePath); + Path fileName = path.getFileName(); + return fileName.toString(); + } + public String getFileDesc() { + return this.fileDesc; + } + public Color getFileDescColor() { + return this.fileDescColor; + } +} diff --git a/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/ClipboardUtils.java b/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/ClipboardUtils.java new file mode 100644 index 00000000..354f8a1e --- /dev/null +++ b/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/ClipboardUtils.java @@ -0,0 +1,16 @@ +package com.linux.permissionmanager.utils; + +import android.content.ClipData; +import android.content.ClipboardManager; +import android.content.Context; + +public class ClipboardUtils { + public static void copyText(Context ctx, String text) { + //获取剪贴板管理器: + ClipboardManager cm = (ClipboardManager)ctx.getSystemService(Context.CLIPBOARD_SERVICE); + // 创建普通字符型ClipData + ClipData mClipData = ClipData.newPlainText("Label", text); + // 将ClipData内容放到系统剪贴板里。 + cm.setPrimaryClip(mClipData); + } +} diff --git a/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/DialogUtils.java b/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/DialogUtils.java new file mode 100644 index 00000000..a3e9a7e1 --- /dev/null +++ b/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/DialogUtils.java @@ -0,0 +1,191 @@ +package com.linux.permissionmanager.utils; + +import android.app.Dialog; +import android.content.Context; +import android.content.DialogInterface; +import android.graphics.drawable.Drawable; +import android.os.Handler; +import android.os.Message; +import android.view.Gravity; +import android.view.View; +import android.view.ViewGroup; +import android.view.Window; +import android.widget.Button; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.TextView; + +import androidx.appcompat.app.AlertDialog; + +import java.util.List; + +public class DialogUtils { + public static void showCustomDialog(Context context, String title, String message, + Drawable icon, + String positiveButtonText, DialogInterface.OnClickListener positiveClickListener, + String negativeButtonText, DialogInterface.OnClickListener negativeClickListener) { + + AlertDialog.Builder builder = new AlertDialog.Builder(context); + builder.setTitle(title) + .setMessage(message) + .setCancelable(false); + + if (icon != null) { + builder.setIcon(icon); + } + + if (positiveButtonText != null && positiveClickListener != null) { + builder.setPositiveButton(positiveButtonText, positiveClickListener); + } + if (negativeButtonText != null && negativeClickListener != null) { + builder.setNegativeButton(negativeButtonText, negativeClickListener); + } + builder.show(); + } + + public static void showNeedPermissionDialog(Context context) { + DialogUtils.showCustomDialog( + context, + "权限申请", + "请授予权限后重新操作", + null, + "确定", (dialog, which) -> { + dialog.dismiss(); + }, + null, null + ); + } + + /** + * 显示带有消息的对话框。 + * + * @param context 上下文 + * @param title 对话框标题 + * @param msg 对话框内容 + * @param icon 对话框图标(可为 null) + */ + public static void showMsgDlg(Context context, String title, String msg, Drawable icon) { + showCustomDialog( + context, + title, + msg, + icon, + "确定", (dialog, which) -> dialog.dismiss(), + null, null + ); + } + + /** + * 显示带有三个按钮的输入对话框。 + * + * @param context 上下文 + * @param defaultText 默认文本 + * @param title 对话框标题 + * @param thirdButtonText 第三个按钮的文本 + * @param confirmCallback 点击确定按钮时的回调 + * @param thirdButtonCallback 第三个按钮的回调 + */ + public static void showInputDlg(Context context, String defaultText, String title, final String thirdButtonText, + final Handler confirmCallback, final Handler thirdButtonCallback) { + final EditText inputTxt = new EditText(context); + inputTxt.setText(defaultText); + inputTxt.setFocusable(true); + inputTxt.setSelection(defaultText.length(), 0); + + AlertDialog.Builder builder = new AlertDialog.Builder(context); + builder.setTitle(title) + .setIcon(android.R.drawable.ic_dialog_info) + .setView(inputTxt) + .setNegativeButton("取消", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + } + }) + .setPositiveButton("确定", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + String text = inputTxt.getText().toString(); + Message msg = new Message(); + msg.obj = text; + confirmCallback.sendMessage(msg); + } + }); + + // 添加第三个按钮 + if (thirdButtonText != null && !thirdButtonText.isEmpty()) { + builder.setNeutralButton(thirdButtonText, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + // 自定义回调 + if (thirdButtonCallback != null) { + thirdButtonCallback.sendMessage(new Message()); + } + } + }); + } + + AlertDialog dialog = builder.create(); + dialog.show(); + } + + + public static void showLogDialog(Context context, List logs) { + String logText = logs.isEmpty() ? "No logs" : android.text.TextUtils.join("\n", logs); + // 创建全屏 Dialog + Dialog dialog = new Dialog(context); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + + // 创建一个外部的线性布局(垂直方向) + LinearLayout layout = new LinearLayout(context); + layout.setOrientation(LinearLayout.VERTICAL); + layout.setPadding(50, 50, 50, 50); + + // 创建 TextView 作为日志显示区域 + TextView textView = new TextView(context); + textView.setTextSize(14); + textView.setText(logText); + textView.setTextIsSelectable(true); // 允许选中复制 + textView.setVerticalScrollBarEnabled(true); + textView.setSingleLine(false); // 允许多行显示 + textView.setMaxLines(Integer.MAX_VALUE); // 让其支持无限行 + textView.setLineSpacing(1.5f, 1.2f); // 增加行间距,增强可读性 + + // ScrollView 使日志可以滚动 + ScrollView scrollView = new ScrollView(context); + scrollView.addView(textView); + scrollView.setLayoutParams(new LinearLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + 0, 1 // 设置权重,让日志区域填满大部分屏幕 + )); + + // 让 ScrollView 自动滚动到底部 + scrollView.getViewTreeObserver().addOnGlobalLayoutListener(() -> { + scrollView.post(() -> scrollView.fullScroll(View.FOCUS_DOWN)); + }); + + + // 创建一个底部的“关闭”按钮 + Button closeButton = new Button(context); + closeButton.setText("关闭"); + closeButton.setOnClickListener(v -> { + dialog.dismiss(); + }); + + // 将 ScrollView 和按钮添加到主布局 + layout.addView(scrollView); + layout.addView(closeButton); + + // 设置 Dialog 的内容 + dialog.setContentView(layout); + + // 设置全屏属性 + Window window = dialog.getWindow(); + if (window != null) { + window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); + window.setGravity(Gravity.CENTER); + } + + dialog.show(); + } +} diff --git a/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/GetAppListPermissionHelper.java b/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/GetAppListPermissionHelper.java new file mode 100644 index 00000000..080314f6 --- /dev/null +++ b/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/GetAppListPermissionHelper.java @@ -0,0 +1,13 @@ +package com.linux.permissionmanager.utils; + +import android.app.Activity; +import android.content.pm.PackageInfo; + +import java.util.List; + +public class GetAppListPermissionHelper { + public static boolean getPermissions(Activity activity) { + List packages = activity.getPackageManager().getInstalledPackages(0); + return packages.size() > 0; + } +} diff --git a/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/ScreenInfoUtils.java b/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/ScreenInfoUtils.java new file mode 100644 index 00000000..97dcd2f9 --- /dev/null +++ b/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/ScreenInfoUtils.java @@ -0,0 +1,187 @@ +package com.linux.permissionmanager.utils; + +import android.app.Activity; +import android.content.Context; +import android.content.res.Resources; +import android.util.DisplayMetrics; +import android.util.Log; +import android.util.TypedValue; +import android.view.Display; +import android.view.WindowManager; + +/** + * Get Screen Information Utils + * + * @author yh + * @date 2018/12/18. + */ +public class ScreenInfoUtils { + + private static final String TAG = "ScreenInfoUtils"; + + /** + * Get Screen Width + */ + public static int getScreenWidth(Context context) { + return getDisplayMetrics(context).widthPixels; + } + + /** + * Get Screen Height + */ + public static int getScreenHeight(Context context) { + return getDisplayMetrics(context).heightPixels; + } + + + /** + * Get Screen Real Height + * + * @param context Context + * @return Real Height + */ + public static int getRealHeight(Context context) { + Display display = getDisplay(context); + if (display == null) { + return 0; + } + DisplayMetrics dm = new DisplayMetrics(); + display.getRealMetrics(dm); + return dm.heightPixels; + } + + /** + * Get Screen Real Width + * + * @param context Context + * @return Real Width + */ + public static int getRealWidth(Context context) { + Display display = getDisplay(context); + if (display == null) { + return 0; + } + DisplayMetrics dm = new DisplayMetrics(); + display.getRealMetrics(dm); + return dm.widthPixels; + } + + /** + * Get StatusBar Height + */ + public static int getStatusBarHeight(Context mContext) { + int resourceId = mContext.getResources().getIdentifier("status_bar_height", "dimen", "android"); + if (resourceId > 0) { + return mContext.getResources().getDimensionPixelSize(resourceId); + } + return 0; + } + + /** + * Get ActionBar Height + */ + public static int getActionBarHeight(Context mContext) { + TypedValue tv = new TypedValue(); + if (mContext.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) { + return TypedValue.complexToDimensionPixelSize(tv.data, mContext.getResources().getDisplayMetrics()); + } + return 0; + } + + /** + * Get NavigationBar Height + */ + public static int getNavigationBarHeight(Context mContext) { + Resources resources = mContext.getResources(); + int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android"); + if (resourceId > 0) { + return resources.getDimensionPixelSize(resourceId); + } + return 0; + } + + /** + * Get Density + */ + private static float getDensity(Context context) { + return getDisplayMetrics(context).density; + } + + /** + * Get Dpi + */ + private static int getDpi(Context context) { + return getDisplayMetrics(context).densityDpi; + } + + /** + * Get Display + * + * @param context Context for get WindowManager + * @return Display + */ + private static Display getDisplay(Context context) { + WindowManager wm; + if (context instanceof Activity) { + Activity activity = (Activity) context; + wm = activity.getWindowManager(); + } else { + wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); + } + if (wm != null) { + return wm.getDefaultDisplay(); + } + return null; + } + + /** + * Get DisplayMetrics + * + * @param context Context for get Resources + * @return DisplayMetrics + */ + private static DisplayMetrics getDisplayMetrics(Context context) { + return context.getResources().getDisplayMetrics(); + } + + + /** + * Get ScreenInfo + */ + private static String getScreenInfo(Context context) { + return " \n" + + "--------ScreenInfo--------" + "\n" + + "Screen Width : " + getScreenWidth(context) + "px\n" + + "Screen RealWidth :" + getRealWidth(context) + "px\n" + + "Screen Height: " + getScreenHeight(context) + "px\n" + + "Screen RealHeight: " + getRealHeight(context) + "px\n" + + "Screen StatusBar Height: " + getStatusBarHeight(context)+ "px\n" + + "Screen ActionBar Height: " + getActionBarHeight(context)+ "px\n" + + "Screen NavigationBar Height: " + getNavigationBarHeight(context)+ "px\n" + + "Screen Dpi: " + getDpi(context) + "\n" + + "Screen Density: " + getDensity(context) + "\n" + + "--------------------------"; + } + + + /** + * 根据手机的分辨率从 dp 的单位 转成为 px(像素) + */ + public static int dip2px(Context context, float dpValue) { + final float scale = context.getResources().getDisplayMetrics().density; + return (int) (dpValue * scale); + } + + /** * 根据手机的分辨率从 px(像素) 的单位 转成为 dp */ + public static int px2dip(Context context, float pxValue) { + final float scale = context.getResources().getDisplayMetrics().density; + return (int) (pxValue / scale); + } + + /** + * Print screenInfo to logcat + */ + public static void printScreenInfo(Context context) { + Log.d(TAG, getScreenInfo(context)); + } +} diff --git a/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/UrlIntentUtils.java b/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/UrlIntentUtils.java new file mode 100644 index 00000000..e7102c2e --- /dev/null +++ b/Lite_version/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/UrlIntentUtils.java @@ -0,0 +1,47 @@ +package com.linux.permissionmanager.utils; + +import android.app.Activity; +import android.content.ActivityNotFoundException; +import android.content.Context; +import android.content.Intent; +import android.net.Uri; +import android.text.TextUtils; +import android.widget.Toast; + +public final class UrlIntentUtils { + private UrlIntentUtils() {} + + /** 在外部浏览器打开链接;支持传 "example.com" 自动补全 https:// */ + public static boolean openUrl(Context context, String url) { + if (context == null) return false; + if (TextUtils.isEmpty(url)) { + Toast.makeText(context, "链接为空", Toast.LENGTH_SHORT).show(); + return false; + } + + String u = url.trim(); + // 没有 scheme 的话补 https:// + if (!u.startsWith("http://") && !u.startsWith("https://")) { + u = "https://" + u; + } + + Uri uri = Uri.parse(u); + Intent intent = new Intent(Intent.ACTION_VIEW, uri); + + // 非 Activity context 需要 NEW_TASK + if (!(context instanceof Activity)) { + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + } + + try { + context.startActivity(intent); + return true; + } catch (ActivityNotFoundException e) { + Toast.makeText(context, "没有可打开链接的应用", Toast.LENGTH_SHORT).show(); + return false; + } catch (Exception e) { + Toast.makeText(context, "打开链接失败", Toast.LENGTH_SHORT).show(); + return false; + } + } +} diff --git a/Lite_version/src/PermissionManager/app/src/main/res/drawable/line.xml b/Lite_version/src/PermissionManager/app/src/main/res/drawable/line.xml new file mode 100644 index 00000000..597142f2 --- /dev/null +++ b/Lite_version/src/PermissionManager/app/src/main/res/drawable/line.xml @@ -0,0 +1,12 @@ + + + + + + + \ No newline at end of file diff --git a/Lite_version/src/PermissionManager/app/src/main/res/drawable/line_drawable.xml b/Lite_version/src/PermissionManager/app/src/main/res/drawable/line_drawable.xml new file mode 100644 index 00000000..4f79f470 --- /dev/null +++ b/Lite_version/src/PermissionManager/app/src/main/res/drawable/line_drawable.xml @@ -0,0 +1,9 @@ + + + + + + \ No newline at end of file diff --git a/Lite_version/src/PermissionManager/app/src/main/res/drawable/ripple_grey.xml b/Lite_version/src/PermissionManager/app/src/main/res/drawable/ripple_grey.xml new file mode 100644 index 00000000..ac736de4 --- /dev/null +++ b/Lite_version/src/PermissionManager/app/src/main/res/drawable/ripple_grey.xml @@ -0,0 +1,6 @@ + +//点击时波纹的颜色 + //未点击时控件的背景(可以是图片,可以是颜色,也可以是drawable里的xml背景(比如圆角)) + \ No newline at end of file diff --git a/Lite_version/src/PermissionManager/app/src/main/res/drawable/shape_wnd_grey_corner.xml b/Lite_version/src/PermissionManager/app/src/main/res/drawable/shape_wnd_grey_corner.xml new file mode 100644 index 00000000..6bc80841 --- /dev/null +++ b/Lite_version/src/PermissionManager/app/src/main/res/drawable/shape_wnd_grey_corner.xml @@ -0,0 +1,9 @@ + + + + + + \ No newline at end of file diff --git a/Lite_version/src/PermissionManager/app/src/main/res/drawable/thumb.xml b/Lite_version/src/PermissionManager/app/src/main/res/drawable/thumb.xml new file mode 100644 index 00000000..0646431b --- /dev/null +++ b/Lite_version/src/PermissionManager/app/src/main/res/drawable/thumb.xml @@ -0,0 +1,11 @@ + + + + + + + + \ No newline at end of file diff --git a/Lite_version/src/PermissionManager/app/src/main/res/drawable/thumb_drawable.xml b/Lite_version/src/PermissionManager/app/src/main/res/drawable/thumb_drawable.xml new file mode 100644 index 00000000..a93b8b83 --- /dev/null +++ b/Lite_version/src/PermissionManager/app/src/main/res/drawable/thumb_drawable.xml @@ -0,0 +1,9 @@ + + + + + + \ No newline at end of file diff --git a/Lite_version/src/PermissionManager/app/src/main/res/layout/activity_main.xml b/Lite_version/src/PermissionManager/app/src/main/res/layout/activity_main.xml new file mode 100644 index 00000000..1743c506 --- /dev/null +++ b/Lite_version/src/PermissionManager/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,203 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ 输出信息: +
+ + +
+ +
+ + + +
+
+ +
+
+
+ + + diff --git a/Lite_version/src/testRoot/kernel_root_kit/src/jni/web_server/jni/Android.mk b/Lite_version/src/testRoot/kernel_root_kit/src/jni/web_server/jni/Android.mk new file mode 100644 index 00000000..6244738c --- /dev/null +++ b/Lite_version/src/testRoot/kernel_root_kit/src/jni/web_server/jni/Android.mk @@ -0,0 +1,17 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) +LOCAL_MODULE := web_server +LOCAL_SRC_FILES := \ +../web_server.cpp \ +../cJSON.cpp + +KERNEL_ROOT_KIT := $(LOCAL_PATH)/../../../../../kernel_root_kit +LOCAL_C_INCLUDES += $(KERNEL_ROOT_KIT) +LOCAL_C_INCLUDES += $(KERNEL_ROOT_KIT)/include +LOCAL_C_INCLUDES += $(KERNEL_ROOT_KIT)/src/jni/ +LOCAL_LDFLAGS += $(KERNEL_ROOT_KIT)/lib/libkernel_root_kit_static.a + +include $(LOCAL_PATH)/build_macros.mk +include $(LOCAL_PATH)/civetweb.mk +include $(BUILD_EXECUTABLE) diff --git a/Lite_version/src/testRoot/kernel_root_kit/src/jni/web_server/jni/Application.mk b/Lite_version/src/testRoot/kernel_root_kit/src/jni/web_server/jni/Application.mk new file mode 100644 index 00000000..2500a8a7 --- /dev/null +++ b/Lite_version/src/testRoot/kernel_root_kit/src/jni/web_server/jni/Application.mk @@ -0,0 +1,2 @@ +APP_ABI := arm64-v8a +APP_STL := c++_static \ No newline at end of file diff --git a/Lite_version/src/testRoot/kernel_root_kit/src/jni/web_server/jni/build_macros.mk b/Lite_version/src/testRoot/kernel_root_kit/src/jni/web_server/jni/build_macros.mk new file mode 100644 index 00000000..66e684cd --- /dev/null +++ b/Lite_version/src/testRoot/kernel_root_kit/src/jni/web_server/jni/build_macros.mk @@ -0,0 +1,7 @@ +COMMON_CPPFLAGS := \ + -std=c++20 \ + -fPIC \ + -fvisibility=hidden \ + -fexceptions + +LOCAL_CPPFLAGS += $(COMMON_CPPFLAGS) diff --git a/Lite_version/src/testRoot/kernel_root_kit/src/jni/web_server/jni/civetweb.mk b/Lite_version/src/testRoot/kernel_root_kit/src/jni/web_server/jni/civetweb.mk new file mode 100644 index 00000000..59290be3 --- /dev/null +++ b/Lite_version/src/testRoot/kernel_root_kit/src/jni/web_server/jni/civetweb.mk @@ -0,0 +1,13 @@ +LOCAL_PATH := $(call my-dir) + +CIVETWEB_ROOT := $(LOCAL_PATH)/../civetweb-1.16 + +CIVETWEB_SRCS := \ + $(patsubst $(LOCAL_PATH)/%,%,$(wildcard $(CIVETWEB_ROOT)/src/*.c)) \ + $(patsubst $(LOCAL_PATH)/%,%,$(wildcard $(CIVETWEB_ROOT)/src/*.cpp)) + +CIVETWEB_INCLUDES := \ + $(CIVETWEB_ROOT)/include + +LOCAL_SRC_FILES += $(CIVETWEB_SRCS) +LOCAL_C_INCLUDES += $(CIVETWEB_INCLUDES) diff --git a/Lite_version/src/testRoot/kernel_root_kit/src/jni/web_server/json_helper.h b/Lite_version/src/testRoot/kernel_root_kit/src/jni/web_server/json_helper.h new file mode 100644 index 00000000..2c2cc37d --- /dev/null +++ b/Lite_version/src/testRoot/kernel_root_kit/src/jni/web_server/json_helper.h @@ -0,0 +1,79 @@ +#pragma once +#include +#include +#include +#include "cJSON.h" + +std::string convert_2_json(const std::string & str, const std::map & appendParam = {}) { + std::string strJson; + cJSON *json = cJSON_CreateObject(); + if(json) { + cJSON_AddStringToObject(json, "content", str.c_str()); + for(const auto & param: appendParam) cJSON_AddStringToObject(json, param.first.c_str(), param.second.c_str()); + char *jsonString = cJSON_Print(json); + if(jsonString) { + strJson = jsonString; + free(jsonString); + } + cJSON_Delete(json); + } + return strJson; +} + +std::string convert_2_json_m(const std::string & str, const std::map & appendParam = {}) { + std::string strJson; + cJSON *json = cJSON_CreateObject(); + if(json) { + cJSON_AddStringToObject(json, "content", str.c_str()); + cJSON *jsonArray = cJSON_CreateArray(); + for(const auto & param: appendParam) { + cJSON *jsonMap = cJSON_CreateObject(); + cJSON_AddStringToObject(jsonMap, param.first.c_str(), param.second.c_str()); + cJSON_AddItemToArray(jsonArray, jsonMap); + } + cJSON_AddItemToObject(json, "arr_map", jsonArray); + char *jsonString = cJSON_Print(json); + if(jsonString) { + strJson = jsonString; + free(jsonString); + } + cJSON_Delete(json); + } + return strJson; +} + +std::string convert_2_json_v(const std::vector &v, const std::map & appendParam = {}) { + std::string strJson; + cJSON *json = cJSON_CreateObject(); + if (json) { + cJSON *jsonArray = cJSON_CreateArray(); + for (const std::string &str : v) cJSON_AddItemToArray(jsonArray, cJSON_CreateString(str.c_str())); + cJSON_AddItemToObject(json, "content", jsonArray); + for(const auto & param: appendParam) cJSON_AddStringToObject(json, param.first.c_str(), param.second.c_str()); + char *jsonString = cJSON_Print(json); + if (jsonString) { + strJson = jsonString; + free(jsonString); + } + cJSON_Delete(json); + } + return strJson; +} + +std::string get_json_str(const std::string& json, const char* key) { + cJSON* root = cJSON_Parse(json.c_str()); + if (!root) return {}; + cJSON* j_str = cJSON_GetObjectItem(root, key); + std::string result = j_str ? j_str->valuestring : ""; + cJSON_Delete(root); + return result; +} + +int get_json_int(const std::string& json, const char* key) { + cJSON* root = cJSON_Parse(json.c_str()); + if (!root) return {}; + cJSON* j_int = cJSON_GetObjectItem(root, key); + int n = j_int ? j_int->valueint : 0; + cJSON_Delete(root); + return n; +} diff --git a/Lite_version/src/testRoot/kernel_root_kit/src/jni/web_server/web_server.cpp b/Lite_version/src/testRoot/kernel_root_kit/src/jni/web_server/web_server.cpp new file mode 100644 index 00000000..552b0c1b --- /dev/null +++ b/Lite_version/src/testRoot/kernel_root_kit/src/jni/web_server/web_server.cpp @@ -0,0 +1,444 @@ +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "web_server.h" +#include "web_server_inline.h" +#include "civetweb-1.16/include/CivetServer.h" +#include "index_html_gz_data.generated.h" +#include "rootkit_umbrella.h" +#include "src/jni/common/android_open_url.h" +#include "json_helper.h" + +#define MAX_HEARTBEAT_TIME_SEC 20 +constexpr const char* recommend_files[] = {"libc++_shared.so"}; +char ROOT_KEY[256] = {0}; +int PORT = 0; +std::atomic g_heartbeat{true}; + +class InjectSuInfo { +public: + std::atomic working{false}; + std::atomic success{false}; + void set_app_name(const std::string & app_name) { + std::lock_guard guard(m_msgLock); + m_app_name = app_name; + } + std::string get_app_name() { + std::lock_guard guard(m_msgLock); + return m_app_name; + } + + void append_console_msg(const std::string & console) { + std::lock_guard guard(m_msgLock); + m_consoleMsg = console + "\n"; + } + void clear_console_msg() { + std::lock_guard guard(m_msgLock); + m_consoleMsg = ""; + } + std::string get_console_msg() { + std::lock_guard guard(m_msgLock); + return m_consoleMsg; + } + +private: + std::string m_app_name; + std::string m_consoleMsg; + std::mutex m_msgLock; +} g_inject_su_info; + +std::tuple handle_index() { + std::string gzip_html; + gzip_html.assign(reinterpret_cast(web_server::index_html_gz_data), web_server::index_html_gz_size); + return { gzip_html, true }; +} + +std::string handle_heartbeat(const std::string & json) { + g_heartbeat = true; + std::string userName = get_json_str(json, "userName"); + return convert_2_json(userName); +} + +std::string handle_test_root() { + std::string report = kernel_root::get_root_test_report(ROOT_KEY); + return convert_2_json(report); +} + +std::string handle_run_root_cmd(const std::string & json) { + std::string cmd = get_json_str(json, "cmd"); + std::string result; + KRootErr err = kernel_root::run_root_cmd(ROOT_KEY, cmd.c_str(), result); + + std::stringstream sstr; + sstr << "run_root_cmd " << to_string(err).c_str() << ", result: " << result; + return convert_2_json(sstr.str()); +} + +std::string handle_run_exec_process(const std::string & json) { + std::string path = get_json_str(json, "path"); + KRootErr err = kernel_root::root_exec_process(ROOT_KEY, path.c_str()); + + std::stringstream sstr; + sstr << "root_exec_processs " << to_string(err).c_str(); + return convert_2_json(sstr.str()); +} + +std::string handle_install_su() { + KRootErr err = KRootErr::OK; + std::string su_hide_full_path; + err = kernel_root::install_su(ROOT_KEY, su_hide_full_path); + + std::stringstream sstr; + sstr << "install su " << to_string(err).c_str() << ", su_hide_full_path:" << su_hide_full_path << std::endl; + + if (is_ok(err)) { + sstr << "install su done."<< std::endl; + } + std::map param; + param["su_hide_full_path"] = su_hide_full_path; + param["err"] = to_string(err); + param["ok"] = is_ok(err) ? "1" : "0"; + return convert_2_json(sstr.str(), param); +} + +std::string handle_uninstall_su() { + KRootErr err = kernel_root::uninstall_su(ROOT_KEY); + std::stringstream sstr; + sstr << "uninstall su " << to_string(err).c_str() << std::endl; + if (is_failed(err)) { + return convert_2_json(sstr.str()); + } + sstr << "uninstall su done."; + + std::map param; + param["err"] = to_string(err); + param["ok"] = is_ok(err) ? "1" : "0"; + return convert_2_json(sstr.str(), param); +} + +std::string handle_get_app_list(const std::string & json) { + bool isShowSystemApp = !!get_json_int(json, "showSystemApp"); + bool isShowThirtyApp = !!get_json_int(json, "showThirdApp"); + bool isShowRunningAPP = !!get_json_int(json, "showRunningApp"); + + std::vector packageNames; + std::string cmd; + if(isShowSystemApp && isShowThirtyApp) cmd = "pm list packages"; + else if(isShowSystemApp) cmd = "pm list packages -s"; + else if(isShowThirtyApp) cmd = "pm list packages -3"; + + std::string packages; + KRootErr err = kernel_root::run_root_cmd(ROOT_KEY, cmd.c_str(), packages); + if (is_failed(err)) return convert_2_json_v(packageNames); + + std::map pid_map; + if(isShowRunningAPP) { + err = kernel_root::get_all_cmdline_process(ROOT_KEY, pid_map); + if (is_failed(err)) return convert_2_json_v(packageNames); + } + // remove "package:" flag + std::istringstream iss(packages); + std::string line; + while (getline(iss, line)) { + size_t pos = line.find("package:"); + if (pos != std::string::npos) { + line.erase(pos, std::string("package:").length()); + } + if(isShowRunningAPP) { + bool isFound = false; + for(auto & item : pid_map) { + if(item.second.find(line) == std::string::npos) continue; + isFound = true; + break; + } + if(!isFound) continue; + } + packageNames.push_back(line); + } + return convert_2_json_v(packageNames); +} + +void inject_su_thread() { + writeToLog("inject_su_thread enter"); + + std::string su_file_path; + KRootErr err = kernel_root::install_su(ROOT_KEY, su_file_path); + std::string su_dir_path = std::filesystem::path(su_file_path).parent_path().string() + "/"; + + g_inject_su_info.append_console_msg("su_dir_path ret val: " + su_dir_path); + + // 1.杀光所有历史进程 + std::set out; + err = kernel_root::find_all_cmdline_process(ROOT_KEY, g_inject_su_info.get_app_name().c_str(), out); + g_inject_su_info.append_console_msg("find_all_cmdline_process " + to_string(err) + ", cnt:" + std::to_string(out.size())); + if (is_failed(err)) { + g_inject_su_info.working = false; + return; + } + + for (pid_t pid : out) { kernel_root::kill_process(ROOT_KEY, pid); } + + // 2.注入su环境变量到指定进程 + g_inject_su_info.append_console_msg("waiting for process creation:" + g_inject_su_info.get_app_name()); + + pid_t pid; + err = kernel_root::wait_and_find_cmdline_process( + ROOT_KEY, g_inject_su_info.get_app_name().c_str(), 60 * 1000, pid); + g_inject_su_info.append_console_msg("waiting for process creation " + to_string(err)); + if (is_failed(err)) { + g_inject_su_info.working = false; + return; + } + err = kernel_root::inject_process_env64_PATH_wrapper(ROOT_KEY, pid, su_dir_path.c_str(), kernel_root::ApiOffsetReadMode::OnlyReadFile); + g_inject_su_info.append_console_msg("inject su " + to_string(err) + ", errmsg: " + strerror(errno)); + g_inject_su_info.success = true; + g_inject_su_info.working = false; +} + +std::string handle_inject_su_in_temp_app(const std::string & json) { + std::string app_name = get_json_str(json, "appName"); + std::map param; + param["errcode"] = "0"; + if(g_inject_su_info.working) { + param["errcode"] = "-1"; + return convert_2_json("inject su thread already running.", param); + } + + if(app_name.empty()) { + param["errcode"] = "-2"; + return convert_2_json("app name is empty.", param); + } + g_inject_su_info.set_app_name(app_name); + writeToLog("start inject su thread, app name: " + app_name); + g_inject_su_info.working = true; + g_inject_su_info.success = false; + std::thread td(inject_su_thread); + td.detach(); + return convert_2_json("ok", param); +} + +std::string handle_get_inject_su_in_temp_app_result() { + //writeToLog("handle_get_inject_su_result enter"); + std::map param; + param["working"] = g_inject_su_info.working ? "1" : "0"; + param["success"] = g_inject_su_info.success ? "1" : "0"; + + std::string console = g_inject_su_info.get_console_msg(); + g_inject_su_info.clear_console_msg(); + + return convert_2_json(console, param); +} + +std::string handle_get_precheck_app_file_list(const std::string & json) { + std::string app_name = get_json_str(json, "appName"); + std::stringstream errmsg; + std::map output_file_path; + std::set pid_arr; + KRootErr err = kernel_root::find_all_cmdline_process(ROOT_KEY, app_name.c_str(), pid_arr); + if (is_failed(err)) { + errmsg << "find_all_cmdline_process " << to_string(err).c_str() << std::endl; + return convert_2_json_m(errmsg.str()); + } + if (pid_arr.size() == 0) { + errmsg << "请先运行目标APP: " << app_name.c_str() << std::endl; + return convert_2_json_m(errmsg.str()); + } + + std::map so_path_list; + err = kernel_root::parasite_precheck_app(ROOT_KEY, app_name.c_str(), so_path_list); + if (is_failed(err)) { + errmsg << "parasite_precheck_app error:" << to_string(err).c_str() << std::endl; + if(err == KRootErr::ERR_EXIST_32BIT) { + errmsg << "此目标APP为32位应用,无法寄生" << to_string(err).c_str() << std::endl; + } + return convert_2_json_m(errmsg.str()); + } + if (!so_path_list.size()) { + errmsg << "无法检测到目标APP的JNI环境,目标APP暂不可被寄生;您可重新运行目标APP后重试;或将APP进行手动加固(加壳),因为加固(加壳)APP后,APP会被产生JNI环境,方可寄生!" << to_string(err).c_str() << std::endl; + return convert_2_json_m(errmsg.str()); + } + + std::vector> sort_printf; + for (const auto& item : so_path_list) { + if(item.second != kernel_root::AppDynlibStatus::Running) continue; + sort_printf.push_back({item.first, item.second}); + } + for (const auto& item : so_path_list) { + if(item.second != kernel_root::AppDynlibStatus::NotRunning) continue; + sort_printf.push_back({item.first, item.second}); + } + for (const auto& item : sort_printf) { + auto file_path = std::get<0>(item); + auto appDynlibStatus = std::get<1>(item); + std::filesystem::path filePath(file_path); + std::string status = appDynlibStatus == kernel_root::AppDynlibStatus::Running ? " (正在运行)" : " (未运行)"; + if(appDynlibStatus == kernel_root::AppDynlibStatus::Running) { + std::string file_name = filePath.filename().string(); + for(auto x = 0; x < sizeof(recommend_files) / sizeof(recommend_files[0]); x++) { + if(file_name == recommend_files[x]) { + status = " (推荐, 正在运行)"; + } + } + } + output_file_path[file_path] = status; + } + return convert_2_json_m(errmsg.str(), output_file_path); +} + +std::string handle_inject_su_in_forever_app(const std::string & json) { + std::string app_name = get_json_str(json, "appName"); + std::string filePath = get_json_str(json, "filePath"); + std::stringstream errmsg; + std::map param; + param["errcode"] = "0"; + + std::string su_file_path; + KRootErr err = kernel_root::install_su(ROOT_KEY, su_file_path); + std::string su_dir_path = is_ok(err) ? (std::filesystem::path(su_file_path).parent_path().string() + "/") : ""; + if (su_dir_path.empty()) { + param["errcode"] = "-1"; + return convert_2_json_m("su_dir_path is empty"); + } + + std::set pid_arr; + err = kernel_root::find_all_cmdline_process(ROOT_KEY, app_name.c_str(), pid_arr); + if (is_failed(err)) { + param["errcode"] = "-2"; + errmsg << "find_all_cmdline_process " << to_string(err).c_str() << std::endl; + return convert_2_json(errmsg.str()); + } + if (pid_arr.size() == 0) { + param["errcode"] = "-3"; + errmsg << "请先运行目标APP: " << app_name.c_str() << std::endl; + return convert_2_json(errmsg.str()); + } + + err = kernel_root::parasite_implant_su_env(ROOT_KEY, app_name.c_str(), filePath.c_str(), su_dir_path.c_str()); + printf("parasite_implant_su_env err:%zd\n", err); + if (is_failed(err)) { + param["errcode"] = "-4"; + std::string msg = "parasite_implant_su_env " + to_string(err); + return convert_2_json(msg); + } + for (pid_t pid : pid_arr) { kernel_root::kill_process(ROOT_KEY, pid); } + return convert_2_json("ok", param); +} + +std::string handle_unknow_type() { + return convert_2_json("unknow command type."); +} + +class MyHttpHandler : public CivetHandler { +public: + bool handleGet(CivetServer* server, struct mg_connection* conn) override { + const struct mg_request_info* req_info = mg_get_request_info(conn); + std::string path = req_info->local_uri ? req_info->local_uri : "/"; + + writeToLog("Get request:" + path); + std::string body; + bool use_gzip = false; + if(path == "/") { + // home page + std::tie(body, use_gzip) = handle_index(); + } + mg_printf(conn, + "HTTP/1.1 200 OK\r\n" + "Access-Control-Allow-Origin: *\r\n" + "Content-Type: text/html; charset=UTF-8\r\n" + "%s" + "Content-Length: %zu\r\n" + "Connection: close\r\n\r\n", + use_gzip ? "Content-Encoding: gzip\r\n" : "", body.size()); + mg_write(conn, body.data(), body.size()); + return true; + } + + bool handlePost(CivetServer* server, struct mg_connection* conn) override { + char buf[1024]; + int len = mg_read(conn, buf, sizeof(buf) - 1); + buf[len > 0 ? len : 0] = '\0'; + + const struct mg_request_info* req_info = mg_get_request_info(conn); + std::string path = req_info->local_uri ? req_info->local_uri : "/"; + std::string body(buf); + + writeToLog("POST request:" + path); + writeToLog("POST body:" + body); + + std::string resp; + if(path == "/heartbeat") resp = handle_heartbeat(body); + else if(path == "/testRoot") resp = handle_test_root(); + else if(path == "/runRootCmd") resp = handle_run_root_cmd(body); + else if(path == "/runExecProc") resp = handle_run_exec_process(body); + else if(path == "/installSu") resp = handle_install_su(); + else if(path == "/uninstallSu") resp = handle_uninstall_su(); + else if(path == "/getAppList") resp = handle_get_app_list(body); + else if(path == "/injectSuInTempApp") resp = handle_inject_su_in_temp_app(body); + else if(path == "/getInjectSuInTempAppResult") resp = handle_get_inject_su_in_temp_app_result(); + else if(path == "/getPrecheckAppFileList") resp = handle_get_precheck_app_file_list(body); + else if(path == "/injectSuInForeverApp") resp = handle_inject_su_in_forever_app(body); + mg_printf(conn, + "HTTP/1.1 200 OK\r\n" + "Content-Type: application/json\r\n" + "Connection: close\r\n\r\n%s", + resp.c_str()); + return true; + } +}; + + +int main(int argc, char* argv[]) { + srand(time(NULL)); + PORT = rand() % 40001 + 20000; + strncpy(ROOT_KEY, const_cast(static_inline_web_server_root_key), sizeof(ROOT_KEY) - 1); + + writeToLog("web_server enter"); + if (is_failed(kernel_root::get_root(ROOT_KEY))) { + writeToLog("web_server root error"); + return 0; + } + + if (setsid() < 0) { + setpgid(0, 0); + } + signal(SIGPIPE, SIG_IGN); + + std::string str_port = std::to_string(PORT); + const char* options[] = { + "listening_ports", str_port.c_str(), + "num_threads", "1", + NULL + }; + + CivetServer server(options); + MyHttpHandler handler; + server.addHandler("/", handler); + + sleep(1); + std::string url = "http://127.0.0.1:" + std::to_string(PORT); + android_open_url(url); + + while (g_heartbeat) { + g_heartbeat = false; + usleep(1000 * 1000 * (MAX_HEARTBEAT_TIME_SEC / 2)); + } + server.close(); + _exit(0); + return 0; +} \ No newline at end of file diff --git a/Lite_version/src/testRoot/kernel_root_kit/src/jni/web_server/web_server.h b/Lite_version/src/testRoot/kernel_root_kit/src/jni/web_server/web_server.h new file mode 100644 index 00000000..a242324d --- /dev/null +++ b/Lite_version/src/testRoot/kernel_root_kit/src/jni/web_server/web_server.h @@ -0,0 +1,16 @@ +#pragma once + +#include +#include + +static void writeToLog(const std::string & message) { + printf("%s\n", message.c_str()); + // std::ofstream logFile("/sdcard/web_server.log", std::ios::app); + // if (!logFile) { + // std::cerr << "Error opening file" << std::endl; + // return; + // } + // logFile << message << std::endl; + // logFile.close(); + // std::cout << message << std::endl; +} \ No newline at end of file diff --git a/Lite_version/src/testRoot/kernel_root_kit/src/jni/web_server/web_server_inline.h b/Lite_version/src/testRoot/kernel_root_kit/src/jni/web_server/web_server_inline.h new file mode 100644 index 00000000..7d58320b --- /dev/null +++ b/Lite_version/src/testRoot/kernel_root_kit/src/jni/web_server/web_server_inline.h @@ -0,0 +1,8 @@ +#pragma once +#include +#include + +static volatile const char static_inline_web_server_root_key[4096] = { + "2fab8fbe825f5b3ec0f93eb16b2a8793eef933b0e14eb38e8371d995aeeaf33972af90a086104ab4fb2f24b4ddb4e757e7b026b6f8980c7c5e859af77fa24658" +}; + diff --git "a/Lite_version/src/testRoot/kernel_root_kit/\347\274\226\350\257\221\346\265\201\347\250\213.txt" "b/Lite_version/src/testRoot/kernel_root_kit/\347\274\226\350\257\221\346\265\201\347\250\213.txt" new file mode 100644 index 00000000..4683f768 --- /dev/null +++ "b/Lite_version/src/testRoot/kernel_root_kit/\347\274\226\350\257\221\346\265\201\347\250\213.txt" @@ -0,0 +1,2 @@ +1.修改build_lib第一行为ndk路径 +2.运行build_lib \ No newline at end of file diff --git a/Lite_version/src/testRoot/testRoot.cpp b/Lite_version/src/testRoot/testRoot.cpp new file mode 100644 index 00000000..5e1218e3 --- /dev/null +++ b/Lite_version/src/testRoot/testRoot.cpp @@ -0,0 +1,314 @@ +#include +#include +#include +#include +#include + +#include "rootkit_umbrella.h" + +char ROOT_KEY[256] = {0}; + +namespace { + constexpr const char* recommend_files[] = {"libc++_shared.so"}; +} +void test_root() { + printf("%s\n", kernel_root::get_root_test_report(ROOT_KEY)); +} + +void test_run_root_cmd(int argc, char* argv[]) { + std::stringstream sstrCmd; + for (int i = 0; i < argc; i++) { + sstrCmd << argv[i]; + if (i != (argc - 1)) { + sstrCmd << " "; + } + } + printf("test_run_root_cmd(%s)\n", sstrCmd.str().c_str()); + + std::string result; + KRootErr err = kernel_root::run_root_cmd(ROOT_KEY, sstrCmd.str().c_str(), result); + printf("test_run_root_cmd err:%s\n", to_string(err).c_str()); + printf("test_run_root_cmd result:%s\n", result.c_str()); +} + +void test_root_exec_process(int argc, char* argv[]) { + std::stringstream ss; + for (int i = 0; i < argc; i++) { + ss << argv[i]; + if (i != (argc - 1)) { + ss << " "; + } + } + printf("test_root_exec_process(%s)\n", ss.str().c_str()); + + KRootErr err = kernel_root::root_exec_process(ROOT_KEY, ss.str().c_str()); + printf("run_init64_cmd_wrapper err:%s\n", to_string(err).c_str()); +} + +void test_install_su_env() { + std::string su_file_path; + KRootErr err = kernel_root::install_su(ROOT_KEY, su_file_path); + printf("install su file path:%s, err:%s\n", su_file_path.c_str(), to_string(err).c_str()); +} + +void test_su_env_temp_inject(const char* target_pid_cmdline) { + if (is_failed(kernel_root::get_root(ROOT_KEY))) return; + + // 1.获取su_xxx隐藏目录 + std::string su_file_path; + KRootErr err = kernel_root::install_su(ROOT_KEY, su_file_path); + std::string su_dir_path = is_ok(err) ? (std::filesystem::path(su_file_path).parent_path().string() + "/") : ""; + if (su_dir_path.empty()) return; + + // 2.杀光所有历史进程 + std::set out; + err = kernel_root::find_all_cmdline_process(ROOT_KEY, target_pid_cmdline, out); + printf("find_all_cmdline_process err:%s, cnt:%zu\n", to_string(err).c_str(), out.size()); + if (is_failed(err)) return; + + for (pid_t pid : out) { kernel_root::kill_process(ROOT_KEY, pid); } + + // 3.注入su环境变量到指定进程 + printf("test_auto_su_env_inject Waiting for process creation(%s)\n", target_pid_cmdline); + pid_t pid; + err = kernel_root::wait_and_find_cmdline_process( + ROOT_KEY, target_pid_cmdline, 60 * 1000, pid); + printf("wait_and_find_cmdline_process(%s)\n", to_string(err).c_str()); + + err = kernel_root::inject_process_env64_PATH_wrapper(ROOT_KEY, pid, + su_dir_path.c_str()); + printf("inject_process_env64_PATH_wrapper ret val:%s, error:%s\n", to_string(err).c_str(), + strerror(errno)); +} + +void test_su_env_forever_inject(const char* target_pid_cmdline) { + if (is_failed(kernel_root::get_root(ROOT_KEY))) return; + + // 1.获取su_xxx隐藏目录 + std::string su_file_path; + KRootErr err = kernel_root::install_su(ROOT_KEY, su_file_path); + std::string su_dir_path = is_ok(err) ? (std::filesystem::path(su_file_path).parent_path().string() + "/") : ""; + if (su_dir_path.empty()) return; + + // 2.寄生预检目标APP + std::set pid_arr; + err = kernel_root::find_all_cmdline_process(ROOT_KEY, target_pid_cmdline, pid_arr); + if (is_failed(err)) { + printf("find_all_cmdline_process err:%s\n", to_string(err).c_str()); + return; + } + if (pid_arr.size() == 0) { + printf("请先运行目标APP: %s\n", target_pid_cmdline); + return; + } + std::map so_path_list; + err = kernel_root::parasite_precheck_app(ROOT_KEY, target_pid_cmdline, so_path_list); + if (is_failed(err)) { + printf("parasite_precheck_app err:%s\n", to_string(err).c_str()); + if(err == KRootErr::ERR_EXIST_32BIT) { + printf("此目标APP为32位应用,无法寄生\n"); + } + return; + } + if (!so_path_list.size()) { + printf("无法检测到目标APP的JNI环境,目标APP暂不可被寄生;您可重新运行目标APP后重试;或将APP进行手动加固(加壳),因为加固(加壳)APP后,APP会被产生JNI环境,方可寄生!\n"); + return; + } + printf("请在以下的目标APP文件列表中选择一个即将要被寄生的文件:\n"); + + std::vector> sort_printf; + for (const auto& item : so_path_list) { + if(item.second != kernel_root::AppDynlibStatus::Running) { + continue; + } + sort_printf.push_back({item.first, item.second}); + } + for (const auto& item : so_path_list) { + if(item.second != kernel_root::AppDynlibStatus::NotRunning) { + continue; + } + sort_printf.push_back({item.first, item.second}); + } + for (const auto& item : sort_printf) { + auto file_path = std::get<0>(item); + auto app_so_status = std::get<1>(item); + std::filesystem::path filePath(file_path); + std::string file_name = filePath.filename().string(); + std::string status = app_so_status == kernel_root::AppDynlibStatus::Running ? "(正在运行)" : "(未运行)"; + if(app_so_status == kernel_root::AppDynlibStatus::Running) { + for(auto x = 0; x < sizeof(recommend_files) / sizeof(recommend_files[0]); x++) { + if(file_name == recommend_files[x]) { + status = "(推荐, 正在运行)"; + } + } + } + printf("\t%s %s\n", file_name.c_str(), status.c_str()); + } + printf("\n"); + printf("请输入将要被寄生的文件名称: "); + std::string user_input_so_name; + std::getline(std::cin, user_input_so_name); + printf("\n"); + auto it = std::find_if(so_path_list.begin(), so_path_list.end(), + [&](const auto& s) { return s.first.find(user_input_so_name) != std::string::npos; }); + if (it == so_path_list.end()) { + printf("Not found: %s\n", user_input_so_name.c_str()); + return; + } + + // 3.寄生植入目标APP + err = kernel_root::parasite_implant_su_env(ROOT_KEY, target_pid_cmdline, it->first.c_str(), su_dir_path.c_str()); + printf("parasite_implant_su_env err:%s\n", to_string(err).c_str()); + if (is_failed(err)) return; + + // 4.杀光所有历史进程 + for (pid_t pid : pid_arr) { kernel_root::kill_process(ROOT_KEY, pid); } +} + +void test_clean_su_env() { + KRootErr err = kernel_root::uninstall_su(ROOT_KEY); + printf("uninstall_su err:%s\n", to_string(err).c_str()); +} + +void test_implant_app(const char* target_pid_cmdline) { + if (is_failed(kernel_root::get_root(ROOT_KEY))) return; + + // 1.寄生预检目标APP + std::set pid_arr; + KRootErr err = kernel_root::find_all_cmdline_process(ROOT_KEY, target_pid_cmdline, pid_arr); + if (is_failed(err)) { + printf("find_all_cmdline_process err:%s\n", to_string(err).c_str()); + return; + } + if (pid_arr.size() == 0) { + printf("请先运行目标APP: %s\n", target_pid_cmdline); + return; + } + std::map so_path_list; + err = kernel_root::parasite_precheck_app(ROOT_KEY, target_pid_cmdline, so_path_list); + if (is_failed(err)) { + printf("parasite_precheck_app err:%s\n", to_string(err).c_str()); + if(err == KRootErr::ERR_EXIST_32BIT) { + printf("此目标APP为32位应用,无法寄生\n"); + } + return; + } + if (!so_path_list.size()) { + printf("无法检测到目标APP的JNI环境,目标APP暂不可被寄生;您可重新运行目标APP后重试;或将APP进行手动加固(加壳),因为加固(加壳)APP后,APP会被产生JNI环境,方可寄生!\n"); + return; + } + printf("请在以下的目标APP文件列表中选择一个即将要被寄生的文件:\n"); + + std::vector> sort_printf; + for (const auto& item : so_path_list) { + if(item.second != kernel_root::AppDynlibStatus::Running) { + continue; + } + sort_printf.push_back({item.first, item.second}); + } + for (const auto& item : so_path_list) { + if(item.second != kernel_root::AppDynlibStatus::NotRunning) { + continue; + } + sort_printf.push_back({item.first, item.second}); + } + for (const auto& item : sort_printf) { + auto file_path = std::get<0>(item); + auto app_so_status = std::get<1>(item); + std::filesystem::path filePath(file_path); + std::string file_name = filePath.filename().string(); + std::string status = app_so_status == kernel_root::AppDynlibStatus::Running ? "(正在运行)" : "(未运行)"; + if(app_so_status == kernel_root::AppDynlibStatus::Running) { + for(auto x = 0; x < sizeof(recommend_files) / sizeof(recommend_files[0]); x++) { + if(file_name == recommend_files[x]) { + status = "(推荐, 正在运行)"; + } + } + } + printf("\t%s %s\n", file_name.c_str(), status.c_str()); + } + printf("\n"); + printf("请输入将要被寄生的文件名称: "); + std::string user_input_so_name; + std::getline(std::cin, user_input_so_name); + printf("\n"); + auto it = std::find_if(so_path_list.begin(), so_path_list.end(), + [&](const auto& s) { return s.first.find(user_input_so_name) != std::string::npos; }); + if (it == so_path_list.end()) { + printf("Not found: %s\n", user_input_so_name.c_str()); + return; + } + + // 2.寄生植入目标APP + err = kernel_root::parasite_implant_app(ROOT_KEY, target_pid_cmdline, it->first.c_str()); + printf("parasite_implant_app err:%s\n", to_string(err).c_str()); + if (is_failed(err)) return; + + // 3.杀光所有历史进程 + for (pid_t pid : pid_arr) kernel_root::kill_process(ROOT_KEY, pid); +} + +int main(int argc, char* argv[]) { + printf( + "=======================================\n" + "本工具名称: SKRoot(Lite) - Linux内核级完美隐藏ROOT演示\n\n" + "本工具功能列表:\n" + + "1. 测试ROOT权限\n" + "\tUsage: testRoot test\n\n" + + "2. 执行ROOT命令\n" + "\tUsage: testRoot cmd \n\n" + + "3. 以ROOT身份直接执行程序\n" + "\tUsage: testRoot exec \n\n" + + "4. 安装部署su\n" + "\tUsage: testRoot su\n\n" + + "5. 临时注入su到指定进程\n" + "\tUsage: testRoot suTemp \n\n" + + "6. 永久注入su到指定进程\n" + "\tUsage: testRoot suForever \n\n" + + "7. 完全卸载清理su\n" + "\tUsage: testRoot cleansu\n\n" + + "8. 寄生目标APP\n" + "\tUsage: testRoot implantApp \n\n" + + "本工具特点:\n" + "新一代 SkRoot,完美隐藏Root功能,兼容安卓 APP 直接JNI调用,稳定不闪退。\n" + "------------------------------------------------------\n" + "如需帮助,请使用对应的命令,或者查看上面的菜单。\n\n"); + ++argv; + --argc; + if (argc < 1) { + std::cout << "error param." << std::endl; + return 0; + } + + //TODO: 在此修改你的Root key值。 + strncpy(ROOT_KEY, "bhuvsUdRKoCLH3OBz6lZeeYYbdsjmRwHc5LDzVPr4LOrq0Uq", sizeof(ROOT_KEY) - 1); + + std::map> command_map = { + {"test", []() { test_root(); }}, + {"cmd", [argc, argv]() { test_run_root_cmd(argc - 1, argv + 1); }}, + {"exec", [argc, argv]() { test_root_exec_process(argc - 1, argv + 1); }}, + {"su", []() { test_install_su_env(); }}, + {"suTemp", [argv]() { test_su_env_temp_inject(argv[1]); }}, + {"suForever", [argv]() { test_su_env_forever_inject(argv[1]); }}, + {"cleansu", []() { test_clean_su_env(); }}, + {"implantApp", [argv]() { test_implant_app(argv[1]); }} + }; + + std::string cmd = argv[0]; + if (command_map.find(cmd) != command_map.end()) { + command_map[cmd](); + } else { + std::cout << "unknown command." << std::endl; + return 1; + } + return 0; +} \ No newline at end of file diff --git "a/Lite_version/src/\345\267\245\347\250\213\347\233\256\345\275\225\350\257\264\346\230\216.txt" "b/Lite_version/src/\345\267\245\347\250\213\347\233\256\345\275\225\350\257\264\346\230\216.txt" new file mode 100644 index 00000000..9dad801e --- /dev/null +++ "b/Lite_version/src/\345\267\245\347\250\213\347\233\256\345\275\225\350\257\264\346\230\216.txt" @@ -0,0 +1,6 @@ +SKRoot (Lite) 工程目录说明: +────────────────────────────── +1. 内核修补工具 .................... patch_kernel_root +2. Root 权限管理 APP ............... PermissionManager +3. Root 权限管理 JNI 程序 .......... testRoot +────────────────────────────── diff --git "a/Lite_version/\345\212\237\350\203\275\346\210\252\345\233\276/1.png" "b/Lite_version/\345\212\237\350\203\275\346\210\252\345\233\276/1.png" new file mode 100644 index 00000000..d5256903 Binary files /dev/null and "b/Lite_version/\345\212\237\350\203\275\346\210\252\345\233\276/1.png" differ diff --git "a/Lite_version/\345\212\237\350\203\275\346\210\252\345\233\276/2.png" "b/Lite_version/\345\212\237\350\203\275\346\210\252\345\233\276/2.png" new file mode 100644 index 00000000..9bdfc028 Binary files /dev/null and "b/Lite_version/\345\212\237\350\203\275\346\210\252\345\233\276/2.png" differ diff --git "a/Lite_version/\345\212\237\350\203\275\346\210\252\345\233\276/3.png" "b/Lite_version/\345\212\237\350\203\275\346\210\252\345\233\276/3.png" new file mode 100644 index 00000000..54373217 Binary files /dev/null and "b/Lite_version/\345\212\237\350\203\275\346\210\252\345\233\276/3.png" differ diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/SKRootPro_4.2.7.apk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/SKRootPro_4.2.7.apk" new file mode 100644 index 00000000..05992a5b Binary files /dev/null and "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/SKRootPro_4.2.7.apk" differ diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/.gitignore" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/.gitignore" new file mode 100644 index 00000000..a3d88905 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/.gitignore" @@ -0,0 +1,16 @@ +*.iml +.idea +.gradle +/local.properties +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +.DS_Store +/build +/captures +.externalNativeBuild +.cxx +local.properties diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/.gitignore" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/.gitignore" new file mode 100644 index 00000000..42afabfd --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/.gitignore" @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/appKey.jks" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/appKey.jks" new file mode 100644 index 00000000..95ea5aef Binary files /dev/null and "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/appKey.jks" differ diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/build.gradle" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/build.gradle" new file mode 100644 index 00000000..c12f52b0 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/build.gradle" @@ -0,0 +1,52 @@ +plugins { + id 'com.android.application' +} + +android { + compileSdk 31 + + defaultConfig { + applicationId "com.linux.permissionmanager" + minSdk 26 + targetSdk 31 + versionCode 1 + versionName "4.2.7" + + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + externalNativeBuild { + cmake { + cppFlags '-std=c++17' + abiFilters "arm64-v8a" + } + } + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + externalNativeBuild { + cmake { + path file('src/main/cpp/CMakeLists.txt') + version '3.18.1' + } + } + buildFeatures { + viewBinding true + } +} + +dependencies { + implementation 'androidx.appcompat:appcompat:1.4.1' + implementation 'com.google.android.material:material:1.5.0' + implementation 'androidx.constraintlayout:constraintlayout:2.1.3' + testImplementation 'junit:junit:4.13.2' + androidTestImplementation 'androidx.test.ext:junit:1.1.3' + androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' +} \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/proguard-rules.pro" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/proguard-rules.pro" new file mode 100644 index 00000000..481bb434 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/proguard-rules.pro" @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/androidTest/java/com/linux/permissionmanager/ExampleInstrumentedTest.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/androidTest/java/com/linux/permissionmanager/ExampleInstrumentedTest.java" new file mode 100644 index 00000000..e63884ad --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/androidTest/java/com/linux/permissionmanager/ExampleInstrumentedTest.java" @@ -0,0 +1,26 @@ +package com.linux.permissionmanager; + +import android.content.Context; + +import androidx.test.platform.app.InstrumentationRegistry; +import androidx.test.ext.junit.runners.AndroidJUnit4; + +import org.junit.Test; +import org.junit.runner.RunWith; + +import static org.junit.Assert.*; + +/** + * Instrumented test, which will execute on an Android device. + * + * @see Testing documentation + */ +@RunWith(AndroidJUnit4.class) +public class ExampleInstrumentedTest { + @Test + public void useAppContext() { + // Context of the app under test. + Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); + assertEquals("com.linux.permissionmanager", appContext.getPackageName()); + } +} \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/AndroidManifest.xml" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/AndroidManifest.xml" new file mode 100644 index 00000000..55a58268 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/AndroidManifest.xml" @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/cpp/CMakeLists.txt" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/cpp/CMakeLists.txt" new file mode 100644 index 00000000..6d7d73dd --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/cpp/CMakeLists.txt" @@ -0,0 +1,64 @@ +# For more information about using CMake with Android Studio, read the +# documentation: https://d.android.com/studio/projects/add-native-code.html + +# Sets the minimum version of CMake required to build the native library. + +cmake_minimum_required(VERSION 3.18.1) + +# Declares and names the project. + +project("permissionmanager") + +set(OTHER_SRC + "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../testInstall/command.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../testInstall/exec_process.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../testInstall/test.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/cJSON.cpp" + "${CMAKE_CURRENT_SOURCE_DIR}/native-lib.cpp" + ) +# Creates and names a library, sets it as either STATIC +# or SHARED, and provides the relative paths to its source code. +# You can define multiple libraries, and CMake builds them for you. +# Gradle automatically packages shared libraries with your APK. + +add_library( # Sets the name of the library. + permissionmanager + + # Sets the library as a shared library. + SHARED + + # Provides a relative path to your source file(s). + ${OTHER_SRC}) + +# Searches for a specified prebuilt library and stores the path as a +# variable. Because CMake includes system libraries in the search path by +# default, you only need to specify the name of the public NDK library +# you want to add. CMake verifies that the library exists before +# completing its build. + +find_library( # Sets the name of the path variable. + log-lib + + # Specifies the name of the NDK library that + # you want CMake to locate. + log) + +# Specifies libraries CMake should link to your target library. You +# can link multiple libraries, such as libraries you define in this +# build script, prebuilt third-party libraries, or system libraries. + +target_include_directories( + permissionmanager + PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/../../../../../testInstall/ + ${CMAKE_CURRENT_SOURCE_DIR}/../../../../../testModule/kernel_module_kit/include/ +) + +target_link_libraries( # Specifies the target library. + permissionmanager + + # Links the target library to the log library + # included in the NDK. + ${CMAKE_CURRENT_SOURCE_DIR}/../../../../../testModule/kernel_module_kit/lib/libkernel_module_kit_static.a + z + ${log-lib}) \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/cpp/cJSON.cpp" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/cpp/cJSON.cpp" new file mode 100644 index 00000000..faa3e297 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/cpp/cJSON.cpp" @@ -0,0 +1,3129 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +/* cJSON */ +/* JSON parser in C. */ + +/* disable warnings about old C89 functions in MSVC */ +#if !defined(_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) +#define _CRT_SECURE_NO_DEPRECATE +#endif + +#ifdef __GNUC__ +#pragma GCC visibility push(default) +#endif +#if defined(_MSC_VER) +#pragma warning (push) +/* disable warning about single line comments in system headers */ +#pragma warning (disable : 4001) +#endif + +#include +#include +#include +#include +#include +#include +#include + +#ifdef ENABLE_LOCALES +#include +#endif + +#if defined(_MSC_VER) +#pragma warning (pop) +#endif +#ifdef __GNUC__ +#pragma GCC visibility pop +#endif + +#include "cJSON.h" + +/* define our own boolean type */ +#ifdef true +#undef true +#endif +#define true ((cJSON_bool)1) + +#ifdef false +#undef false +#endif +#define false ((cJSON_bool)0) + +/* define isnan and isinf for ANSI C, if in C99 or above, isnan and isinf has been defined in math.h */ +#ifndef isinf +#define isinf(d) (isnan((d - d)) && !isnan(d)) +#endif +#ifndef isnan +#define isnan(d) (d != d) +#endif + +#ifndef NAN +#ifdef _WIN32 +#define NAN sqrt(-1.0) +#else +#define NAN 0.0/0.0 +#endif +#endif + +typedef struct { + const unsigned char *json; + size_t position; +} error; +static error global_error = { NULL, 0 }; + +CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void) +{ + return (const char*) (global_error.json + global_error.position); +} + +CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item) +{ + if (!cJSON_IsString(item)) + { + return NULL; + } + + return item->valuestring; +} + +CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item) +{ + if (!cJSON_IsNumber(item)) + { + return (double) NAN; + } + + return item->valuedouble; +} + +/* This is a safeguard to prevent copy-pasters from using incompatible C and header files */ +#if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 7) || (CJSON_VERSION_PATCH != 16) + #error cJSON.h and cJSON.c have different versions. Make sure that both have the same. +#endif + +CJSON_PUBLIC(const char*) cJSON_Version(void) +{ + static char version[15]; + sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH); + + return version; +} + +/* Case insensitive string comparison, doesn't consider two NULL pointers equal though */ +static int case_insensitive_strcmp(const unsigned char *string1, const unsigned char *string2) +{ + if ((string1 == NULL) || (string2 == NULL)) + { + return 1; + } + + if (string1 == string2) + { + return 0; + } + + for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++) + { + if (*string1 == '\0') + { + return 0; + } + } + + return tolower(*string1) - tolower(*string2); +} + +typedef struct internal_hooks +{ + void *(CJSON_CDECL *allocate)(size_t size); + void (CJSON_CDECL *deallocate)(void *pointer); + void *(CJSON_CDECL *reallocate)(void *pointer, size_t size); +} internal_hooks; + +#if defined(_MSC_VER) +/* work around MSVC error C2322: '...' address of dllimport '...' is not static */ +static void * CJSON_CDECL internal_malloc(size_t size) +{ + return malloc(size); +} +static void CJSON_CDECL internal_free(void *pointer) +{ + free(pointer); +} +static void * CJSON_CDECL internal_realloc(void *pointer, size_t size) +{ + return realloc(pointer, size); +} +#else +#define internal_malloc malloc +#define internal_free free +#define internal_realloc realloc +#endif + +/* strlen of character literals resolved at compile time */ +#define static_strlen(string_literal) (sizeof(string_literal) - sizeof("")) + +static internal_hooks global_hooks = { internal_malloc, internal_free, internal_realloc }; + +static unsigned char* cJSON_strdup(const unsigned char* string, const internal_hooks * const hooks) +{ + size_t length = 0; + unsigned char *copy = NULL; + + if (string == NULL) + { + return NULL; + } + + length = strlen((const char*)string) + sizeof(""); + copy = (unsigned char*)hooks->allocate(length); + if (copy == NULL) + { + return NULL; + } + memcpy(copy, string, length); + + return copy; +} + +CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks) +{ + if (hooks == NULL) + { + /* Reset hooks */ + global_hooks.allocate = malloc; + global_hooks.deallocate = free; + global_hooks.reallocate = realloc; + return; + } + + global_hooks.allocate = malloc; + if (hooks->malloc_fn != NULL) + { + global_hooks.allocate = hooks->malloc_fn; + } + + global_hooks.deallocate = free; + if (hooks->free_fn != NULL) + { + global_hooks.deallocate = hooks->free_fn; + } + + /* use realloc only if both free and malloc are used */ + global_hooks.reallocate = NULL; + if ((global_hooks.allocate == malloc) && (global_hooks.deallocate == free)) + { + global_hooks.reallocate = realloc; + } +} + +/* Internal constructor. */ +static cJSON *cJSON_New_Item(const internal_hooks * const hooks) +{ + cJSON* node = (cJSON*)hooks->allocate(sizeof(cJSON)); + if (node) + { + memset(node, '\0', sizeof(cJSON)); + } + + return node; +} + +/* Delete a cJSON structure. */ +CJSON_PUBLIC(void) cJSON_Delete(cJSON *item) +{ + cJSON *next = NULL; + while (item != NULL) + { + next = item->next; + if (!(item->type & cJSON_IsReference) && (item->child != NULL)) + { + cJSON_Delete(item->child); + } + if (!(item->type & cJSON_IsReference) && (item->valuestring != NULL)) + { + global_hooks.deallocate(item->valuestring); + } + if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) + { + global_hooks.deallocate(item->string); + } + global_hooks.deallocate(item); + item = next; + } +} + +/* get the decimal point character of the current locale */ +static unsigned char get_decimal_point(void) +{ +#ifdef ENABLE_LOCALES + struct lconv *lconv = localeconv(); + return (unsigned char) lconv->decimal_point[0]; +#else + return '.'; +#endif +} + +typedef struct +{ + const unsigned char *content; + size_t length; + size_t offset; + size_t depth; /* How deeply nested (in arrays/objects) is the input at the current offset. */ + internal_hooks hooks; +} parse_buffer; + +/* check if the given size is left to read in a given parse buffer (starting with 1) */ +#define can_read(buffer, size) ((buffer != NULL) && (((buffer)->offset + size) <= (buffer)->length)) +/* check if the buffer can be accessed at the given index (starting with 0) */ +#define can_access_at_index(buffer, index) ((buffer != NULL) && (((buffer)->offset + index) < (buffer)->length)) +#define cannot_access_at_index(buffer, index) (!can_access_at_index(buffer, index)) +/* get a pointer to the buffer at the position */ +#define buffer_at_offset(buffer) ((buffer)->content + (buffer)->offset) + +/* Parse the input text to generate a number, and populate the result into item. */ +static cJSON_bool parse_number(cJSON * const item, parse_buffer * const input_buffer) +{ + double number = 0; + unsigned char *after_end = NULL; + unsigned char number_c_string[64]; + unsigned char decimal_point = get_decimal_point(); + size_t i = 0; + + if ((input_buffer == NULL) || (input_buffer->content == NULL)) + { + return false; + } + + /* copy the number into a temporary buffer and replace '.' with the decimal point + * of the current locale (for strtod) + * This also takes care of '\0' not necessarily being available for marking the end of the input */ + for (i = 0; (i < (sizeof(number_c_string) - 1)) && can_access_at_index(input_buffer, i); i++) + { + switch (buffer_at_offset(input_buffer)[i]) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case '+': + case '-': + case 'e': + case 'E': + number_c_string[i] = buffer_at_offset(input_buffer)[i]; + break; + + case '.': + number_c_string[i] = decimal_point; + break; + + default: + goto loop_end; + } + } +loop_end: + number_c_string[i] = '\0'; + + number = strtod((const char*)number_c_string, (char**)&after_end); + if (number_c_string == after_end) + { + return false; /* parse_error */ + } + + item->valuedouble = number; + + /* use saturation in case of overflow */ + if (number >= INT_MAX) + { + item->valueint = INT_MAX; + } + else if (number <= (double)INT_MIN) + { + item->valueint = INT_MIN; + } + else + { + item->valueint = (int)number; + } + + item->type = cJSON_Number; + + input_buffer->offset += (size_t)(after_end - number_c_string); + return true; +} + +/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */ +CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number) +{ + if (number >= INT_MAX) + { + object->valueint = INT_MAX; + } + else if (number <= (double)INT_MIN) + { + object->valueint = INT_MIN; + } + else + { + object->valueint = (int)number; + } + + return object->valuedouble = number; +} + +CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring) +{ + char *copy = NULL; + /* if object's type is not cJSON_String or is cJSON_IsReference, it should not set valuestring */ + if ((object == NULL) || !(object->type & cJSON_String) || (object->type & cJSON_IsReference)) + { + return NULL; + } + /* return NULL if the object is corrupted */ + if (object->valuestring == NULL) + { + return NULL; + } + if (strlen(valuestring) <= strlen(object->valuestring)) + { + strcpy(object->valuestring, valuestring); + return object->valuestring; + } + copy = (char*) cJSON_strdup((const unsigned char*)valuestring, &global_hooks); + if (copy == NULL) + { + return NULL; + } + if (object->valuestring != NULL) + { + cJSON_free(object->valuestring); + } + object->valuestring = copy; + + return copy; +} + +typedef struct +{ + unsigned char *buffer; + size_t length; + size_t offset; + size_t depth; /* current nesting depth (for formatted printing) */ + cJSON_bool noalloc; + cJSON_bool format; /* is this print a formatted print */ + internal_hooks hooks; +} printbuffer; + +/* realloc printbuffer if necessary to have at least "needed" bytes more */ +static unsigned char* ensure(printbuffer * const p, size_t needed) +{ + unsigned char *newbuffer = NULL; + size_t newsize = 0; + + if ((p == NULL) || (p->buffer == NULL)) + { + return NULL; + } + + if ((p->length > 0) && (p->offset >= p->length)) + { + /* make sure that offset is valid */ + return NULL; + } + + if (needed > INT_MAX) + { + /* sizes bigger than INT_MAX are currently not supported */ + return NULL; + } + + needed += p->offset + 1; + if (needed <= p->length) + { + return p->buffer + p->offset; + } + + if (p->noalloc) { + return NULL; + } + + /* calculate new buffer size */ + if (needed > (INT_MAX / 2)) + { + /* overflow of int, use INT_MAX if possible */ + if (needed <= INT_MAX) + { + newsize = INT_MAX; + } + else + { + return NULL; + } + } + else + { + newsize = needed * 2; + } + + if (p->hooks.reallocate != NULL) + { + /* reallocate with realloc if available */ + newbuffer = (unsigned char*)p->hooks.reallocate(p->buffer, newsize); + if (newbuffer == NULL) + { + p->hooks.deallocate(p->buffer); + p->length = 0; + p->buffer = NULL; + + return NULL; + } + } + else + { + /* otherwise reallocate manually */ + newbuffer = (unsigned char*)p->hooks.allocate(newsize); + if (!newbuffer) + { + p->hooks.deallocate(p->buffer); + p->length = 0; + p->buffer = NULL; + + return NULL; + } + + memcpy(newbuffer, p->buffer, p->offset + 1); + p->hooks.deallocate(p->buffer); + } + p->length = newsize; + p->buffer = newbuffer; + + return newbuffer + p->offset; +} + +/* calculate the new length of the string in a printbuffer and update the offset */ +static void update_offset(printbuffer * const buffer) +{ + const unsigned char *buffer_pointer = NULL; + if ((buffer == NULL) || (buffer->buffer == NULL)) + { + return; + } + buffer_pointer = buffer->buffer + buffer->offset; + + buffer->offset += strlen((const char*)buffer_pointer); +} + +/* securely comparison of floating-point variables */ +static cJSON_bool compare_double(double a, double b) +{ + double maxVal = fabs(a) > fabs(b) ? fabs(a) : fabs(b); + return (fabs(a - b) <= maxVal * DBL_EPSILON); +} + +/* Render the number nicely from the given item into a string. */ +static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + double d = item->valuedouble; + int length = 0; + size_t i = 0; + unsigned char number_buffer[26] = {0}; /* temporary buffer to print the number into */ + unsigned char decimal_point = get_decimal_point(); + double test = 0.0; + + if (output_buffer == NULL) + { + return false; + } + + /* This checks for NaN and Infinity */ + if (isnan(d) || isinf(d)) + { + length = sprintf((char*)number_buffer, "null"); + } + else if(d == (double)item->valueint) + { + length = sprintf((char*)number_buffer, "%d", item->valueint); + } + else + { + /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */ + length = sprintf((char*)number_buffer, "%1.15g", d); + + /* Check whether the original double can be recovered */ + if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || !compare_double((double)test, d)) + { + /* If not, print with 17 decimal places of precision */ + length = sprintf((char*)number_buffer, "%1.17g", d); + } + } + + /* sprintf failed or buffer overrun occurred */ + if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1))) + { + return false; + } + + /* reserve appropriate space in the output */ + output_pointer = ensure(output_buffer, (size_t)length + sizeof("")); + if (output_pointer == NULL) + { + return false; + } + + /* copy the printed number to the output and replace locale + * dependent decimal point with '.' */ + for (i = 0; i < ((size_t)length); i++) + { + if (number_buffer[i] == decimal_point) + { + output_pointer[i] = '.'; + continue; + } + + output_pointer[i] = number_buffer[i]; + } + output_pointer[i] = '\0'; + + output_buffer->offset += (size_t)length; + + return true; +} + +/* parse 4 digit hexadecimal number */ +static unsigned parse_hex4(const unsigned char * const input) +{ + unsigned int h = 0; + size_t i = 0; + + for (i = 0; i < 4; i++) + { + /* parse digit */ + if ((input[i] >= '0') && (input[i] <= '9')) + { + h += (unsigned int) input[i] - '0'; + } + else if ((input[i] >= 'A') && (input[i] <= 'F')) + { + h += (unsigned int) 10 + input[i] - 'A'; + } + else if ((input[i] >= 'a') && (input[i] <= 'f')) + { + h += (unsigned int) 10 + input[i] - 'a'; + } + else /* invalid */ + { + return 0; + } + + if (i < 3) + { + /* shift left to make place for the next nibble */ + h = h << 4; + } + } + + return h; +} + +/* converts a UTF-16 literal to UTF-8 + * A literal can be one or two sequences of the form \uXXXX */ +static unsigned char utf16_literal_to_utf8(const unsigned char * const input_pointer, const unsigned char * const input_end, unsigned char **output_pointer) +{ + long unsigned int codepoint = 0; + unsigned int first_code = 0; + const unsigned char *first_sequence = input_pointer; + unsigned char utf8_length = 0; + unsigned char utf8_position = 0; + unsigned char sequence_length = 0; + unsigned char first_byte_mark = 0; + + if ((input_end - first_sequence) < 6) + { + /* input ends unexpectedly */ + goto fail; + } + + /* get the first utf16 sequence */ + first_code = parse_hex4(first_sequence + 2); + + /* check that the code is valid */ + if (((first_code >= 0xDC00) && (first_code <= 0xDFFF))) + { + goto fail; + } + + /* UTF16 surrogate pair */ + if ((first_code >= 0xD800) && (first_code <= 0xDBFF)) + { + const unsigned char *second_sequence = first_sequence + 6; + unsigned int second_code = 0; + sequence_length = 12; /* \uXXXX\uXXXX */ + + if ((input_end - second_sequence) < 6) + { + /* input ends unexpectedly */ + goto fail; + } + + if ((second_sequence[0] != '\\') || (second_sequence[1] != 'u')) + { + /* missing second half of the surrogate pair */ + goto fail; + } + + /* get the second utf16 sequence */ + second_code = parse_hex4(second_sequence + 2); + /* check that the code is valid */ + if ((second_code < 0xDC00) || (second_code > 0xDFFF)) + { + /* invalid second half of the surrogate pair */ + goto fail; + } + + + /* calculate the unicode codepoint from the surrogate pair */ + codepoint = 0x10000 + (((first_code & 0x3FF) << 10) | (second_code & 0x3FF)); + } + else + { + sequence_length = 6; /* \uXXXX */ + codepoint = first_code; + } + + /* encode as UTF-8 + * takes at maximum 4 bytes to encode: + * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */ + if (codepoint < 0x80) + { + /* normal ascii, encoding 0xxxxxxx */ + utf8_length = 1; + } + else if (codepoint < 0x800) + { + /* two bytes, encoding 110xxxxx 10xxxxxx */ + utf8_length = 2; + first_byte_mark = 0xC0; /* 11000000 */ + } + else if (codepoint < 0x10000) + { + /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */ + utf8_length = 3; + first_byte_mark = 0xE0; /* 11100000 */ + } + else if (codepoint <= 0x10FFFF) + { + /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */ + utf8_length = 4; + first_byte_mark = 0xF0; /* 11110000 */ + } + else + { + /* invalid unicode codepoint */ + goto fail; + } + + /* encode as utf8 */ + for (utf8_position = (unsigned char)(utf8_length - 1); utf8_position > 0; utf8_position--) + { + /* 10xxxxxx */ + (*output_pointer)[utf8_position] = (unsigned char)((codepoint | 0x80) & 0xBF); + codepoint >>= 6; + } + /* encode first byte */ + if (utf8_length > 1) + { + (*output_pointer)[0] = (unsigned char)((codepoint | first_byte_mark) & 0xFF); + } + else + { + (*output_pointer)[0] = (unsigned char)(codepoint & 0x7F); + } + + *output_pointer += utf8_length; + + return sequence_length; + +fail: + return 0; +} + +/* Parse the input text into an unescaped cinput, and populate item. */ +static cJSON_bool parse_string(cJSON * const item, parse_buffer * const input_buffer) +{ + const unsigned char *input_pointer = buffer_at_offset(input_buffer) + 1; + const unsigned char *input_end = buffer_at_offset(input_buffer) + 1; + unsigned char *output_pointer = NULL; + unsigned char *output = NULL; + + /* not a string */ + if (buffer_at_offset(input_buffer)[0] != '\"') + { + goto fail; + } + + { + /* calculate approximate size of the output (overestimate) */ + size_t allocation_length = 0; + size_t skipped_bytes = 0; + while (((size_t)(input_end - input_buffer->content) < input_buffer->length) && (*input_end != '\"')) + { + /* is escape sequence */ + if (input_end[0] == '\\') + { + if ((size_t)(input_end + 1 - input_buffer->content) >= input_buffer->length) + { + /* prevent buffer overflow when last input character is a backslash */ + goto fail; + } + skipped_bytes++; + input_end++; + } + input_end++; + } + if (((size_t)(input_end - input_buffer->content) >= input_buffer->length) || (*input_end != '\"')) + { + goto fail; /* string ended unexpectedly */ + } + + /* This is at most how much we need for the output */ + allocation_length = (size_t) (input_end - buffer_at_offset(input_buffer)) - skipped_bytes; + output = (unsigned char*)input_buffer->hooks.allocate(allocation_length + sizeof("")); + if (output == NULL) + { + goto fail; /* allocation failure */ + } + } + + output_pointer = output; + /* loop through the string literal */ + while (input_pointer < input_end) + { + if (*input_pointer != '\\') + { + *output_pointer++ = *input_pointer++; + } + /* escape sequence */ + else + { + unsigned char sequence_length = 2; + if ((input_end - input_pointer) < 1) + { + goto fail; + } + + switch (input_pointer[1]) + { + case 'b': + *output_pointer++ = '\b'; + break; + case 'f': + *output_pointer++ = '\f'; + break; + case 'n': + *output_pointer++ = '\n'; + break; + case 'r': + *output_pointer++ = '\r'; + break; + case 't': + *output_pointer++ = '\t'; + break; + case '\"': + case '\\': + case '/': + *output_pointer++ = input_pointer[1]; + break; + + /* UTF-16 literal */ + case 'u': + sequence_length = utf16_literal_to_utf8(input_pointer, input_end, &output_pointer); + if (sequence_length == 0) + { + /* failed to convert UTF16-literal to UTF-8 */ + goto fail; + } + break; + + default: + goto fail; + } + input_pointer += sequence_length; + } + } + + /* zero terminate the output */ + *output_pointer = '\0'; + + item->type = cJSON_String; + item->valuestring = (char*)output; + + input_buffer->offset = (size_t) (input_end - input_buffer->content); + input_buffer->offset++; + + return true; + +fail: + if (output != NULL) + { + input_buffer->hooks.deallocate(output); + } + + if (input_pointer != NULL) + { + input_buffer->offset = (size_t)(input_pointer - input_buffer->content); + } + + return false; +} + +/* Render the cstring provided to an escaped version that can be printed. */ +static cJSON_bool print_string_ptr(const unsigned char * const input, printbuffer * const output_buffer) +{ + const unsigned char *input_pointer = NULL; + unsigned char *output = NULL; + unsigned char *output_pointer = NULL; + size_t output_length = 0; + /* numbers of additional characters needed for escaping */ + size_t escape_characters = 0; + + if (output_buffer == NULL) + { + return false; + } + + /* empty string */ + if (input == NULL) + { + output = ensure(output_buffer, sizeof("\"\"")); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "\"\""); + + return true; + } + + /* set "flag" to 1 if something needs to be escaped */ + for (input_pointer = input; *input_pointer; input_pointer++) + { + switch (*input_pointer) + { + case '\"': + case '\\': + case '\b': + case '\f': + case '\n': + case '\r': + case '\t': + /* one character escape sequence */ + escape_characters++; + break; + default: + if (*input_pointer < 32) + { + /* UTF-16 escape sequence uXXXX */ + escape_characters += 5; + } + break; + } + } + output_length = (size_t)(input_pointer - input) + escape_characters; + + output = ensure(output_buffer, output_length + sizeof("\"\"")); + if (output == NULL) + { + return false; + } + + /* no characters have to be escaped */ + if (escape_characters == 0) + { + output[0] = '\"'; + memcpy(output + 1, input, output_length); + output[output_length + 1] = '\"'; + output[output_length + 2] = '\0'; + + return true; + } + + output[0] = '\"'; + output_pointer = output + 1; + /* copy the string */ + for (input_pointer = input; *input_pointer != '\0'; (void)input_pointer++, output_pointer++) + { + if ((*input_pointer > 31) && (*input_pointer != '\"') && (*input_pointer != '\\')) + { + /* normal character, copy */ + *output_pointer = *input_pointer; + } + else + { + /* character needs to be escaped */ + *output_pointer++ = '\\'; + switch (*input_pointer) + { + case '\\': + *output_pointer = '\\'; + break; + case '\"': + *output_pointer = '\"'; + break; + case '\b': + *output_pointer = 'b'; + break; + case '\f': + *output_pointer = 'f'; + break; + case '\n': + *output_pointer = 'n'; + break; + case '\r': + *output_pointer = 'r'; + break; + case '\t': + *output_pointer = 't'; + break; + default: + /* escape and print as unicode codepoint */ + sprintf((char*)output_pointer, "u%04x", *input_pointer); + output_pointer += 4; + break; + } + } + } + output[output_length + 1] = '\"'; + output[output_length + 2] = '\0'; + + return true; +} + +/* Invoke print_string_ptr (which is useful) on an item. */ +static cJSON_bool print_string(const cJSON * const item, printbuffer * const p) +{ + return print_string_ptr((unsigned char*)item->valuestring, p); +} + +/* Predeclare these prototypes. */ +static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer); +static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer); +static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer); + +/* Utility to jump whitespace and cr/lf */ +static parse_buffer *buffer_skip_whitespace(parse_buffer * const buffer) +{ + if ((buffer == NULL) || (buffer->content == NULL)) + { + return NULL; + } + + if (cannot_access_at_index(buffer, 0)) + { + return buffer; + } + + while (can_access_at_index(buffer, 0) && (buffer_at_offset(buffer)[0] <= 32)) + { + buffer->offset++; + } + + if (buffer->offset == buffer->length) + { + buffer->offset--; + } + + return buffer; +} + +/* skip the UTF-8 BOM (byte order mark) if it is at the beginning of a buffer */ +static parse_buffer *skip_utf8_bom(parse_buffer * const buffer) +{ + if ((buffer == NULL) || (buffer->content == NULL) || (buffer->offset != 0)) + { + return NULL; + } + + if (can_access_at_index(buffer, 4) && (strncmp((const char*)buffer_at_offset(buffer), "\xEF\xBB\xBF", 3) == 0)) + { + buffer->offset += 3; + } + + return buffer; +} + +CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated) +{ + size_t buffer_length; + + if (NULL == value) + { + return NULL; + } + + /* Adding null character size due to require_null_terminated. */ + buffer_length = strlen(value) + sizeof(""); + + return cJSON_ParseWithLengthOpts(value, buffer_length, return_parse_end, require_null_terminated); +} + +/* Parse an object - create a new root, and populate. */ +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated) +{ + parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } }; + cJSON *item = NULL; + + /* reset error position */ + global_error.json = NULL; + global_error.position = 0; + + if (value == NULL || 0 == buffer_length) + { + goto fail; + } + + buffer.content = (const unsigned char*)value; + buffer.length = buffer_length; + buffer.offset = 0; + buffer.hooks = global_hooks; + + item = cJSON_New_Item(&global_hooks); + if (item == NULL) /* memory fail */ + { + goto fail; + } + + if (!parse_value(item, buffer_skip_whitespace(skip_utf8_bom(&buffer)))) + { + /* parse failure. ep is set. */ + goto fail; + } + + /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */ + if (require_null_terminated) + { + buffer_skip_whitespace(&buffer); + if ((buffer.offset >= buffer.length) || buffer_at_offset(&buffer)[0] != '\0') + { + goto fail; + } + } + if (return_parse_end) + { + *return_parse_end = (const char*)buffer_at_offset(&buffer); + } + + return item; + +fail: + if (item != NULL) + { + cJSON_Delete(item); + } + + if (value != NULL) + { + error local_error; + local_error.json = (const unsigned char*)value; + local_error.position = 0; + + if (buffer.offset < buffer.length) + { + local_error.position = buffer.offset; + } + else if (buffer.length > 0) + { + local_error.position = buffer.length - 1; + } + + if (return_parse_end != NULL) + { + *return_parse_end = (const char*)local_error.json + local_error.position; + } + + global_error = local_error; + } + + return NULL; +} + +/* Default options for cJSON_Parse */ +CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value) +{ + return cJSON_ParseWithOpts(value, 0, 0); +} + +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length) +{ + return cJSON_ParseWithLengthOpts(value, buffer_length, 0, 0); +} + +#define cjson_min(a, b) (((a) < (b)) ? (a) : (b)) + +static unsigned char *print(const cJSON * const item, cJSON_bool format, const internal_hooks * const hooks) +{ + static const size_t default_buffer_size = 256; + printbuffer buffer[1]; + unsigned char *printed = NULL; + + memset(buffer, 0, sizeof(buffer)); + + /* create buffer */ + buffer->buffer = (unsigned char*) hooks->allocate(default_buffer_size); + buffer->length = default_buffer_size; + buffer->format = format; + buffer->hooks = *hooks; + if (buffer->buffer == NULL) + { + goto fail; + } + + /* print the value */ + if (!print_value(item, buffer)) + { + goto fail; + } + update_offset(buffer); + + /* check if reallocate is available */ + if (hooks->reallocate != NULL) + { + printed = (unsigned char*) hooks->reallocate(buffer->buffer, buffer->offset + 1); + if (printed == NULL) { + goto fail; + } + buffer->buffer = NULL; + } + else /* otherwise copy the JSON over to a new buffer */ + { + printed = (unsigned char*) hooks->allocate(buffer->offset + 1); + if (printed == NULL) + { + goto fail; + } + memcpy(printed, buffer->buffer, cjson_min(buffer->length, buffer->offset + 1)); + printed[buffer->offset] = '\0'; /* just to be sure */ + + /* free the buffer */ + hooks->deallocate(buffer->buffer); + } + + return printed; + +fail: + if (buffer->buffer != NULL) + { + hooks->deallocate(buffer->buffer); + } + + if (printed != NULL) + { + hooks->deallocate(printed); + } + + return NULL; +} + +/* Render a cJSON item/entity/structure to text. */ +CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item) +{ + return (char*)print(item, true, &global_hooks); +} + +CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item) +{ + return (char*)print(item, false, &global_hooks); +} + +CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt) +{ + printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; + + if (prebuffer < 0) + { + return NULL; + } + + p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer); + if (!p.buffer) + { + return NULL; + } + + p.length = (size_t)prebuffer; + p.offset = 0; + p.noalloc = false; + p.format = fmt; + p.hooks = global_hooks; + + if (!print_value(item, &p)) + { + global_hooks.deallocate(p.buffer); + return NULL; + } + + return (char*)p.buffer; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format) +{ + printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; + + if ((length < 0) || (buffer == NULL)) + { + return false; + } + + p.buffer = (unsigned char*)buffer; + p.length = (size_t)length; + p.offset = 0; + p.noalloc = true; + p.format = format; + p.hooks = global_hooks; + + return print_value(item, &p); +} + +/* Parser core - when encountering text, process appropriately. */ +static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer) +{ + if ((input_buffer == NULL) || (input_buffer->content == NULL)) + { + return false; /* no input */ + } + + /* parse the different types of values */ + /* null */ + if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "null", 4) == 0)) + { + item->type = cJSON_NULL; + input_buffer->offset += 4; + return true; + } + /* false */ + if (can_read(input_buffer, 5) && (strncmp((const char*)buffer_at_offset(input_buffer), "false", 5) == 0)) + { + item->type = cJSON_False; + input_buffer->offset += 5; + return true; + } + /* true */ + if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "true", 4) == 0)) + { + item->type = cJSON_True; + item->valueint = 1; + input_buffer->offset += 4; + return true; + } + /* string */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '\"')) + { + return parse_string(item, input_buffer); + } + /* number */ + if (can_access_at_index(input_buffer, 0) && ((buffer_at_offset(input_buffer)[0] == '-') || ((buffer_at_offset(input_buffer)[0] >= '0') && (buffer_at_offset(input_buffer)[0] <= '9')))) + { + return parse_number(item, input_buffer); + } + /* array */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '[')) + { + return parse_array(item, input_buffer); + } + /* object */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '{')) + { + return parse_object(item, input_buffer); + } + + return false; +} + +/* Render a value to text. */ +static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output = NULL; + + if ((item == NULL) || (output_buffer == NULL)) + { + return false; + } + + switch ((item->type) & 0xFF) + { + case cJSON_NULL: + output = ensure(output_buffer, 5); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "null"); + return true; + + case cJSON_False: + output = ensure(output_buffer, 6); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "false"); + return true; + + case cJSON_True: + output = ensure(output_buffer, 5); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "true"); + return true; + + case cJSON_Number: + return print_number(item, output_buffer); + + case cJSON_Raw: + { + size_t raw_length = 0; + if (item->valuestring == NULL) + { + return false; + } + + raw_length = strlen(item->valuestring) + sizeof(""); + output = ensure(output_buffer, raw_length); + if (output == NULL) + { + return false; + } + memcpy(output, item->valuestring, raw_length); + return true; + } + + case cJSON_String: + return print_string(item, output_buffer); + + case cJSON_Array: + return print_array(item, output_buffer); + + case cJSON_Object: + return print_object(item, output_buffer); + + default: + return false; + } +} + +/* Build an array from input text. */ +static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer) +{ + cJSON *head = NULL; /* head of the linked list */ + cJSON *current_item = NULL; + + if (input_buffer->depth >= CJSON_NESTING_LIMIT) + { + return false; /* to deeply nested */ + } + input_buffer->depth++; + + if (buffer_at_offset(input_buffer)[0] != '[') + { + /* not an array */ + goto fail; + } + + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ']')) + { + /* empty array */ + goto success; + } + + /* check if we skipped to the end of the buffer */ + if (cannot_access_at_index(input_buffer, 0)) + { + input_buffer->offset--; + goto fail; + } + + /* step back to character in front of the first element */ + input_buffer->offset--; + /* loop through the comma separated array elements */ + do + { + /* allocate next item */ + cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); + if (new_item == NULL) + { + goto fail; /* allocation failure */ + } + + /* attach next item to list */ + if (head == NULL) + { + /* start the linked list */ + current_item = head = new_item; + } + else + { + /* add to the end and advance */ + current_item->next = new_item; + new_item->prev = current_item; + current_item = new_item; + } + + /* parse next value */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_value(current_item, input_buffer)) + { + goto fail; /* failed to parse value */ + } + buffer_skip_whitespace(input_buffer); + } + while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ',')); + + if (cannot_access_at_index(input_buffer, 0) || buffer_at_offset(input_buffer)[0] != ']') + { + goto fail; /* expected end of array */ + } + +success: + input_buffer->depth--; + + if (head != NULL) { + head->prev = current_item; + } + + item->type = cJSON_Array; + item->child = head; + + input_buffer->offset++; + + return true; + +fail: + if (head != NULL) + { + cJSON_Delete(head); + } + + return false; +} + +/* Render an array to text */ +static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + size_t length = 0; + cJSON *current_element = item->child; + + if (output_buffer == NULL) + { + return false; + } + + /* Compose the output array. */ + /* opening square bracket */ + output_pointer = ensure(output_buffer, 1); + if (output_pointer == NULL) + { + return false; + } + + *output_pointer = '['; + output_buffer->offset++; + output_buffer->depth++; + + while (current_element != NULL) + { + if (!print_value(current_element, output_buffer)) + { + return false; + } + update_offset(output_buffer); + if (current_element->next) + { + length = (size_t) (output_buffer->format ? 2 : 1); + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ','; + if(output_buffer->format) + { + *output_pointer++ = ' '; + } + *output_pointer = '\0'; + output_buffer->offset += length; + } + current_element = current_element->next; + } + + output_pointer = ensure(output_buffer, 2); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ']'; + *output_pointer = '\0'; + output_buffer->depth--; + + return true; +} + +/* Build an object from the text. */ +static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer) +{ + cJSON *head = NULL; /* linked list head */ + cJSON *current_item = NULL; + + if (input_buffer->depth >= CJSON_NESTING_LIMIT) + { + return false; /* to deeply nested */ + } + input_buffer->depth++; + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '{')) + { + goto fail; /* not an object */ + } + + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '}')) + { + goto success; /* empty object */ + } + + /* check if we skipped to the end of the buffer */ + if (cannot_access_at_index(input_buffer, 0)) + { + input_buffer->offset--; + goto fail; + } + + /* step back to character in front of the first element */ + input_buffer->offset--; + /* loop through the comma separated array elements */ + do + { + /* allocate next item */ + cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); + if (new_item == NULL) + { + goto fail; /* allocation failure */ + } + + /* attach next item to list */ + if (head == NULL) + { + /* start the linked list */ + current_item = head = new_item; + } + else + { + /* add to the end and advance */ + current_item->next = new_item; + new_item->prev = current_item; + current_item = new_item; + } + + /* parse the name of the child */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_string(current_item, input_buffer)) + { + goto fail; /* failed to parse name */ + } + buffer_skip_whitespace(input_buffer); + + /* swap valuestring and string, because we parsed the name */ + current_item->string = current_item->valuestring; + current_item->valuestring = NULL; + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != ':')) + { + goto fail; /* invalid object */ + } + + /* parse the value */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_value(current_item, input_buffer)) + { + goto fail; /* failed to parse value */ + } + buffer_skip_whitespace(input_buffer); + } + while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ',')); + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '}')) + { + goto fail; /* expected end of object */ + } + +success: + input_buffer->depth--; + + if (head != NULL) { + head->prev = current_item; + } + + item->type = cJSON_Object; + item->child = head; + + input_buffer->offset++; + return true; + +fail: + if (head != NULL) + { + cJSON_Delete(head); + } + + return false; +} + +/* Render an object to text. */ +static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + size_t length = 0; + cJSON *current_item = item->child; + + if (output_buffer == NULL) + { + return false; + } + + /* Compose the output: */ + length = (size_t) (output_buffer->format ? 2 : 1); /* fmt: {\n */ + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + + *output_pointer++ = '{'; + output_buffer->depth++; + if (output_buffer->format) + { + *output_pointer++ = '\n'; + } + output_buffer->offset += length; + + while (current_item) + { + if (output_buffer->format) + { + size_t i; + output_pointer = ensure(output_buffer, output_buffer->depth); + if (output_pointer == NULL) + { + return false; + } + for (i = 0; i < output_buffer->depth; i++) + { + *output_pointer++ = '\t'; + } + output_buffer->offset += output_buffer->depth; + } + + /* print key */ + if (!print_string_ptr((unsigned char*)current_item->string, output_buffer)) + { + return false; + } + update_offset(output_buffer); + + length = (size_t) (output_buffer->format ? 2 : 1); + output_pointer = ensure(output_buffer, length); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ':'; + if (output_buffer->format) + { + *output_pointer++ = '\t'; + } + output_buffer->offset += length; + + /* print value */ + if (!print_value(current_item, output_buffer)) + { + return false; + } + update_offset(output_buffer); + + /* print comma if not last */ + length = ((size_t)(output_buffer->format ? 1 : 0) + (size_t)(current_item->next ? 1 : 0)); + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + if (current_item->next) + { + *output_pointer++ = ','; + } + + if (output_buffer->format) + { + *output_pointer++ = '\n'; + } + *output_pointer = '\0'; + output_buffer->offset += length; + + current_item = current_item->next; + } + + output_pointer = ensure(output_buffer, output_buffer->format ? (output_buffer->depth + 1) : 2); + if (output_pointer == NULL) + { + return false; + } + if (output_buffer->format) + { + size_t i; + for (i = 0; i < (output_buffer->depth - 1); i++) + { + *output_pointer++ = '\t'; + } + } + *output_pointer++ = '}'; + *output_pointer = '\0'; + output_buffer->depth--; + + return true; +} + +/* Get Array size/item / object item. */ +CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array) +{ + cJSON *child = NULL; + size_t size = 0; + + if (array == NULL) + { + return 0; + } + + child = array->child; + + while(child != NULL) + { + size++; + child = child->next; + } + + /* FIXME: Can overflow here. Cannot be fixed without breaking the API */ + + return (int)size; +} + +static cJSON* get_array_item(const cJSON *array, size_t index) +{ + cJSON *current_child = NULL; + + if (array == NULL) + { + return NULL; + } + + current_child = array->child; + while ((current_child != NULL) && (index > 0)) + { + index--; + current_child = current_child->next; + } + + return current_child; +} + +CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index) +{ + if (index < 0) + { + return NULL; + } + + return get_array_item(array, (size_t)index); +} + +static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive) +{ + cJSON *current_element = NULL; + + if ((object == NULL) || (name == NULL)) + { + return NULL; + } + + current_element = object->child; + if (case_sensitive) + { + while ((current_element != NULL) && (current_element->string != NULL) && (strcmp(name, current_element->string) != 0)) + { + current_element = current_element->next; + } + } + else + { + while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0)) + { + current_element = current_element->next; + } + } + + if ((current_element == NULL) || (current_element->string == NULL)) { + return NULL; + } + + return current_element; +} + +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string) +{ + return get_object_item(object, string, false); +} + +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string) +{ + return get_object_item(object, string, true); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string) +{ + return cJSON_GetObjectItem(object, string) ? 1 : 0; +} + +/* Utility for array list handling. */ +static void suffix_object(cJSON *prev, cJSON *item) +{ + prev->next = item; + item->prev = prev; +} + +/* Utility for handling references. */ +static cJSON *create_reference(const cJSON *item, const internal_hooks * const hooks) +{ + cJSON *reference = NULL; + if (item == NULL) + { + return NULL; + } + + reference = cJSON_New_Item(hooks); + if (reference == NULL) + { + return NULL; + } + + memcpy(reference, item, sizeof(cJSON)); + reference->string = NULL; + reference->type |= cJSON_IsReference; + reference->next = reference->prev = NULL; + return reference; +} + +static cJSON_bool add_item_to_array(cJSON *array, cJSON *item) +{ + cJSON *child = NULL; + + if ((item == NULL) || (array == NULL) || (array == item)) + { + return false; + } + + child = array->child; + /* + * To find the last item in array quickly, we use prev in array + */ + if (child == NULL) + { + /* list is empty, start new one */ + array->child = item; + item->prev = item; + item->next = NULL; + } + else + { + /* append to the end */ + if (child->prev) + { + suffix_object(child->prev, item); + array->child->prev = item; + } + } + + return true; +} + +/* Add item to array/object. */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item) +{ + return add_item_to_array(array, item); +} + +#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) + #pragma GCC diagnostic push +#endif +#ifdef __GNUC__ +#pragma GCC diagnostic ignored "-Wcast-qual" +#endif +/* helper function to cast away const */ +static void* cast_away_const(const void* string) +{ + return (void*)string; +} +#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) + #pragma GCC diagnostic pop +#endif + + +static cJSON_bool add_item_to_object(cJSON * const object, const char * const string, cJSON * const item, const internal_hooks * const hooks, const cJSON_bool constant_key) +{ + char *new_key = NULL; + int new_type = cJSON_Invalid; + + if ((object == NULL) || (string == NULL) || (item == NULL) || (object == item)) + { + return false; + } + + if (constant_key) + { + new_key = (char*)cast_away_const(string); + new_type = item->type | cJSON_StringIsConst; + } + else + { + new_key = (char*)cJSON_strdup((const unsigned char*)string, hooks); + if (new_key == NULL) + { + return false; + } + + new_type = item->type & ~cJSON_StringIsConst; + } + + if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) + { + hooks->deallocate(item->string); + } + + item->string = new_key; + item->type = new_type; + + return add_item_to_array(object, item); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item) +{ + return add_item_to_object(object, string, item, &global_hooks, false); +} + +/* Add an item to an object with constant string as key */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item) +{ + return add_item_to_object(object, string, item, &global_hooks, true); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) +{ + if (array == NULL) + { + return false; + } + + return add_item_to_array(array, create_reference(item, &global_hooks)); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item) +{ + if ((object == NULL) || (string == NULL)) + { + return false; + } + + return add_item_to_object(object, string, create_reference(item, &global_hooks), &global_hooks, false); +} + +CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name) +{ + cJSON *null = cJSON_CreateNull(); + if (add_item_to_object(object, name, null, &global_hooks, false)) + { + return null; + } + + cJSON_Delete(null); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name) +{ + cJSON *true_item = cJSON_CreateTrue(); + if (add_item_to_object(object, name, true_item, &global_hooks, false)) + { + return true_item; + } + + cJSON_Delete(true_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name) +{ + cJSON *false_item = cJSON_CreateFalse(); + if (add_item_to_object(object, name, false_item, &global_hooks, false)) + { + return false_item; + } + + cJSON_Delete(false_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean) +{ + cJSON *bool_item = cJSON_CreateBool(boolean); + if (add_item_to_object(object, name, bool_item, &global_hooks, false)) + { + return bool_item; + } + + cJSON_Delete(bool_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number) +{ + cJSON *number_item = cJSON_CreateNumber(number); + if (add_item_to_object(object, name, number_item, &global_hooks, false)) + { + return number_item; + } + + cJSON_Delete(number_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string) +{ + cJSON *string_item = cJSON_CreateString(string); + if (add_item_to_object(object, name, string_item, &global_hooks, false)) + { + return string_item; + } + + cJSON_Delete(string_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw) +{ + cJSON *raw_item = cJSON_CreateRaw(raw); + if (add_item_to_object(object, name, raw_item, &global_hooks, false)) + { + return raw_item; + } + + cJSON_Delete(raw_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name) +{ + cJSON *object_item = cJSON_CreateObject(); + if (add_item_to_object(object, name, object_item, &global_hooks, false)) + { + return object_item; + } + + cJSON_Delete(object_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name) +{ + cJSON *array = cJSON_CreateArray(); + if (add_item_to_object(object, name, array, &global_hooks, false)) + { + return array; + } + + cJSON_Delete(array); + return NULL; +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item) +{ + if ((parent == NULL) || (item == NULL)) + { + return NULL; + } + + if (item != parent->child) + { + /* not the first element */ + item->prev->next = item->next; + } + if (item->next != NULL) + { + /* not the last element */ + item->next->prev = item->prev; + } + + if (item == parent->child) + { + /* first element */ + parent->child = item->next; + } + else if (item->next == NULL) + { + /* last element */ + parent->child->prev = item->prev; + } + + /* make sure the detached item doesn't point anywhere anymore */ + item->prev = NULL; + item->next = NULL; + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which) +{ + if (which < 0) + { + return NULL; + } + + return cJSON_DetachItemViaPointer(array, get_array_item(array, (size_t)which)); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which) +{ + cJSON_Delete(cJSON_DetachItemFromArray(array, which)); +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string) +{ + cJSON *to_detach = cJSON_GetObjectItem(object, string); + + return cJSON_DetachItemViaPointer(object, to_detach); +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string) +{ + cJSON *to_detach = cJSON_GetObjectItemCaseSensitive(object, string); + + return cJSON_DetachItemViaPointer(object, to_detach); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string) +{ + cJSON_Delete(cJSON_DetachItemFromObject(object, string)); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string) +{ + cJSON_Delete(cJSON_DetachItemFromObjectCaseSensitive(object, string)); +} + +/* Replace array/object items with new ones. */ +CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem) +{ + cJSON *after_inserted = NULL; + + if (which < 0 || newitem == NULL) + { + return false; + } + + after_inserted = get_array_item(array, (size_t)which); + if (after_inserted == NULL) + { + return add_item_to_array(array, newitem); + } + + if (after_inserted != array->child && newitem->prev == NULL) { + /* return false if after_inserted is a corrupted array item */ + return false; + } + + newitem->next = after_inserted; + newitem->prev = after_inserted->prev; + after_inserted->prev = newitem; + if (after_inserted == array->child) + { + array->child = newitem; + } + else + { + newitem->prev->next = newitem; + } + return true; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement) +{ + if ((parent == NULL) || (parent->child == NULL) || (replacement == NULL) || (item == NULL)) + { + return false; + } + + if (replacement == item) + { + return true; + } + + replacement->next = item->next; + replacement->prev = item->prev; + + if (replacement->next != NULL) + { + replacement->next->prev = replacement; + } + if (parent->child == item) + { + if (parent->child->prev == parent->child) + { + replacement->prev = replacement; + } + parent->child = replacement; + } + else + { /* + * To find the last item in array quickly, we use prev in array. + * We can't modify the last item's next pointer where this item was the parent's child + */ + if (replacement->prev != NULL) + { + replacement->prev->next = replacement; + } + if (replacement->next == NULL) + { + parent->child->prev = replacement; + } + } + + item->next = NULL; + item->prev = NULL; + cJSON_Delete(item); + + return true; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem) +{ + if (which < 0) + { + return false; + } + + return cJSON_ReplaceItemViaPointer(array, get_array_item(array, (size_t)which), newitem); +} + +static cJSON_bool replace_item_in_object(cJSON *object, const char *string, cJSON *replacement, cJSON_bool case_sensitive) +{ + if ((replacement == NULL) || (string == NULL)) + { + return false; + } + + /* replace the name in the replacement */ + if (!(replacement->type & cJSON_StringIsConst) && (replacement->string != NULL)) + { + cJSON_free(replacement->string); + } + replacement->string = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks); + if (replacement->string == NULL) + { + return false; + } + + replacement->type &= ~cJSON_StringIsConst; + + return cJSON_ReplaceItemViaPointer(object, get_object_item(object, string, case_sensitive), replacement); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem) +{ + return replace_item_in_object(object, string, newitem, false); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, cJSON *newitem) +{ + return replace_item_in_object(object, string, newitem, true); +} + +/* Create basic types: */ +CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_NULL; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_True; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_False; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = boolean ? cJSON_True : cJSON_False; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_Number; + item->valuedouble = num; + + /* use saturation in case of overflow */ + if (num >= INT_MAX) + { + item->valueint = INT_MAX; + } + else if (num <= (double)INT_MIN) + { + item->valueint = INT_MIN; + } + else + { + item->valueint = (int)num; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_String; + item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks); + if(!item->valuestring) + { + cJSON_Delete(item); + return NULL; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) + { + item->type = cJSON_String | cJSON_IsReference; + item->valuestring = (char*)cast_away_const(string); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) { + item->type = cJSON_Object | cJSON_IsReference; + item->child = (cJSON*)cast_away_const(child); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child) { + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) { + item->type = cJSON_Array | cJSON_IsReference; + item->child = (cJSON*)cast_away_const(child); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_Raw; + item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks); + if(!item->valuestring) + { + cJSON_Delete(item); + return NULL; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type=cJSON_Array; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item) + { + item->type = cJSON_Object; + } + + return item; +} + +/* Create Arrays: */ +CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for(i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber(numbers[i]); + if (!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for(i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber((double)numbers[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for(i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber(numbers[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (strings == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for (i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateString(strings[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p,n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +/* Duplication */ +CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse) +{ + cJSON *newitem = NULL; + cJSON *child = NULL; + cJSON *next = NULL; + cJSON *newchild = NULL; + + /* Bail on bad ptr */ + if (!item) + { + goto fail; + } + /* Create new item */ + newitem = cJSON_New_Item(&global_hooks); + if (!newitem) + { + goto fail; + } + /* Copy over all vars */ + newitem->type = item->type & (~cJSON_IsReference); + newitem->valueint = item->valueint; + newitem->valuedouble = item->valuedouble; + if (item->valuestring) + { + newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks); + if (!newitem->valuestring) + { + goto fail; + } + } + if (item->string) + { + newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks); + if (!newitem->string) + { + goto fail; + } + } + /* If non-recursive, then we're done! */ + if (!recurse) + { + return newitem; + } + /* Walk the ->next chain for the child. */ + child = item->child; + while (child != NULL) + { + newchild = cJSON_Duplicate(child, true); /* Duplicate (with recurse) each item in the ->next chain */ + if (!newchild) + { + goto fail; + } + if (next != NULL) + { + /* If newitem->child already set, then crosswire ->prev and ->next and move on */ + next->next = newchild; + newchild->prev = next; + next = newchild; + } + else + { + /* Set newitem->child and move to it */ + newitem->child = newchild; + next = newchild; + } + child = child->next; + } + if (newitem && newitem->child) + { + newitem->child->prev = newchild; + } + + return newitem; + +fail: + if (newitem != NULL) + { + cJSON_Delete(newitem); + } + + return NULL; +} + +static void skip_oneline_comment(char **input) +{ + *input += static_strlen("//"); + + for (; (*input)[0] != '\0'; ++(*input)) + { + if ((*input)[0] == '\n') { + *input += static_strlen("\n"); + return; + } + } +} + +static void skip_multiline_comment(char **input) +{ + *input += static_strlen("/*"); + + for (; (*input)[0] != '\0'; ++(*input)) + { + if (((*input)[0] == '*') && ((*input)[1] == '/')) + { + *input += static_strlen("*/"); + return; + } + } +} + +static void minify_string(char **input, char **output) { + (*output)[0] = (*input)[0]; + *input += static_strlen("\""); + *output += static_strlen("\""); + + + for (; (*input)[0] != '\0'; (void)++(*input), ++(*output)) { + (*output)[0] = (*input)[0]; + + if ((*input)[0] == '\"') { + (*output)[0] = '\"'; + *input += static_strlen("\""); + *output += static_strlen("\""); + return; + } else if (((*input)[0] == '\\') && ((*input)[1] == '\"')) { + (*output)[1] = (*input)[1]; + *input += static_strlen("\""); + *output += static_strlen("\""); + } + } +} + +CJSON_PUBLIC(void) cJSON_Minify(char *json) +{ + char *into = json; + + if (json == NULL) + { + return; + } + + while (json[0] != '\0') + { + switch (json[0]) + { + case ' ': + case '\t': + case '\r': + case '\n': + json++; + break; + + case '/': + if (json[1] == '/') + { + skip_oneline_comment(&json); + } + else if (json[1] == '*') + { + skip_multiline_comment(&json); + } else { + json++; + } + break; + + case '\"': + minify_string(&json, (char**)&into); + break; + + default: + into[0] = json[0]; + json++; + into++; + } + } + + /* and null-terminate. */ + *into = '\0'; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Invalid; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_False; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xff) == cJSON_True; +} + + +CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & (cJSON_True | cJSON_False)) != 0; +} +CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_NULL; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Number; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_String; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Array; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Object; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Raw; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive) +{ + if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF))) + { + return false; + } + + /* check if type is valid */ + switch (a->type & 0xFF) + { + case cJSON_False: + case cJSON_True: + case cJSON_NULL: + case cJSON_Number: + case cJSON_String: + case cJSON_Raw: + case cJSON_Array: + case cJSON_Object: + break; + + default: + return false; + } + + /* identical objects are equal */ + if (a == b) + { + return true; + } + + switch (a->type & 0xFF) + { + /* in these cases and equal type is enough */ + case cJSON_False: + case cJSON_True: + case cJSON_NULL: + return true; + + case cJSON_Number: + if (compare_double(a->valuedouble, b->valuedouble)) + { + return true; + } + return false; + + case cJSON_String: + case cJSON_Raw: + if ((a->valuestring == NULL) || (b->valuestring == NULL)) + { + return false; + } + if (strcmp(a->valuestring, b->valuestring) == 0) + { + return true; + } + + return false; + + case cJSON_Array: + { + cJSON *a_element = a->child; + cJSON *b_element = b->child; + + for (; (a_element != NULL) && (b_element != NULL);) + { + if (!cJSON_Compare(a_element, b_element, case_sensitive)) + { + return false; + } + + a_element = a_element->next; + b_element = b_element->next; + } + + /* one of the arrays is longer than the other */ + if (a_element != b_element) { + return false; + } + + return true; + } + + case cJSON_Object: + { + cJSON *a_element = NULL; + cJSON *b_element = NULL; + cJSON_ArrayForEach(a_element, a) + { + /* TODO This has O(n^2) runtime, which is horrible! */ + b_element = get_object_item(b, a_element->string, case_sensitive); + if (b_element == NULL) + { + return false; + } + + if (!cJSON_Compare(a_element, b_element, case_sensitive)) + { + return false; + } + } + + /* doing this twice, once on a and b to prevent true comparison if a subset of b + * TODO: Do this the proper way, this is just a fix for now */ + cJSON_ArrayForEach(b_element, b) + { + a_element = get_object_item(a, b_element->string, case_sensitive); + if (a_element == NULL) + { + return false; + } + + if (!cJSON_Compare(b_element, a_element, case_sensitive)) + { + return false; + } + } + + return true; + } + + default: + return false; + } +} + +CJSON_PUBLIC(void *) cJSON_malloc(size_t size) +{ + return global_hooks.allocate(size); +} + +CJSON_PUBLIC(void) cJSON_free(void *object) +{ + global_hooks.deallocate(object); +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/cpp/cJSON.h" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/cpp/cJSON.h" new file mode 100644 index 00000000..2628d763 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/cpp/cJSON.h" @@ -0,0 +1,300 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#ifndef cJSON__h +#define cJSON__h + +#ifdef __cplusplus +extern "C" +{ +#endif + +#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32)) +#define __WINDOWS__ +#endif + +#ifdef __WINDOWS__ + +/* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention. For windows you have 3 define options: + +CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols +CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default) +CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol + +For *nix builds that support visibility attribute, you can define similar behavior by + +setting default visibility to hidden by adding +-fvisibility=hidden (for gcc) +or +-xldscope=hidden (for sun cc) +to CFLAGS + +then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does + +*/ + +#define CJSON_CDECL __cdecl +#define CJSON_STDCALL __stdcall + +/* export symbols by default, this is necessary for copy pasting the C and header file */ +#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS) +#define CJSON_EXPORT_SYMBOLS +#endif + +#if defined(CJSON_HIDE_SYMBOLS) +#define CJSON_PUBLIC(type) type CJSON_STDCALL +#elif defined(CJSON_EXPORT_SYMBOLS) +#define CJSON_PUBLIC(type) __declspec(dllexport) type CJSON_STDCALL +#elif defined(CJSON_IMPORT_SYMBOLS) +#define CJSON_PUBLIC(type) __declspec(dllimport) type CJSON_STDCALL +#endif +#else /* !__WINDOWS__ */ +#define CJSON_CDECL +#define CJSON_STDCALL + +#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY) +#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type +#else +#define CJSON_PUBLIC(type) type +#endif +#endif + +/* project version */ +#define CJSON_VERSION_MAJOR 1 +#define CJSON_VERSION_MINOR 7 +#define CJSON_VERSION_PATCH 16 + +#include + +/* cJSON Types: */ +#define cJSON_Invalid (0) +#define cJSON_False (1 << 0) +#define cJSON_True (1 << 1) +#define cJSON_NULL (1 << 2) +#define cJSON_Number (1 << 3) +#define cJSON_String (1 << 4) +#define cJSON_Array (1 << 5) +#define cJSON_Object (1 << 6) +#define cJSON_Raw (1 << 7) /* raw json */ + +#define cJSON_IsReference 256 +#define cJSON_StringIsConst 512 + +/* The cJSON structure: */ +typedef struct cJSON +{ + /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */ + struct cJSON *next; + struct cJSON *prev; + /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */ + struct cJSON *child; + + /* The type of the item, as above. */ + int type; + + /* The item's string, if type==cJSON_String and type == cJSON_Raw */ + char *valuestring; + /* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */ + int valueint; + /* The item's number, if type==cJSON_Number */ + double valuedouble; + + /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */ + char *string; +} cJSON; + +typedef struct cJSON_Hooks +{ + /* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */ + void *(CJSON_CDECL *malloc_fn)(size_t sz); + void (CJSON_CDECL *free_fn)(void *ptr); +} cJSON_Hooks; + +typedef int cJSON_bool; + +/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them. + * This is to prevent stack overflows. */ +#ifndef CJSON_NESTING_LIMIT +#define CJSON_NESTING_LIMIT 1000 +#endif + +/* returns the version of cJSON as a string */ +CJSON_PUBLIC(const char*) cJSON_Version(void); + +/* Supply malloc, realloc and free functions to cJSON */ +CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks); + +/* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */ +/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */ +CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value); +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length); +/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */ +/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */ +CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated); +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated); + +/* Render a cJSON entity to text for transfer/storage. */ +CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item); +/* Render a cJSON entity to text for transfer/storage without any formatting. */ +CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item); +/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */ +CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt); +/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */ +/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */ +CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format); +/* Delete a cJSON entity and all subentities. */ +CJSON_PUBLIC(void) cJSON_Delete(cJSON *item); + +/* Returns the number of items in an array (or object). */ +CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array); +/* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */ +CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index); +/* Get item "string" from object. Case insensitive. */ +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string); +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string); +CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string); +/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */ +CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void); + +/* Check item type and return its value */ +CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item); +CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item); + +/* These functions check the type of an item */ +CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item); + +/* These calls create a cJSON item of the appropriate type. */ +CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean); +CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num); +CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string); +/* raw json */ +CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw); +CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void); + +/* Create a string where valuestring references a string so + * it will not be freed by cJSON_Delete */ +CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string); +/* Create an object/array that only references it's elements so + * they will not be freed by cJSON_Delete */ +CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child); +CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child); + +/* These utilities create an Array of count items. + * The parameter count cannot be greater than the number of elements in the number array, otherwise array access will be out of bounds.*/ +CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count); + +/* Append item to the specified array/object. */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item); +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item); +/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object. + * WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before + * writing to `item->string` */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item); +/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item); +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item); + +/* Remove/Detach items from Arrays/Objects. */ +CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which); +CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string); +CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string); +CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string); + +/* Update array items. */ +CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */ +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement); +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem); +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem); +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem); + +/* Duplicate a cJSON item */ +CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse); +/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will + * need to be released. With recurse!=0, it will duplicate any children connected to the item. + * The item->next and ->prev pointers are always zero on return from Duplicate. */ +/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal. + * case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */ +CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive); + +/* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from strings. + * The input pointer json cannot point to a read-only address area, such as a string constant, + * but should point to a readable and writable address area. */ +CJSON_PUBLIC(void) cJSON_Minify(char *json); + +/* Helper functions for creating and adding items to an object at the same time. + * They return the added item or NULL on failure. */ +CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean); +CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number); +CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string); +CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw); +CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name); + +/* When assigning an integer value, it needs to be propagated to valuedouble too. */ +#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number)) +/* helper for the cJSON_SetNumberValue macro */ +CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number); +#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number)) +/* Change the valuestring of a cJSON_String object, only takes effect when type of object is cJSON_String */ +CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring); + +/* If the object is not a boolean type this does nothing and returns cJSON_Invalid else it returns the new type*/ +#define cJSON_SetBoolValue(object, boolValue) ( \ + (object != NULL && ((object)->type & (cJSON_False|cJSON_True))) ? \ + (object)->type=((object)->type &(~(cJSON_False|cJSON_True)))|((boolValue)?cJSON_True:cJSON_False) : \ + cJSON_Invalid\ +) + +/* Macro for iterating over an array or object */ +#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next) + +/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */ +CJSON_PUBLIC(void *) cJSON_malloc(size_t size); +CJSON_PUBLIC(void) cJSON_free(void *object); + +#ifdef __cplusplus +} +#endif + +#endif diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/cpp/native-lib.cpp" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/cpp/native-lib.cpp" new file mode 100644 index 00000000..9ca505d4 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/cpp/native-lib.cpp" @@ -0,0 +1,460 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +#include "kernel_module_kit_umbrella.h" + +#include "command.h" +#include "exec_process.h" +#include "test.h" +#include "urlEncodeUtils.h" +#include "cJSON.h" + +using namespace std; + +static string jstringToStr(JNIEnv* env, jstring jstring1) { + const char *str1 = env->GetStringUTFChars(jstring1, 0); + string s = str1; + env->ReleaseStringUTFChars(jstring1, str1); + return s; +} + +static string urlEncodeToStr(string str) { + size_t len = str.length(); + size_t max_encoded_len = 3 * len + 1; + vector buf(max_encoded_len); + url_encode(const_cast(str.c_str()), (char*)buf.data()); + return (char*)buf.data(); +} + +static cJSON * suAuthToJsonObj(skroot_env::su_auth_item & auth) { + cJSON *item = cJSON_CreateObject(); + string encodeAppName = urlEncodeToStr(auth.app_package_name); + cJSON_AddStringToObject(item, "app_package_name", encodeAppName.c_str()); + return item; +} + +static cJSON * moduleDescToJsonObj(skroot_env::module_desc & desc) { + cJSON *item = cJSON_CreateObject(); + string encodeName = urlEncodeToStr(desc.name); + string encodeVer = urlEncodeToStr(desc.version); + string encodeDesc = urlEncodeToStr(desc.desc); + string encodeAuthor = urlEncodeToStr(desc.author); + string encodeUuid = urlEncodeToStr(desc.uuid); + string encodeUpdateJson = urlEncodeToStr(desc.update_json); + stringstream ss; + ss << desc.min_sdk_ver.major << "." << desc.min_sdk_ver.minor << "." << desc.min_sdk_ver.patch; + string encodeMiniSDK = urlEncodeToStr(ss.str().c_str()); + cJSON_AddStringToObject(item, "name", encodeName.c_str()); + cJSON_AddStringToObject(item, "ver", encodeVer.c_str()); + cJSON_AddStringToObject(item, "desc", encodeDesc.c_str()); + cJSON_AddStringToObject(item, "author", encodeAuthor.c_str()); + cJSON_AddStringToObject(item, "uuid", encodeUuid.c_str()); + cJSON_AddStringToObject(item, "update_json", encodeUpdateJson.c_str()); + cJSON_AddBoolToObject(item, "web_ui", desc.web_ui); + cJSON_AddStringToObject(item, "min_sdk_ver", encodeMiniSDK.c_str()); + return item; +} + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_installSkrootEnv( + JNIEnv* env, + jclass /* this */, + jstring rootKey) { + string strRootKey = jstringToStr(env, rootKey); + + KModErr err = skroot_env::install_skroot_environment(strRootKey.c_str()); + stringstream sstr; + sstr << "install_skroot_environment: " << to_string(err).c_str(); + if(is_ok(err)) sstr << ",将在重启后生效"; + return env->NewStringUTF(sstr.str().c_str()); +} + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_uninstallSkrootEnv( + JNIEnv* env, + jclass /* this */, + jstring rootKey) { + string strRootKey = jstringToStr(env, rootKey); + + KModErr err = skroot_env::uninstall_skroot_environment(strRootKey.c_str()); + stringstream sstr; + sstr << "uninstall_skroot_environment: " << to_string(err).c_str(); + if(is_ok(err)) sstr << ",将在重启后生效"; + return env->NewStringUTF(sstr.str().c_str()); +} + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_getSkrootEnvState( + JNIEnv* env, + jclass /* this */, + jstring rootKey) { + string strRootKey = jstringToStr(env, rootKey); + + using SkrootEnvState = skroot_env::SkrootEnvState; + static std::map m = { + {SkrootEnvState::NotInstalled, "NotInstalled"}, + {SkrootEnvState::Running, "Running"}, + {SkrootEnvState::Fault, "Fault"}, + }; + SkrootEnvState state = skroot_env::get_skroot_environment_state(strRootKey.c_str()); + return env->NewStringUTF(m[state]); +} + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_getInstalledSkrootEnvVersion( + JNIEnv* env, + jclass /* this */, + jstring rootKey) { + string strRootKey = jstringToStr(env, rootKey); + + skroot_env::SkrootSdkVersion ver; + KModErr err = skroot_env::get_installed_skroot_environment_version(strRootKey.c_str(), ver); + if(is_failed(err)) return env->NewStringUTF(to_string(err).c_str()); + + stringstream sstr; + sstr << ver.major << "." << ver.minor << "." << ver.patch; + return env->NewStringUTF(sstr.str().c_str()); +} + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_getSdkVersion( + JNIEnv* env, + jclass /* this */) { + skroot_env::SkrootSdkVersion ver = skroot_env::get_sdk_version(); + stringstream sstr; + sstr << ver.major << "." << ver.minor << "." << ver.patch; + return env->NewStringUTF(sstr.str().c_str()); +} + + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_testRoot( + JNIEnv* env, + jclass /* this */, + jstring rootKey) { + string strRootKey = jstringToStr(env, rootKey); + + string result = get_root_test_report(strRootKey.c_str()); + return env->NewStringUTF(result.c_str()); +} + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_runRootCmd( + JNIEnv* env, + jclass /* this */, + jstring rootKey, + jstring cmd) { + string strRootKey = jstringToStr(env, rootKey); + string strCmd = jstringToStr(env, cmd); + + string result; + bool success = run_root_cmd(strRootKey.c_str(), strCmd.c_str(), result); + stringstream sstr; + sstr << "run_root_cmd err: " << (success ? "OK" : "FAILED") << ", result:" << result; + return env->NewStringUTF(sstr.str().c_str()); +} + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_rootExecProcessCmd( + JNIEnv* env, + jclass /* this */, + jstring rootKey, + jstring cmd) { + string strRootKey = jstringToStr(env, rootKey); + string strCmd = jstringToStr(env, cmd); + + bool success = root_exec_process(strRootKey.c_str(), strCmd.c_str()); + stringstream sstr; + sstr << "root_exec_process err: " << (success ? "OK" : "FAILED"); + return env->NewStringUTF(sstr.str().c_str()); +} + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_addSuAuth( + JNIEnv* env, + jclass /* this */, + jstring rootKey, + jstring appPackageName) { + string strRootKey = jstringToStr(env, rootKey); + string strAppPackageName = jstringToStr(env, appPackageName); + + KModErr err = skroot_env::add_su_auth_list(strRootKey.c_str(), strAppPackageName.c_str()); + stringstream sstr; + sstr << "add_su_auth_list: " << to_string(err).c_str(); + return env->NewStringUTF(sstr.str().c_str()); +} + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_removeSuAuth( + JNIEnv* env, + jclass /* this */, + jstring rootKey, + jstring modUuid) { + string strRootKey = jstringToStr(env, rootKey); + string strModUuid = jstringToStr(env, modUuid); + + KModErr err = skroot_env::remove_su_auth_list(strRootKey.c_str(), strModUuid.c_str()); + stringstream sstr; + sstr << "remove_su_auth_list: " << to_string(err).c_str(); + return env->NewStringUTF(sstr.str().c_str()); +} + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_getSuAuthList( + JNIEnv* env, + jclass /* this */, + jstring rootKey) { + string strRootKey = jstringToStr(env, rootKey); + + stringstream ss; + vector pkgs; + KModErr err = skroot_env::get_su_auth_list(strRootKey.c_str(), pkgs); + if(is_failed(err)) { + ss << "get_su_auth_list: " << to_string(err).c_str(); + return env->NewStringUTF(ss.str().c_str()); + } + + cJSON *root = cJSON_CreateArray(); + for (auto & iter : pkgs) { + cJSON *item = suAuthToJsonObj(iter); + cJSON_AddItemToArray(root, item); + } + ss << cJSON_Print(root); + cJSON_Delete(root); + return env->NewStringUTF(ss.str().c_str()); +} + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_clearSuAuthList( + JNIEnv* env, + jclass /* this */, + jstring rootKey) { + string strRootKey = jstringToStr(env, rootKey); + + KModErr err = skroot_env::clear_su_auth_list(strRootKey.c_str()); + stringstream sstr; + sstr << "clear_su_auth_list: " << to_string(err).c_str(); + return env->NewStringUTF(sstr.str().c_str()); +} + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_installSkrootModule( + JNIEnv* env, + jclass /* this */, + jstring rootKey, + jstring zipFilePath) { + string strRootKey = jstringToStr(env, rootKey); + string strZipFilePath = jstringToStr(env, zipFilePath); + + string reason; + KModErr err = skroot_env::install_module(strRootKey.c_str(), strZipFilePath.c_str(), reason); + stringstream sstr; + if(is_ok(err)) sstr << "install_module: " << to_string(err).c_str(); + else sstr << "install_module: " << to_string(err).c_str() << ", reason: " << reason.c_str(); + return env->NewStringUTF(sstr.str().c_str()); +} + + + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_uninstallSkrootModule( + JNIEnv* env, + jclass /* this */, + jstring rootKey, + jstring modUuid) { + string strRootKey = jstringToStr(env, rootKey); + string strModUuid = jstringToStr(env, modUuid); + + KModErr err = skroot_env::uninstall_module(strRootKey.c_str(), strModUuid.c_str()); + stringstream sstr; + sstr << "uninstall_module: " << to_string(err).c_str(); + return env->NewStringUTF(sstr.str().c_str()); +} + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_getSkrootModuleList( + JNIEnv* env, + jclass /* this */, + jstring rootKey, + jboolean runningOnly, + jboolean abnormalOnly) { + string strRootKey = jstringToStr(env, rootKey); + + stringstream ss; + vector list; + KModErr err = skroot_env::get_all_modules_list(strRootKey.c_str(), list, + runningOnly ? skroot_env::ModuleListMode::RunningOnly : + abnormalOnly ? skroot_env::ModuleListMode::AbnormalOnly : + skroot_env::ModuleListMode::All); + if(is_failed(err)) { + ss << "get_all_modules_list: " << to_string(err).c_str(); + return env->NewStringUTF(ss.str().c_str()); + } + + cJSON *root = cJSON_CreateArray(); + for (auto & iter : list) { + cJSON *item = moduleDescToJsonObj(iter); + cJSON_AddItemToArray(root, item); + } + ss << cJSON_Print(root); + cJSON_Delete(root); + return env->NewStringUTF(ss.str().c_str()); +} + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_parseSkrootModuleDesc( + JNIEnv* env, + jclass /* this */, + jstring rootKey, + jstring zipFilePath) { + string strRootKey = jstringToStr(env, rootKey); + string strZipFilePath = jstringToStr(env, zipFilePath); + + stringstream ss; + skroot_env::module_desc desc; + KModErr err = skroot_env::parse_module_desc_from_zip_file(strRootKey.c_str(), strZipFilePath.c_str(), desc); + if(is_ok(err)) { + cJSON *root = moduleDescToJsonObj(desc); + ss << cJSON_Print(root); + cJSON_Delete(root); + } else { + ss << "parse_module_desc_from_zip_file: " << to_string(err).c_str(); + } + return env->NewStringUTF(ss.str().c_str()); + +} + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_openSkrootModuleWebUI( + JNIEnv* env, + jclass /* this */, + jstring rootKey, + jstring modUuid) { + string strRootKey = jstringToStr(env, rootKey); + string strModUuid = jstringToStr(env, modUuid); + + int port = 0; + KModErr err = skroot_env::features::web_ui::start_module_web_ui_server_async(strRootKey.c_str(), strModUuid.c_str(), port); + stringstream sstr; + sstr << "start_module_web_ui_server_async: " << to_string(err).c_str() << ", port:" << port; + return env->NewStringUTF(sstr.str().c_str()); +} + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_setBootFailProtectEnabled( + JNIEnv* env, + jclass /* this */, + jstring rootKey, + jboolean enable) { + string strRootKey = jstringToStr(env, rootKey); + + KModErr err = skroot_env::set_boot_fail_protect_enabled(strRootKey.c_str(), enable); + + stringstream sstr; + sstr << "set_boot_fail_protect_enabled: " << to_string(err).c_str(); + return env->NewStringUTF(sstr.str().c_str()); +} + +extern "C" JNIEXPORT jboolean JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_isBootFailProtectEnabled( + JNIEnv* env, + jclass /* this */, + jstring rootKey) { + string strRootKey = jstringToStr(env, rootKey); + return skroot_env::is_boot_fail_protect_enabled(strRootKey.c_str()) ? JNI_TRUE : JNI_FALSE; +} + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_testSkrootBasics( + JNIEnv* env, + jclass /* this */, + jstring rootKey, + jstring item) { + string strRootKey = jstringToStr(env, rootKey); + string strItem = jstringToStr(env, item); + + skroot_env::BasicItem basicItem; + if(strItem == "Channel") basicItem = skroot_env::BasicItem::Channel; + else if(strItem == "KernelBase") basicItem = skroot_env::BasicItem::KernelBase; + else if(strItem == "WriteTest") basicItem = skroot_env::BasicItem::WriteTest; + else if(strItem == "ReadTrampoline") basicItem = skroot_env::BasicItem::ReadTrampoline; + else if(strItem == "WriteTrampoline") basicItem = skroot_env::BasicItem::WriteTrampoline; + else return env->NewStringUTF(strItem.c_str()); + + stringstream sstr; + string info; + KModErr err = skroot_env::test_skroot_basics(strRootKey.c_str(), basicItem, info); + sstr << info.c_str() << "\n"; + sstr << "Test " << strItem.c_str() <<": " << to_string(err).c_str(); + return env->NewStringUTF(sstr.str().c_str()); +} + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_testSkrootDefaultModule( + JNIEnv* env, + jclass /* this */, + jstring rootKey, + jstring name) { + string strRootKey = jstringToStr(env, rootKey); + string strName = jstringToStr(env, name); + + skroot_env::DeafultModuleName defName; + if(strName == "RootBridgePrint") defName = skroot_env::DeafultModuleName::RootBridgePrint; + else if(strName == "RootBridgeExec") defName = skroot_env::DeafultModuleName::RootBridgeExec; + else if(strName == "SuRedirectPrint") defName = skroot_env::DeafultModuleName::SuRedirectPrint; + else if(strName == "SuRedirectExec") defName = skroot_env::DeafultModuleName::SuRedirectExec; + else return env->NewStringUTF(strName.c_str()); + + stringstream sstr; + string info; + KModErr err = skroot_env::test_skroot_deafult_module(strRootKey.c_str(), defName, info); + sstr << info.c_str() << "\n"; + sstr << "Test " << strName.c_str() <<": " << to_string(err).c_str(); + return env->NewStringUTF(sstr.str().c_str()); +} + + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_setSkrootLogEnabled( + JNIEnv* env, + jclass /* this */, + jstring rootKey, + jboolean enable) { + string strRootKey = jstringToStr(env, rootKey); + + KModErr err = skroot_env::set_skroot_log_enabled(strRootKey.c_str(), enable); + + stringstream sstr; + sstr << "set_skroot_log_enabled: " << to_string(err).c_str(); + return env->NewStringUTF(sstr.str().c_str()); +} + +extern "C" JNIEXPORT jboolean JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_isSkrootLogEnabled( + JNIEnv* env, + jclass /* this */, + jstring rootKey) { + string strRootKey = jstringToStr(env, rootKey); + return skroot_env::is_skroot_log_enabled(strRootKey.c_str()) ? JNI_TRUE : JNI_FALSE; +} + +extern "C" JNIEXPORT jstring JNICALL +Java_com_linux_permissionmanager_bridge_NativeBridge_readSkrootLog( + JNIEnv* env, + jclass /* this */, + jstring rootKey) { + string strRootKey = jstringToStr(env, rootKey); + + string log; + KModErr err = skroot_env::read_skroot_log(strRootKey.c_str(), log); + if(is_failed(err)) log = to_string(err); + return env->NewStringUTF(log.c_str()); +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/cpp/urlEncodeUtils.h" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/cpp/urlEncodeUtils.h" new file mode 100644 index 00000000..0d1482f7 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/cpp/urlEncodeUtils.h" @@ -0,0 +1,74 @@ +#ifndef URL_ENCODE_UTILS_H_ +#define URL_ENCODE_UTILS_H_ +#include +#include + +static inline char to_hex(char code) { + static char hex[] = "0123456789ABCDEF"; + return hex[code & 15]; +} +static inline char from_hex(char ch) { + return isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10; +} + +/* +//使用例子 +int main() { + char str[] = "你好,世界"; + char encoded_str[256]; + url_encode(str, encoded_str); + printf("Encoded URL: %s\n", encoded_str); + return 0; +} +*/ +static void url_encode(char *str, char *encoded_str) { + char *pstr = str, *buf = encoded_str; + while (*pstr) { + unsigned char c = *pstr; + if (c <= 0x7F) { // ASCII + if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') { + *buf++ = c; + } else if (c == ' ') { + *buf++ = '+'; + } else { + *buf++ = '%', *buf++ = to_hex(c >> 4), *buf++ = to_hex(c & 15); + } + } else { // Non-ASCII + while (c) { + *buf++ = '%', *buf++ = to_hex(c >> 4), *buf++ = to_hex(c & 15); + c = *(++pstr); + } + continue; + } + pstr++; + } + *buf = '\0'; +} +/* +//使用例子 +int main() { + char url[] = "%E4%BD%A0%E5%A5%BD%EF%BC%8C%E4%B8%96%E7%95%8C"; // "你好,世界"的URL编码 + char decoded_str[256]; + url_decode(url, decoded_str); + printf("Decoded URL: %s\n", decoded_str); + return 0; +} +*/ +static void url_decode(char *str, char *decoded_str) { + char *pstr = str, *buf = decoded_str; + while (*pstr) { + if (*pstr == '%') { + if (pstr[1] && pstr[2]) { + *buf++ = from_hex(pstr[1]) << 4 | from_hex(pstr[2]); + pstr += 2; + } + } else if (*pstr == '+') { + *buf++ = ' '; + } else { + *buf++ = *pstr; + } + pstr++; + } + *buf = '\0'; +} +#endif \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/ic_launcher-playstore.png" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/ic_launcher-playstore.png" new file mode 100644 index 00000000..58a6a725 Binary files /dev/null and "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/ic_launcher-playstore.png" differ diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/ActivityResultId.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/ActivityResultId.java" new file mode 100644 index 00000000..5b6cdd59 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/ActivityResultId.java" @@ -0,0 +1,5 @@ +package com.linux.permissionmanager; + +public class ActivityResultId { + public static final int REQUEST_CODE_CHOOSE_FILE= 1001; +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/AppSettings.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/AppSettings.java" new file mode 100644 index 00000000..c065f5e7 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/AppSettings.java" @@ -0,0 +1,69 @@ +package com.linux.permissionmanager; + +import android.content.Context; +import android.content.SharedPreferences; + +import java.util.Collections; +import java.util.Set; + +public class AppSettings { + private static SharedPreferences preferences; + + public static void init(Context context) { + if (preferences == null) { + preferences = context.getSharedPreferences("AppSettings", Context.MODE_PRIVATE); + } + } + + public static void setBoolean(String key, boolean value) { + preferences.edit().putBoolean(key, value).apply(); + } + + public static boolean getBoolean(String key, boolean defaultValue) { + try { + return preferences.getBoolean(key, defaultValue); + } catch (Exception e) { + e.printStackTrace(); + } + return defaultValue; + } + + public static void setString(String key, String value) { + preferences.edit().putString(key, value).apply(); + } + + public static String getString(String key, String defaultValue) { + try { + return preferences.getString(key, defaultValue); + } catch (Exception e) { + e.printStackTrace(); + } + return defaultValue; + } + + public static void setInt(String key, int value) { + preferences.edit().putInt(key, value).apply(); + } + + public static int getInt(String key, int defaultValue) { + try { + return preferences.getInt(key, defaultValue); + } catch (Exception e) { + e.printStackTrace(); + } + return defaultValue; + } + + public static void setStringSet(String key, Set value) { + preferences.edit().putStringSet(key, value).apply(); + } + + public static Set getStringSet(String key, Set defaultValue) { + try { + return preferences.getStringSet(key, defaultValue); + } catch (Exception e) { + e.printStackTrace(); + } + return defaultValue != null ? defaultValue : Collections.emptySet(); + } +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/MainActivity.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/MainActivity.java" new file mode 100644 index 00000000..48d01c08 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/MainActivity.java" @@ -0,0 +1,142 @@ +package com.linux.permissionmanager; + +import android.content.Intent; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AppCompatActivity; +import androidx.fragment.app.Fragment; + +import com.google.android.material.tabs.TabLayout; +import com.linux.permissionmanager.fragment.SuAuthFragment; +import com.linux.permissionmanager.fragment.HomeFragment; +import com.linux.permissionmanager.fragment.SettingsFragment; +import com.linux.permissionmanager.fragment.SkrModFragment; +import com.linux.permissionmanager.utils.DialogUtils; +import com.linux.permissionmanager.utils.GetAppListPermissionHelper; + + +public class MainActivity extends AppCompatActivity { + private String mRootKey = ""; + + private HomeFragment mHomeFragm; + private SuAuthFragment mSuAuthFragm; + private SkrModFragment mSkrModFragm; + private SettingsFragment mSettingsFragm; + + private TabLayout mBottomTab; + private MenuItem mMainMenu; + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_main); + AppSettings.init(this); + mRootKey = AppSettings.getString("rootKey", mRootKey); + checkGetAppListPermission(); + showInputRootKeyDlg(); + setupFragment(); + } + + private void showInputRootKeyDlg() { + Handler inputCallback = new Handler() { + @Override + public void handleMessage(@NonNull Message msg) { + String text = (String)msg.obj; + mRootKey = text; + AppSettings.setString("rootKey", mRootKey); + setupFragment(); + switchPage(0); + super.handleMessage(msg); + } + }; + DialogUtils.showInputDlg(this, mRootKey,"请输入ROOT权限的KEY", null, inputCallback, null); + } + + private void checkGetAppListPermission() { + if(GetAppListPermissionHelper.getPermissions(this)) return; + DialogUtils.showCustomDialog( + this,"权限申请","请授予读取APP列表权限,再重新打开",null,"确定", + (dialog, which) -> { + dialog.dismiss(); + finish(); + },null, null); + } + + private void setupFragment() { + mBottomTab = findViewById(R.id.bottom_tab); + mBottomTab.removeAllTabs(); + mBottomTab.addTab(mBottomTab.newTab().setText("主页"), true); + mBottomTab.addTab(mBottomTab.newTab().setText("授权")); + mBottomTab.addTab(mBottomTab.newTab().setText("模块")); + mBottomTab.addTab(mBottomTab.newTab().setText("设置")); + + // 默认页 + mHomeFragm = new HomeFragment(MainActivity.this, mRootKey); + mSuAuthFragm = new SuAuthFragment(MainActivity.this, mRootKey); + mSkrModFragm = new SkrModFragment(MainActivity.this, mRootKey); + mSettingsFragm = new SettingsFragment(MainActivity.this, mRootKey); + switchPage(0); + mBottomTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { + @Override public void onTabSelected(TabLayout.Tab tab) { switchPage(tab.getPosition()); } + @Override public void onTabUnselected(TabLayout.Tab tab) {} + @Override public void onTabReselected(TabLayout.Tab tab) {} + }); + } + + private void switchPage(int index) { + Fragment f; + switch (index) { + case 0: f = mHomeFragm; break; + case 1: f = mSuAuthFragm; break; + case 2: f = mSkrModFragm; break; + default: f = mSettingsFragm; break; + } + if(f == null) return; + getSupportFragmentManager() + .beginTransaction() + .replace(R.id.frame_layout, f) + .commit(); + if(mMainMenu != null) { + mMainMenu.setVisible(index == 1 || index == 2); + } + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + getMenuInflater().inflate(R.menu.menu_main, menu); + mMainMenu = menu.findItem(R.id.action_add); + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + if (item.getItemId() == R.id.action_add) { + View anchor = findViewById(R.id.action_add); + showMainPopupMenu(anchor); + return true; + } + return super.onOptionsItemSelected(item); + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + onChooseFileActivityResult(requestCode, resultCode, data); + } + + private void showMainPopupMenu(View v) { + int index = mBottomTab.getSelectedTabPosition(); + if(index == 1) mSuAuthFragm.showSuAuthMainPopupMenu(v); + if(index == 2) mSkrModFragm.showSkrModMainPopupMenu(v); + } + + private void onChooseFileActivityResult(int requestCode, int resultCode, Intent data) { + mSkrModFragm.onChooseFileActivityResult(requestCode, resultCode, data); + } + +} \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/adapter/SelectAppAdapter.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/adapter/SelectAppAdapter.java" new file mode 100644 index 00000000..1f798e59 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/adapter/SelectAppAdapter.java" @@ -0,0 +1,104 @@ +package com.linux.permissionmanager.adapter; + +import android.graphics.Color; +import android.graphics.drawable.Drawable; +import android.text.SpannableStringBuilder; +import android.text.Spanned; +import android.text.style.ForegroundColorSpan; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ImageView; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.recyclerview.widget.RecyclerView; + +import com.linux.permissionmanager.model.SelectAppItem; +import com.linux.permissionmanager.R; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class SelectAppAdapter extends RecyclerView.Adapter { + + public interface OnAppSelectedListener { + void onAppSelected(@NonNull SelectAppItem item); + } + + private final int itemLayoutId; + private final List items = new ArrayList<>(); + @NonNull private final OnAppSelectedListener listener; + + public SelectAppAdapter(int itemLayoutId, @NonNull List initialItems, @NonNull OnAppSelectedListener listener) { + this.itemLayoutId = itemLayoutId; + this.listener = listener; + setData(initialItems); + } + + public void setData(@Nullable List newList) { + items.clear(); + if (newList != null) items.addAll(newList); + notifyDataSetChanged(); + } + + @NonNull + public List getData() { + return Collections.unmodifiableList(items); + } + + @NonNull + @Override + public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { + View v = LayoutInflater.from(parent.getContext()).inflate(itemLayoutId, parent, false); + return new ViewHolder(v); + } + + @Override + public void onBindViewHolder(@NonNull ViewHolder holder, int position) { + SelectAppItem item = items.get(position); + + Drawable icon = item.getDrawable(holder.itemView.getContext()); + String showName = item.getShowName(holder.itemView.getContext()); + String packageName = item.getPackageName(); + + holder.icon.setImageDrawable(icon); + holder.name.setText(buildColoredTitle(showName, packageName)); + holder.pkg.setText(packageName); + + holder.itemView.setOnClickListener(v -> listener.onAppSelected(item)); + } + + @Override + public int getItemCount() { + return items.size(); + } + + private CharSequence buildColoredTitle(String showName, String packageName) { + SpannableStringBuilder ssb = new SpannableStringBuilder(); + + int startName = ssb.length(); + ssb.append(showName); + ssb.setSpan(new ForegroundColorSpan(Color.parseColor("#88CC88")), startName, ssb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + ssb.append(" "); + int startPkg = ssb.length(); + ssb.append("(").append(packageName).append(")"); + ssb.setSpan(new ForegroundColorSpan(Color.parseColor("#88CCCC")), startPkg, ssb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + return ssb; + } + + static class ViewHolder extends RecyclerView.ViewHolder { + final ImageView icon; + final TextView name; + final TextView pkg; + + ViewHolder(@NonNull View itemView) { + super(itemView); + icon = itemView.findViewById(R.id.select_app_icon); + name = itemView.findViewById(R.id.select_app_text); + pkg = itemView.findViewById(R.id.select_package_name); + } + } +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/adapter/SelectFileAdapter.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/adapter/SelectFileAdapter.java" new file mode 100644 index 00000000..c5a9ab1f --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/adapter/SelectFileAdapter.java" @@ -0,0 +1,98 @@ +package com.linux.permissionmanager.adapter; + +import android.content.Context; +import android.graphics.Color; +import android.os.Handler; +import android.os.Message; +import android.text.Html; +import android.text.SpannableStringBuilder; +import android.text.Spanned; +import android.text.style.ForegroundColorSpan; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.PopupWindow; +import android.widget.TextView; + +import androidx.annotation.ColorInt; +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.recyclerview.widget.RecyclerView; + +import com.linux.permissionmanager.model.SelectFileItem; +import com.linux.permissionmanager.R; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +public class SelectFileAdapter extends RecyclerView.Adapter { + + public interface OnFileSelectedListener { + void onFileSelected(@NonNull SelectFileItem item); + } + private final int itemLayoutId; + private final List items = new ArrayList<>(); + @NonNull private final OnFileSelectedListener listener; + + public SelectFileAdapter(int itemLayoutId, @NonNull List initialItems, @NonNull OnFileSelectedListener listener) { + this.itemLayoutId = itemLayoutId; + this.listener = listener; + setData(initialItems); + } + + public void setData(@Nullable List newList) { + items.clear(); + if (newList != null) items.addAll(newList); + notifyDataSetChanged(); + } + + @NonNull + public List getData() { + return Collections.unmodifiableList(items); + } + + @NonNull + @Override + public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { + View v = LayoutInflater.from(parent.getContext()).inflate(itemLayoutId, parent, false); + return new ViewHolder(v); + } + + @Override + public void onBindViewHolder(@NonNull ViewHolder holder, int position) { + SelectFileItem item = items.get(position); + + String fileName = item.getFileName(); + String fileDesc = item.getFileDesc(); + + Color fileDescColor = item.getFileDescColor(); + @ColorInt int descColor = fileDescColor.toArgb(); + + holder.name.setText(buildColoredText(fileName, 0xFF88CC88)); + holder.desc.setText(buildColoredText(fileDesc, descColor)); + + holder.itemView.setOnClickListener(v -> listener.onFileSelected(item)); + } + + @Override + public int getItemCount() { + return items.size(); + } + + private CharSequence buildColoredText(String text, @ColorInt int color) { + SpannableStringBuilder ssb = new SpannableStringBuilder(text); + ssb.setSpan(new ForegroundColorSpan(color), 0, ssb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + return ssb; + } + + static class ViewHolder extends RecyclerView.ViewHolder { + final TextView name; + final TextView desc; + + ViewHolder(@NonNull View itemView) { + super(itemView); + name = itemView.findViewById(R.id.select_file_name); + desc = itemView.findViewById(R.id.select_file_desc); + } + } +} \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/adapter/SkrModInstalledAdapter.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/adapter/SkrModInstalledAdapter.java" new file mode 100644 index 00000000..87d92441 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/adapter/SkrModInstalledAdapter.java" @@ -0,0 +1,131 @@ +package com.linux.permissionmanager.adapter; + +import android.graphics.Color; +import android.text.TextUtils; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.Button; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.recyclerview.widget.RecyclerView; + +import com.linux.permissionmanager.R; +import com.linux.permissionmanager.model.SkrModInstalledItem; +import com.linux.permissionmanager.model.SkrModMarketItem; +import com.linux.permissionmanager.model.SkrModRunState; +import com.linux.permissionmanager.model.SkrModUpdateInfo; + +import java.util.ArrayList; +import java.util.List; + +public class SkrModInstalledAdapter extends RecyclerView.Adapter { + private final int SkrModRunningColor = Color.parseColor("#16A34A"); + private final int SkrModNotRunningColor = Color.parseColor("#F59E0B"); + private final int SkrModAbnormalColor = Color.parseColor("#EF4444"); + + private List skrmods; + private OnItemClickListener listener; + + public interface OnItemClickListener { + void onOpenWebUIBtnClick(View v, SkrModInstalledItem skrmod); + void onNewVersionBtnClick(View v, SkrModInstalledItem skrmod); + void onMoreBtnClick(View v, SkrModInstalledItem skrmod); + } + + public SkrModInstalledAdapter(List skrmods, OnItemClickListener listener) { + this.skrmods = skrmods; + this.listener = listener; + } + + @NonNull + @Override + public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { + View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_skr_mod_installed, parent, false); + return new ViewHolder(view); + } + + private static void setTextOrGone(TextView tv, String s) { + if (tv == null) return; + boolean hidden = TextUtils.isEmpty(s) || TextUtils.isEmpty(s.trim()); + tv.setText(s); + tv.setVisibility(hidden ? View.GONE : View.VISIBLE); + } + + @Override + public void onBindViewHolder(ViewHolder holder, int position) { + SkrModInstalledItem skrmod = skrmods.get(position); + holder.tvName.setText(skrmod.getName()); + + setTextOrGone(holder.tvDesc, skrmod.getDesc()); + holder.tvVer.setText(skrmod.getVer()); + holder.tvAuthor.setText(skrmod.getAuthor()); + SkrModRunState state = skrmod.getRunState(); + holder.tvStatus.setText( + state == SkrModRunState.RUNNING ? "运行中" : + state == SkrModRunState.ABNORMAL ? "运行异常" : + "未启动" + ); + holder.tvStatus.setTextColor( + state == SkrModRunState.RUNNING ? SkrModRunningColor : + state == SkrModRunState.ABNORMAL ? SkrModAbnormalColor : + SkrModNotRunningColor + ); + holder.btnWebUI.setVisibility(skrmod.isWebUi() ? View.VISIBLE : View.GONE); + holder.btnWebUI.setOnClickListener(v -> { + if (listener != null) listener.onOpenWebUIBtnClick(v, skrmod); + }); + + holder.btnMore.setOnClickListener(v -> { + if (listener != null) listener.onMoreBtnClick(v, skrmod); + }); + + boolean hasNewVer = skrmod.getUpdateInfo() != null && skrmod.getUpdateInfo().isHasNewVersion(); + holder.btnNewVersion.setVisibility(hasNewVer ? View.VISIBLE : View.GONE); + holder.btnNewVersion.setOnClickListener(v -> { + if (listener != null) listener.onNewVersionBtnClick(v, skrmod); + }); + } + + public void updateModuleUpdateInfo(String uuid, SkrModUpdateInfo updateInfo) { + if (uuid == null) return; + for (int i = 0; i < skrmods.size(); i++) { + SkrModInstalledItem item = skrmods.get(i); + if (uuid.equals(item.getUuid())) { + item.setUpdateInfo(updateInfo); + notifyItemChanged(i); + break; + } + } + } + + @Override + public int getItemCount() { + return skrmods.size(); + } + + public static class ViewHolder extends RecyclerView.ViewHolder { + public TextView tvName; + public TextView tvDesc; + public TextView tvVer; + public TextView tvAuthor; + public TextView tvStatus; + public Button btnWebUI; + public Button btnNewVersion; + public Button btnMore; + + public ViewHolder(View itemView) { + super(itemView); + tvName = itemView.findViewById(R.id.name_tv); + tvDesc = itemView.findViewById(R.id.desc_tv); + tvVer = itemView.findViewById(R.id.ver_tv); + tvAuthor = itemView.findViewById(R.id.author_tv); + tvStatus = itemView.findViewById(R.id.status_tv); + btnMore = itemView.findViewById(R.id.more_btn); + btnWebUI = itemView.findViewById(R.id.web_ui_btn); + btnNewVersion = itemView.findViewById(R.id.new_version_btn); + } + } + +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/adapter/SkrModMarketAdapter.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/adapter/SkrModMarketAdapter.java" new file mode 100644 index 00000000..1afd782e --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/adapter/SkrModMarketAdapter.java" @@ -0,0 +1,90 @@ +package com.linux.permissionmanager.adapter; + +import android.text.TextUtils; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.Button; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.recyclerview.widget.RecyclerView; + +import com.linux.permissionmanager.R; +import com.linux.permissionmanager.model.SkrModMarketItem; +import com.linux.permissionmanager.model.SkrModUpdateInfo; + +import java.util.ArrayList; +import java.util.List; + +public class SkrModMarketAdapter extends RecyclerView.Adapter { + private List skrmods; + private OnItemClickListener listener; + + public interface OnItemClickListener { + void onActionsBtnClick(View v, SkrModMarketItem skrmod); + } + + public SkrModMarketAdapter(List skrmods, OnItemClickListener listener) { + this.skrmods = skrmods; + this.listener = listener; + } + + public void setData(List list) { + this.skrmods = (list == null) ? new ArrayList<>() : list; + notifyDataSetChanged(); + } + + @NonNull + @Override + public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { + View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_skr_mod_market, parent, false); + return new ViewHolder(view); + } + + private static void setTextOrGone(TextView tv, String s) { + if (tv == null) return; + boolean hidden = TextUtils.isEmpty(s) || TextUtils.isEmpty(s.trim()); + tv.setText(s); + tv.setVisibility(hidden ? View.GONE : View.VISIBLE); + } + + @Override + public void onBindViewHolder(ViewHolder holder, int position) { + SkrModMarketItem skrmod = skrmods.get(position); + holder.tvName.setText(skrmod.getChnName()); + + setTextOrGone(holder.tvDesc, skrmod.getDesc()); + holder.tvVer.setText(skrmod.getVer()); + holder.tvAuthor.setText(skrmod.getAuthor()); + holder.tvUpdateDate.setText(skrmod.getUpdateDate()); + holder.btnActions.setOnClickListener(v -> { + if (listener != null) listener.onActionsBtnClick(v, skrmod); + }); + } + + @Override + public int getItemCount() { + return skrmods.size(); + } + + public static class ViewHolder extends RecyclerView.ViewHolder { + public TextView tvName; + public TextView tvDesc; + public TextView tvVer; + public TextView tvAuthor; + public TextView tvUpdateDate; + public Button btnActions; + + public ViewHolder(View itemView) { + super(itemView); + tvName = itemView.findViewById(R.id.name_tv); + tvDesc = itemView.findViewById(R.id.desc_tv); + tvVer = itemView.findViewById(R.id.ver_tv); + tvAuthor = itemView.findViewById(R.id.author_tv); + tvUpdateDate = itemView.findViewById(R.id.update_date_tv); + btnActions = itemView.findViewById(R.id.actions_btn); + } + } + +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/adapter/SkrModPrinter.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/adapter/SkrModPrinter.java" new file mode 100644 index 00000000..8941e2ee --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/adapter/SkrModPrinter.java" @@ -0,0 +1,33 @@ +package com.linux.permissionmanager.adapter; + +import android.text.TextUtils; + +import com.linux.permissionmanager.model.SkrModInstalledItem; + +public final class SkrModPrinter { + public static String buildModuleMeta(SkrModInstalledItem m) { + StringBuilder sb = new StringBuilder(256); + sb.append("----- SKRoot 模块详情 -----\n"); + sb.append("名称:").append(nvl(m.getName())).append('\n'); + sb.append("版本:").append(nvl(m.getVer())).append('\n'); + sb.append("描述:").append(nvl(m.getDesc())).append('\n'); + sb.append("作者:").append(nvl(m.getAuthor())).append('\n'); + sb.append("UUID:").append(nvl(m.getUuid())).append('\n'); + sb.append("最低SDK要求:").append(nvl(m.getMiniSdk())).append('\n'); + + boolean onlineUpdate = !TextUtils.isEmpty(m.getUpdateJson()); + boolean anyFeature = m.isWebUi() || onlineUpdate; + if (anyFeature) { + sb.append("特性:\n"); + if (m.isWebUi()) sb.append(" [+] Web UI\n"); + if (onlineUpdate) sb.append(" [+] Online Update\n"); + } + + sb.append("------------------------------\n"); + return sb.toString(); + } + + private static String nvl(String s) { + return (s == null || s.isEmpty()) ? "(空)" : s; + } +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/adapter/SuAuthAdapter.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/adapter/SuAuthAdapter.java" new file mode 100644 index 00000000..07e068d3 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/adapter/SuAuthAdapter.java" @@ -0,0 +1,74 @@ +package com.linux.permissionmanager.adapter; + +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.Button; +import android.widget.ImageView; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.recyclerview.widget.RecyclerView; + +import com.linux.permissionmanager.R; +import com.linux.permissionmanager.model.SkrModMarketItem; +import com.linux.permissionmanager.model.SuAuthItem; + +import java.util.ArrayList; +import java.util.List; + +public class SuAuthAdapter extends RecyclerView.Adapter { + + private List suAuths; + private OnItemClickListener listener; + + public interface OnItemClickListener { + void onRemoveSuAuthBtnClick(View v, SuAuthItem suAuth); + } + + public SuAuthAdapter(List suAuths, OnItemClickListener listener) { + this.suAuths = suAuths; + this.listener = listener; + } + + @NonNull + @Override + public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { + View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_su_auth, parent, false); + return new ViewHolder(view); + } + + @Override + public void onBindViewHolder(ViewHolder holder, int position) { + SuAuthItem suAuth = suAuths.get(position); + if(suAuth.getIcon() != null) holder.tvAppIcon.setImageDrawable(suAuth.getIcon()); + holder.tvAppName.setText(suAuth.getAppName()); + holder.tvAppPackageName.setText(suAuth.getAppPackageName()); + holder.btnRemove.setOnClickListener(v -> { + if (listener != null) { + listener.onRemoveSuAuthBtnClick(v, suAuth); + } + }); + } + + @Override + public int getItemCount() { + return suAuths.size(); + } + + public static class ViewHolder extends RecyclerView.ViewHolder { + public ImageView tvAppIcon; + public TextView tvAppName; + public TextView tvAppPackageName; + public Button btnRemove; + + public ViewHolder(View itemView) { + super(itemView); + tvAppIcon = itemView.findViewById(R.id.app_icon_iv); + tvAppName = itemView.findViewById(R.id.app_name_tv); + tvAppPackageName = itemView.findViewById(R.id.app_package_name_tv); + btnRemove = itemView.findViewById(R.id.remove_btn); + + } + } +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/bridge/NativeBridge.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/bridge/NativeBridge.java" new file mode 100644 index 00000000..9a97af5b --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/bridge/NativeBridge.java" @@ -0,0 +1,37 @@ +package com.linux.permissionmanager.bridge; + +public final class NativeBridge { + static { System.loadLibrary("permissionmanager"); } + + public static native String installSkrootEnv(String rootKey); + public static native String uninstallSkrootEnv(String rootKey); + public static native String getSkrootEnvState(String rootKey); + public static native String getInstalledSkrootEnvVersion(String rootKey); + public static native String getSdkVersion(); + + public static native String testRoot(String rootKey); + public static native String runRootCmd(String rootKey, String cmd); + public static native String rootExecProcessCmd(String rootKey, String cmd); + + public static native String addSuAuth(String rootKey, String appPackageName); + public static native String removeSuAuth(String rootKey, String appPackageName); + public static native String getSuAuthList(String rootKey); + public static native String clearSuAuthList(String rootKey); + + public static native String installSkrootModule(String rootKey, String zipFilePath); + public static native String uninstallSkrootModule(String rootKey, String modUuid); + public static native String getSkrootModuleList(String rootKey, boolean runningOnly, boolean abnormalOnly); + public static native String parseSkrootModuleDesc(String rootKey, String zipFilePath); + public static native String openSkrootModuleWebUI(String rootKey, String modUuid); + + public static native String setBootFailProtectEnabled(String rootKey, boolean enable); + public static native boolean isBootFailProtectEnabled(String rootKey); + public static native String testSkrootBasics(String rootKey, String item); + public static native String testSkrootDefaultModule(String rootKey, String name); + + public static native String setSkrootLogEnabled(String rootKey, boolean enable); + public static native boolean isSkrootLogEnabled(String rootKey); + public static native String readSkrootLog(String rootKey); + + +} \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/fragment/HomeFragment.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/fragment/HomeFragment.java" new file mode 100644 index 00000000..91a25aaa --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/fragment/HomeFragment.java" @@ -0,0 +1,169 @@ +package com.linux.permissionmanager.fragment; + +import android.app.Activity; +import android.app.ProgressDialog; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.Button; +import android.widget.EditText; +import android.widget.Toast; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.fragment.app.Fragment; + +import com.linux.permissionmanager.AppSettings; +import com.linux.permissionmanager.R; +import com.linux.permissionmanager.bridge.NativeBridge; +import com.linux.permissionmanager.utils.ClipboardUtils; +import com.linux.permissionmanager.utils.DialogUtils; + +public class HomeFragment extends Fragment implements View.OnClickListener { + private Activity mActivity; + private String mRootKey = ""; + private String lastInputCmd = "id"; + private String lastInputRootExecPath = ""; + + private EditText mConsoleEdit; + public HomeFragment(Activity activity, String rootKey) { + mActivity = activity; + mRootKey = rootKey; + } + @Nullable + @Override + public View onCreateView(@NonNull LayoutInflater inflater, + @Nullable ViewGroup container, + @Nullable Bundle savedInstanceState) { + return inflater.inflate(R.layout.fragment_home, container, false); + } + + @Override + public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); + + lastInputCmd = AppSettings.getString("lastInputCmd", lastInputCmd); + lastInputRootExecPath = AppSettings.getString("lastInputRootExecPath", lastInputRootExecPath); + + Button install_skroot_env_btn = view.findViewById(R.id.install_skroot_env_btn); + Button uninstall_skroot_env_btn = view.findViewById(R.id.uninstall_skroot_env_btn); + Button test_root_btn = view.findViewById(R.id.test_root_btn); + Button run_root_cmd_btn = view.findViewById(R.id.run_root_cmd_btn); + Button implant_app_btn_btn = view.findViewById(R.id.implant_app_btn); + Button copy_info_btn = view.findViewById(R.id.copy_info_btn); + Button clean_info_btn = view.findViewById(R.id.clean_info_btn); + mConsoleEdit = view.findViewById(R.id.console_edit); + + install_skroot_env_btn.setOnClickListener(this); + uninstall_skroot_env_btn.setOnClickListener(this); + test_root_btn.setOnClickListener(this); + run_root_cmd_btn.setOnClickListener(this); + implant_app_btn_btn.setOnClickListener(this); + copy_info_btn.setOnClickListener(this); + clean_info_btn.setOnClickListener(this); + showSkrootStatus(); + } + + @Override + public void onClick(View v) { + switch (v.getId()) { + case R.id.install_skroot_env_btn: + onClickInstallSkrootEnvBtn(); + break; + case R.id.uninstall_skroot_env_btn: + onClickUninstallSkrootEnvBtn(); + break; + case R.id.test_root_btn: + appendConsoleMsg(NativeBridge.testRoot(mRootKey)); + break; + case R.id.run_root_cmd_btn: + showInputRootCmdDlg(); + break; + case R.id.implant_app_btn: + break; + case R.id.copy_info_btn: + copyConsoleMsg(); + break; + case R.id.clean_info_btn: + cleanConsoleMsg(); + break; + default: + break; + } + } + + private void showSkrootStatus() { + String curState = NativeBridge.getSkrootEnvState(mRootKey); + String installedVer = NativeBridge.getInstalledSkrootEnvVersion(mRootKey); + String sdkVer = NativeBridge.getSdkVersion(); + + if(curState.indexOf("NotInstalled") != -1) { + appendConsoleMsg("SKRoot环境未安装!"); + } else if(curState.indexOf("Fault") != -1) { + appendConsoleMsg("SKRoot环境出现故障,核心版本:" + installedVer); + } else if(curState.indexOf("Running") != -1) { + if (sdkVer.equals(installedVer)) { + appendConsoleMsg("SKRoot环境运行中,核心版本:" + installedVer); + } else { + appendConsoleMsg("SKRoot环境运行中,核心版本:" + installedVer + ",版本太低,请升级!"); + appendConsoleMsg("升级方法:重新点击“安装SKRoot环境”按钮。"); + } + } + } + + private void showInputRootCmdDlg() { + Handler inputCallback = new Handler() { + @Override + public void handleMessage(@NonNull Message msg) { + String text = (String)msg.obj; + lastInputCmd = text; + AppSettings.setString("lastInputCmd", lastInputCmd); + appendConsoleMsg(text + "\n" + NativeBridge.runRootCmd(mRootKey, text)); + super.handleMessage(msg); + } + }; + DialogUtils.showInputDlg(mActivity, lastInputCmd, "请输入ROOT命令", null, inputCallback, null); + } + + private void onClickInstallSkrootEnvBtn() { + appendConsoleMsg(NativeBridge.installSkrootEnv(mRootKey)); + } + + private void onClickUninstallSkrootEnvBtn() { + DialogUtils.showCustomDialog( + mActivity, + "确认", + "确定要卸载SKRoot环境吗?这会同时清空 SU 授权列表和删除已安装的模块", + null, + "确定", (dialog, which) -> { + dialog.dismiss(); + appendConsoleMsg(NativeBridge.uninstallSkrootEnv(mRootKey)); + }, + "取消", (dialog, which) -> { + dialog.dismiss(); + } + ); + } + + private void appendConsoleMsg(String msg) { + StringBuffer txt = new StringBuffer(); + txt.append(mConsoleEdit.getText().toString()); + if (txt.length() != 0) txt.append("\n"); + txt.append(msg); + txt.append("\n"); + mConsoleEdit.setText(txt.toString()); + mConsoleEdit.setSelection(txt.length()); + } + + private void copyConsoleMsg() { + ClipboardUtils.copyText(mActivity, mConsoleEdit.getText().toString()); + Toast.makeText(mActivity, "复制成功", Toast.LENGTH_SHORT).show(); + } + + private void cleanConsoleMsg() { + mConsoleEdit.setText(""); + } +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/fragment/SettingsFragment.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/fragment/SettingsFragment.java" new file mode 100644 index 00000000..6dbc37ec --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/fragment/SettingsFragment.java" @@ -0,0 +1,215 @@ +package com.linux.permissionmanager.fragment; + +import android.app.Activity; +import android.content.DialogInterface; +import android.content.Intent; +import android.graphics.Color; +import android.graphics.Paint; +import android.net.Uri; +import android.os.Bundle; +import android.text.SpannableString; +import android.text.Spanned; +import android.text.style.UnderlineSpan; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.Button; +import android.widget.CheckBox; +import android.widget.LinearLayout; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.appcompat.app.AlertDialog; +import androidx.fragment.app.Fragment; + +import com.linux.permissionmanager.R; +import com.linux.permissionmanager.bridge.NativeBridge; +import com.linux.permissionmanager.model.AppUpdateInfo; +import com.linux.permissionmanager.update.AppUpdateManager; +import com.linux.permissionmanager.utils.DialogUtils; +import com.linux.permissionmanager.utils.UrlIntentUtils; + +public class SettingsFragment extends Fragment { + private Activity mActivity; + private String mRootKey = ""; + + private CheckBox mCkboxEnableBootFailProtect; + private Button mBtnTestSkrootBasics; + private Button mBtnTestSkrootDefaultModule; + private CheckBox mCkboxEnableSkrootLog; + private Button mBtnShowSkrootLog; + private TextView mTvAboutVer; + private TextView mTvLink; + + // Update component + private LinearLayout mTvUpdateBlock; + private TextView mTvUpdateFound; + private TextView mTvUpdateChangelog; + private TextView mTvUpdateDownload; + private AppUpdateManager mUpdateManager; + + public SettingsFragment(Activity activity, String rootKey) { + mActivity = activity; + mRootKey = rootKey; + } + + @Nullable + @Override + public View onCreateView(@NonNull LayoutInflater inflater, + @Nullable ViewGroup container, + @Nullable Bundle savedInstanceState) { + return inflater.inflate(R.layout.fragment_settings, container, false); + } + + @Override + public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); + mCkboxEnableBootFailProtect = view.findViewById(R.id.enable_boot_fail_protect_ckbox); + mBtnTestSkrootBasics = view.findViewById(R.id.test_skroot_basics_btn); + mBtnTestSkrootDefaultModule = view.findViewById(R.id.test_skroot_default_module_btn); + mCkboxEnableSkrootLog = view.findViewById(R.id.enable_skroot_log_ckbox); + mBtnShowSkrootLog = view.findViewById(R.id.show_skroot_log_btn); + mTvAboutVer = view.findViewById(R.id.about_ver_tv); + mTvLink = view.findViewById(R.id.link_tv); + + // Update component + mTvUpdateBlock = view.findViewById(R.id.core_update_block); + mTvUpdateFound = view.findViewById(R.id.core_update_found_tv); + mTvUpdateChangelog = view.findViewById(R.id.core_update_changelog_tv); + mTvUpdateDownload = view.findViewById(R.id.core_update_download_tv); + initSettingsControl(); + } + + private void initSettingsControl() { + mCkboxEnableBootFailProtect.setChecked(NativeBridge.isBootFailProtectEnabled(mRootKey)); + mCkboxEnableBootFailProtect.setOnCheckedChangeListener( + (v, isChecked) -> { + String tip = NativeBridge.setBootFailProtectEnabled(mRootKey, isChecked); + DialogUtils.showMsgDlg(mActivity, "执行结果", tip, null); + } + ); + mBtnTestSkrootBasics.setOnClickListener((v) -> showSelectTestSkrootBasicsDlg()); + mBtnTestSkrootDefaultModule.setOnClickListener((v) -> showSelectTestDefaultModuleDlg()); + + mCkboxEnableSkrootLog.setChecked(NativeBridge.isSkrootLogEnabled(mRootKey)); + mCkboxEnableSkrootLog.setOnCheckedChangeListener( + (v, isChecked) -> { + String tip = NativeBridge.setSkrootLogEnabled(mRootKey, isChecked); + DialogUtils.showMsgDlg(mActivity, "执行结果", tip, null); + } + ); + mBtnShowSkrootLog.setOnClickListener(v -> showSkrootLogDlg()); + mUpdateManager = new AppUpdateManager(mActivity); + initAboutText(); + initLink(); + initUpdateBlock(); + } + + private void showSelectTestSkrootBasicsDlg() { + final String[] items = {"1.通道检查", "2.内核起始地址检查", "3.写入内存测试", "4.读取跳板测试", "5.写入跳板测试"}; + AlertDialog.Builder builder = new AlertDialog.Builder(mActivity); + builder.setTitle("请选择一个选项"); + builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + String item = ""; + if(which == 0) item = "Channel"; + else if(which == 1) item = "KernelBase"; + else if(which == 2) item = "WriteTest"; + else if(which == 3) item = "ReadTrampoline"; + else if(which == 4) item = "WriteTrampoline"; + String log = NativeBridge.testSkrootBasics(mRootKey, item); + DialogUtils.showLogDialog(mActivity, log); + } + }); + builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } + }); + AlertDialog dialog = builder.create(); + dialog.show(); + } + + private void showSelectTestDefaultModuleDlg() { + final String[] items = {"1.ROOT 权限模块 (打印)", "2.ROOT 权限模块 (执行)", "3.SU 重定向模块 (打印)", "4.SU 重定向模块 (执行)"}; + AlertDialog.Builder builder = new AlertDialog.Builder(mActivity); + builder.setTitle("选择一个选项"); + builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + String defName = ""; + if(which == 0) defName = "RootBridgePrint"; + else if(which == 1) defName = "RootBridgeExec"; + else if(which == 2) defName = "SuRedirectPrint"; + else if(which == 3) defName = "SuRedirectExec"; + String log = NativeBridge.testSkrootDefaultModule(mRootKey, defName); + DialogUtils.showLogDialog(mActivity, log); + } + }); + builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } + }); + AlertDialog dialog = builder.create(); + dialog.show(); + } + + private void showSkrootLogDlg() { + String log = NativeBridge.readSkrootLog(mRootKey); + DialogUtils.showLogDialog(mActivity, log); + } + + private void initAboutText() { + StringBuffer sb = new StringBuffer(); + sb.append("内置核心版本:"); + sb.append(NativeBridge.getSdkVersion()); + mTvAboutVer.setText(sb.toString()); + } + + private void initLink() { + mTvLink.setText("https://github.com/abcz316/SKRoot-linuxKernelRoot"); + mTvLink.setOnClickListener(v -> { + UrlIntentUtils.openUrl(mActivity, mTvLink.getText().toString()); + }); + makeUnderline(mTvLink); + } + + private void onDownloadChangeLogApp(AppUpdateInfo updateInfo) { + mUpdateManager.requestAppChangelog( + updateInfo, + (content) -> DialogUtils.showLogDialog(mActivity, content), + (e) -> DialogUtils.showMsgDlg(mActivity, "提示", "App 更新日志下载失败:" + e.getMessage(),null) + ); + } + + private void initUpdateBlock() { + mUpdateManager.requestAppUpdate( + (info) -> { + if (info == null || !info.isHasNewVersion()) return; + mTvUpdateBlock.setVisibility(View.VISIBLE); + mTvUpdateFound.setText("发现新版本:" + info.getLatestVer()); + mTvUpdateChangelog.setOnClickListener(v -> onDownloadChangeLogApp(info)); + mTvUpdateDownload.setOnClickListener(v -> UrlIntentUtils.openUrl(mActivity, info.getDownloadUrl())); + DialogUtils.showCustomDialog( + mActivity, "提示", "发现新版本:" + info.getLatestVer(),null,"确定", + (dialog, which) -> { + UrlIntentUtils.openUrl(mActivity, info.getDownloadUrl()); + dialog.dismiss(); + }, + "取消", + (dialog, which) -> dialog.dismiss() + ); + }, + (e) -> {} + ); + makeUnderline(mTvUpdateChangelog); + makeUnderline(mTvUpdateDownload); + } + + private void makeUnderline(TextView tv) { + tv.getPaint().setFlags(tv.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); + } +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/fragment/SkrModFragment.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/fragment/SkrModFragment.java" new file mode 100644 index 00000000..0eb5b1ce --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/fragment/SkrModFragment.java" @@ -0,0 +1,87 @@ +package com.linux.permissionmanager.fragment; + +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.PopupMenu; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.fragment.app.Fragment; +import androidx.viewpager2.widget.ViewPager2; + +import com.google.android.material.tabs.TabLayout; +import com.google.android.material.tabs.TabLayoutMediator; +import com.linux.permissionmanager.ActivityResultId; +import com.linux.permissionmanager.R; +import com.linux.permissionmanager.page.SkrModInstalledPage; +import com.linux.permissionmanager.page.SkrModMarketPage; +import com.linux.permissionmanager.utils.DialogUtils; +import com.linux.permissionmanager.utils.GetSdcardPermissionsHelper; + +public class SkrModFragment extends Fragment { + private Activity mActivity; + private String mRootKey = ""; + + private TabLayout mTabLayout; + private View mInstalled; + private View mMarket; + + private SkrModInstalledPage mModInstalledPage; + private SkrModMarketPage mModMarketPage; + + public SkrModFragment(Activity activity, String rootKey) { + mActivity = activity; + mRootKey = rootKey; + mModInstalledPage = new SkrModInstalledPage(activity, rootKey); + mModMarketPage = new SkrModMarketPage(activity, rootKey); + } + + @Nullable + @Override + public View onCreateView(@NonNull LayoutInflater inflater, + @Nullable ViewGroup container, + @Nullable Bundle savedInstanceState) { + return inflater.inflate(R.layout.fragment_skr_mod, container, false); + } + + @Override + public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); + mTabLayout = view.findViewById(R.id.tab_layout); + mInstalled = view.findViewById(R.id.page_installed); + mMarket = view.findViewById(R.id.page_market); + mModInstalledPage.bindPage(mInstalled); + mModMarketPage.bindPage(mMarket); + initTabLayout(); + } + + private void initTabLayout() { + mTabLayout.addTab(mTabLayout.newTab().setText("已安装"), true); + mTabLayout.addTab(mTabLayout.newTab().setText("模块市场")); + + mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { + @Override public void onTabSelected(TabLayout.Tab t) { + boolean showInstalled = t.getPosition() == 0; + mInstalled.setVisibility(showInstalled ? View.VISIBLE : View.GONE); + mMarket.setVisibility(showInstalled ? View.GONE : View.VISIBLE); + + if(showInstalled) mModInstalledPage.refreshPage(); + else mModMarketPage.refreshPage(); + } + @Override public void onTabUnselected(TabLayout.Tab t) {} + @Override public void onTabReselected(TabLayout.Tab t) {} + }); + } + + public void showSkrModMainPopupMenu(View v) { + mModInstalledPage.showSkrModMainPopupMenu(v); + } + + public void onChooseFileActivityResult(int requestCode, int resultCode, Intent data) { + mModInstalledPage.onChooseFileActivityResult(requestCode, resultCode, data); + } +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/fragment/SuAuthFragment.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/fragment/SuAuthFragment.java" new file mode 100644 index 00000000..bc7f039c --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/fragment/SuAuthFragment.java" @@ -0,0 +1,188 @@ +package com.linux.permissionmanager.fragment; + +import android.app.Activity; +import android.app.ProgressDialog; +import android.content.pm.PackageInfo; +import android.graphics.drawable.Drawable; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.CheckBox; +import android.widget.PopupMenu; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.fragment.app.Fragment; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import com.linux.permissionmanager.R; +import com.linux.permissionmanager.adapter.SuAuthAdapter; +import com.linux.permissionmanager.bridge.NativeBridge; +import com.linux.permissionmanager.helper.SelectAppDlg; +import com.linux.permissionmanager.model.SelectAppItem; +import com.linux.permissionmanager.model.SuAuthItem; +import com.linux.permissionmanager.utils.DialogUtils; + +import org.json.JSONArray; +import org.json.JSONObject; + +import java.net.URLDecoder; +import java.util.ArrayList; +import java.util.List; + +public class SuAuthFragment extends Fragment { + private Activity mActivity; + private String mRootKey = ""; + + private TextView mTextEmptyTips; + private RecyclerView mSuAuthRecyclerView; + + private SuAuthAdapter mAdapter; + + public SuAuthFragment(Activity activity, String rootKey) { + mActivity = activity; + mRootKey = rootKey; + } + + @Nullable + @Override + public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { + return inflater.inflate(R.layout.fragment_su_auth, container, false); + } + + @Override + public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); + mTextEmptyTips = view.findViewById(R.id.empty_tips_tv); + mSuAuthRecyclerView = view.findViewById(R.id.su_auth_recycler_view); + setupSuAuthRecyclerView(); + } + + private void setupSuAuthRecyclerView() { + String json = NativeBridge.getSuAuthList(mRootKey); + List skrModList = parseSuAuthList(json); + mAdapter = new SuAuthAdapter(skrModList, new SuAuthAdapter.OnItemClickListener() { + @Override + public void onRemoveSuAuthBtnClick(View v, SuAuthItem suAuth) { onRemoveSuAuth(suAuth); } + }); + mSuAuthRecyclerView.setAdapter(mAdapter); + mSuAuthRecyclerView.setLayoutManager(new LinearLayoutManager(getContext())); + mSuAuthRecyclerView.setVisibility(skrModList.size() == 0 ? View.GONE : View.VISIBLE); + mTextEmptyTips.setVisibility(skrModList.size() == 0 ? View.VISIBLE : View.GONE); + } + + private String findAppName(List packages, String appPackageName) { + for (int i = 0; i < packages.size(); i++) { + PackageInfo packageInfo = packages.get(i); + String packageName = packageInfo.applicationInfo.packageName; + if(!packageName.equals(appPackageName)) continue; + String showName = packageInfo.applicationInfo.loadLabel(mActivity.getPackageManager()).toString(); + return showName; + } + return ""; + } + + private Drawable findAppIcon(List packages, String appPackageName) { + for (int i = 0; i < packages.size(); i++) { + PackageInfo packageInfo = packages.get(i); + String packageName = packageInfo.applicationInfo.packageName; + if(!packageName.equals(appPackageName)) continue; + Drawable icon = packageInfo.applicationInfo.loadIcon(mActivity.getPackageManager()); + return icon; + } + return null; + } + + private List parseSuAuthList(String jsonStr) { + List packages = mActivity.getPackageManager().getInstalledPackages(0); + List list = new ArrayList<>(); + try { + JSONArray jsonArray = new JSONArray(jsonStr); + for (int i = 0; i < jsonArray.length(); i++) { + JSONObject jsonObject = jsonArray.getJSONObject(i); + + String appPackageName = URLDecoder.decode(jsonObject.getString("app_package_name"), "UTF-8"); + Drawable icon = findAppIcon(packages, appPackageName); + String appName = findAppName(packages, appPackageName); + SuAuthItem e = new SuAuthItem(icon, appName, appPackageName); + list.add(e); + } + } catch (Exception e) { + DialogUtils.showMsgDlg(mActivity, "发生错误", jsonStr, null); + e.printStackTrace(); + } + return list; + } + + public void showSuAuthMainPopupMenu(View v) { + PopupMenu popupMenu = new PopupMenu(mActivity, v); + popupMenu.getMenuInflater().inflate(R.menu.popup_su_auth_main_menu, popupMenu.getMenu()); + popupMenu.setOnMenuItemClickListener(item -> { + int itemId = item.getItemId(); + if (itemId == R.id.add_su_auth) onShowSelectAddSuAuthList(); + else if (itemId == R.id.clear_su_auth) onClearSuAuth(); + return true; + }); + + popupMenu.show(); + } + + private void onShowSelectAddSuAuthList() { + Handler selectImplantAppCallback = new Handler() { + @Override + public void handleMessage(@NonNull Message msg) { + SelectAppItem app = (SelectAppItem) msg.obj; + onAddSuAuth(app); + super.handleMessage(msg); + } + }; + View view = SelectAppDlg.showSelectAppDlg(mActivity, mRootKey, selectImplantAppCallback); + CheckBox show_system_app_ckbox = view.findViewById(R.id.show_system_app_ckbox); + CheckBox show_thirty_app_ckbox = view.findViewById(R.id.show_thirty_app_ckbox); + show_system_app_ckbox.setChecked(false); + show_thirty_app_ckbox.setChecked(true); + } + + private void onAddSuAuth(SelectAppItem app) { + String appPackageName = app.getPackageName(); + String tip = NativeBridge.addSuAuth(mRootKey, appPackageName); + DialogUtils.showMsgDlg(mActivity, "执行结果", tip, null); + setupSuAuthRecyclerView(); + } + + private void onRemoveSuAuth(SuAuthItem suAuth) { + String appName = suAuth.getAppName(); + String appPackageName = suAuth.getAppPackageName(); + String showName = appName != null && !appName.isEmpty() ? appName : appPackageName; + DialogUtils.showCustomDialog(mActivity, "确认", "确定要移除 " + showName +" 吗?", null,"确定", + (dialog, which) -> { + dialog.dismiss(); + String tip = NativeBridge.removeSuAuth(mRootKey, appPackageName); + DialogUtils.showMsgDlg(mActivity, "执行结果", tip, null); + setupSuAuthRecyclerView(); + }, + "取消", (dialog, which) -> { + dialog.dismiss(); + } + ); + } + + private void onClearSuAuth() { + DialogUtils.showCustomDialog(mActivity, "确认", "确定要清空 SU 授权列表吗?", null, "确定", + (dialog, which) -> { + dialog.dismiss(); + String tip = NativeBridge.clearSuAuthList(mRootKey); + DialogUtils.showMsgDlg(mActivity, "执行结果", tip, null); + setupSuAuthRecyclerView(); + }, + "取消", (dialog, which) -> { + dialog.dismiss(); + } + ); + } +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/helper/SelectAppDlg.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/helper/SelectAppDlg.java" new file mode 100644 index 00000000..c1076fd1 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/helper/SelectAppDlg.java" @@ -0,0 +1,148 @@ +package com.linux.permissionmanager.helper; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageInfo; +import android.graphics.drawable.ColorDrawable; +import android.os.Handler; +import android.os.Message; +import android.text.Editable; +import android.text.TextWatcher; +import android.view.Gravity; +import android.view.View; +import android.view.ViewGroup; +import android.widget.CheckBox; +import android.widget.CompoundButton; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.PopupWindow; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; + +import com.linux.permissionmanager.R; +import com.linux.permissionmanager.adapter.SelectAppAdapter; +import com.linux.permissionmanager.model.SelectAppItem; +import com.linux.permissionmanager.utils.ScreenInfoUtils; + +import java.util.ArrayList; +import java.util.List; + +public class SelectAppDlg { + public static View showSelectAppDlg(Activity activity, String rootKey, Handler selectAppCallback) { + final PopupWindow popupWindow = new PopupWindow(activity); + View view = View.inflate(activity, R.layout.select_app_wnd, null); + popupWindow.setContentView(view); + popupWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT); + popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT); + popupWindow.setBackgroundDrawable(new ColorDrawable(0x9B000000)); + popupWindow.setOutsideTouchable(true); + popupWindow.setFocusable(true); + popupWindow.setTouchable(true); + + //全屏 + View parent = View.inflate(activity, R.layout.activity_main, null); + popupWindow.showAtLocation(parent, Gravity.NO_GRAVITY, 0, 0); + popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() { + @Override + public void onDismiss() {} + }); + + final int screenWidth = ScreenInfoUtils.getRealWidth(activity); + final int screenHeight = ScreenInfoUtils.getRealHeight(activity); + + final double centerWidth = ((double) screenWidth) * 0.80; + final double centerHeight = ((double) screenHeight) * 0.90; + + LinearLayout center_layout = (LinearLayout) view.findViewById(R.id.center_layout); + ViewGroup.LayoutParams lp = center_layout.getLayoutParams(); + lp.width = (int) centerWidth; + lp.height = (int) centerHeight; + center_layout.setLayoutParams(lp); + + // 外层容器:点到阴影就关闭弹窗 + View outside = view.findViewById(R.id.popup_outside_container); + outside.setOnClickListener(v -> popupWindow.dismiss()); + // 中间内容区域:消费点击,不往外传(防止点内容也被当成点阴影) + center_layout.setOnClickListener(v -> { + // 什么都不做,只是阻止事件传到 outside + }); + + List appList = new ArrayList<>(); + List packages = activity.getPackageManager().getInstalledPackages(0); + for (int i = 0; i < packages.size(); i++) { + PackageInfo packageInfo = packages.get(i); + String packageName = packageInfo.applicationInfo.packageName; + if(packageName.equals(activity.getPackageName())) continue; + appList.add(new SelectAppItem(packageInfo)); + } + + SelectAppAdapter adapter = new SelectAppAdapter(R.layout.select_app_recycler_item, appList, + item -> { + popupWindow.dismiss(); + Message msg = new Message(); msg.obj = item; + selectAppCallback.sendMessage(msg); + } + ); + RecyclerView select_app_recycler_view = (RecyclerView) view.findViewById(R.id.select_app_recycler_view); + LinearLayoutManager linearLayoutManager = new LinearLayoutManager(activity); + linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL); + select_app_recycler_view.setLayoutManager(linearLayoutManager); + select_app_recycler_view.setAdapter(adapter); + TextView clear_search_btn = view.findViewById(R.id.clear_search_btn); + EditText search_edit = view.findViewById(R.id.search_edit); + CheckBox show_system_app_ckbox = view.findViewById(R.id.show_system_app_ckbox); + CheckBox show_thirty_app_ckbox = view.findViewById(R.id.show_thirty_app_ckbox); + show_system_app_ckbox.setEnabled(true); + show_thirty_app_ckbox.setEnabled(true); + @SuppressLint("HandlerLeak") Handler updateAppListFunc = new Handler() { + @Override + public void handleMessage(@NonNull Message msg) { + List newAppList = new ArrayList<>(); + String filterText = search_edit.getText().toString(); + for(SelectAppItem item : appList) { + PackageInfo pack = item.getPackageInfo(); + if(!show_system_app_ckbox.isChecked()) { + if ((pack.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) continue; //系统应用 + } + if(!show_thirty_app_ckbox.isChecked()) { + if ((pack.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) continue; // 第三方应用 + } + if(item.getPackageName().indexOf(filterText) != -1 || item.getShowName(activity).indexOf(filterText) != -1) newAppList.add(item); + } + adapter.setData(newAppList); + super.handleMessage(msg); + } + }; + search_edit.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged(CharSequence s, int start, int count, int after) {} + @Override + public void onTextChanged(CharSequence s, int start, int before, int count) { + clear_search_btn.setVisibility(s.toString().length() > 0 ? View.VISIBLE : View.GONE); + updateAppListFunc.sendMessage(new Message()); + } + @Override + public void afterTextChanged(Editable s) {} + }); + clear_search_btn.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { search_edit.setText(""); } + }); + + show_system_app_ckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { + @Override + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { updateAppListFunc.sendMessage(new Message()); } + }); + show_thirty_app_ckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { + @Override + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { updateAppListFunc.sendMessage(new Message()); } + }); + updateAppListFunc.sendMessage(new Message()); + return view; + } + +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/model/AppUpdateInfo.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/model/AppUpdateInfo.java" new file mode 100644 index 00000000..03a868a0 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/model/AppUpdateInfo.java" @@ -0,0 +1,50 @@ +package com.linux.permissionmanager.model; + +public class AppUpdateInfo { + private boolean hasNewVersion; + private String latestVer; + private String downloadUrl; + private String changelogUrl; + + public AppUpdateInfo(boolean hasNewVersion, + String latestVer, + String downloadUrl, + String changelogUrl) { + this.hasNewVersion = hasNewVersion; + this.latestVer = latestVer; + this.downloadUrl = downloadUrl; + this.changelogUrl = changelogUrl; + } + + public boolean isHasNewVersion() { + return hasNewVersion; + } + + public void setHasNewVersion(boolean hasNewVersion) { + this.hasNewVersion = hasNewVersion; + } + + public String getLatestVer() { + return latestVer; + } + + public void setLatestVer(String latestVer) { + this.latestVer = latestVer; + } + + public String getDownloadUrl() { + return downloadUrl; + } + + public void setDownloadUrl(String downloadUrl) { + this.downloadUrl = downloadUrl; + } + + public String getChangelogUrl() { + return changelogUrl; + } + + public void setChangelogUrl(String changelogUrl) { + this.changelogUrl = changelogUrl; + } +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/model/SelectAppItem.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/model/SelectAppItem.java" new file mode 100644 index 00000000..205dc4e9 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/model/SelectAppItem.java" @@ -0,0 +1,31 @@ +package com.linux.permissionmanager.model; + +import android.content.Context; +import android.content.pm.PackageInfo; +import android.graphics.drawable.Drawable; + +public class SelectAppItem { + private PackageInfo packageInfo; + + public SelectAppItem(PackageInfo packageInfo){ + this.packageInfo = packageInfo; + } + + public PackageInfo getPackageInfo() { + return packageInfo; + } + + public String getShowName(Context ctx) { + String showName = this.packageInfo.applicationInfo.loadLabel(ctx.getPackageManager()).toString(); + return showName; + } + public String getPackageName() { + String packageName = this.packageInfo.applicationInfo.packageName; + return packageName; + } + public Drawable getDrawable(Context ctx) { + Drawable icon = this.packageInfo.applicationInfo.loadIcon(ctx.getPackageManager()); + return icon; + } + +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/model/SelectFileItem.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/model/SelectFileItem.java" new file mode 100644 index 00000000..be366ef8 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/model/SelectFileItem.java" @@ -0,0 +1,34 @@ +package com.linux.permissionmanager.model; + +import android.graphics.Color; + +import java.nio.file.Path; +import java.nio.file.Paths; + +public class SelectFileItem { + private String filePath; + private String fileDesc; + private Color fileDescColor; + + public SelectFileItem(String filePath, String fileDesc, Color fileDescColor){ + this.filePath = filePath; + this.fileDesc = fileDesc; + this.fileDescColor = fileDescColor; + } + + public String getFilePath() { + return this.filePath; + } + + public String getFileName() { + Path path = Paths.get(filePath); + Path fileName = path.getFileName(); + return fileName.toString(); + } + public String getFileDesc() { + return this.fileDesc; + } + public Color getFileDescColor() { + return this.fileDescColor; + } +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/model/SkrModInstalledItem.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/model/SkrModInstalledItem.java" new file mode 100644 index 00000000..5d83b53e --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/model/SkrModInstalledItem.java" @@ -0,0 +1,122 @@ +package com.linux.permissionmanager.model; + +import android.text.TextUtils; + +public class SkrModInstalledItem { + private String name; + private String desc; + private String ver; + private String uuid; + private String author; + private String updateJson; + private String miniSdk; + private boolean webUi; + private SkrModRunState runState; + + private SkrModUpdateInfo updateInfo; + + public SkrModInstalledItem(String name, + String desc, + String ver, + String uuid, + String author, + String updateJson, + String miniSdk, + boolean webUi, + SkrModRunState runState) { + this.name = name; + this.desc = desc; + this.ver = ver; + this.uuid = uuid; + this.author = author; + this.updateJson = updateJson; + this.miniSdk = miniSdk; + this.webUi = webUi; + this.runState = runState == null ? SkrModRunState.NOT_RUNNING : runState; + this.updateInfo = null; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public String getVer() { + return ver; + } + + public void setVer(String ver) { + this.ver = ver; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getUpdateJson() { + return updateJson; + } + + public void setUpdateJson(String updateJson) { + this.updateJson = updateJson; + } + + public String getMiniSdk() { + return miniSdk; + } + + public void setMiniSdk(String miniSdk) { + this.miniSdk = miniSdk; + } + + public boolean isWebUi() { + return webUi; + } + + public void setWebUi(boolean webUi) { + this.webUi = webUi; + } + + public SkrModRunState getRunState() { + return runState; + } + + public void setRunState(SkrModRunState runState) { + this.runState = runState; + } + + public SkrModUpdateInfo getUpdateInfo() { + return updateInfo; + } + + public void setUpdateInfo(SkrModUpdateInfo updateInfo) { + this.updateInfo = updateInfo; + } + + public boolean hasChangelog() { + return updateInfo != null && !TextUtils.isEmpty(updateInfo.getChangelogUrl()); + } +} \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/model/SkrModMarketItem.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/model/SkrModMarketItem.java" new file mode 100644 index 00000000..bd913e8e --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/model/SkrModMarketItem.java" @@ -0,0 +1,117 @@ +package com.linux.permissionmanager.model; + +public class SkrModMarketItem { + private String chnName; + private String engName; + private String desc; + private String ver; + private String uuid; + private String author; + private String updateDate; + private String sourceUrl; + private String downloadUrl; + private String downloadChnAlert; + private String downloadEngAlert; + + public String getChnName() { + return chnName; + } + + public void setChnName(String chnName) { + this.chnName = chnName; + } + + public String getEngName() { + return engName; + } + + public void setEngName(String engName) { + this.engName = engName; + } + + public String getDesc() { + return desc; + } + + public void setDesc(String desc) { + this.desc = desc; + } + + public String getVer() { + return ver; + } + + public void setVer(String ver) { + this.ver = ver; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public String getUpdateDate() { + return updateDate; + } + + public void setUpdateDate(String updateDate) { + this.updateDate = updateDate; + } + + public String getSourceUrl() { + return sourceUrl; + } + + public void setSourceUrl(String sourceUrl) { + this.sourceUrl = sourceUrl; + } + + public String getDownloadUrl() { + return downloadUrl; + } + + public void setDownloadUrl(String downloadUrl) { + this.downloadUrl = downloadUrl; + } + + public String getDownloadChnAlert() { + return downloadChnAlert; + } + + public void setDownloadChnAlert(String downloadChnAlert) { + this.downloadChnAlert = downloadChnAlert; + } + + public String getDownloadEngAlert() { + return downloadEngAlert; + } + + public void setDownloadEngAlert(String downloadEngAlert) { + this.downloadEngAlert = downloadEngAlert; + } + + public SkrModMarketItem(String chnName, String engName, String desc, String ver, String uuid, String author, String updateDate, String sourceUrl, String downloadUrl, String downloadChnAlert, String downloadEngAlert) { + this.chnName = chnName; + this.engName = engName; + this.desc = desc; + this.ver = ver; + this.uuid = uuid; + this.author = author; + this.updateDate = updateDate; + this.sourceUrl = sourceUrl; + this.downloadUrl = downloadUrl; + this.downloadChnAlert = downloadChnAlert; + this.downloadEngAlert = downloadEngAlert; + } +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/model/SkrModRunState.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/model/SkrModRunState.java" new file mode 100644 index 00000000..62de245f --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/model/SkrModRunState.java" @@ -0,0 +1,7 @@ +package com.linux.permissionmanager.model; + +public enum SkrModRunState { + NOT_RUNNING, + RUNNING, + ABNORMAL +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/model/SkrModUpdateInfo.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/model/SkrModUpdateInfo.java" new file mode 100644 index 00000000..e4079e2b --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/model/SkrModUpdateInfo.java" @@ -0,0 +1,50 @@ +package com.linux.permissionmanager.model; + +public class SkrModUpdateInfo { + private boolean hasNewVersion; + private String latestVer; + private String downloadUrl; + private String changelogUrl; + + public SkrModUpdateInfo(boolean hasNewVersion, + String latestVer, + String downloadUrl, + String changelogUrl) { + this.hasNewVersion = hasNewVersion; + this.latestVer = latestVer; + this.downloadUrl = downloadUrl; + this.changelogUrl = changelogUrl; + } + + public boolean isHasNewVersion() { + return hasNewVersion; + } + + public void setHasNewVersion(boolean hasNewVersion) { + this.hasNewVersion = hasNewVersion; + } + + public String getLatestVer() { + return latestVer; + } + + public void setLatestVer(String latestVer) { + this.latestVer = latestVer; + } + + public String getDownloadUrl() { + return downloadUrl; + } + + public void setDownloadUrl(String downloadUrl) { + this.downloadUrl = downloadUrl; + } + + public String getChangelogUrl() { + return changelogUrl; + } + + public void setChangelogUrl(String changelogUrl) { + this.changelogUrl = changelogUrl; + } +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/model/SuAuthItem.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/model/SuAuthItem.java" new file mode 100644 index 00000000..c9af7cf0 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/model/SuAuthItem.java" @@ -0,0 +1,40 @@ +package com.linux.permissionmanager.model; + +import android.graphics.drawable.Drawable; + +public class SuAuthItem { + private Drawable icon; + private String appName; + private String appPackageName; + + public SuAuthItem(Drawable icon, String appName, String appPackageName) { + this.icon = icon; + this.appName = appName; + this.appPackageName = appPackageName; + } + + public Drawable getIcon() { + return icon; + } + + public void setIcon(Drawable icon) { + this.icon = icon; + } + + public String getAppName() { + return appName; + } + + public void setAppName(String appName) { + this.appName = appName; + } + + public String getAppPackageName() { + return appPackageName; + } + + public void setAppPackageName(String appPackageName) { + this.appPackageName = appPackageName; + } + +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/page/SkrModInstalledPage.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/page/SkrModInstalledPage.java" new file mode 100644 index 00000000..aa49cbe0 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/page/SkrModInstalledPage.java" @@ -0,0 +1,275 @@ +package com.linux.permissionmanager.page; + +import android.app.Activity; +import android.content.Intent; +import android.net.Uri; +import android.text.TextUtils; +import android.util.Log; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.PopupMenu; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.recyclerview.widget.SimpleItemAnimator; + +import com.linux.permissionmanager.ActivityResultId; +import com.linux.permissionmanager.R; +import com.linux.permissionmanager.adapter.SkrModInstalledAdapter; +import com.linux.permissionmanager.adapter.SkrModPrinter; +import com.linux.permissionmanager.bridge.NativeBridge; +import com.linux.permissionmanager.model.SkrModInstalledItem; +import com.linux.permissionmanager.model.SkrModRunState; +import com.linux.permissionmanager.model.SkrModUpdateInfo; +import com.linux.permissionmanager.update.SkrModDownloader; +import com.linux.permissionmanager.update.SkrModInstaller; +import com.linux.permissionmanager.update.SkrModUpdateChecker; +import com.linux.permissionmanager.utils.DialogUtils; +import com.linux.permissionmanager.utils.FileUtils; +import com.linux.permissionmanager.utils.GetSdcardPermissionsHelper; + +import org.json.JSONArray; +import org.json.JSONObject; + +import java.io.File; +import java.net.URLDecoder; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +public class SkrModInstalledPage { + private Activity mActivity; + private String mRootKey = ""; + + private RecyclerView mSkrModInstalledRecyclerView; + private TextView mTextEmptyTips; + + private SkrModInstalledAdapter mAdapter; + private SkrModUpdateChecker mUpdateManager; + + public SkrModInstalledPage(Activity activity, String rootKey) { + mActivity = activity; + mRootKey = rootKey; + } + + public void bindPage(@NonNull View view) { + mSkrModInstalledRecyclerView = view.findViewById(R.id.skr_mod_installed_recycler_view); + mTextEmptyTips = view.findViewById(R.id.empty_tips_tv); + + mUpdateManager = new SkrModUpdateChecker(mActivity); + setupSkrModRecyclerView(); + } + + public void refreshPage() { setupSkrModRecyclerView(); } + + private Set queryModuleUuidSet(boolean runningOnly, boolean abnormalOnly) { + String json = NativeBridge.getSkrootModuleList(mRootKey, runningOnly, abnormalOnly); + List list = parseSkrModList(json); + if (list == null || list.isEmpty()) return Collections.emptySet(); + return list.stream().map(SkrModInstalledItem::getUuid).filter(Objects::nonNull).collect(Collectors.toSet()); + } + + private void setupSkrModRecyclerView() { + String jsonAll = NativeBridge.getSkrootModuleList(mRootKey, false, false); + List listAll = parseSkrModList(jsonAll); + + if (listAll != null && !listAll.isEmpty()) { + Set runningUuids = queryModuleUuidSet(true, false); + Set abnormalUuids = queryModuleUuidSet(false, true); + for (SkrModInstalledItem it : listAll) { + String uuid = it.getUuid(); + if (uuid == null) continue; + if (abnormalUuids.contains(uuid)) it.setRunState(SkrModRunState.ABNORMAL); + else if (runningUuids.contains(uuid)) it.setRunState(SkrModRunState.RUNNING); + } + } + mAdapter = new SkrModInstalledAdapter(listAll, new SkrModInstalledAdapter.OnItemClickListener() { + @Override + public void onOpenWebUIBtnClick(View v, SkrModInstalledItem skrmod) { onOpenSkrModWebUI(skrmod); } + @Override + public void onNewVersionBtnClick(View v, SkrModInstalledItem skrmod) { onUpdateSkrMod(skrmod); } + @Override + public void onMoreBtnClick(View v, SkrModInstalledItem skrmod) { showSkrModItemPopupMenu(v, skrmod); } + }); + mSkrModInstalledRecyclerView.setAdapter(mAdapter); + mSkrModInstalledRecyclerView.setLayoutManager(new LinearLayoutManager(mActivity)); + mSkrModInstalledRecyclerView.setVisibility(listAll.size() == 0 ? View.GONE : View.VISIBLE); + mTextEmptyTips.setVisibility(listAll.size() == 0 ? View.VISIBLE : View.GONE); + RecyclerView.ItemAnimator animator = mSkrModInstalledRecyclerView.getItemAnimator(); + if (animator instanceof SimpleItemAnimator) ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false); + checkAllModulesUpdate(listAll); + } + + private List parseSkrModList(String jsonStr) { + List list = new ArrayList<>(); + try { + JSONArray jsonArray = new JSONArray(jsonStr); + for (int i = 0; i < jsonArray.length(); i++) { + JSONObject jsonObject = jsonArray.getJSONObject(i); + String name = URLDecoder.decode(jsonObject.getString("name"), "UTF-8"); + String ver = URLDecoder.decode(jsonObject.getString("ver"), "UTF-8"); + String desc = URLDecoder.decode(jsonObject.getString("desc"), "UTF-8"); + String author = URLDecoder.decode(jsonObject.getString("author"), "UTF-8"); + String uuid = URLDecoder.decode(jsonObject.getString("uuid"), "UTF-8"); + String update_json = URLDecoder.decode(jsonObject.getString("update_json"), "UTF-8"); + boolean web_ui = jsonObject.getBoolean("web_ui"); + String min_sdk_ver = URLDecoder.decode(jsonObject.getString("min_sdk_ver"), "UTF-8"); + SkrModInstalledItem e = new SkrModInstalledItem(name, desc, ver, uuid, author, update_json, min_sdk_ver, web_ui, null); + list.add(e); + } + } catch (Exception e) { + DialogUtils.showMsgDlg(mActivity, "发生错误", jsonStr, null); + e.printStackTrace(); + } + return list; + } + + private void showSkrModItemPopupMenu(View v, SkrModInstalledItem skrMod) { + PopupMenu popupMenu = new PopupMenu(mActivity, v); + Menu menu = popupMenu.getMenu(); + popupMenu.getMenuInflater().inflate(R.menu.popup_skr_mod_installed_item_menu, menu); + + // 是否显示“更新”菜单 + MenuItem updateItem = menu.findItem(R.id.update); + updateItem.setVisible(skrMod.getUpdateJson().length() > 0); + + // 是否显示“更新日志”菜单 + MenuItem changelogItem = menu.findItem(R.id.changelog); + changelogItem.setVisible(updateItem.isVisible()); + changelogItem.setEnabled(skrMod.hasChangelog()); + + popupMenu.setOnMenuItemClickListener(item -> { + int itemId = item.getItemId(); + if (itemId == R.id.del) onDeleteSkrMod(skrMod); + else if (itemId == R.id.update) onUpdateSkrMod(skrMod); + else if (itemId == R.id.changelog) onDownloadChangeLogSkrMod(skrMod); + else if (itemId == R.id.details) onShowDetailsSkrMod(skrMod); + return true; + }); + popupMenu.show(); + } + + private void onAddSkrMod(String zipFilePath) { + SkrModInstaller.installFromZip(mActivity, mRootKey, zipFilePath); + refreshPage(); + } + + private void onDeleteSkrMod(SkrModInstalledItem skrMod) { + DialogUtils.showCustomDialog(mActivity, "确认", "确定要删除 " + skrMod.getName() + " 模块吗?", null, "确定", + (dialog, which) -> { + dialog.dismiss(); + String tip = NativeBridge.uninstallSkrootModule(mRootKey, skrMod.getUuid()); + if(tip.indexOf("OK") != -1) tip += ",重启后生效"; + DialogUtils.showMsgDlg(mActivity, "执行结果", tip, null); + refreshPage(); + }, + "取消", (dialog, which) -> dialog.dismiss() + ); + } + + private void onShowDetailsSkrMod(SkrModInstalledItem skrMod) { + String details = SkrModPrinter.buildModuleMeta(skrMod); + DialogUtils.showLogDialog(mActivity, details); + } + + private void onOpenSkrModWebUI(SkrModInstalledItem skrMod) { + String tip = NativeBridge.openSkrootModuleWebUI(mRootKey, skrMod.getUuid()); + DialogUtils.showMsgDlg(mActivity, "执行结果", tip, null); + } + + private void onUpdateSkrMod(SkrModInstalledItem skrMod) { + mUpdateManager.requestModuleUpdate( + skrMod, + (item, info) -> { + if (info != null) mAdapter.updateModuleUpdateInfo(item.getUuid(), info); + if (info == null || !info.isHasNewVersion()) { + DialogUtils.showMsgDlg(mActivity, "提示", "当前已是最新版本", null); + return; + } + String message = "检测到新版本:" + info.getLatestVer() + "\n\n是否下载并更新该模块?"; + DialogUtils.showCustomDialog(mActivity,"模块更新", message,null,"立即更新", (dialog, which) -> { + dialog.dismiss(); + onDownloadNewSkrMod(item, info); + },"取消", (dialog, which) -> dialog.dismiss()); + }, + (item, e) -> DialogUtils.showMsgDlg(mActivity,"提示","检查模块 \"" + item.getName() + "\" 更新失败:" + e.getMessage(),null) + ); + } + + private void onDownloadChangeLogSkrMod(SkrModInstalledItem skrMod) { + mUpdateManager.requestModuleChangelog(skrMod, + (item, content) -> DialogUtils.showLogDialog(mActivity, content), + (item, e) -> DialogUtils.showMsgDlg(mActivity,"提示", "下载模块 \"" + item.getName() + "\" 的更新日志失败:" + e.getMessage(),null) + ); + } + + private void checkAllModulesUpdate(List listAll) { + if (listAll == null || listAll.isEmpty()) return; + mUpdateManager.checkAllModulesUpdate( + listAll, + (mod, info) -> { + if (info != null && mAdapter != null) mAdapter.updateModuleUpdateInfo(mod.getUuid(), info); + }, + (mod, e) -> Log.w("SkrMod", "check update failed: " + mod.getName(), e) + ); + } + + private void onDownloadNewSkrMod(SkrModInstalledItem skrMod, SkrModUpdateInfo updateInfo) { + String url = updateInfo.getDownloadUrl(); + if (TextUtils.isEmpty(url)) { + DialogUtils.showMsgDlg(mActivity, "提示","模块 \"" + skrMod.getName() + "\" 未提供下载地址。", null); + return; + } + SkrModDownloader downloader = new SkrModDownloader(mActivity); + downloader.downloadToCache(url, skrMod.getUuid() + "_" + updateInfo.getLatestVer() + ".zip", SkrModDownloader.AutoDelete.ON_BOTH, + new SkrModDownloader.Callback() { + @Override + public void onSuccess(File file) { onAddSkrMod(file.getAbsolutePath()); } + @Override + public void onError(Exception e) { + DialogUtils.showMsgDlg(mActivity, "下载失败", e != null ? e.getMessage() : "未知错误", null); + } + }); + } + + public void showSkrModMainPopupMenu(View v) { + PopupMenu popupMenu = new PopupMenu(mActivity, v); + popupMenu.getMenuInflater().inflate(R.menu.popup_skr_mod_main_menu, popupMenu.getMenu()); + popupMenu.setOnMenuItemClickListener(item -> { + int itemId = item.getItemId(); + if (itemId == R.id.add_skr_mod) chooseFile(); + return true; + }); + popupMenu.show(); + } + + private void chooseFile() { + if(!GetSdcardPermissionsHelper.getPermissions(mActivity, mActivity, mActivity.getPackageName())) { + DialogUtils.showNeedPermissionDialog(mActivity); + return; + } + Intent intent = new Intent(Intent.ACTION_GET_CONTENT); + intent.setType("application/zip"); + mActivity.startActivityForResult(intent, ActivityResultId.REQUEST_CODE_CHOOSE_FILE); + } + + public void onChooseFileActivityResult(int requestCode, int resultCode, Intent data) { + if (requestCode == ActivityResultId.REQUEST_CODE_CHOOSE_FILE && resultCode == Activity.RESULT_OK) { + Uri uri = data.getData(); + String filePath = FileUtils.getRealPathFromURI(mActivity, uri); + if (filePath == null) { + Log.e("SkrModFragment", "Invalid file path"); + return; + } + onAddSkrMod(filePath); + } + } + + +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/page/SkrModMarketPage.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/page/SkrModMarketPage.java" new file mode 100644 index 00000000..a0f34853 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/page/SkrModMarketPage.java" @@ -0,0 +1,263 @@ +package com.linux.permissionmanager.page; + +import android.app.Activity; +import android.content.DialogInterface; +import android.text.Editable; +import android.text.TextUtils; +import android.text.TextWatcher; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.Button; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.PopupMenu; +import android.widget.TextView; + +import androidx.annotation.NonNull; +import androidx.appcompat.app.AlertDialog; +import androidx.recyclerview.widget.LinearLayoutManager; +import androidx.recyclerview.widget.RecyclerView; +import androidx.recyclerview.widget.SimpleItemAnimator; + +import com.linux.permissionmanager.R; +import com.linux.permissionmanager.adapter.SkrModMarketAdapter; +import com.linux.permissionmanager.bridge.NativeBridge; +import com.linux.permissionmanager.model.SkrModInstalledItem; +import com.linux.permissionmanager.model.SkrModMarketItem; +import com.linux.permissionmanager.update.SkrModDownloader; +import com.linux.permissionmanager.update.SkrModInstaller; +import com.linux.permissionmanager.utils.DialogUtils; +import com.linux.permissionmanager.utils.NetUtils; +import com.linux.permissionmanager.utils.UrlIntentUtils; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.File; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.function.Consumer; + +public class SkrModMarketPage { + private Activity mActivity; + private String mRootKey = ""; + + private final String marketJsonUrl = "https://abcz316.github.io/SKRoot-linuxKernelRoot/skroot_pro_app/module_market.json"; + + private EditText mSearchEdit; + private RecyclerView mSkrModMarketRecyclerView; + private TextView mTextLoadingTips; + private LinearLayout mErrorContainer; + private Button mBtnRetry; + + private List mModList = new ArrayList<>(); + + private SkrModMarketAdapter mAdapter; + + public SkrModMarketPage(Activity activity, String rootKey) { + mActivity = activity; + mRootKey = rootKey; + } + + public void bindPage(@NonNull View view) { + mSearchEdit = view.findViewById(R.id.market_search_edit); + mSearchEdit.addTextChangedListener(new TextWatcher() { + @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {} + @Override public void onTextChanged(CharSequence s, int start, int before, int count) {} + @Override + public void afterTextChanged(Editable s) { + applyFilter(s == null ? "" : s.toString()); + } + }); + + mSkrModMarketRecyclerView = view.findViewById(R.id.skr_mod_market_recycler_view); + mTextLoadingTips = view.findViewById(R.id.loading_tips_tv); + mErrorContainer = view.findViewById(R.id.error_container); + mBtnRetry = view.findViewById(R.id.btn_retry); + mBtnRetry.setOnClickListener(v -> initMarketList()); + initMarketList(); + } + + public void refreshPage() { setupSkrModRecyclerView(mModList); } + + private void setupSkrModRecyclerView(List list) { + mAdapter = new SkrModMarketAdapter(list, new SkrModMarketAdapter.OnItemClickListener() { + @Override + public void onActionsBtnClick(View v, SkrModMarketItem skrmod) { showSkrModItemPopupMenu(v, skrmod); } + }); + mSkrModMarketRecyclerView.setAdapter(mAdapter); + mSkrModMarketRecyclerView.setLayoutManager(new LinearLayoutManager(mActivity)); + mSkrModMarketRecyclerView.setVisibility(list.size() == 0 ? View.GONE : View.VISIBLE); + RecyclerView.ItemAnimator animator = mSkrModMarketRecyclerView.getItemAnimator(); + if (animator instanceof SimpleItemAnimator) ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false); + } + + private void onAddSkrMod(String zipFilePath) { + SkrModInstaller.installFromZip(mActivity, mRootKey, zipFilePath); + refreshPage(); + } + + private void downloadAndInstallModule(SkrModMarketItem skrMod) { + String url = skrMod.getDownloadUrl(); + if (TextUtils.isEmpty(url)) return; + SkrModDownloader downloader = new SkrModDownloader(mActivity); + downloader.downloadToCache(url, skrMod.getUuid() + "_" + skrMod.getVer() + ".zip", SkrModDownloader.AutoDelete.ON_BOTH, + new SkrModDownloader.Callback() { + @Override + public void onSuccess(File file) { onAddSkrMod(file.getAbsolutePath()); } + @Override + public void onError(Exception e) { + DialogUtils.showMsgDlg(mActivity, "下载失败", e != null ? e.getMessage() : "未知错误", null); + } + }); + } + + private void showSelectDownloadDlg(SkrModMarketItem skrMod) { + final String[] items = {"1.自动下载并安装(推荐)", "2.浏览器手动下载"}; + AlertDialog.Builder builder = new AlertDialog.Builder(mActivity); + builder.setTitle("选择下载方式"); + builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + if(which == 0) downloadAndInstallModule(skrMod); + else if(which == 1) UrlIntentUtils.openUrl(mActivity, skrMod.getDownloadUrl()); + } + }); + builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } + }); + AlertDialog dialog = builder.create(); + dialog.show(); + } + + private void showDownloadConfirmDlg(SkrModMarketItem skrMod) { + if(TextUtils.isEmpty(skrMod.getDownloadChnAlert())) { showSelectDownloadDlg(skrMod); return; } + DialogUtils.showCustomDialog(mActivity, "提示", skrMod.getDownloadChnAlert(), null, "确认", + (dialog, which) -> { + dialog.dismiss(); + showSelectDownloadDlg(skrMod); + }, + "取消", (dialog, which) -> { + dialog.dismiss(); + } + ); + } + + private void showSkrModItemPopupMenu(View v, SkrModMarketItem skrMod) { + PopupMenu popupMenu = new PopupMenu(mActivity, v); + Menu menu = popupMenu.getMenu(); + popupMenu.getMenuInflater().inflate(R.menu.popup_skr_mod_market_item_menu, menu); + + // 是否显示“查看源代码”菜单 + MenuItem sourceItem = menu.findItem(R.id.source); + sourceItem.setVisible(!TextUtils.isEmpty(skrMod.getSourceUrl())); + + popupMenu.setOnMenuItemClickListener(item -> { + int itemId = item.getItemId(); + if (itemId == R.id.download) showDownloadConfirmDlg(skrMod); + else if (itemId == R.id.source) UrlIntentUtils.openUrl(mActivity, skrMod.getSourceUrl()); + return true; + }); + popupMenu.show(); + } + + private void initMarketList() { + mTextLoadingTips.setVisibility(View.VISIBLE); + mErrorContainer.setVisibility(View.GONE); + requestMarketJson( + (modArr) -> { + mTextLoadingTips.setVisibility(View.GONE); + if (modArr != null && modArr.size() > 0) mModList = modArr; + setupSkrModRecyclerView(mModList); + }, (e) -> { + mTextLoadingTips.setVisibility(View.GONE); + mErrorContainer.setVisibility(View.VISIBLE); + setupSkrModRecyclerView(mModList); + } + ); + } + + private void requestMarketJson(Consumer> onSuccessUi, Consumer onErrorUi) { + NetUtils.downloadText(marketJsonUrl, new NetUtils.TextDownloadCallback() { + @Override + public void onSuccess(String content) { + try { + List modArr = parseMarketJson(content); + if (onSuccessUi != null) mActivity.runOnUiThread(() -> onSuccessUi.accept(modArr)); + } catch (Exception e) { onError(e); } + } + @Override + public void onError(Exception e) { + if (onErrorUi != null) mActivity.runOnUiThread(() -> onErrorUi.accept(e)); + } + }); + } + + private List parseMarketJson(String jsonStr) throws JSONException { + if (jsonStr == null || jsonStr.trim().isEmpty()) return Collections.emptyList(); + + JSONObject root = new JSONObject(jsonStr); + JSONArray list = root.optJSONArray("module_list"); + if (list == null || list.length() == 0) return Collections.emptyList(); + + List result = new ArrayList<>(list.length()); + for (int i = 0; i < list.length(); i++) { + JSONObject it = list.optJSONObject(i); + if (it == null) continue; + String chnName = it.optString("chn_name", ""); + String engName = it.optString("eng_name", ""); + String desc = it.optString("desc", ""); + String ver = it.optString("ver", ""); + String uuid = it.optString("uuid", ""); + String author = it.optString("author", ""); + String updateDate = it.optString("update_date", ""); + String sourceUrl = it.optString("source_url", ""); + String downloadUrl = it.optString("download_url", ""); + String downloadChnAlert = it.optString("download_chn_alert", ""); + String downloadEngAlert = it.optString("download_eng_alert", ""); + result.add(new SkrModMarketItem( + chnName, + engName, + desc, + ver, + uuid, + author, + updateDate, + sourceUrl, + downloadUrl, + downloadChnAlert, + downloadEngAlert + )); + } + return result; + } + + private void applyFilter(String key) { + if (mAdapter == null || mModList.size() == 0) return; + String k = key == null ? "" : key.trim().toLowerCase(); + List out = new ArrayList<>(); + if (k.isEmpty()) out.addAll(mModList); + else { + for (SkrModMarketItem it : mModList) { + if (match(it, k)) out.add(it); + } + } + mAdapter.setData(out); + } + + private boolean match(SkrModMarketItem it, String k) { + return contains(it.getChnName(), k) + || contains(it.getEngName(), k) + || contains(it.getAuthor(), k) + || contains(it.getDesc(), k) + || contains(it.getUuid(), k) + || contains(it.getVer(), k); + } + + private boolean contains(String s, String k) { return s != null && s.toLowerCase().contains(k); } +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/update/AppUpdateManager.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/update/AppUpdateManager.java" new file mode 100644 index 00000000..c4ac62eb --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/update/AppUpdateManager.java" @@ -0,0 +1,82 @@ +package com.linux.permissionmanager.update; + +import android.app.Activity; +import android.text.TextUtils; + +import com.linux.permissionmanager.BuildConfig; +import com.linux.permissionmanager.model.AppUpdateInfo; +import com.linux.permissionmanager.utils.NetUtils; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.function.Consumer; + +public class AppUpdateManager { + + private final Activity activity; + private final String updateJsonUrl = "https://abcz316.github.io/SKRoot-linuxKernelRoot/skroot_pro_app/update.json"; + + public AppUpdateManager(Activity activity) { + this.activity = activity; + } + + /** + * 主工程 App:请求更新信息(在子线程下载,回调已切回 UI 线程) + */ + public void requestAppUpdate(Consumer onSuccessUi, Consumer onErrorUi) { + NetUtils.downloadText(updateJsonUrl, new NetUtils.TextDownloadCallback() { + @Override + public void onSuccess(String content) { + try { + AppUpdateInfo updateInfo = parseAppUpdateJson(content, BuildConfig.VERSION_NAME); + if (onSuccessUi != null) activity.runOnUiThread(() -> onSuccessUi.accept(updateInfo)); + } catch (Exception e) { onError(e); } + } + + @Override + public void onError(Exception e) { + if (onErrorUi != null) activity.runOnUiThread(() -> onErrorUi.accept(e)); + } + }); + } + + /** + * 主工程 App:请求更新日志内容 + */ + public void requestAppChangelog(AppUpdateInfo updateInfo, Consumer onSuccessUi, Consumer onErrorUi) { + if (updateInfo == null) { + if (onErrorUi != null) activity.runOnUiThread(() -> onErrorUi.accept(new IllegalStateException("updateInfo is null"))); + return; + } + + String url = updateInfo.getChangelogUrl(); + if (TextUtils.isEmpty(url)) { + if (onErrorUi != null) activity.runOnUiThread(() -> onErrorUi.accept(new IllegalStateException("changelogUrl is empty"))); + return; + } + + NetUtils.downloadText(url, new NetUtils.TextDownloadCallback() { + @Override + public void onSuccess(String content) { + if (onSuccessUi != null) activity.runOnUiThread(() -> onSuccessUi.accept(content)); + } + + @Override + public void onError(Exception e) { + if (onErrorUi != null) activity.runOnUiThread(() -> onErrorUi.accept(e)); + } + }); + } + + private AppUpdateInfo parseAppUpdateJson(String jsonStr, String currentVersion) throws JSONException { + if (jsonStr == null || jsonStr.trim().isEmpty()) return null; + JSONObject obj = new JSONObject(jsonStr); + String latestVer = obj.optString("version", ""); + String downloadUrl = obj.optString("appUrl", ""); + String changelogUrl = obj.optString("changelog", ""); + if (latestVer.isEmpty() || downloadUrl.isEmpty()) return null; + boolean hasNew = !latestVer.equals(currentVersion); + return new AppUpdateInfo(hasNew, latestVer, downloadUrl, changelogUrl); + } +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/update/SkrModDownloader.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/update/SkrModDownloader.java" new file mode 100644 index 00000000..a6abe849 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/update/SkrModDownloader.java" @@ -0,0 +1,155 @@ +package com.linux.permissionmanager.update; + +import android.app.Activity; +import android.net.Uri; +import android.text.TextUtils; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; + +import com.linux.permissionmanager.utils.DownloadDialogHelper; +import com.linux.permissionmanager.utils.FileUtils; + +import java.io.File; + +public class SkrModDownloader { + + public interface Callback { + void onSuccess(@NonNull File file); + void onError(@NonNull Exception e); + } + + /** 自动删除策略 */ + public enum AutoDelete { + NONE, // 不自动删 + ON_ERROR, // 失败自动删 + ON_SUCCESS, // 成功回调后自动删 + ON_BOTH // 成功/失败都自动删 + } + + private final Activity mActivity; + + public SkrModDownloader(@NonNull Activity activity) { + this.mActivity = activity; + } + + // ---------------- public API ---------------- + + /** 默认:不自动删 */ + public void downloadToCache(@NonNull String url, @Nullable String fileNameHint, @Nullable Callback cb) { + downloadToCache(url, fileNameHint, AutoDelete.NONE, cb); + } + + /** 支持自动删除策略 */ + public void downloadToCache(@NonNull String url, @Nullable String fileNameHint, @NonNull AutoDelete autoDelete, @Nullable Callback cb) { + if (TextUtils.isEmpty(url)) { + postError(cb, new IllegalArgumentException("url is empty")); + return; + } + + File dir = getDefaultCacheDir(); + if (!ensureDir(dir)) { + postError(cb, new IllegalStateException("create cache dir failed: " + dir.getAbsolutePath())); + return; + } + + String fileName = buildFileName(url, fileNameHint); + File destFile = new File(dir, fileName); + downloadToFile(url, destFile, autoDelete, cb); + } + + /** 下载到指定文件(默认不自动删) */ + public void downloadToFile(@NonNull String url, @NonNull File destFile, @Nullable Callback cb) { + downloadToFile(url, destFile, AutoDelete.NONE, cb); + } + + /** 下载到指定文件(支持自动删) */ + public void downloadToFile(@NonNull String url, @NonNull File destFile, @NonNull AutoDelete autoDelete, @Nullable Callback cb) { + if (TextUtils.isEmpty(url)) { + postError(cb, new IllegalArgumentException("url is empty")); + return; + } + File parent = destFile.getParentFile(); + if (parent != null && !ensureDir(parent)) { + postError(cb, new IllegalStateException("create dest dir failed: " + parent.getAbsolutePath())); + return; + } + + DownloadDialogHelper.startDownloadWithDialog(mActivity, url, destFile, + new DownloadDialogHelper.DownloadResultCallback() { + @Override + public void onSuccess(File file) { + final File out = (file != null) ? file : destFile; + mActivity.runOnUiThread(() -> { + try { + if (cb != null) cb.onSuccess(out); + } finally { + if (autoDelete == AutoDelete.ON_SUCCESS || autoDelete == AutoDelete.ON_BOTH) { + safeDelete(out); + } + } + }); + } + + @Override + public void onError(Exception e) { + final Exception ex = (e != null) ? e : new RuntimeException("download failed: unknown error"); + mActivity.runOnUiThread(() -> { + try { + if (cb != null) cb.onError(ex); + } finally { + if (autoDelete == AutoDelete.ON_ERROR || autoDelete == AutoDelete.ON_BOTH) { + safeDelete(destFile); + } + } + }); + } + } + ); + } + + // ---------------- internal ---------------- + + private File getDefaultCacheDir() { + return new File(mActivity.getCacheDir(), "skrmods"); + } + + private boolean ensureDir(@NonNull File dir) { + if (dir.exists()) return dir.isDirectory(); + return dir.mkdirs(); + } + + private String buildFileName(@NonNull String url, @Nullable String fileNameHint) { + if (!TextUtils.isEmpty(fileNameHint)) return sanitizeFileName(fileNameHint); + + try { + Uri uri = Uri.parse(url); + String last = uri.getLastPathSegment(); + if (!TextUtils.isEmpty(last)) return sanitizeFileName(last); + } catch (Exception ignored) {} + + return "skrmod_" + System.currentTimeMillis() + ".zip"; + } + + private String sanitizeFileName(@NonNull String name) { + String n = name.trim(); + if (n.isEmpty()) return "skrmod_" + System.currentTimeMillis() + ".zip"; + n = n.replaceAll("[\\\\/:*?\"<>|]", "_"); + return n; + } + + private void safeDelete(@NonNull File f) { + try { + FileUtils.deleteFile(f); + } catch (Throwable t) { + try { + f.delete(); + } catch (Throwable ignored) {} + } + } + + private void postError(@Nullable Callback cb, @NonNull Exception e) { + if (cb == null) return; + mActivity.runOnUiThread(() -> cb.onError(e)); + } +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/update/SkrModInstaller.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/update/SkrModInstaller.java" new file mode 100644 index 00000000..e5ec831a --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/update/SkrModInstaller.java" @@ -0,0 +1,28 @@ +package com.linux.permissionmanager.update; + +import android.app.Activity; +import android.net.Uri; +import android.text.TextUtils; +import android.util.Log; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; + +import com.linux.permissionmanager.bridge.NativeBridge; +import com.linux.permissionmanager.utils.DialogUtils; +import com.linux.permissionmanager.utils.DownloadDialogHelper; +import com.linux.permissionmanager.utils.FileUtils; + +import java.io.File; + +public class SkrModInstaller { + public static void installFromZip(Activity activity, String rootKey, String zipFilePath) { + Log.d("SkrModFragment", "Add skr module file path: " + zipFilePath); + String tip = NativeBridge.installSkrootModule(rootKey, zipFilePath); + if(tip.indexOf("OK") != -1) tip += ",重启后生效"; + if(tip.indexOf("ERR_MODULE_REQUIRE_MIN_SDK") != -1) tip += ",当前SKRoot环境版本太低,请先升级SKRoot"; + if(tip.indexOf("ERR_MODULE_SDK_TOO_OLD") != -1) tip += ",该模块SDK版本太低,已不支持安装"; + DialogUtils.showMsgDlg(activity, "执行结果", tip, null); + } + +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/update/SkrModUpdateChecker.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/update/SkrModUpdateChecker.java" new file mode 100644 index 00000000..4c37a357 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/update/SkrModUpdateChecker.java" @@ -0,0 +1,136 @@ +package com.linux.permissionmanager.update; + +import android.app.Activity; +import android.text.TextUtils; +import android.util.Log; + +import com.linux.permissionmanager.model.SkrModInstalledItem; +import com.linux.permissionmanager.model.SkrModUpdateInfo; +import com.linux.permissionmanager.utils.NetUtils; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.List; +import java.util.function.BiConsumer; + +public class SkrModUpdateChecker { + + private final Activity activity; + + public SkrModUpdateChecker(Activity activity) { + this.activity = activity; + } + + /** + * 单个模块:请求更新信息(在子线程下载,回调已切回 UI 线程) + */ + public void requestModuleUpdate( + SkrModInstalledItem item, + BiConsumer onSuccessUi, + BiConsumer onErrorUi + ) { + if (item == null) return; + + String updateUrl = item.getUpdateJson(); + if (TextUtils.isEmpty(updateUrl)) { + // 没有配置更新地址,直接回调「无更新信息」 + if (onSuccessUi != null) activity.runOnUiThread(() -> onSuccessUi.accept(item, null)); + return; + } + + NetUtils.downloadText(updateUrl, new NetUtils.TextDownloadCallback() { + @Override + public void onSuccess(String content) { + try { + SkrModUpdateInfo updateInfo = parse(content, item.getVer()); + if (onSuccessUi != null) activity.runOnUiThread(() -> onSuccessUi.accept(item, updateInfo)); + } catch (Exception e) { + onError(e); + } + } + + @Override + public void onError(Exception e) { + if (onErrorUi != null) activity.runOnUiThread(() -> onErrorUi.accept(item, e)); + } + }); + } + + /** + * 单个模块:请求更新日志内容 + */ + public void requestModuleChangelog( + SkrModInstalledItem item, + BiConsumer onSuccessUi, + BiConsumer onErrorUi + ) { + if (item == null || item.getUpdateInfo() == null) { + if (onErrorUi != null) activity.runOnUiThread(() -> onErrorUi.accept(item, new IllegalStateException("updateInfo is null"))); + return; + } + + String url = item.getUpdateInfo().getChangelogUrl(); + if (TextUtils.isEmpty(url)) { + if (onErrorUi != null) activity.runOnUiThread(() -> onErrorUi.accept(item, new IllegalStateException("changelogUrl is empty"))); + return; + } + + NetUtils.downloadText(url, new NetUtils.TextDownloadCallback() { + @Override + public void onSuccess(String content) { + if (onSuccessUi != null) activity.runOnUiThread(() -> onSuccessUi.accept(item, content)); + } + + @Override + public void onError(Exception e) { + if (onErrorUi != null) activity.runOnUiThread(() -> onErrorUi.accept(item, e)); + } + }); + } + + /** + * 批量检查所有模块更新 + */ + public void checkAllModulesUpdate( + List allModules, + BiConsumer onEachSuccessUi, + BiConsumer onEachErrorUi + ) { + if (allModules == null || allModules.isEmpty()) return; + + for (SkrModInstalledItem item : allModules) { + // 没有配置 updateJson 的直接跳过 + if (item.getUpdateJson() == null || item.getUpdateJson().isEmpty()) continue; + requestModuleUpdate( + item, + (mod, info) -> { + if (onEachSuccessUi != null) onEachSuccessUi.accept(mod, info); + }, + (mod, e) -> { + Log.w("SkrModUpdate", "check update failed: " + mod.getName(), e); + if (onEachErrorUi != null) onEachErrorUi.accept(mod, e); + } + ); + } + } + + /** + * 解析服务器返回的模块更新 JSON,并结合当前版本号,生成 SkrModUpdateInfo + * + * @param jsonStr 服务器返回的 JSON 字符串 + * @param currentVersion 当前本地模块版本号,例如 "0.9.0" + */ + private SkrModUpdateInfo parse(String jsonStr, String currentVersion) throws JSONException { + if (jsonStr == null || jsonStr.trim().isEmpty()) return null; + + JSONObject obj = new JSONObject(jsonStr); + String latestVer = obj.optString("version", ""); + String downloadUrl = obj.optString("zipUrl", ""); + String changelogUrl = obj.optString("changelog", ""); + + if (latestVer.isEmpty() || downloadUrl.isEmpty()) return null; + boolean hasNew = !latestVer.equals(currentVersion); + return new SkrModUpdateInfo(hasNew, latestVer, downloadUrl, changelogUrl); + } +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/ClipboardUtils.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/ClipboardUtils.java" new file mode 100644 index 00000000..354f8a1e --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/ClipboardUtils.java" @@ -0,0 +1,16 @@ +package com.linux.permissionmanager.utils; + +import android.content.ClipData; +import android.content.ClipboardManager; +import android.content.Context; + +public class ClipboardUtils { + public static void copyText(Context ctx, String text) { + //获取剪贴板管理器: + ClipboardManager cm = (ClipboardManager)ctx.getSystemService(Context.CLIPBOARD_SERVICE); + // 创建普通字符型ClipData + ClipData mClipData = ClipData.newPlainText("Label", text); + // 将ClipData内容放到系统剪贴板里。 + cm.setPrimaryClip(mClipData); + } +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/DialogUtils.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/DialogUtils.java" new file mode 100644 index 00000000..f4e7563b --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/DialogUtils.java" @@ -0,0 +1,213 @@ +package com.linux.permissionmanager.utils; + +import android.app.Dialog; +import android.content.ClipData; +import android.content.ClipboardManager; +import android.content.Context; +import android.content.DialogInterface; +import android.graphics.drawable.Drawable; +import android.os.Handler; +import android.os.Message; +import android.view.Gravity; +import android.view.View; +import android.view.ViewGroup; +import android.view.Window; +import android.widget.Button; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.TextView; +import android.widget.Toast; + +import androidx.appcompat.app.AlertDialog; + +import java.util.List; + +public class DialogUtils { + public static void showCustomDialog(Context context, String title, String message, + Drawable icon, + String positiveButtonText, DialogInterface.OnClickListener positiveClickListener, + String negativeButtonText, DialogInterface.OnClickListener negativeClickListener) { + + AlertDialog.Builder builder = new AlertDialog.Builder(context); + builder.setTitle(title) + .setMessage(message) + .setCancelable(false); + + if (icon != null) { + builder.setIcon(icon); + } + + if (positiveButtonText != null && positiveClickListener != null) { + builder.setPositiveButton(positiveButtonText, positiveClickListener); + } + if (negativeButtonText != null && negativeClickListener != null) { + builder.setNegativeButton(negativeButtonText, negativeClickListener); + } + builder.show(); + } + + public static void showNeedPermissionDialog(Context context) { + DialogUtils.showCustomDialog( + context, "权限申请", "请授予权限后重新操作", null, "确定", + (dialog, which) -> dialog.dismiss(), + null, null + ); + } + + /** + * 显示带有消息的对话框。 + * + * @param context 上下文 + * @param title 对话框标题 + * @param msg 对话框内容 + * @param icon 对话框图标(可为 null) + */ + public static void showMsgDlg(Context context, String title, String msg, Drawable icon) { + showCustomDialog( + context, + title, + msg, + icon, + "确定", (dialog, which) -> dialog.dismiss(), + null, null + ); + } + + /** + * 显示带有三个按钮的输入对话框。 + * + * @param context 上下文 + * @param defaultText 默认文本 + * @param title 对话框标题 + * @param thirdButtonText 第三个按钮的文本 + * @param confirmCallback 点击确定按钮时的回调 + * @param thirdButtonCallback 第三个按钮的回调 + */ + public static void showInputDlg(Context context, String defaultText, String title, final String thirdButtonText, + final Handler confirmCallback, final Handler thirdButtonCallback) { + final EditText inputTxt = new EditText(context); + inputTxt.setText(defaultText); + inputTxt.setFocusable(true); + inputTxt.setSelection(defaultText.length(), 0); + + AlertDialog.Builder builder = new AlertDialog.Builder(context); + builder.setTitle(title) + .setIcon(android.R.drawable.ic_dialog_info) + .setView(inputTxt) + .setNegativeButton("取消", new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + } + }) + .setPositiveButton("确定", new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int which) { + String text = inputTxt.getText().toString(); + Message msg = new Message(); + msg.obj = text; + confirmCallback.sendMessage(msg); + } + }); + + // 添加第三个按钮 + if (thirdButtonText != null && !thirdButtonText.isEmpty()) { + builder.setNeutralButton(thirdButtonText, new DialogInterface.OnClickListener() { + @Override + public void onClick(DialogInterface dialog, int which) { + // 自定义回调 + if (thirdButtonCallback != null) { + thirdButtonCallback.sendMessage(new Message()); + } + } + }); + } + + AlertDialog dialog = builder.create(); + dialog.show(); + } + + public static void showLogDialog(Context context, String logs) { + // 创建全屏 Dialog + Dialog dialog = new Dialog(context); + dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); + + // 创建一个外部的线性布局(垂直方向) + LinearLayout layout = new LinearLayout(context); + layout.setOrientation(LinearLayout.VERTICAL); + layout.setPadding(50, 50, 50, 50); + + // 创建 TextView 作为日志显示区域 + TextView textView = new TextView(context); + textView.setTextSize(14); + textView.setText(logs); + textView.setTextIsSelectable(true); // 允许选中复制 + textView.setVerticalScrollBarEnabled(true); + textView.setSingleLine(false); // 允许多行显示 + textView.setMaxLines(Integer.MAX_VALUE); // 让其支持无限行 + textView.setLineSpacing(1.5f, 1.2f); // 增加行间距,增强可读性 + + // ScrollView 使日志可以滚动 + ScrollView scrollView = new ScrollView(context); + scrollView.addView(textView); + scrollView.setLayoutParams(new LinearLayout.LayoutParams( + ViewGroup.LayoutParams.MATCH_PARENT, + 0, 1 // 设置权重,让日志区域填满大部分屏幕 + )); + + // 让 ScrollView 自动滚动到底部 + scrollView.getViewTreeObserver().addOnGlobalLayoutListener(() -> { + scrollView.post(() -> scrollView.fullScroll(View.FOCUS_DOWN)); + }); + + // === 底部按钮区域:复制 + 关闭 === + LinearLayout buttonBar = new LinearLayout(context); + buttonBar.setOrientation(LinearLayout.HORIZONTAL); + buttonBar.setGravity(Gravity.END); + + LinearLayout.LayoutParams btnLp = new LinearLayout.LayoutParams( + 0, + ViewGroup.LayoutParams.WRAP_CONTENT, + 1f + ); + btnLp.setMargins(10, 30, 10, 0); // 按钮之间稍微留点间距 + + // 【复制】按钮 + Button copyButton = new Button(context); + copyButton.setText("复制"); + copyButton.setLayoutParams(btnLp); + copyButton.setOnClickListener(v -> { + ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); + if (cm != null) { + cm.setPrimaryClip(ClipData.newPlainText("logs", logs)); + Toast.makeText(context, "日志已复制到剪贴板", Toast.LENGTH_SHORT).show(); + } + }); + + // 【关闭】按钮 + Button closeButton = new Button(context); + closeButton.setText("关闭"); + closeButton.setLayoutParams(btnLp); + closeButton.setOnClickListener(v -> dialog.dismiss()); + + buttonBar.addView(copyButton); + buttonBar.addView(closeButton); + + // 将 ScrollView 和按钮栏添加到主布局 + layout.addView(scrollView); + layout.addView(buttonBar); + + // 设置 Dialog 的内容 + dialog.setContentView(layout); + + // 设置全屏属性 + Window window = dialog.getWindow(); + if (window != null) { + window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); + window.setGravity(Gravity.CENTER); + } + + dialog.show(); + } + +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/DownloadDialogHelper.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/DownloadDialogHelper.java" new file mode 100644 index 00000000..ed19a89b --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/DownloadDialogHelper.java" @@ -0,0 +1,110 @@ +package com.linux.permissionmanager.utils; + +import android.app.Activity; +import android.app.ProgressDialog; +import android.content.DialogInterface; +import java.io.File; + +public final class DownloadDialogHelper { + + private DownloadDialogHelper() { + throw new AssertionError("No DownloadDialogHelper instances!"); + } + + /** + * 带系统 ProgressDialog 的下载封装 + * + * @param activity 当前 Activity(用来跑 runOnUiThread 和创建对话框) + * @param url 下载链接 + * @param destFile 目标文件 + * @param callback 下载回调(可为 null) + */ + public static void startDownloadWithDialog( + Activity activity, + String url, + File destFile, + DownloadResultCallback callback + ) { + ProgressDialog dialog = new ProgressDialog(activity); + dialog.setTitle("正在下载"); + dialog.setMessage("准备中..."); + dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); + dialog.setIndeterminate(true); + dialog.setCancelable(true); + + // 标记是否用户主动取消,用来决定是否回调 onSuccess + final boolean[] isCanceled = {false}; + + // 负按钮:取消 + dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", + (d, which) -> { + isCanceled[0] = true; + d.dismiss(); + // 这里只是关闭对话框,底层 NetUtils 暂时还没有取消逻辑 + // 如果以后 NetUtils 支持取消,这里可以顺便调用 cancel + }); + + // 按返回键关闭对话框时,也视为取消 + dialog.setOnCancelListener(d -> isCanceled[0] = true); + dialog.show(); + + NetUtils.downloadFile(url, destFile, new NetUtils.DownloadCallback() { + @Override + public void onStart(long totalBytes) { + activity.runOnUiThread(() -> { + if (totalBytes > 0) { + dialog.setIndeterminate(false); + dialog.setMax(100); + } else { + dialog.setIndeterminate(true); + dialog.setMessage("大小未知,正在下载..."); + } + }); + } + + @Override + public void onProgress(long downloadedBytes, long totalBytes) { + activity.runOnUiThread(() -> { + if (totalBytes > 0) { + int progress = (int) (downloadedBytes * 100 / totalBytes); + dialog.setIndeterminate(false); + dialog.setProgress(progress); + + String msg = String.format("%s / %s", FileUtils.formatFileSize(downloadedBytes), FileUtils.formatFileSize(totalBytes)); + dialog.setMessage(msg); + } else { + dialog.setIndeterminate(true); + String msg = String.format("%s / ?", FileUtils.formatFileSize(downloadedBytes)); + dialog.setMessage(msg); + } + }); + } + + @Override + public void onCompleted(File file) { + activity.runOnUiThread(() -> { + dialog.dismiss(); + if (!isCanceled[0] && callback != null) { + // 只有没被用户取消时才通知成功 + callback.onSuccess(file); + } + }); + } + + @Override + public void onError(Exception e) { + activity.runOnUiThread(() -> { + dialog.dismiss(); + if (callback != null) { + callback.onError(e); // 失败回调出去,带原因 + } + }); + } + }); + } + + public interface DownloadResultCallback { + void onSuccess(File destFile); + void onError(Exception e); + } +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/FileUtils.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/FileUtils.java" new file mode 100644 index 00000000..06bc463c --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/FileUtils.java" @@ -0,0 +1,70 @@ +package com.linux.permissionmanager.utils; + +import android.content.Context; +import android.content.res.AssetManager; +import android.database.Cursor; +import android.net.Uri; +import android.os.Environment; +import android.provider.DocumentsContract; +import android.provider.MediaStore; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.util.Objects; +import java.util.stream.Stream; + +public class FileUtils { + public static String getRealPathFromURI(Context context, Uri uri) { + String path = null; + if (DocumentsContract.isDocumentUri(context, uri)) { + String docId = DocumentsContract.getDocumentId(uri); + String[] split = docId.split(":"); + String type = split[0]; + if ("primary".equalsIgnoreCase(type)) { + path = Environment.getExternalStorageDirectory() + "/" + split[1]; + } + } else if ("content".equalsIgnoreCase(uri.getScheme())) { + String[] projection = {MediaStore.Images.Media.DATA}; + Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null); + if (cursor != null && cursor.moveToFirst()) { + int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); + path = cursor.getString(columnIndex); + cursor.close(); + } + } else if ("file".equalsIgnoreCase(uri.getScheme())) { + path = uri.getPath(); + } + return path; + } + + public static void deleteFile(File destFile) { + try { + if (destFile != null && destFile.exists()) destFile.delete(); + } catch (Exception ignore) {} + } + + public static String formatFileSize(long size) { + // 定义单位 + final long K = 1024; + final long M = K * 1024; + final long G = M * 1024; + if (size >= G) { + // 大于或等于GB + return String.format("%.2f GB", (double) size / G); + } else if (size >= M) { + // 大于或等于MB + return String.format("%.2f MB", (double) size / M); + } else if (size >= K) { + // 大于或等于KB + return String.format("%.2f KB", (double) size / K); + } else { + // 小于KB + return size + " B"; + } + } +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/GetAppListPermissionHelper.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/GetAppListPermissionHelper.java" new file mode 100644 index 00000000..080314f6 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/GetAppListPermissionHelper.java" @@ -0,0 +1,13 @@ +package com.linux.permissionmanager.utils; + +import android.app.Activity; +import android.content.pm.PackageInfo; + +import java.util.List; + +public class GetAppListPermissionHelper { + public static boolean getPermissions(Activity activity) { + List packages = activity.getPackageManager().getInstalledPackages(0); + return packages.size() > 0; + } +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/GetSdcardPermissionsHelper.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/GetSdcardPermissionsHelper.java" new file mode 100644 index 00000000..c1e07064 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/GetSdcardPermissionsHelper.java" @@ -0,0 +1,51 @@ +package com.linux.permissionmanager.utils; + +import android.Manifest; +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.content.pm.PackageManager; +import android.net.Uri; +import android.os.Build; +import android.os.Environment; +import android.provider.Settings; + +import androidx.core.app.ActivityCompat; + +public class GetSdcardPermissionsHelper { + public static boolean getPermissions(Activity activity, Context ctx, String packageName) { +// 普通权限:只需要在清单文件中注册即可 +// 危险权限(Android 6.0 之后):需要在代码中动态申请,以弹系统 Dialog 的形式进行请求 +// 特殊权限(Android 11(含) 之后):需要在代码中动态申请,以跳系统 Activity 的形式进行请求 + //android版本大于等于11 + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {//必须要MANAGE_EXTERNAL_STORAGE权限,但Google Play Console审核不通过 + // 先判断有没有权限 + if (Environment.isExternalStorageManager()) { + //有权限 + return true; + } else { + Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION); + intent.setData(Uri.parse("package:" + packageName)); + activity.startActivityForResult(intent, 0); + return false; + } + } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + int permission_write= ActivityCompat.checkSelfPermission(ctx, + Manifest.permission.WRITE_EXTERNAL_STORAGE); + int permission_read=ActivityCompat.checkSelfPermission(ctx, + Manifest.permission.READ_EXTERNAL_STORAGE); + if(permission_write!= PackageManager.PERMISSION_GRANTED + || permission_read!= PackageManager.PERMISSION_GRANTED){ + //申请权限,特征码自定义为0,可在回调时进行相关判断 + activity.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},0); + return false; + } else { + //有权限后需要处理的功能 + return true; + } + } else { + //有权限后需要处理的功能 + return true; + } + } +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/NetUtils.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/NetUtils.java" new file mode 100644 index 00000000..acecc255 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/NetUtils.java" @@ -0,0 +1,260 @@ +package com.linux.permissionmanager.utils; + +import org.json.JSONException; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.net.URLConnection; +import java.nio.charset.StandardCharsets; + +public final class NetUtils { + + // 工具类不允许实例化 + private NetUtils() { + throw new AssertionError("No NetUtils instances for you!"); + } + + public static final class DownloadHandle { + private volatile boolean cancelled = false; + private Thread workerThread; + + private void setWorkerThread(Thread t) { + this.workerThread = t; + } + + /** 外面调用这个方法取消下载 */ + public void cancel() { + cancelled = true; + // 如果有阻塞 read,可以通过中断加快结束 + if (workerThread != null) { + workerThread.interrupt(); + } + } + + public boolean isCancelled() { + return cancelled; + } + } + + //================================================================== + // 1) 下载文本(.txt / .json 等),内部开新线程,通过回调返回 + //================================================================== + + /** + * 异步下载文本内容(适合 .txt / .json 等),支持取消 + * + * @param urlString 形如 "https://example.com/config.json" + * @param callback 下载结果回调(在子线程调用) + * @return DownloadHandle 可通过 handle.cancel() 取消 + * + * 注意: + * - callback 的 onSuccess/onError 都在内部新开的子线程中调用, + * 如果要更新 UI,需要自己在外面切回主线程(比如 runOnUiThread)。 + */ + public static DownloadHandle downloadText(final String urlString, + final TextDownloadCallback callback) { + final DownloadHandle handle = new DownloadHandle(); + + Thread t = new Thread(new Runnable() { + @Override + public void run() { + URLConnection conn = null; + InputStream is = null; + BufferedReader br = null; + + try { + URL myURL = new URL(urlString); + conn = myURL.openConnection(); + conn.setConnectTimeout(1000 * 60 * 5); + conn.setReadTimeout(1000 * 60 * 5); + conn.connect(); + + is = conn.getInputStream(); + br = new BufferedReader( + new InputStreamReader(is, StandardCharsets.UTF_8) + ); + + StringBuilder sb = new StringBuilder(); + String line; + + while ((line = br.readLine()) != null) { + // 每次读一行都检查是否被取消 + if (handle.isCancelled()) { + throw new IOException("Text download cancelled"); + } + sb.append(line).append('\n'); + } + + // 读完再检查一次 + if (handle.isCancelled()) { + throw new IOException("Text download cancelled"); + } + + if (callback != null) callback.onSuccess(sb.toString()); + } catch (Exception e) { + if (callback != null) { + if (handle.isCancelled()) { + callback.onError(new IOException("文本下载已被取消", e)); + } else { + callback.onError(e); + } + } + } finally { + try { + if (br != null) br.close(); + } catch (IOException ignored) {} + try { + if (is != null) is.close(); + } catch (IOException ignored) {} + } + } + }); + + handle.setWorkerThread(t); + t.start(); + return handle; + } + + public interface TextDownloadCallback { + void onSuccess(String content) throws JSONException; + void onError(Exception e); + } + + //================================================================== + // 2) 下载文件到本地,带进度回调,内部开新线程 + //================================================================== + + /** + * 异步下载文件到本地 destFile + * + * @param urlString 下载链接 + * @param destFile 目标文件路径(会自动创建父目录) + * @param callback 下载进度/结果回调(在子线程调用) + * @return DownloadHandle 通过 handle.cancel() 取消下载 + */ + public static DownloadHandle downloadFile(final String urlString, + final File destFile, + final DownloadCallback callback) { + final DownloadHandle handle = new DownloadHandle(); + + Thread t = new Thread(new Runnable() { + @Override + public void run() { + URLConnection conn = null; + InputStream is = null; + FileOutputStream fos = null; + File tmpFile = null; + + try { + URL myURL = new URL(urlString); + conn = myURL.openConnection(); + conn.setConnectTimeout(1000 * 60 * 5); + conn.setReadTimeout(1000 * 60 * 5); + conn.connect(); + + int fileSize = conn.getContentLength(); // 可能为 -1 + + if (callback != null && !handle.isCancelled()) { + callback.onStart(fileSize); + } + + // 确保目录存在 + File parent = destFile.getParentFile(); + if (parent != null && !parent.exists()) { + if (!parent.mkdirs() && !parent.isDirectory()) { + throw new IOException("无法创建目录: " + parent.getAbsolutePath()); + } + } + + // 临时文件 + tmpFile = new File(destFile.getAbsolutePath() + ".download"); + + is = conn.getInputStream(); + fos = new FileOutputStream(tmpFile); + + byte[] buffer = new byte[8 * 1024]; + int len; + long totalRead = 0; + + while ((len = is.read(buffer)) != -1) { + // 每次读完先检查是否取消 + if (handle.isCancelled()) { + throw new IOException("Download cancelled"); + } + + fos.write(buffer, 0, len); + totalRead += len; + + if (callback != null && !handle.isCancelled()) { + callback.onProgress(totalRead, fileSize); + } + } + + // 再检查一次是否取消 + if (handle.isCancelled()) { + throw new IOException("Download cancelled"); + } + + fos.getFD().sync(); + + if (!tmpFile.renameTo(destFile)) { + throw new IOException("重命名下载文件失败: " + tmpFile.getAbsolutePath()); + } + + if (callback != null && !handle.isCancelled()) { + callback.onCompleted(destFile); + } + + } catch (Exception e) { + if (callback != null) { + // 你可以选择区分“取消”和“真实错误” + if (handle.isCancelled()) { + // 可选:如果你愿意,可以给 DownloadCallback 增加 onCancelled() + callback.onError(new IOException("下载已被取消", e)); + } else { + callback.onError(e); + } + } + } finally { + try { + if (fos != null) fos.close(); + } catch (IOException ignored) {} + try { + if (is != null) is.close(); + } catch (IOException ignored) {} + + // 失败/取消时清理临时文件 + if (tmpFile != null && tmpFile.exists() && !tmpFile.equals(destFile)) { + //noinspection ResultOfMethodCallIgnored + tmpFile.delete(); + } + } + } + }); + + handle.setWorkerThread(t); + t.start(); + return handle; + } + + public interface DownloadCallback { + /** 开始下载时调用,totalBytes 可能为 -1(服务端没返回 Content-Length) */ + void onStart(long totalBytes); + + /** 进度回调:downloadedBytes 已下载字节数,totalBytes 总字节数(可能为 -1) */ + void onProgress(long downloadedBytes, long totalBytes); + + /** 下载完成 */ + void onCompleted(File destFile); + + /** 失败 */ + void onError(Exception e); + } + + +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/ScreenInfoUtils.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/ScreenInfoUtils.java" new file mode 100644 index 00000000..97dcd2f9 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/ScreenInfoUtils.java" @@ -0,0 +1,187 @@ +package com.linux.permissionmanager.utils; + +import android.app.Activity; +import android.content.Context; +import android.content.res.Resources; +import android.util.DisplayMetrics; +import android.util.Log; +import android.util.TypedValue; +import android.view.Display; +import android.view.WindowManager; + +/** + * Get Screen Information Utils + * + * @author yh + * @date 2018/12/18. + */ +public class ScreenInfoUtils { + + private static final String TAG = "ScreenInfoUtils"; + + /** + * Get Screen Width + */ + public static int getScreenWidth(Context context) { + return getDisplayMetrics(context).widthPixels; + } + + /** + * Get Screen Height + */ + public static int getScreenHeight(Context context) { + return getDisplayMetrics(context).heightPixels; + } + + + /** + * Get Screen Real Height + * + * @param context Context + * @return Real Height + */ + public static int getRealHeight(Context context) { + Display display = getDisplay(context); + if (display == null) { + return 0; + } + DisplayMetrics dm = new DisplayMetrics(); + display.getRealMetrics(dm); + return dm.heightPixels; + } + + /** + * Get Screen Real Width + * + * @param context Context + * @return Real Width + */ + public static int getRealWidth(Context context) { + Display display = getDisplay(context); + if (display == null) { + return 0; + } + DisplayMetrics dm = new DisplayMetrics(); + display.getRealMetrics(dm); + return dm.widthPixels; + } + + /** + * Get StatusBar Height + */ + public static int getStatusBarHeight(Context mContext) { + int resourceId = mContext.getResources().getIdentifier("status_bar_height", "dimen", "android"); + if (resourceId > 0) { + return mContext.getResources().getDimensionPixelSize(resourceId); + } + return 0; + } + + /** + * Get ActionBar Height + */ + public static int getActionBarHeight(Context mContext) { + TypedValue tv = new TypedValue(); + if (mContext.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) { + return TypedValue.complexToDimensionPixelSize(tv.data, mContext.getResources().getDisplayMetrics()); + } + return 0; + } + + /** + * Get NavigationBar Height + */ + public static int getNavigationBarHeight(Context mContext) { + Resources resources = mContext.getResources(); + int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android"); + if (resourceId > 0) { + return resources.getDimensionPixelSize(resourceId); + } + return 0; + } + + /** + * Get Density + */ + private static float getDensity(Context context) { + return getDisplayMetrics(context).density; + } + + /** + * Get Dpi + */ + private static int getDpi(Context context) { + return getDisplayMetrics(context).densityDpi; + } + + /** + * Get Display + * + * @param context Context for get WindowManager + * @return Display + */ + private static Display getDisplay(Context context) { + WindowManager wm; + if (context instanceof Activity) { + Activity activity = (Activity) context; + wm = activity.getWindowManager(); + } else { + wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); + } + if (wm != null) { + return wm.getDefaultDisplay(); + } + return null; + } + + /** + * Get DisplayMetrics + * + * @param context Context for get Resources + * @return DisplayMetrics + */ + private static DisplayMetrics getDisplayMetrics(Context context) { + return context.getResources().getDisplayMetrics(); + } + + + /** + * Get ScreenInfo + */ + private static String getScreenInfo(Context context) { + return " \n" + + "--------ScreenInfo--------" + "\n" + + "Screen Width : " + getScreenWidth(context) + "px\n" + + "Screen RealWidth :" + getRealWidth(context) + "px\n" + + "Screen Height: " + getScreenHeight(context) + "px\n" + + "Screen RealHeight: " + getRealHeight(context) + "px\n" + + "Screen StatusBar Height: " + getStatusBarHeight(context)+ "px\n" + + "Screen ActionBar Height: " + getActionBarHeight(context)+ "px\n" + + "Screen NavigationBar Height: " + getNavigationBarHeight(context)+ "px\n" + + "Screen Dpi: " + getDpi(context) + "\n" + + "Screen Density: " + getDensity(context) + "\n" + + "--------------------------"; + } + + + /** + * 根据手机的分辨率从 dp 的单位 转成为 px(像素) + */ + public static int dip2px(Context context, float dpValue) { + final float scale = context.getResources().getDisplayMetrics().density; + return (int) (dpValue * scale); + } + + /** * 根据手机的分辨率从 px(像素) 的单位 转成为 dp */ + public static int px2dip(Context context, float pxValue) { + final float scale = context.getResources().getDisplayMetrics().density; + return (int) (pxValue / scale); + } + + /** + * Print screenInfo to logcat + */ + public static void printScreenInfo(Context context) { + Log.d(TAG, getScreenInfo(context)); + } +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/UrlIntentUtils.java" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/UrlIntentUtils.java" new file mode 100644 index 00000000..e7102c2e --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/java/com/linux/permissionmanager/utils/UrlIntentUtils.java" @@ -0,0 +1,47 @@ +package com.linux.permissionmanager.utils; + +import android.app.Activity; +import android.content.ActivityNotFoundException; +import android.content.Context; +import android.content.Intent; +import android.net.Uri; +import android.text.TextUtils; +import android.widget.Toast; + +public final class UrlIntentUtils { + private UrlIntentUtils() {} + + /** 在外部浏览器打开链接;支持传 "example.com" 自动补全 https:// */ + public static boolean openUrl(Context context, String url) { + if (context == null) return false; + if (TextUtils.isEmpty(url)) { + Toast.makeText(context, "链接为空", Toast.LENGTH_SHORT).show(); + return false; + } + + String u = url.trim(); + // 没有 scheme 的话补 https:// + if (!u.startsWith("http://") && !u.startsWith("https://")) { + u = "https://" + u; + } + + Uri uri = Uri.parse(u); + Intent intent = new Intent(Intent.ACTION_VIEW, uri); + + // 非 Activity context 需要 NEW_TASK + if (!(context instanceof Activity)) { + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + } + + try { + context.startActivity(intent); + return true; + } catch (ActivityNotFoundException e) { + Toast.makeText(context, "没有可打开链接的应用", Toast.LENGTH_SHORT).show(); + return false; + } catch (Exception e) { + Toast.makeText(context, "打开链接失败", Toast.LENGTH_SHORT).show(); + return false; + } + } +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/color/tab_text_color.xml" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/color/tab_text_color.xml" new file mode 100644 index 00000000..89342823 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/color/tab_text_color.xml" @@ -0,0 +1,5 @@ + + + + + diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/bg_search_light.xml" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/bg_search_light.xml" new file mode 100644 index 00000000..47ae67dc --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/bg_search_light.xml" @@ -0,0 +1,6 @@ + + + + + + diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/bg_tab_container_light.xml" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/bg_tab_container_light.xml" new file mode 100644 index 00000000..8588f784 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/bg_tab_container_light.xml" @@ -0,0 +1,5 @@ + + + + + diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/bg_tab_indicator_light.xml" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/bg_tab_indicator_light.xml" new file mode 100644 index 00000000..c6816010 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/bg_tab_indicator_light.xml" @@ -0,0 +1,13 @@ + + + + + + + + + diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/ic_add_white.xml" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/ic_add_white.xml" new file mode 100644 index 00000000..2c9c4006 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/ic_add_white.xml" @@ -0,0 +1,11 @@ + + + + + diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/ic_search_24.xml" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/ic_search_24.xml" new file mode 100644 index 00000000..28955280 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/ic_search_24.xml" @@ -0,0 +1,11 @@ + + + + + diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/line.xml" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/line.xml" new file mode 100644 index 00000000..597142f2 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/line.xml" @@ -0,0 +1,12 @@ + + + + + + + \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/line_drawable.xml" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/line_drawable.xml" new file mode 100644 index 00000000..4f79f470 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/line_drawable.xml" @@ -0,0 +1,9 @@ + + + + + + \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/ripple_grey.xml" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/ripple_grey.xml" new file mode 100644 index 00000000..ac736de4 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/ripple_grey.xml" @@ -0,0 +1,6 @@ + +//点击时波纹的颜色 + //未点击时控件的背景(可以是图片,可以是颜色,也可以是drawable里的xml背景(比如圆角)) + \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/shape_wnd_grey_corner.xml" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/shape_wnd_grey_corner.xml" new file mode 100644 index 00000000..6bc80841 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/shape_wnd_grey_corner.xml" @@ -0,0 +1,9 @@ + + + + + + \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/textview_border.xml" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/textview_border.xml" new file mode 100644 index 00000000..dbefbf4b --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/textview_border.xml" @@ -0,0 +1,7 @@ + + + + + + + diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/thumb.xml" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/thumb.xml" new file mode 100644 index 00000000..0646431b --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/thumb.xml" @@ -0,0 +1,11 @@ + + + + + + + + \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/thumb_drawable.xml" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/thumb_drawable.xml" new file mode 100644 index 00000000..a93b8b83 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/drawable/thumb_drawable.xml" @@ -0,0 +1,9 @@ + + + + + + \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/layout/activity_main.xml" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/layout/activity_main.xml" new file mode 100644 index 00000000..f079777d --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/layout/activity_main.xml" @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/layout/fragment_home.xml" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/layout/fragment_home.xml" new file mode 100644 index 00000000..9e397660 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/PermissionManager/app/src/main/res/layout/fragment_home.xml" @@ -0,0 +1,178 @@ + + + + + + + + + + + + + + + + + + + + + + + + +
+
+

已选择

+

0

+
+
+
+ +
+
+ + + + +
+ 重启后生效 +
+ + + + + + + + diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\262\350\256\276\345\244\207\346\240\207\350\256\260\344\270\216\350\207\252\345\212\250\346\270\205\347\220\206/webroot/main.js" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\262\350\256\276\345\244\207\346\240\207\350\256\260\344\270\216\350\207\252\345\212\250\346\270\205\347\220\206/webroot/main.js" new file mode 100644 index 00000000..6688621d --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\262\350\256\276\345\244\207\346\240\207\350\256\260\344\270\216\350\207\252\345\212\250\346\270\205\347\220\206/webroot/main.js" @@ -0,0 +1,261 @@ +/** ===== 状态 ===== */ +let pkgs = []; +let candidates = []; +let candSelected = new Set(); + +// 同步相关:最后一次成功同步的快照(用于失败回滚) +let lastSyncedPkgs = []; +let syncInFlight = 0; + +const els = { + pkgList: document.getElementById("pkgList"), + emptyTips: document.getElementById("emptyTips"), + countText: document.getElementById("countText"), + barSub: document.getElementById("barSub"), + + btnPick: document.getElementById("btnPick"), + + toast: document.getElementById("toast"), + toastText: document.getElementById("toastText"), + + pickMask: document.getElementById("pickMask"), + pickMini: document.getElementById("pickMini"), + pickSearch: document.getElementById("pickSearch"), + pickAll: document.getElementById("pickAll"), + pickClear: document.getElementById("pickClear"), + candList: document.getElementById("candList"), + pickSelCount: document.getElementById("pickSelCount"), + pickOk: document.getElementById("pickOk"), + btnPickClose: document.getElementById("btnPickClose"), +}; + +/** ===== 工具 ===== */ +function escapeHtml(s){ + return String(s ?? "") + .replaceAll("&","&") + .replaceAll("<","<") + .replaceAll(">",">") + .replaceAll('"',""") + .replaceAll("'","'"); +} +function uniqKeepOrder(arr){ + const seen = new Set(); + const out = []; + for (const x of arr){ + if (!seen.has(x)){ + seen.add(x); + out.push(x); + } + } + return out; +} +function normalizePkgs(arr){ + return uniqKeepOrder((arr || []).map(s => (s || "").trim()).filter(Boolean)); +} +function sameArray(a, b){ + if (a.length !== b.length) return false; + for (let i=0;i${escapeHtml(p)}`; + + const right = document.createElement("div"); + right.className = "right"; + + const btnDel = document.createElement("button"); + btnDel.className = "danger"; + btnDel.textContent = "删除"; + btnDel.addEventListener("click", async (e) => { + e.stopPropagation(); + + // 先改前端 + pkgs.splice(i, 1); + refreshUI(); + + // 同步后台 + await syncTargets(); + }); + + right.appendChild(btnDel); + row.appendChild(left); + row.appendChild(right); + els.pkgList.appendChild(row); + } +} + +/** ===== Modal 通用 ===== */ +function openMask(maskEl){ + maskEl.style.display = "flex"; + maskEl.setAttribute("aria-hidden", "false"); + document.body.style.overflow = "hidden"; +} +function closeMask(maskEl){ + maskEl.style.display = "none"; + maskEl.setAttribute("aria-hidden", "true"); + document.body.style.overflow = ""; +} + +/** ===== 候选选择 ===== */ +function updatePickCount(){ + els.pickSelCount.textContent = String(candSelected.size); + els.pickOk.disabled = (candSelected.size === 0); + els.pickMini.textContent = `候选:${candidates.length},已选:${candSelected.size}`; +} +function renderCandidates(){ + const kw = (els.pickSearch.value || "").trim().toLowerCase(); + + const list = candidates.filter(it => { + const pkg = (it.pkg ?? it) + ""; + if (!kw) return true; + return pkg.toLowerCase().includes(kw); + }); + + els.candList.innerHTML = ""; + if (list.length === 0){ + const empty = document.createElement("div"); + empty.className = "cand-item"; + empty.innerHTML = `
无匹配结果
`; + els.candList.appendChild(empty); + return; + } + + for (const it of list){ + const pkg = (it.pkg ?? it) + ""; + + const row = document.createElement("div"); + row.className = "cand-item"; + + const left = document.createElement("div"); + left.className = "name"; + left.innerHTML = `
${escapeHtml(pkg)}
`; + + const cb = document.createElement("input"); + cb.type = "checkbox"; + cb.checked = candSelected.has(pkg); + cb.addEventListener("change", () => { + if (cb.checked) candSelected.add(pkg); + else candSelected.delete(pkg); + updatePickCount(); + }); + + row.addEventListener("click", (e) => { + if (e.target === cb) return; + cb.checked = !cb.checked; + cb.dispatchEvent(new Event("change")); + }); + + row.appendChild(left); + row.appendChild(cb); + els.candList.appendChild(row); + } +} + +async function openPickModal(){ + candSelected.clear(); + openMask(els.pickMask); + els.pickSearch.value = ""; + els.pickMini.textContent = "加载中…"; + els.pickOk.disabled = true; + + try{ + if (candidates.length === 0){ + candidates = JSON.parse(await RequestApi.getCandidatesPkgJson()); + } + renderCandidates(); + updatePickCount(); + }catch(e){ + els.pickMini.textContent = "加载失败"; + showToast("加载失败", "danger"); + } +} +function closePickModal(){ closeMask(els.pickMask); } + +els.btnPick.addEventListener("click", openPickModal); +els.btnPickClose.addEventListener("click", closePickModal); +els.pickMask.addEventListener("click", (e) => { + if (e.target === els.pickMask) closePickModal(); +}); +els.pickSearch.addEventListener("input", () => renderCandidates()); + +els.pickAll.addEventListener("click", () => { + const kw = (els.pickSearch.value || "").trim().toLowerCase(); + for (const it of candidates){ + const pkg = (it.pkg ?? it) + ""; + if (!kw || pkg.toLowerCase().includes(kw)) candSelected.add(pkg); + } + renderCandidates(); + updatePickCount(); +}); + +els.pickClear.addEventListener("click", () => { + candSelected.clear(); + renderCandidates(); + updatePickCount(); +}); + +els.pickOk.addEventListener("click", async () => { + if (candSelected.size === 0) return; + + const before = pkgs.length; + pkgs = normalizePkgs(pkgs.concat(Array.from(candSelected))); + const added = pkgs.length - before; + + refreshUI(); + closePickModal(); + + if (added <= 0){ + showToast("没有新增", "success"); + return; + } + + // 同步后台 + await syncTargets(); +}); + +/** ===== 初始化 ===== */ +(async function init(){ + els.barSub.textContent = "加载中…"; + try{ + const data = await RequestApi.getTargetPkgJson(); + pkgs = data ? normalizePkgs(JSON.parse(data)) : []; + lastSyncedPkgs = pkgs.slice(); + refreshUI(); + }catch(e){ + els.barSub.textContent = "加载失败"; + const msg = (e && e.message) ? e.message : "加载失败"; + showToast("加载失败:" + msg, "danger"); + } +})(); \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\262\350\256\276\345\244\207\346\240\207\350\256\260\344\270\216\350\207\252\345\212\250\346\270\205\347\220\206/webroot/request.js" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\262\350\256\276\345\244\207\346\240\207\350\256\260\344\270\216\350\207\252\345\212\250\346\270\205\347\220\206/webroot/request.js" new file mode 100644 index 00000000..b60162e0 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\262\350\256\276\345\244\207\346\240\207\350\256\260\344\270\216\350\207\252\345\212\250\346\270\205\347\220\206/webroot/request.js" @@ -0,0 +1,27 @@ +const RequestApi = (() => { + function postText(path, bodyText = "") { + const url = new URL(path, window.location.href); + return fetch(url, { method: 'POST', body: bodyText }); + } + + async function getCandidatesPkgJson() { + const resp = await postText('/getCandidatesPkgJson'); + return resp.ok ? await resp.text() : ('HTTP ' + resp.status); + } + + async function getTargetPkgJson() { + const resp = await postText('/getTargetPkgJson'); + return resp.ok ? await resp.text() : ('HTTP ' + resp.status); + } + + async function setTargetPkgJson(json) { + const resp = await postText('/setTargetPkgJson', json); + return resp.ok ? await resp.text() : ('HTTP ' + resp.status); + } + + return { + getCandidatesPkgJson, + getTargetPkgJson, + setTargetPkgJson + }; +})(); diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\262\350\256\276\345\244\207\346\240\207\350\256\260\344\270\216\350\207\252\345\212\250\346\270\205\347\220\206/webroot/style.css" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\262\350\256\276\345\244\207\346\240\207\350\256\260\344\270\216\350\207\252\345\212\250\346\270\205\347\220\206/webroot/style.css" new file mode 100644 index 00000000..2663170d --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\262\350\256\276\345\244\207\346\240\207\350\256\260\344\270\216\350\207\252\345\212\250\346\270\205\347\220\206/webroot/style.css" @@ -0,0 +1,344 @@ +:root{ + --bg:#f6f7fb; + --card:#ffffff; + --text:#111827; + --muted:#6b7280; + --line:#e5e7eb; + --shadow: 0 10px 22px rgba(17,24,39,.08); + --primary:#2563eb; + --primary2:#1d4ed8; + --r:16px; +} +*{ box-sizing:border-box; } +body{ + margin:0; + font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "PingFang SC", "Noto Sans CJK SC", "Microsoft YaHei", Arial, sans-serif; + background: + radial-gradient(1100px 700px at 15% -10%, rgba(37,99,235,.16), transparent 55%), + radial-gradient(900px 600px at 95% 0%, rgba(34,197,94,.10), transparent 55%), + var(--bg); + color: var(--text); + min-height:100vh; + padding: 14px 12px 28px; +} +.wrap{ max-width:720px; margin:0 auto; } + +.header{ + margin: 6px 2px 10px; + display:flex; + flex-direction:column; + gap: 8px; +} +.header h1{ + margin:0; + font-size: 18px; + letter-spacing:.2px; +} +.sub{ + display:flex; + flex-wrap:wrap; + gap: 8px; + align-items:center; + color: var(--muted); + font-size: 12.5px; +} +.pill{ + display:inline-flex; + align-items:center; + gap:6px; + padding: 6px 10px; + border: 1px solid var(--line); + background: rgba(255,255,255,.75); + border-radius: 999px; + user-select:none; +} +.dot{ + width:8px;height:8px;border-radius:50%; + background: rgba(52, 199, 89, 0.96); + box-shadow: 0 0 0 3px rgba(52, 199, 89, .16); +} + +.sticky{ + position: sticky; + top: 10px; + z-index: 20; + margin: 8px 0 12px; +} +.sticky .bar{ + background: rgba(255,255,255,.92); + border: 1px solid var(--line); + border-radius: 14px; + box-shadow: 0 10px 18px rgba(17,24,39,.06); + backdrop-filter: blur(10px); + padding: 10px 12px; + display:flex; + align-items:center; + justify-content:space-between; + gap: 10px; +} +.bar .left{ + display:flex; + flex-direction:column; + gap: 2px; + min-width:0; +} +.bar .left .t{ + font-weight: 950; + font-size: 13.5px; + margin:0; + line-height: 1.2; +} +.bar .left .s{ + color: var(--muted); + font-size: 12px; + margin:0; + white-space:nowrap; + overflow:hidden; + text-overflow:ellipsis; + max-width: 60vw; +} +.bar .right{ flex:0 0 auto; } + +button{ + appearance:none; + border: 1px solid var(--line); + padding: 9px 12px; + border-radius: 12px; + background: #fff; + color: var(--text); + font-weight: 950; + font-size: 13px; + cursor:pointer; + transition: transform .05s ease, background .2s ease, border-color .2s ease; + line-height: 1; + white-space:nowrap; +} +button:active{ transform: translateY(1px); } +button.primary{ + border-color: rgba(37,99,235,.25); + background: rgba(37,99,235,.10); + color: var(--primary2); +} +button.primary:hover{ background: rgba(37,99,235,.14); } +button.danger{ + border-color: rgba(239,68,68,.25); + background: rgba(239,68,68,.10); + color: #b91c1c; +} +button.solid{ + border-color: rgba(37,99,235,.35); + background: rgba(37,99,235,.12); + color: var(--primary2); +} +button.solid:disabled{ + opacity:.55; + cursor:not-allowed; +} + +.card{ + background: var(--card); + border: 1px solid var(--line); + border-radius: var(--r); + box-shadow: var(--shadow); + overflow:hidden; +} +.card-hd{ + padding: 12px 14px; + border-bottom: 1px solid var(--line); + display:flex; + align-items:center; + justify-content:space-between; + gap: 10px; +} +.card-hd .title{ + margin:0; + font-weight: 950; + font-size: 13.5px; + letter-spacing:.2px; +} +.card-hd .meta{ + margin:0; + color: var(--muted); + font-size: 12px; + white-space:nowrap; +} +.card-bd{ padding: 10px; } + +.list{ + display:flex; + flex-direction:column; + gap: 8px; +} +.row-item{ + display:flex; + align-items:center; + justify-content:space-between; + gap: 10px; + padding: 10px 10px; + border-radius: 14px; + border: 1px solid var(--line); + background: #fff; +} +.row-item:hover{ background:#f9fafb; } +.row-item .left{ + min-width:0; + display:flex; + flex-direction:column; + gap: 2px; +} +.pkg{ + font-size: 13.5px; + font-weight: 950; + overflow:hidden; + text-overflow:ellipsis; + white-space:nowrap; +} +.row-item .right{ flex:0 0 auto; } + +.empty{ + padding: 18px 12px; + color: var(--muted); + font-size: 13px; + text-align:center; +} + +.modal-mask{ + position: fixed; + inset: 0; + background: rgba(17,24,39,.45); + display:none; + align-items:flex-end; + justify-content:center; + z-index: 60; + padding: 12px 12px calc(12px + env(safe-area-inset-bottom)); +} +.modal{ + width: min(720px, 100%); + background: #fff; + border: 1px solid var(--line); + border-radius: 18px; + box-shadow: var(--shadow); + overflow:hidden; + + height: 76vh; + min-height: 520px; + max-height: 78vh; + + display:flex; + flex-direction:column; +} +@media (max-height: 700px){ + .modal{ min-height: 0; height: 82vh; } +} + +.modal-hd{ + padding: 12px 14px 10px; + border-bottom: 1px solid var(--line); + display:flex; + align-items:center; + justify-content:space-between; + gap: 10px; + flex:0 0 auto; +} +.modal-hd h3{ + margin:0; + font-size: 14.5px; + font-weight: 950; +} +.modal-hd .mini{ + color: var(--muted); + font-size: 12px; + margin-top: 3px; +} + +.modal-bd{ + padding: 12px 14px; + overflow: hidden; + flex: 1 1 auto; + min-height: 0; + display:flex; + flex-direction:column; + gap: 10px; +} + +.modal-ft{ + padding: 10px 14px 12px; + border-top: 1px solid var(--line); + display:flex; + gap: 10px; + align-items:center; + justify-content:space-between; + flex:0 0 auto; +} +.modal-ft .left{ + color: var(--muted); + font-size: 12px; + line-height:1.3; +} + +.search{ + display:flex; + gap: 8px; + align-items:center; + flex:0 0 auto; +} +.search input{ + flex: 1 1 auto; + min-width: 0; + width: 0; + border-radius: 12px; + border: 1px solid var(--line); + background: #fbfbfd; + color: var(--text); + padding: 10px 12px; + font-size: 13.5px; + outline:none; +} + +.search input:focus{ + border-color: rgba(37,99,235,.55); + box-shadow: 0 0 0 4px rgba(37,99,235,.12); + background:#fff; +} +.search button{ flex: 0 0 auto; } + +.cand-list{ + display:flex; + flex-direction:column; + gap: 8px; + overflow: auto; + flex: 1 1 auto; + min-height: 0; + padding-bottom: 2px; + -webkit-overflow-scrolling: touch; +} + +.cand-item{ + display:flex; + align-items:center; + justify-content:space-between; + gap: 10px; + padding: 10px 10px; + border-radius: 14px; + border: 1px solid var(--line); + background: #fff; +} +.cand-item:hover{ background:#f9fafb; } +.cand-item .name{ + display:flex; + flex-direction:column; + gap: 3px; + min-width:0; +} +.cand-item .pkg{ + font-size: 13.5px; + font-weight: 950; + overflow:hidden; + text-overflow:ellipsis; + white-space:nowrap; +} +.cand-item input[type="checkbox"]{ + width: 18px; height: 18px; + accent-color: #2563eb; + flex:0 0 auto; +} \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\262\350\256\276\345\244\207\346\240\207\350\256\260\344\270\216\350\207\252\345\212\250\346\270\205\347\220\206/webroot/toast.css" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\262\350\256\276\345\244\207\346\240\207\350\256\260\344\270\216\350\207\252\345\212\250\346\270\205\347\220\206/webroot/toast.css" new file mode 100644 index 00000000..3703a381 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\262\350\256\276\345\244\207\346\240\207\350\256\260\344\270\216\350\207\252\345\212\250\346\270\205\347\220\206/webroot/toast.css" @@ -0,0 +1,23 @@ +.toast { + position: fixed; + left: 50%; + top: 50%; + transform: translate(-50%, -50%) translateY(8px); + padding: 10px 18px; + border-radius: 999px; + font-size: 14px; + font-weight: 500; + color: #fff; + background: rgba(15, 23, 42, 0.96); + box-shadow: 0 12px 30px rgba(15, 23, 42, 0.45); + opacity: 0; + pointer-events: none; + z-index: 999; + transition: opacity .26s ease, transform .26s ease; +} +.toast--success { background: rgba(52, 199, 89, 0.96); } +.toast--danger { background: rgba(255, 59, 48, 0.96); } +.toast--show { + opacity: 1; + transform: translate(-50%, -50%) translateY(0); +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\262\350\256\276\345\244\207\346\240\207\350\256\260\344\270\216\350\207\252\345\212\250\346\270\205\347\220\206/webroot/toast.js" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\262\350\256\276\345\244\207\346\240\207\350\256\260\344\270\216\350\207\252\345\212\250\346\270\205\347\220\206/webroot/toast.js" new file mode 100644 index 00000000..dd2cc0a3 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\262\350\256\276\345\244\207\346\240\207\350\256\260\344\270\216\350\207\252\345\212\250\346\270\205\347\220\206/webroot/toast.js" @@ -0,0 +1,21 @@ + +/** ===== Toast ===== */ +let toastTimer = null; +let toastSeq = 0; +function showToast(msg, kind = "success", durationMs = 1800) { + toastSeq++; + const mySeq = toastSeq; + + const el = els.toast; + el.classList.remove("toast--success", "toast--danger", "toast--show"); + el.classList.add(kind === "danger" ? "toast--danger" : "toast--success"); + els.toastText.textContent = msg; + el.offsetHeight; + el.classList.add("toast--show"); + + if (toastTimer) clearTimeout(toastTimer); + toastTimer = setTimeout(() => { + if (mySeq !== toastSeq) return; + el.classList.remove("toast--show"); + }, durationMs); +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_OppoFindX8Ultra/jni/Android.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_OppoFindX8Ultra/jni/Android.mk" new file mode 100644 index 00000000..187c987f --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_OppoFindX8Ultra/jni/Android.mk" @@ -0,0 +1,16 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) +LOCAL_MODULE := module_fake_device + +LOCAL_SRC_FILES := ../main.cpp + +KERNEL_MODULE_KIT := $(LOCAL_PATH)/../../../kernel_module_kit +LOCAL_C_INCLUDES += $(KERNEL_MODULE_KIT)/include +LOCAL_LDFLAGS += $(KERNEL_MODULE_KIT)/lib/libkernel_module_kit_static.a + +include $(LOCAL_PATH)/build_macros.mk + +include $(BUILD_SHARED_LIBRARY) + + diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_OppoFindX8Ultra/jni/Application.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_OppoFindX8Ultra/jni/Application.mk" new file mode 100644 index 00000000..2500a8a7 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_OppoFindX8Ultra/jni/Application.mk" @@ -0,0 +1,2 @@ +APP_ABI := arm64-v8a +APP_STL := c++_static \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_OppoFindX8Ultra/jni/build_macros.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_OppoFindX8Ultra/jni/build_macros.mk" new file mode 100644 index 00000000..a6f31501 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_OppoFindX8Ultra/jni/build_macros.mk" @@ -0,0 +1,21 @@ +COMMON_CPPFLAGS := \ + -std=c++20 \ + -fPIC \ + -fvisibility=hidden \ + -fno-stack-protector \ + -ffunction-sections \ + -fdata-sections \ + -flto=thin + +COMMON_LDFLAGS := \ + -Wl,-O2 \ + -Wl,--gc-sections \ + -Wl,-s \ + -flto=thin + +COMMON_INCLUDES := \ + $(LOCAL_PATH)/../../../ + +LOCAL_CPPFLAGS += $(COMMON_CPPFLAGS) +LOCAL_LDFLAGS += $(COMMON_LDFLAGS) +LOCAL_C_INCLUDES += $(COMMON_INCLUDES) diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_OppoFindX8Ultra/main.cpp" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_OppoFindX8Ultra/main.cpp" new file mode 100644 index 00000000..47cd4105 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_OppoFindX8Ultra/main.cpp" @@ -0,0 +1,54 @@ +#include +#include +#include +#include +#include +#include +#include "kernel_module_kit_umbrella.h" + +#define SYSTEM_PROP_SH "system_prop.sh" + +static void android_open_url(const std::string& url) { + std::string cmd = "am start -a android.intent.action.VIEW -d " + url; + FILE * fp = popen(cmd.c_str(), "r"); + if(fp) pclose(fp); +} + +static void run_script(const char* script) { + const char* sh = "/system/bin/sh"; + char* const argv[] = { + (char*)sh, + (char*)script, + nullptr + }; + execve(sh, argv, environ); +} + +// SKRoot模块入口函数 +int skroot_module_main(const char* root_key, const char* module_private_dir) { + printf("*******************************\n"); + printf(" 全局模拟机型:OPPO Find X8 Ultra\n"); + printf(" 阿灵\n"); + printf("*******************************\n"); + pid_t pid = ::fork(); + if (pid == 0) { + run_script(SYSTEM_PROP_SH); + _exit(127); + } + int status; waitpid(pid, &status, 0); + return 0; +} + +std::string module_on_install(const char* root_key, const char* module_private_dir) { + android_open_url("tg://resolve?domain=ALING521"); + return ""; +} + +// SKRoot 模块名片 +SKROOT_MODULE_NAME("阿灵的机型模拟 OPPO Find X8 Ultra") +SKROOT_MODULE_VERSION("5.2.0") +SKROOT_MODULE_DESC("全局机型模拟为OPPO Find X8 Ultra,TG频道:@Whitelist520") +SKROOT_MODULE_AUTHOR("阿灵") +SKROOT_MODULE_UUID32("8nNPjlwLSXmwRA0i9P3yKAFO1SkaBtg0") +SKROOT_MODULE_ON_INSTALL(module_on_install) +SKROOT_MODULE_UPDATE_JSON("https://abcz316.github.io/SKRoot-linuxKernelRoot/module_fake_device/aling_oppoFindX8Ultra_update.json") \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_OppoFindX8Ultra/resetprop" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_OppoFindX8Ultra/resetprop" new file mode 100644 index 00000000..feeb0284 Binary files /dev/null and "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_OppoFindX8Ultra/resetprop" differ diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_OppoFindX8Ultra/system_prop.sh" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_OppoFindX8Ultra/system_prop.sh" new file mode 100644 index 00000000..6bb3de9d --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_OppoFindX8Ultra/system_prop.sh" @@ -0,0 +1,40 @@ +#!/system/bin/sh +check_reset_prop() { + local NAME=$1 + local EXPECTED=$2 + local VALUE=$(resetprop $NAME) + [ -z $VALUE ] || [ $VALUE = $EXPECTED ] || resetprop $NAME $EXPECTED +} + + +#设备信息 +check_reset_prop "ro.product.brand" "oppo" +check_reset_prop "ro.product.manufacturer" "oppo" +check_reset_prop "ro.product.model" "PKJ110" +check_reset_prop "ro.product.device" "PKJ110" +check_reset_prop "ro.product.name" "PKJ110" +check_reset_prop "ro.product.marketname" "Find X8 Ultra" + +# 产品信息 +check_reset_prop "ro.product.system.brand" "oppo" +check_reset_prop "ro.product.system.name" "PKJ110" +check_reset_prop "ro.product.system.device" "PKJ110" +check_reset_prop "ro.build.product" "PKJ110" +check_reset_prop "ro.build.flavor" "PKJ110-user" + +# 指纹信息 (基于官方信息构造的标准格式) +check_reset_prop "ro.build.fingerprint" "oppo/PKJ110/PKJ110:15/AP3A.240617.008/1758264862075:user/release-keys" +check_reset_prop "ro.build.description" "PKJ110-user 15 PKJ110_15.1.1.501CN01 eng.root.20250101.000000 release-keys" + +# 构建信息 +check_reset_prop "ro.build.id" "AP3A.240617.008" +check_reset_prop "ro.build.version.incremental" "1758264862075" +check_reset_prop "ro.build.version.security_patch" "2025-11-05" +check_reset_prop "ro.build.display.id" "AP3A.240617.008 dev-keys" + +#check_reset_prop "ro.build.version.release" "15" +#check_reset_prop "ro.build.version.release_or_codename" "15" +#check_reset_prop "ro.build.version.sdk" "35" + +# 处理平台 +#check_reset_prop "ro.hardware" "qcom" diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\24015/jni/Android.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\24015/jni/Android.mk" new file mode 100644 index 00000000..187c987f --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\24015/jni/Android.mk" @@ -0,0 +1,16 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) +LOCAL_MODULE := module_fake_device + +LOCAL_SRC_FILES := ../main.cpp + +KERNEL_MODULE_KIT := $(LOCAL_PATH)/../../../kernel_module_kit +LOCAL_C_INCLUDES += $(KERNEL_MODULE_KIT)/include +LOCAL_LDFLAGS += $(KERNEL_MODULE_KIT)/lib/libkernel_module_kit_static.a + +include $(LOCAL_PATH)/build_macros.mk + +include $(BUILD_SHARED_LIBRARY) + + diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\24015/jni/Application.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\24015/jni/Application.mk" new file mode 100644 index 00000000..2500a8a7 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\24015/jni/Application.mk" @@ -0,0 +1,2 @@ +APP_ABI := arm64-v8a +APP_STL := c++_static \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\24015/jni/build_macros.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\24015/jni/build_macros.mk" new file mode 100644 index 00000000..a6f31501 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\24015/jni/build_macros.mk" @@ -0,0 +1,21 @@ +COMMON_CPPFLAGS := \ + -std=c++20 \ + -fPIC \ + -fvisibility=hidden \ + -fno-stack-protector \ + -ffunction-sections \ + -fdata-sections \ + -flto=thin + +COMMON_LDFLAGS := \ + -Wl,-O2 \ + -Wl,--gc-sections \ + -Wl,-s \ + -flto=thin + +COMMON_INCLUDES := \ + $(LOCAL_PATH)/../../../ + +LOCAL_CPPFLAGS += $(COMMON_CPPFLAGS) +LOCAL_LDFLAGS += $(COMMON_LDFLAGS) +LOCAL_C_INCLUDES += $(COMMON_INCLUDES) diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\24015/main.cpp" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\24015/main.cpp" new file mode 100644 index 00000000..375293df --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\24015/main.cpp" @@ -0,0 +1,54 @@ +#include +#include +#include +#include +#include +#include +#include "kernel_module_kit_umbrella.h" + +#define SYSTEM_PROP_SH "system_prop.sh" + +static void android_open_url(const std::string& url) { + std::string cmd = "am start -a android.intent.action.VIEW -d " + url; + FILE * fp = popen(cmd.c_str(), "r"); + if(fp) pclose(fp); +} + +static void run_script(const char* script) { + const char* sh = "/system/bin/sh"; + char* const argv[] = { + (char*)sh, + (char*)script, + nullptr + }; + execve(sh, argv, environ); +} + +// SKRoot模块入口函数 +int skroot_module_main(const char* root_key, const char* module_private_dir) { + printf("*******************************\n"); + printf(" 全局模拟机型:一加 15\n"); + printf(" 阿灵\n"); + printf("*******************************\n"); + pid_t pid = ::fork(); + if (pid == 0) { + run_script(SYSTEM_PROP_SH); + _exit(127); + } + int status; waitpid(pid, &status, 0); + return 0; +} + +std::string module_on_install(const char* root_key, const char* module_private_dir) { + android_open_url("tg://resolve?domain=ALING521"); + return ""; +} + +// SKRoot 模块名片 +SKROOT_MODULE_NAME("阿灵的机型模拟 一加15") +SKROOT_MODULE_VERSION("5.2.0") +SKROOT_MODULE_DESC("全局机型模拟为一加15,TG频道:@Whitelist520") +SKROOT_MODULE_AUTHOR("阿灵") +SKROOT_MODULE_UUID32("evq0GG8tdzT5dki8Be84aULan31w6tH6") +SKROOT_MODULE_ON_INSTALL(module_on_install) +SKROOT_MODULE_UPDATE_JSON("https://abcz316.github.io/SKRoot-linuxKernelRoot/module_fake_device/aling_oneplus15_update.json") \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\24015/resetprop" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\24015/resetprop" new file mode 100644 index 00000000..feeb0284 Binary files /dev/null and "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\24015/resetprop" differ diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\24015/system_prop.sh" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\24015/system_prop.sh" new file mode 100644 index 00000000..0f68c954 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\24015/system_prop.sh" @@ -0,0 +1,12 @@ +#!/system/bin/sh +check_reset_prop() { + local NAME=$1 + local EXPECTED=$2 + local VALUE=$(resetprop $NAME) + [ -z $VALUE ] || [ $VALUE = $EXPECTED ] || resetprop $NAME $EXPECTED +} + +check_reset_prop "ro.product.manufacturer" "OnePlus" +check_reset_prop "ro.product.brand" "OnePlus" +check_reset_prop "ro.product.model" "PLK110" +check_reset_prop "ro.product.marketname" "OnePlus 15" diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\240Ace6/jni/Android.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\240Ace6/jni/Android.mk" new file mode 100644 index 00000000..187c987f --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\240Ace6/jni/Android.mk" @@ -0,0 +1,16 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) +LOCAL_MODULE := module_fake_device + +LOCAL_SRC_FILES := ../main.cpp + +KERNEL_MODULE_KIT := $(LOCAL_PATH)/../../../kernel_module_kit +LOCAL_C_INCLUDES += $(KERNEL_MODULE_KIT)/include +LOCAL_LDFLAGS += $(KERNEL_MODULE_KIT)/lib/libkernel_module_kit_static.a + +include $(LOCAL_PATH)/build_macros.mk + +include $(BUILD_SHARED_LIBRARY) + + diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\240Ace6/jni/Application.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\240Ace6/jni/Application.mk" new file mode 100644 index 00000000..2500a8a7 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\240Ace6/jni/Application.mk" @@ -0,0 +1,2 @@ +APP_ABI := arm64-v8a +APP_STL := c++_static \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\240Ace6/jni/build_macros.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\240Ace6/jni/build_macros.mk" new file mode 100644 index 00000000..a6f31501 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\240Ace6/jni/build_macros.mk" @@ -0,0 +1,21 @@ +COMMON_CPPFLAGS := \ + -std=c++20 \ + -fPIC \ + -fvisibility=hidden \ + -fno-stack-protector \ + -ffunction-sections \ + -fdata-sections \ + -flto=thin + +COMMON_LDFLAGS := \ + -Wl,-O2 \ + -Wl,--gc-sections \ + -Wl,-s \ + -flto=thin + +COMMON_INCLUDES := \ + $(LOCAL_PATH)/../../../ + +LOCAL_CPPFLAGS += $(COMMON_CPPFLAGS) +LOCAL_LDFLAGS += $(COMMON_LDFLAGS) +LOCAL_C_INCLUDES += $(COMMON_INCLUDES) diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\240Ace6/main.cpp" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\240Ace6/main.cpp" new file mode 100644 index 00000000..e666677c --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\240Ace6/main.cpp" @@ -0,0 +1,54 @@ +#include +#include +#include +#include +#include +#include +#include "kernel_module_kit_umbrella.h" + +#define SYSTEM_PROP_SH "system_prop.sh" + +static void android_open_url(const std::string& url) { + std::string cmd = "am start -a android.intent.action.VIEW -d " + url; + FILE * fp = popen(cmd.c_str(), "r"); + if(fp) pclose(fp); +} + +static void run_script(const char* script) { + const char* sh = "/system/bin/sh"; + char* const argv[] = { + (char*)sh, + (char*)script, + nullptr + }; + execve(sh, argv, environ); +} + +// SKRoot模块入口函数 +int skroot_module_main(const char* root_key, const char* module_private_dir) { + printf("*******************************\n"); + printf(" 全局模拟机型:ACE 6\n"); + printf(" 阿灵\n"); + printf("*******************************\n"); + pid_t pid = ::fork(); + if (pid == 0) { + run_script(SYSTEM_PROP_SH); + _exit(127); + } + int status; waitpid(pid, &status, 0); + return 0; +} + +std::string module_on_install(const char* root_key, const char* module_private_dir) { + android_open_url("tg://resolve?domain=ALING521"); + return ""; +} + +// SKRoot 模块名片 +SKROOT_MODULE_NAME("阿灵的机型模拟 一加ACE 6") +SKROOT_MODULE_VERSION("5.2.0") +SKROOT_MODULE_DESC("全局机型模拟为一加ACE 6,TG频道:@Whitelist520") +SKROOT_MODULE_AUTHOR("阿灵") +SKROOT_MODULE_UUID32("Pr596Oi52bfandlOpzjPIWGIHEK0YYCo") +SKROOT_MODULE_ON_INSTALL(module_on_install) +SKROOT_MODULE_UPDATE_JSON("https://abcz316.github.io/SKRoot-linuxKernelRoot/module_fake_device/aling_oneplus_ace6_update.json") \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\240Ace6/resetprop" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\240Ace6/resetprop" new file mode 100644 index 00000000..feeb0284 Binary files /dev/null and "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\240Ace6/resetprop" differ diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\240Ace6/system_prop.sh" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\240Ace6/system_prop.sh" new file mode 100644 index 00000000..30fd0f6b --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\344\270\200\345\212\240Ace6/system_prop.sh" @@ -0,0 +1,12 @@ +#!/system/bin/sh +check_reset_prop() { + local NAME=$1 + local EXPECTED=$2 + local VALUE=$(resetprop $NAME) + [ -z $VALUE ] || [ $VALUE = $EXPECTED ] || resetprop $NAME $EXPECTED +} + +check_reset_prop "ro.product.manufacturer" "OnePlus" +check_reset_prop "ro.product.brand" "OnePlus" +check_reset_prop "ro.product.model" "PLQ110" +check_reset_prop "ro.product.marketname" "OnePlus 15" diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\345\215\216\344\270\272Mate80ProMax/jni/Android.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\345\215\216\344\270\272Mate80ProMax/jni/Android.mk" new file mode 100644 index 00000000..187c987f --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\345\215\216\344\270\272Mate80ProMax/jni/Android.mk" @@ -0,0 +1,16 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) +LOCAL_MODULE := module_fake_device + +LOCAL_SRC_FILES := ../main.cpp + +KERNEL_MODULE_KIT := $(LOCAL_PATH)/../../../kernel_module_kit +LOCAL_C_INCLUDES += $(KERNEL_MODULE_KIT)/include +LOCAL_LDFLAGS += $(KERNEL_MODULE_KIT)/lib/libkernel_module_kit_static.a + +include $(LOCAL_PATH)/build_macros.mk + +include $(BUILD_SHARED_LIBRARY) + + diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\345\215\216\344\270\272Mate80ProMax/jni/Application.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\345\215\216\344\270\272Mate80ProMax/jni/Application.mk" new file mode 100644 index 00000000..2500a8a7 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\345\215\216\344\270\272Mate80ProMax/jni/Application.mk" @@ -0,0 +1,2 @@ +APP_ABI := arm64-v8a +APP_STL := c++_static \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\345\215\216\344\270\272Mate80ProMax/jni/build_macros.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\345\215\216\344\270\272Mate80ProMax/jni/build_macros.mk" new file mode 100644 index 00000000..a6f31501 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\345\215\216\344\270\272Mate80ProMax/jni/build_macros.mk" @@ -0,0 +1,21 @@ +COMMON_CPPFLAGS := \ + -std=c++20 \ + -fPIC \ + -fvisibility=hidden \ + -fno-stack-protector \ + -ffunction-sections \ + -fdata-sections \ + -flto=thin + +COMMON_LDFLAGS := \ + -Wl,-O2 \ + -Wl,--gc-sections \ + -Wl,-s \ + -flto=thin + +COMMON_INCLUDES := \ + $(LOCAL_PATH)/../../../ + +LOCAL_CPPFLAGS += $(COMMON_CPPFLAGS) +LOCAL_LDFLAGS += $(COMMON_LDFLAGS) +LOCAL_C_INCLUDES += $(COMMON_INCLUDES) diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\345\215\216\344\270\272Mate80ProMax/main.cpp" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\345\215\216\344\270\272Mate80ProMax/main.cpp" new file mode 100644 index 00000000..453e2cdf --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\345\215\216\344\270\272Mate80ProMax/main.cpp" @@ -0,0 +1,54 @@ +#include +#include +#include +#include +#include +#include +#include "kernel_module_kit_umbrella.h" + +#define SYSTEM_PROP_SH "system_prop.sh" + +static void android_open_url(const std::string& url) { + std::string cmd = "am start -a android.intent.action.VIEW -d " + url; + FILE * fp = popen(cmd.c_str(), "r"); + if(fp) pclose(fp); +} + +static void run_script(const char* script) { + const char* sh = "/system/bin/sh"; + char* const argv[] = { + (char*)sh, + (char*)script, + nullptr + }; + execve(sh, argv, environ); +} + +// SKRoot模块入口函数 +int skroot_module_main(const char* root_key, const char* module_private_dir) { + printf("*******************************\n"); + printf(" 全局模拟机型:华为 Mate 80 Pro Max\n"); + printf(" 阿灵\n"); + printf("*******************************\n"); + pid_t pid = ::fork(); + if (pid == 0) { + run_script(SYSTEM_PROP_SH); + _exit(127); + } + int status; waitpid(pid, &status, 0); + return 0; +} + +std::string module_on_install(const char* root_key, const char* module_private_dir) { + android_open_url("tg://resolve?domain=ALING521"); + return ""; +} + +// SKRoot 模块名片 +SKROOT_MODULE_NAME("阿灵的机型模拟 华为 Mate 80 Pro Max") +SKROOT_MODULE_VERSION("5.2.0") +SKROOT_MODULE_DESC("全局机型模拟为华为 Mate 80 Pro Max,TG频道:@Whitelist520") +SKROOT_MODULE_AUTHOR("阿灵") +SKROOT_MODULE_UUID32("mznMiXB7H5RCBUldFMKagfFwzzdrm711") +SKROOT_MODULE_ON_INSTALL(module_on_install) +SKROOT_MODULE_UPDATE_JSON("https://abcz316.github.io/SKRoot-linuxKernelRoot/module_fake_device/aling_huaweiMate80ProMax_update.json") \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\345\215\216\344\270\272Mate80ProMax/resetprop" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\345\215\216\344\270\272Mate80ProMax/resetprop" new file mode 100644 index 00000000..feeb0284 Binary files /dev/null and "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\345\215\216\344\270\272Mate80ProMax/resetprop" differ diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\345\215\216\344\270\272Mate80ProMax/system_prop.sh" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\345\215\216\344\270\272Mate80ProMax/system_prop.sh" new file mode 100644 index 00000000..2f2df02c --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\345\215\216\344\270\272Mate80ProMax/system_prop.sh" @@ -0,0 +1,11 @@ +#!/system/bin/sh +check_reset_prop() { + local NAME=$1 + local EXPECTED=$2 + local VALUE=$(resetprop $NAME) + [ -z $VALUE ] || [ $VALUE = $EXPECTED ] || resetprop $NAME $EXPECTED +} + +check_reset_prop "ro.product.manufacturer" "huawei" +check_reset_prop "ro.product.brand" "huawei" +check_reset_prop "ro.product.model" "SGT-AL00" diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\22410sPro/jni/Android.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\22410sPro/jni/Android.mk" new file mode 100644 index 00000000..187c987f --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\22410sPro/jni/Android.mk" @@ -0,0 +1,16 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) +LOCAL_MODULE := module_fake_device + +LOCAL_SRC_FILES := ../main.cpp + +KERNEL_MODULE_KIT := $(LOCAL_PATH)/../../../kernel_module_kit +LOCAL_C_INCLUDES += $(KERNEL_MODULE_KIT)/include +LOCAL_LDFLAGS += $(KERNEL_MODULE_KIT)/lib/libkernel_module_kit_static.a + +include $(LOCAL_PATH)/build_macros.mk + +include $(BUILD_SHARED_LIBRARY) + + diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\22410sPro/jni/Application.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\22410sPro/jni/Application.mk" new file mode 100644 index 00000000..2500a8a7 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\22410sPro/jni/Application.mk" @@ -0,0 +1,2 @@ +APP_ABI := arm64-v8a +APP_STL := c++_static \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\22410sPro/jni/build_macros.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\22410sPro/jni/build_macros.mk" new file mode 100644 index 00000000..a6f31501 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\22410sPro/jni/build_macros.mk" @@ -0,0 +1,21 @@ +COMMON_CPPFLAGS := \ + -std=c++20 \ + -fPIC \ + -fvisibility=hidden \ + -fno-stack-protector \ + -ffunction-sections \ + -fdata-sections \ + -flto=thin + +COMMON_LDFLAGS := \ + -Wl,-O2 \ + -Wl,--gc-sections \ + -Wl,-s \ + -flto=thin + +COMMON_INCLUDES := \ + $(LOCAL_PATH)/../../../ + +LOCAL_CPPFLAGS += $(COMMON_CPPFLAGS) +LOCAL_LDFLAGS += $(COMMON_LDFLAGS) +LOCAL_C_INCLUDES += $(COMMON_INCLUDES) diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\22410sPro/main.cpp" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\22410sPro/main.cpp" new file mode 100644 index 00000000..b1daf4a2 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\22410sPro/main.cpp" @@ -0,0 +1,54 @@ +#include +#include +#include +#include +#include +#include +#include "kernel_module_kit_umbrella.h" + +#define SYSTEM_PROP_SH "system_prop.sh" + +static void android_open_url(const std::string& url) { + std::string cmd = "am start -a android.intent.action.VIEW -d " + url; + FILE * fp = popen(cmd.c_str(), "r"); + if(fp) pclose(fp); +} + +static void run_script(const char* script) { + const char* sh = "/system/bin/sh"; + char* const argv[] = { + (char*)sh, + (char*)script, + nullptr + }; + execve(sh, argv, environ); +} + +// SKRoot模块入口函数 +int skroot_module_main(const char* root_key, const char* module_private_dir) { + printf("*******************************\n"); + printf(" 全局模拟机型:红魔10S Pro\n"); + printf(" 阿灵\n"); + printf("*******************************\n"); + pid_t pid = ::fork(); + if (pid == 0) { + run_script(SYSTEM_PROP_SH); + _exit(127); + } + int status; waitpid(pid, &status, 0); + return 0; +} + +std::string module_on_install(const char* root_key, const char* module_private_dir) { + android_open_url("tg://resolve?domain=ALING521"); + return ""; +} + +// SKRoot 模块名片 +SKROOT_MODULE_NAME("阿灵的机型模拟 红魔10S Pro") +SKROOT_MODULE_VERSION("5.2.0") +SKROOT_MODULE_DESC("全局机型模拟为红魔10S Pro,TG频道:@Whitelist520") +SKROOT_MODULE_AUTHOR("阿灵") +SKROOT_MODULE_UUID32("uE3f2cG9omHPOYsfKXTLzVvdZBrOoREM") +SKROOT_MODULE_ON_INSTALL(module_on_install) +SKROOT_MODULE_UPDATE_JSON("https://abcz316.github.io/SKRoot-linuxKernelRoot/module_fake_device/aling_nubia10spro_update.json") \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\22410sPro/resetprop" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\22410sPro/resetprop" new file mode 100644 index 00000000..feeb0284 Binary files /dev/null and "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\22410sPro/resetprop" differ diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\22410sPro/system_prop.sh" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\22410sPro/system_prop.sh" new file mode 100644 index 00000000..ebc6a24d --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\22410sPro/system_prop.sh" @@ -0,0 +1,11 @@ +#!/system/bin/sh +check_reset_prop() { + local NAME=$1 + local EXPECTED=$2 + local VALUE=$(resetprop $NAME) + [ -z $VALUE ] || [ $VALUE = $EXPECTED ] || resetprop $NAME $EXPECTED +} + +check_reset_prop "ro.product.manufacturer" "nubia" +check_reset_prop "ro.product.brand" "nubia" +check_reset_prop "ro.product.model" "NX789J" \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\224\347\224\265\347\253\236\345\271\263\346\235\2773Pro/jni/Android.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\224\347\224\265\347\253\236\345\271\263\346\235\2773Pro/jni/Android.mk" new file mode 100644 index 00000000..187c987f --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\224\347\224\265\347\253\236\345\271\263\346\235\2773Pro/jni/Android.mk" @@ -0,0 +1,16 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) +LOCAL_MODULE := module_fake_device + +LOCAL_SRC_FILES := ../main.cpp + +KERNEL_MODULE_KIT := $(LOCAL_PATH)/../../../kernel_module_kit +LOCAL_C_INCLUDES += $(KERNEL_MODULE_KIT)/include +LOCAL_LDFLAGS += $(KERNEL_MODULE_KIT)/lib/libkernel_module_kit_static.a + +include $(LOCAL_PATH)/build_macros.mk + +include $(BUILD_SHARED_LIBRARY) + + diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\224\347\224\265\347\253\236\345\271\263\346\235\2773Pro/jni/Application.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\224\347\224\265\347\253\236\345\271\263\346\235\2773Pro/jni/Application.mk" new file mode 100644 index 00000000..2500a8a7 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\224\347\224\265\347\253\236\345\271\263\346\235\2773Pro/jni/Application.mk" @@ -0,0 +1,2 @@ +APP_ABI := arm64-v8a +APP_STL := c++_static \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\224\347\224\265\347\253\236\345\271\263\346\235\2773Pro/jni/build_macros.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\224\347\224\265\347\253\236\345\271\263\346\235\2773Pro/jni/build_macros.mk" new file mode 100644 index 00000000..a6f31501 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\224\347\224\265\347\253\236\345\271\263\346\235\2773Pro/jni/build_macros.mk" @@ -0,0 +1,21 @@ +COMMON_CPPFLAGS := \ + -std=c++20 \ + -fPIC \ + -fvisibility=hidden \ + -fno-stack-protector \ + -ffunction-sections \ + -fdata-sections \ + -flto=thin + +COMMON_LDFLAGS := \ + -Wl,-O2 \ + -Wl,--gc-sections \ + -Wl,-s \ + -flto=thin + +COMMON_INCLUDES := \ + $(LOCAL_PATH)/../../../ + +LOCAL_CPPFLAGS += $(COMMON_CPPFLAGS) +LOCAL_LDFLAGS += $(COMMON_LDFLAGS) +LOCAL_C_INCLUDES += $(COMMON_INCLUDES) diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\224\347\224\265\347\253\236\345\271\263\346\235\2773Pro/main.cpp" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\224\347\224\265\347\253\236\345\271\263\346\235\2773Pro/main.cpp" new file mode 100644 index 00000000..4f124555 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\224\347\224\265\347\253\236\345\271\263\346\235\2773Pro/main.cpp" @@ -0,0 +1,54 @@ +#include +#include +#include +#include +#include +#include +#include "kernel_module_kit_umbrella.h" + +#define SYSTEM_PROP_SH "system_prop.sh" + +static void android_open_url(const std::string& url) { + std::string cmd = "am start -a android.intent.action.VIEW -d " + url; + FILE * fp = popen(cmd.c_str(), "r"); + if(fp) pclose(fp); +} + +static void run_script(const char* script) { + const char* sh = "/system/bin/sh"; + char* const argv[] = { + (char*)sh, + (char*)script, + nullptr + }; + execve(sh, argv, environ); +} + +// SKRoot模块入口函数 +int skroot_module_main(const char* root_key, const char* module_private_dir) { + printf("*******************************\n"); + printf(" 全局模拟机型:华为 Mate 80 Pro Max\n"); + printf(" 阿灵\n"); + printf("*******************************\n"); + pid_t pid = ::fork(); + if (pid == 0) { + run_script(SYSTEM_PROP_SH); + _exit(127); + } + int status; waitpid(pid, &status, 0); + return 0; +} + +std::string module_on_install(const char* root_key, const char* module_private_dir) { + android_open_url("tg://resolve?domain=ALING521"); + return ""; +} + +// SKRoot 模块名片 +SKROOT_MODULE_NAME("阿灵的机型模拟 红魔电竞平板3 Pro") +SKROOT_MODULE_VERSION("5.2.0") +SKROOT_MODULE_DESC("全局机型模拟为红魔电竞平板3 Pro,TG频道:@Whitelist520") +SKROOT_MODULE_AUTHOR("阿灵") +SKROOT_MODULE_UUID32("6lkERo1vmLxcFVYz6TYcagYoJPlAwSql") +SKROOT_MODULE_ON_INSTALL(module_on_install) +SKROOT_MODULE_UPDATE_JSON("https://abcz316.github.io/SKRoot-linuxKernelRoot/module_fake_device/aling_nubiaPad3pro_update.json") \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\224\347\224\265\347\253\236\345\271\263\346\235\2773Pro/resetprop" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\224\347\224\265\347\253\236\345\271\263\346\235\2773Pro/resetprop" new file mode 100644 index 00000000..feeb0284 Binary files /dev/null and "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\224\347\224\265\347\253\236\345\271\263\346\235\2773Pro/resetprop" differ diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\224\347\224\265\347\253\236\345\271\263\346\235\2773Pro/system_prop.sh" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\224\347\224\265\347\253\236\345\271\263\346\235\2773Pro/system_prop.sh" new file mode 100644 index 00000000..2cb11c44 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_device/\351\230\277\347\201\265\347\232\204\346\234\272\345\236\213\346\250\241\346\213\237_\347\272\242\351\255\224\347\224\265\347\253\236\345\271\263\346\235\2773Pro/system_prop.sh" @@ -0,0 +1,36 @@ +#!/system/bin/sh +check_reset_prop() { + local NAME=$1 + local EXPECTED=$2 + local VALUE=$(resetprop $NAME) + [ -z $VALUE ] || [ $VALUE = $EXPECTED ] || resetprop $NAME $EXPECTED +} + +# 设备信息 +check_reset_prop "ro.product.brand" "nubia" +check_reset_prop "ro.product.manufacturer" "nubia" +check_reset_prop "ro.product.model" "NP05J" +check_reset_prop "ro.product.device" "PQ84P01" +check_reset_prop "ro.product.name" "CN_PQ84P01" +check_reset_prop "ro.product.marketname" "红魔电竞平板3 Pro" + +# 产品信息 +check_reset_prop "ro.product.system.brand" "nubia" +check_reset_prop "ro.product.system.name" "CN_PQ84P01" +check_reset_prop "ro.product.system.device" "PQ84P01" +check_reset_prop "ro.build.product" "PQ84P01" +check_reset_prop "ro.build.flavor" "qssi_64-user" + +# 指纹信息 (基于您提供的官方信息) +check_reset_prop "ro.build.fingerprint" "nubia/CN_PQ84P01/PQ84P01:15/AQ3A.240812.002/20250730.005045:user/release-keys" +check_reset_prop "ro.build.description" "qssi_64-user 15 AQ3A.240812.002 20250730.005045 release-keys" + +# 构建信息 +check_reset_prop "ro.build.id" "AQ3A.240812.002" +check_reset_prop "ro.build.version.incremental" "20250730.005045" +check_reset_prop "ro.build.version.security_patch" "2025-06-01" +check_reset_prop "ro.build.display.id" "RedMagicOS10.5.19_NP05J" + +#check_reset_prop "ro.build.version.release" "15" +#check_reset_prop "ro.build.version.release_or_codename" "15" +#check_reset_prop "ro.build.version.sdk" "35" diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_system_file/fd_guard.h" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_system_file/fd_guard.h" new file mode 100644 index 00000000..6da66fe1 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_system_file/fd_guard.h" @@ -0,0 +1,29 @@ +#pragma once +#include + +struct fd_guard { + int fd = -1; + + fd_guard() = default; + explicit fd_guard(int f) : fd(f) {} + + fd_guard(const fd_guard&) = delete; + fd_guard& operator=(const fd_guard&) = delete; + + fd_guard(fd_guard&& o) noexcept : fd(o.fd) { o.fd = -1; } + fd_guard& operator=(fd_guard&& o) noexcept { + if (this != &o) { reset(o.fd); o.fd = -1; } + return *this; + } + + ~fd_guard() { reset(-1); } + + int get() const { return fd; } + + int release() { int t = fd; fd = -1; return t; } + + void reset(int f) { + if (fd >= 0) (void)::close(fd); + fd = f; + } +}; diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_system_file/hosts" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_system_file/hosts" new file mode 100644 index 00000000..ec8f0920 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_system_file/hosts" @@ -0,0 +1,4 @@ +127.0.0.1 localhost +::1 ip6-localhost + +123.123.123.123 www.aaa316.com diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_system_file/jni/Android.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_system_file/jni/Android.mk" new file mode 100644 index 00000000..713183fb --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_system_file/jni/Android.mk" @@ -0,0 +1,16 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) +LOCAL_MODULE := module_fake_system_file + +LOCAL_SRC_FILES := ../module_fake_system_file.cpp + +KERNEL_MODULE_KIT := $(LOCAL_PATH)/../../kernel_module_kit +LOCAL_C_INCLUDES += $(KERNEL_MODULE_KIT)/include +LOCAL_LDFLAGS += $(KERNEL_MODULE_KIT)/lib/libkernel_module_kit_static.a + +include $(LOCAL_PATH)/build_macros.mk + +include $(BUILD_SHARED_LIBRARY) + + diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_system_file/jni/Application.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_system_file/jni/Application.mk" new file mode 100644 index 00000000..2500a8a7 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_system_file/jni/Application.mk" @@ -0,0 +1,2 @@ +APP_ABI := arm64-v8a +APP_STL := c++_static \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_system_file/jni/build_macros.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_system_file/jni/build_macros.mk" new file mode 100644 index 00000000..a6f31501 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_system_file/jni/build_macros.mk" @@ -0,0 +1,21 @@ +COMMON_CPPFLAGS := \ + -std=c++20 \ + -fPIC \ + -fvisibility=hidden \ + -fno-stack-protector \ + -ffunction-sections \ + -fdata-sections \ + -flto=thin + +COMMON_LDFLAGS := \ + -Wl,-O2 \ + -Wl,--gc-sections \ + -Wl,-s \ + -flto=thin + +COMMON_INCLUDES := \ + $(LOCAL_PATH)/../../../ + +LOCAL_CPPFLAGS += $(COMMON_CPPFLAGS) +LOCAL_LDFLAGS += $(COMMON_LDFLAGS) +LOCAL_C_INCLUDES += $(COMMON_INCLUDES) diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_system_file/kernel_func_executor_helper.h" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_system_file/kernel_func_executor_helper.h" new file mode 100644 index 00000000..ce8e9ae2 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_system_file/kernel_func_executor_helper.h" @@ -0,0 +1,14 @@ +#pragma once +#include "kernel_module_kit_umbrella.h" + +#include + +static KModErr get_kernel_shellcode_u64_result(std::function fn, uint64_t & result) { + aarch64_asm_ctx asm_ctx = init_aarch64_asm(); + auto a = asm_ctx.assembler(); + kernel_module::arm64_module_asm_func_start(a); + asmjit::a64::GpX x = asmjit::a64::x0; + RETURN_IF_ERROR(fn(a, x)); + kernel_module::arm64_module_asm_func_end(a, x); + return kernel_module::execute_kernel_asm_func(aarch64_asm_to_bytes(a), result); +} \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_system_file/kernel_struct_path_helper.h" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_system_file/kernel_struct_path_helper.h" new file mode 100644 index 00000000..f4ffed40 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_system_file/kernel_struct_path_helper.h" @@ -0,0 +1,88 @@ +#pragma once +#include +#include + +#include "kernel_module_kit_umbrella.h" +#include "kernel_func_executor_helper.h" + +namespace { +using namespace asmjit; +using namespace asmjit::a64; +using namespace asmjit::a64::Predicate; + +struct kpath { + uint64_t mnt = 0; + uint64_t dentry = 0; +}; + +struct scoped_kpath { + scoped_kpath() = default; + ~scoped_kpath() { reset(); } + + scoped_kpath(const scoped_kpath&) = delete; + scoped_kpath& operator=(const scoped_kpath&) = delete; + scoped_kpath(scoped_kpath&&) = delete; + scoped_kpath& operator=(scoped_kpath&&) = delete; + + void init(uint64_t buf_kaddr, const kpath& p) { + reset(); + _buf_kaddr = buf_kaddr; + raw = p; + } + + void reset() { + if (!_buf_kaddr) { raw = {}; return; } + + uint64_t kaddr = _buf_kaddr; + _buf_kaddr = 0; + raw = {}; + + uint64_t r = 0; + get_kernel_shellcode_u64_result([kaddr](Assembler* a, GpX& x) -> KModErr { + KModErr err = KModErr::ERR_MODULE_PARAM; + kernel_module::export_symbol::path_put(a, err, kaddr); + RETURN_IF_ERROR(err); + return KModErr::OK; + }, r); + + kernel_module::free_kernel_mem(kaddr); + } + + uint64_t release_kaddr() { + uint64_t kaddr = _buf_kaddr; + _buf_kaddr = 0; + raw = {}; + return kaddr; + } + + kpath raw{}; + +private: + uint64_t _buf_kaddr = 0; +}; + +KModErr acquire_kpath(const std::string & path_str, scoped_kpath & out_scoped) { + using LookupFlags = kernel_module::export_symbol::LookupFlags; + + int page_size = kernel_module::get_page_size(); + + uint64_t buf_kaddr = 0; + RETURN_IF_ERROR(kernel_module::alloc_kernel_mem(page_size, buf_kaddr)); + RETURN_IF_ERROR(kernel_module::fill00_kernel_mem(buf_kaddr, page_size)); + + uint64_t r = 0; + RETURN_IF_ERROR(get_kernel_shellcode_u64_result([buf_kaddr, &path_str](Assembler* a, GpX & x) -> KModErr { + KModErr err = KModErr::ERR_MODULE_PARAM; + aarch64_asm_set_x_cstr_ptr(a, x10, path_str); + kernel_module::export_symbol::kern_path(a, err, x10, LookupFlags::LOOKUP_FOLLOW, buf_kaddr); + RETURN_IF_ERROR(err); + return KModErr::OK; + }, r)); + + kpath st_kp = {0}; + RETURN_IF_ERROR(kernel_module::read_kernel_mem(buf_kaddr, &st_kp, sizeof(st_kp))); + out_scoped.init(buf_kaddr, st_kp); + return KModErr::OK; +} + +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_system_file/module_fake_system_file.cpp" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_system_file/module_fake_system_file.cpp" new file mode 100644 index 00000000..e3b6c3b7 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_system_file/module_fake_system_file.cpp" @@ -0,0 +1,127 @@ +#include +#include +#include +#include + +#include "kernel_struct_path_helper.h" +#include "fd_guard.h" + +namespace fs = std::filesystem; + +#define SK_DEBUG_MODE +#ifdef SK_DEBUG_MODE + #define LOG_DBG(fmt, ...) printf(" [Debug] " fmt, ##__VA_ARGS__) +#else + #define LOG_DBG(fmt, ...) do {} while(0) +#endif + +struct FakeFile { + fs::path system_file_path; + fs::path fake_file_path; + FakeFile(fs::path target, fs::path source) + : system_file_path(std::move(target)), fake_file_path(std::move(source)) {} +}; + +KModErr kernel_hijack_file(const fs::path& system_file_path, const fs::path& fake_file_path) { + std::error_code ec; + if (!fs::exists(system_file_path, ec) || ec) return KModErr::ERR_MODULE_OPEN_FILE; + if (!fs::exists(fake_file_path, ec) || ec) return KModErr::ERR_MODULE_OPEN_FILE; + if (!fs::is_regular_file(system_file_path, ec) || ec) return KModErr::ERR_MODULE_OPEN_FILE; + if (!fs::is_regular_file(fake_file_path, ec) || ec) return KModErr::ERR_MODULE_OPEN_FILE; + + uint32_t i_mapping_offset = 0; + RETURN_IF_ERROR(kernel_module::get_inode_i_mapping_offset(i_mapping_offset)); + LOG_DBG("i_mapping_offset:%d\n", i_mapping_offset); + + uint32_t i_size_offset = 0; + RETURN_IF_ERROR(kernel_module::get_inode_i_size_offset(i_size_offset)); + LOG_DBG("i_size_offset:%d\n", i_size_offset); + + int fd = open(system_file_path.c_str(), O_RDONLY); + int fake_fd = open(fake_file_path.c_str(), O_RDONLY); + + fd_guard f(fd); + fd_guard fake_f(fake_fd); + + scoped_kpath kpath; + scoped_kpath fake_kpath; + RETURN_IF_ERROR(acquire_kpath(system_file_path.c_str(), kpath)); + RETURN_IF_ERROR(acquire_kpath(fake_file_path.c_str(), fake_kpath)); + + uint32_t d_inode_offset = 0; + RETURN_IF_ERROR(kernel_module::get_dentry_d_inode_offset(d_inode_offset)); + + uint64_t inode_ptr = 0; + uint64_t fake_inode_ptr = 0; + RETURN_IF_ERROR(kernel_module::read_kernel_mem(kpath.raw.dentry + d_inode_offset, &inode_ptr, sizeof(inode_ptr))); + RETURN_IF_ERROR(kernel_module::read_kernel_mem(fake_kpath.raw.dentry + d_inode_offset, &fake_inode_ptr, sizeof(fake_inode_ptr))); + LOG_DBG("inode:%lx\n", inode_ptr); + LOG_DBG("fake_inode:%lx\n", fake_inode_ptr); + + uint64_t i_mapping_pptr = inode_ptr + i_mapping_offset; + uint64_t i_mapping_ptr = 0; + uint64_t fake_i_mapping_pptr = fake_inode_ptr + i_mapping_offset; + uint64_t fake_i_mapping_ptr = 0; + RETURN_IF_ERROR(kernel_module::read_kernel_mem(i_mapping_pptr, &i_mapping_ptr, sizeof(i_mapping_ptr))); + RETURN_IF_ERROR(kernel_module::read_kernel_mem(fake_i_mapping_pptr, &fake_i_mapping_ptr, sizeof(fake_i_mapping_ptr))); + LOG_DBG("i_mapping_ptr:%lx\n", i_mapping_ptr); + LOG_DBG("fake_i_mapping_ptr:%lx\n", fake_i_mapping_ptr); + + RETURN_IF_ERROR(kernel_module::write_kernel_rw_mem_atomic64(i_mapping_pptr, fake_i_mapping_ptr)); + + uint64_t r = 0; + RETURN_IF_ERROR(get_kernel_shellcode_u64_result([inode_ptr, i_mapping_pptr, i_mapping_ptr, fake_i_mapping_ptr](Assembler* a, GpX & x) -> KModErr { + KModErr err = KModErr::ERR_MODULE_PARAM; + aarch64_asm_mov_x(a, x10, i_mapping_ptr); + kernel_module::export_symbol::invalidate_inode_pages2(a, err, x10); + RETURN_IF_ERROR(err); + return KModErr::OK; + }, r)); + + uint64_t i_size_pptr = inode_ptr + i_size_offset; + uint64_t fake_i_size_pptr = fake_inode_ptr + i_size_offset; + uint64_t fake_i_size = 0; + RETURN_IF_ERROR(kernel_module::read_kernel_mem(fake_i_size_pptr, &fake_i_size, sizeof(fake_i_size))); + LOG_DBG("fake_i_size:%ld\n", fake_i_size); + RETURN_IF_ERROR(kernel_module::write_kernel_rw_mem_atomic64(i_size_pptr, fake_i_size)); + + kpath.release_kaddr(); + fake_kpath.release_kaddr(); + return KModErr::OK; +} + +// SKRoot模块入口函数 +int skroot_module_main(const char* root_key, const char* module_private_dir) { + printf("[SKRoot] Module Start: System File Fake Demo\n"); + + fs::path base_dir = module_private_dir; + + // 演示替换 /system/etc/hosts,重启后 ping www.aaa316.com,显示 123.123.123.123 即成功伪造。 + std::vector vec_fake_file = { + // 格式: { 目标系统路径, 你的伪造文件路径 } + { "/system/etc/hosts", base_dir / "hosts" }, + //{ "/system/framework/framework.jar", base_dir / "framework.jar" }, + //{ "/system/framework/services.jar", base_dir / "services.jar" }, + + // 如果需要修改build.prop里的属性,则还需要同时使用resetprop进行修改,两个一起修改就可以做到无痕。 + // 这里伪造build.prop文件的目的是为了防止App利用漏洞提权到system权限,导致暴露身份; + //{ "/system/build.prop", base_dir / "build.prop" }, + }; + + printf("[SKRoot] Loading file redirection rules...\n"); + for (const auto& item : vec_fake_file) { + printf(" [+] Rule Added:\n"); + printf(" Target: %s\n", item.system_file_path.c_str()); + printf(" Source: %s\n", item.fake_file_path.c_str()); + KModErr err = kernel_hijack_file(item.system_file_path, item.fake_file_path); + printf(" Result: [%s]\n", to_string(err).c_str()); + } + printf("[SKRoot] All rules loaded.\n"); + return 0; +} + +SKROOT_MODULE_NAME("系统文件伪造 Demo") +SKROOT_MODULE_VERSION("1.0.0") +SKROOT_MODULE_DESC("内核级伪造 /system 只读文件,实现内容无痕篡改;无视任何文件校验,完美过所有侦测手段。") +SKROOT_MODULE_AUTHOR("SKRoot") +SKROOT_MODULE_UUID32("xhTxKsI5kHacgHJ04b5VhO4ffiOP4sdc") \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_thermal/jni/Android.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_thermal/jni/Android.mk" new file mode 100644 index 00000000..81864fb6 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_thermal/jni/Android.mk" @@ -0,0 +1,16 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) +LOCAL_MODULE := module_fake_thermal + +LOCAL_SRC_FILES := ../module_fake_thermal.cpp ../patch_base.cpp ../patch_thermal_zone_get_temp.cpp + +KERNEL_MODULE_KIT := $(LOCAL_PATH)/../../kernel_module_kit +LOCAL_C_INCLUDES += $(KERNEL_MODULE_KIT)/include +LOCAL_LDFLAGS += $(KERNEL_MODULE_KIT)/lib/libkernel_module_kit_static.a + +include $(LOCAL_PATH)/build_macros.mk + +include $(BUILD_SHARED_LIBRARY) + + diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_thermal/jni/Application.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_thermal/jni/Application.mk" new file mode 100644 index 00000000..2500a8a7 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_thermal/jni/Application.mk" @@ -0,0 +1,2 @@ +APP_ABI := arm64-v8a +APP_STL := c++_static \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_thermal/jni/build_macros.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_thermal/jni/build_macros.mk" new file mode 100644 index 00000000..a6f31501 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_thermal/jni/build_macros.mk" @@ -0,0 +1,21 @@ +COMMON_CPPFLAGS := \ + -std=c++20 \ + -fPIC \ + -fvisibility=hidden \ + -fno-stack-protector \ + -ffunction-sections \ + -fdata-sections \ + -flto=thin + +COMMON_LDFLAGS := \ + -Wl,-O2 \ + -Wl,--gc-sections \ + -Wl,-s \ + -flto=thin + +COMMON_INCLUDES := \ + $(LOCAL_PATH)/../../../ + +LOCAL_CPPFLAGS += $(COMMON_CPPFLAGS) +LOCAL_LDFLAGS += $(COMMON_LDFLAGS) +LOCAL_C_INCLUDES += $(COMMON_INCLUDES) diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_thermal/module_fake_thermal.cpp" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_thermal/module_fake_thermal.cpp" new file mode 100644 index 00000000..6708ffa7 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_thermal/module_fake_thermal.cpp" @@ -0,0 +1,31 @@ +#include "patch_thermal_zone_get_temp.h" +#include "kernel_module_kit_umbrella.h" + +// 开始修补内核 +static KModErr patch_kernel_handler() { + uint64_t thermal_zone_get_temp = 0; + RETURN_IF_ERROR(kernel_module::kallsyms_lookup_name("thermal_zone_get_temp", thermal_zone_get_temp)); + printf("thermal_zone_get_temp, addr: %p\n", (void*)thermal_zone_get_temp); + + PatchBase patchBase; + PatchThermalZoneGetTemp patchThermalZoneGetTemp(patchBase, thermal_zone_get_temp); + KModErr err = patchThermalZoneGetTemp.patch_thermal_zone_get_temp(); + printf("patch thermal_zone_get_temp ret: %s\n", to_string(err).c_str()); + return err; +} + +// SKRoot模块入口函数 +int skroot_module_main(const char* root_key, const char* module_private_dir) { + printf("Hello! module_fake_thermal!\n"); + KModErr err = patch_kernel_handler(); + printf("patch_kernel_handler ret:%s\n", to_string(err).c_str()); + return 0; +} + +// SKRoot 模块名片 +SKROOT_MODULE_NAME("温控解除") +SKROOT_MODULE_VERSION("1.0.0") +SKROOT_MODULE_DESC("内核级伪装处理器温度曲线,实现去除温控,安全可靠。") +SKROOT_MODULE_AUTHOR("SKRoot") +SKROOT_MODULE_UUID32("kO8hT9tT2fB0hY9hV2bB4eJ6aY2nQ6kL") +SKROOT_MODULE_UPDATE_JSON("https://abcz316.github.io/SKRoot-linuxKernelRoot/module_fake_thermal/update.json") \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_thermal/patch_base.cpp" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_thermal/patch_base.cpp" new file mode 100644 index 00000000..e72728fa --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_thermal/patch_base.cpp" @@ -0,0 +1,22 @@ +#include "patch_base.h" +using namespace asmjit; +using namespace asmjit::a64; +using namespace asmjit::a64::Predicate; + +PatchBase::PatchBase() {} + +PatchBase::PatchBase(const PatchBase& other) {} + +PatchBase::~PatchBase() {} + +KModErr PatchBase::patch_kernel_before_hook(uint64_t kaddr, const Assembler* a) { + std::vector bytes = aarch64_asm_to_bytes(a); + RETURN_IF_ERROR(kernel_module::install_kernel_function_before_hook(kaddr, bytes)); + return KModErr::OK; +} + +KModErr PatchBase::patch_kernel_after_hook(uint64_t kaddr, const Assembler* a) { + std::vector bytes = aarch64_asm_to_bytes(a); + RETURN_IF_ERROR(kernel_module::install_kernel_function_after_hook(kaddr, bytes)); + return KModErr::OK; +} \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_thermal/patch_base.h" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_thermal/patch_base.h" new file mode 100644 index 00000000..9413cf75 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_thermal/patch_base.h" @@ -0,0 +1,14 @@ +#pragma once +#include +#include +#include "kernel_module_kit_umbrella.h" + +class PatchBase { +public: + PatchBase(); + PatchBase(const PatchBase& other); + ~PatchBase(); +protected: + KModErr patch_kernel_before_hook(uint64_t kaddr, const asmjit::a64::Assembler* a); + KModErr patch_kernel_after_hook(uint64_t kaddr, const asmjit::a64::Assembler* a); +}; diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_thermal/patch_thermal_zone_get_temp.cpp" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_thermal/patch_thermal_zone_get_temp.cpp" new file mode 100644 index 00000000..cc2a7180 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_thermal/patch_thermal_zone_get_temp.cpp" @@ -0,0 +1,90 @@ +#include "patch_thermal_zone_get_temp.h" +#include +using namespace asmjit; +using namespace asmjit::a64; +using namespace asmjit::a64::Predicate; + +/* +在 AArch64(ARM64)架构中, 根据 AAPCS64 调用约定: + X0–X7:传递参数和返回值 + X8:系统调用号或临时 + X9–X15:调用者易失(caller‑saved)临时寄存器 + X16–X17(IP0/IP1):过程内调用临时寄存器,用于短期跳转代码 + X18:平台保留寄存器(platform register),arm64内核启用SCS时,会x18作为shadow call stack指针 + X19–X28:被调用者保存寄存器(callee‑saved) + X29(FP):帧指针 + X30(LR):链接寄存器 + SP:栈指针 + +在HOOK内核函数中: +1.必须要保存、恢复的寄存器:x0–x7、X19–X28、X29-X30 +2.能自由修改、无需额外保存/恢复的寄存器是:x9–x15 或 x16–x17(IP0/IP1) +3.尽量避开使用的寄存器:x18 + +简而言之:X9到X15之间的寄存器可以随便用,其他寄存器需要先保存再用,用完需恢复。 + +ABI 规定哪些寄存器需要保存? +caller-saved(会被调用者破坏):X0..X17、Q0..Q7 +callee-saved(必须由被调函数保存):X19..X29、Q8..Q15、SP、FP、LR +也就是说,像 get_task_mm 这种标准C函数,它自己保证不会破坏 callee-saved 寄存器。 +*/ + +PatchThermalZoneGetTemp::PatchThermalZoneGetTemp(const PatchBase& patch_base, uint64_t thermal_zone_get_temp) : PatchBase(patch_base), m_thermal_zone_get_temp(thermal_zone_get_temp) {} + +PatchThermalZoneGetTemp::~PatchThermalZoneGetTemp() {} + +KModErr PatchThermalZoneGetTemp::patch_thermal_zone_get_temp() { + KModErr err = KModErr::OK; + aarch64_asm_ctx asm_ctx = init_aarch64_asm(); + auto a = asm_ctx.assembler(); + Label L_end = a->newLabel(); + kernel_module::arm64_before_hook_start(a); + + kernel_module::arm64hook_emit_load_original_func(a, x10); + { + RegProtectGuard g1(a, x1); + a->blr(x10); // 手动调用一次内核原始获取温度函数。 + } + a->cbnz(w0, L_end); // 返回值非0,代表不成功,则直接结束。 + + a->ldr(w10, ptr(x1)); // 读取内核即将要输出的温度。 + + aarch64_asm_mov_w(a, w11, 35000); // 低温区放行 + a->cmp(w10, w11); + a->b(CondCode::kLE, L_end); + + aarch64_asm_mov_w(a, w11, 95000); // 熔断保护 (通用版底线 95度) + a->cmp(w10, w11); + a->b(CondCode::kGE, L_end); + + // 精细化系数 0.37 (37%) + // 逻辑:(Real - 35) * 0.37 + 35 + // 效果:95度(真实) -> 59.1度(伪装)。 + // 这是一个巧妙的数值:平时奔放,极限时触发轻度温控保护主板。 + // int fake = 35000 + ((real - 35000) * 37 / 100); + // kernel_module::export_symbol::printk(a, err, "[!!!] thermal_zone_get_temp real val: %d\n", w10); + + // (real - 35000) + aarch64_asm_mov_w(a, w11, 35000); + a->sub(w12, w10, w11); + + // (real - 35000) * 35 + aarch64_asm_mov_w(a, w11, 35); + a->mul(w12, w12, w11); + + // (real - 35000) * 35 / 100 + aarch64_asm_mov_w(a, w11, 100); + a->sdiv(w12, w12, w11); + + // 35000 + ((real - 35000) * 35 / 100) + aarch64_asm_mov_w(a, w11, 35000); + a->add(w12, w12, w11); + + // kernel_module::export_symbol::printk(a, err, "[!!!] thermal_zone_get_temp fake val: %d\n", w12); + + a->str(w12, ptr(x1)); + + a->bind(L_end); + kernel_module::arm64_before_hook_end(a, false); + return patch_kernel_before_hook(m_thermal_zone_get_temp, a); +} \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_thermal/patch_thermal_zone_get_temp.h" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_thermal/patch_thermal_zone_get_temp.h" new file mode 100644 index 00000000..85e4a4ce --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_fake_thermal/patch_thermal_zone_get_temp.h" @@ -0,0 +1,14 @@ +#pragma once +#include +#include +#include "patch_base.h" + +class PatchThermalZoneGetTemp : public PatchBase { +public: + PatchThermalZoneGetTemp(const PatchBase& patch_base, uint64_t thermal_zone_get_temp); + ~PatchThermalZoneGetTemp(); + + KModErr patch_thermal_zone_get_temp(); +private: + uint64_t m_thermal_zone_get_temp = 0; +}; \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hello_world/jni/Android.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hello_world/jni/Android.mk" new file mode 100644 index 00000000..0f6859ec --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hello_world/jni/Android.mk" @@ -0,0 +1,17 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) +LOCAL_MODULE := module_hello_world + +LOCAL_SRC_FILES := \ + $(LOCAL_PATH)/../module_hello_world.cpp\ + +KERNEL_MODULE_KIT := $(LOCAL_PATH)/../../kernel_module_kit +LOCAL_C_INCLUDES += $(KERNEL_MODULE_KIT)/include +LOCAL_LDFLAGS += $(KERNEL_MODULE_KIT)/lib/libkernel_module_kit_static.a + +include $(LOCAL_PATH)/build_macros.mk + +include $(BUILD_SHARED_LIBRARY) + + diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hello_world/jni/Application.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hello_world/jni/Application.mk" new file mode 100644 index 00000000..2500a8a7 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hello_world/jni/Application.mk" @@ -0,0 +1,2 @@ +APP_ABI := arm64-v8a +APP_STL := c++_static \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hello_world/jni/build_macros.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hello_world/jni/build_macros.mk" new file mode 100644 index 00000000..a6f31501 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hello_world/jni/build_macros.mk" @@ -0,0 +1,21 @@ +COMMON_CPPFLAGS := \ + -std=c++20 \ + -fPIC \ + -fvisibility=hidden \ + -fno-stack-protector \ + -ffunction-sections \ + -fdata-sections \ + -flto=thin + +COMMON_LDFLAGS := \ + -Wl,-O2 \ + -Wl,--gc-sections \ + -Wl,-s \ + -flto=thin + +COMMON_INCLUDES := \ + $(LOCAL_PATH)/../../../ + +LOCAL_CPPFLAGS += $(COMMON_CPPFLAGS) +LOCAL_LDFLAGS += $(COMMON_LDFLAGS) +LOCAL_C_INCLUDES += $(COMMON_INCLUDES) diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hello_world/module_hello_world.cpp" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hello_world/module_hello_world.cpp" new file mode 100644 index 00000000..8f38e1d2 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hello_world/module_hello_world.cpp" @@ -0,0 +1,49 @@ +#include +#include "kernel_module_kit_umbrella.h" + +using namespace asmjit; +using namespace asmjit::a64; +using namespace asmjit::a64::Predicate; + +KModErr run_kernel_shellcode(uint64_t & result) { + aarch64_asm_ctx asm_ctx = init_aarch64_asm(); + auto a = asm_ctx.assembler(); + kernel_module::arm64_module_asm_func_start(a); + + // TODO: 在此开始输入你的aarch64 asm指令 + aarch64_asm_mov_x(a, x0, 0x12345); + kernel_module::arm64_module_asm_func_end(a, x0); + std::vector bytes = aarch64_asm_to_bytes(a); + RETURN_IF_ERROR(kernel_module::execute_kernel_asm_func(bytes, result)); + return KModErr::OK; +} + +/*************************************************************************** + * SKRoot 模块入口函数(必须提供) + * 被执行时机:在 zygote64 进程启动前。 + * 参数: + * root_key ROOT 密钥文本。 + * module_private_dir 模块私有目录(受隐藏保护;需隐藏的文件请放在此目录)。 + * 返回值:默认 0;任意返回值仅记录到日志,便于排查。 + * 说明:skroot_module_main 返回后,代表本模块执行结束。如需继续运行请fork(); + ***************************************************************************/ +int skroot_module_main(const char* root_key, const char* module_private_dir) { + printf("[module_hello_world] starting... \n"); + printf("[module_hello_world] root_key len=%zu\n", strlen(root_key)); + printf("[module_hello_world] module_private_dir=%s\n", module_private_dir); + + // 开始执行内核shellcode。 + uint64_t result = 0; + KModErr err = run_kernel_shellcode(result); + printf("run_kernel_shellcode err: %s\n", to_string(err).c_str()); + printf(result == 0x12345 ? "OK" : "FAILED"); + printf("\n"); + return (int)result; +} + +// SKRoot 模块名片 +SKROOT_MODULE_NAME("演示模块名称") // 在此填写模块名称 +SKROOT_MODULE_VERSION("1.0.0") // 在此填写模块版本号 +SKROOT_MODULE_DESC("演示模块描述") // 在此填写模块描述文本 +SKROOT_MODULE_AUTHOR("演示作者名字") // 在此填写模块作者 +SKROOT_MODULE_UUID32("3608c9af28db4dcfc05c32bbc584753e") // 在此填写模块UUID,32个随机字符 [0-9a-zA-Z] \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/cJSON.cpp" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/cJSON.cpp" new file mode 100644 index 00000000..faa3e297 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/cJSON.cpp" @@ -0,0 +1,3129 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +/* cJSON */ +/* JSON parser in C. */ + +/* disable warnings about old C89 functions in MSVC */ +#if !defined(_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) +#define _CRT_SECURE_NO_DEPRECATE +#endif + +#ifdef __GNUC__ +#pragma GCC visibility push(default) +#endif +#if defined(_MSC_VER) +#pragma warning (push) +/* disable warning about single line comments in system headers */ +#pragma warning (disable : 4001) +#endif + +#include +#include +#include +#include +#include +#include +#include + +#ifdef ENABLE_LOCALES +#include +#endif + +#if defined(_MSC_VER) +#pragma warning (pop) +#endif +#ifdef __GNUC__ +#pragma GCC visibility pop +#endif + +#include "cJSON.h" + +/* define our own boolean type */ +#ifdef true +#undef true +#endif +#define true ((cJSON_bool)1) + +#ifdef false +#undef false +#endif +#define false ((cJSON_bool)0) + +/* define isnan and isinf for ANSI C, if in C99 or above, isnan and isinf has been defined in math.h */ +#ifndef isinf +#define isinf(d) (isnan((d - d)) && !isnan(d)) +#endif +#ifndef isnan +#define isnan(d) (d != d) +#endif + +#ifndef NAN +#ifdef _WIN32 +#define NAN sqrt(-1.0) +#else +#define NAN 0.0/0.0 +#endif +#endif + +typedef struct { + const unsigned char *json; + size_t position; +} error; +static error global_error = { NULL, 0 }; + +CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void) +{ + return (const char*) (global_error.json + global_error.position); +} + +CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item) +{ + if (!cJSON_IsString(item)) + { + return NULL; + } + + return item->valuestring; +} + +CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item) +{ + if (!cJSON_IsNumber(item)) + { + return (double) NAN; + } + + return item->valuedouble; +} + +/* This is a safeguard to prevent copy-pasters from using incompatible C and header files */ +#if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 7) || (CJSON_VERSION_PATCH != 16) + #error cJSON.h and cJSON.c have different versions. Make sure that both have the same. +#endif + +CJSON_PUBLIC(const char*) cJSON_Version(void) +{ + static char version[15]; + sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH); + + return version; +} + +/* Case insensitive string comparison, doesn't consider two NULL pointers equal though */ +static int case_insensitive_strcmp(const unsigned char *string1, const unsigned char *string2) +{ + if ((string1 == NULL) || (string2 == NULL)) + { + return 1; + } + + if (string1 == string2) + { + return 0; + } + + for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++) + { + if (*string1 == '\0') + { + return 0; + } + } + + return tolower(*string1) - tolower(*string2); +} + +typedef struct internal_hooks +{ + void *(CJSON_CDECL *allocate)(size_t size); + void (CJSON_CDECL *deallocate)(void *pointer); + void *(CJSON_CDECL *reallocate)(void *pointer, size_t size); +} internal_hooks; + +#if defined(_MSC_VER) +/* work around MSVC error C2322: '...' address of dllimport '...' is not static */ +static void * CJSON_CDECL internal_malloc(size_t size) +{ + return malloc(size); +} +static void CJSON_CDECL internal_free(void *pointer) +{ + free(pointer); +} +static void * CJSON_CDECL internal_realloc(void *pointer, size_t size) +{ + return realloc(pointer, size); +} +#else +#define internal_malloc malloc +#define internal_free free +#define internal_realloc realloc +#endif + +/* strlen of character literals resolved at compile time */ +#define static_strlen(string_literal) (sizeof(string_literal) - sizeof("")) + +static internal_hooks global_hooks = { internal_malloc, internal_free, internal_realloc }; + +static unsigned char* cJSON_strdup(const unsigned char* string, const internal_hooks * const hooks) +{ + size_t length = 0; + unsigned char *copy = NULL; + + if (string == NULL) + { + return NULL; + } + + length = strlen((const char*)string) + sizeof(""); + copy = (unsigned char*)hooks->allocate(length); + if (copy == NULL) + { + return NULL; + } + memcpy(copy, string, length); + + return copy; +} + +CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks) +{ + if (hooks == NULL) + { + /* Reset hooks */ + global_hooks.allocate = malloc; + global_hooks.deallocate = free; + global_hooks.reallocate = realloc; + return; + } + + global_hooks.allocate = malloc; + if (hooks->malloc_fn != NULL) + { + global_hooks.allocate = hooks->malloc_fn; + } + + global_hooks.deallocate = free; + if (hooks->free_fn != NULL) + { + global_hooks.deallocate = hooks->free_fn; + } + + /* use realloc only if both free and malloc are used */ + global_hooks.reallocate = NULL; + if ((global_hooks.allocate == malloc) && (global_hooks.deallocate == free)) + { + global_hooks.reallocate = realloc; + } +} + +/* Internal constructor. */ +static cJSON *cJSON_New_Item(const internal_hooks * const hooks) +{ + cJSON* node = (cJSON*)hooks->allocate(sizeof(cJSON)); + if (node) + { + memset(node, '\0', sizeof(cJSON)); + } + + return node; +} + +/* Delete a cJSON structure. */ +CJSON_PUBLIC(void) cJSON_Delete(cJSON *item) +{ + cJSON *next = NULL; + while (item != NULL) + { + next = item->next; + if (!(item->type & cJSON_IsReference) && (item->child != NULL)) + { + cJSON_Delete(item->child); + } + if (!(item->type & cJSON_IsReference) && (item->valuestring != NULL)) + { + global_hooks.deallocate(item->valuestring); + } + if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) + { + global_hooks.deallocate(item->string); + } + global_hooks.deallocate(item); + item = next; + } +} + +/* get the decimal point character of the current locale */ +static unsigned char get_decimal_point(void) +{ +#ifdef ENABLE_LOCALES + struct lconv *lconv = localeconv(); + return (unsigned char) lconv->decimal_point[0]; +#else + return '.'; +#endif +} + +typedef struct +{ + const unsigned char *content; + size_t length; + size_t offset; + size_t depth; /* How deeply nested (in arrays/objects) is the input at the current offset. */ + internal_hooks hooks; +} parse_buffer; + +/* check if the given size is left to read in a given parse buffer (starting with 1) */ +#define can_read(buffer, size) ((buffer != NULL) && (((buffer)->offset + size) <= (buffer)->length)) +/* check if the buffer can be accessed at the given index (starting with 0) */ +#define can_access_at_index(buffer, index) ((buffer != NULL) && (((buffer)->offset + index) < (buffer)->length)) +#define cannot_access_at_index(buffer, index) (!can_access_at_index(buffer, index)) +/* get a pointer to the buffer at the position */ +#define buffer_at_offset(buffer) ((buffer)->content + (buffer)->offset) + +/* Parse the input text to generate a number, and populate the result into item. */ +static cJSON_bool parse_number(cJSON * const item, parse_buffer * const input_buffer) +{ + double number = 0; + unsigned char *after_end = NULL; + unsigned char number_c_string[64]; + unsigned char decimal_point = get_decimal_point(); + size_t i = 0; + + if ((input_buffer == NULL) || (input_buffer->content == NULL)) + { + return false; + } + + /* copy the number into a temporary buffer and replace '.' with the decimal point + * of the current locale (for strtod) + * This also takes care of '\0' not necessarily being available for marking the end of the input */ + for (i = 0; (i < (sizeof(number_c_string) - 1)) && can_access_at_index(input_buffer, i); i++) + { + switch (buffer_at_offset(input_buffer)[i]) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case '+': + case '-': + case 'e': + case 'E': + number_c_string[i] = buffer_at_offset(input_buffer)[i]; + break; + + case '.': + number_c_string[i] = decimal_point; + break; + + default: + goto loop_end; + } + } +loop_end: + number_c_string[i] = '\0'; + + number = strtod((const char*)number_c_string, (char**)&after_end); + if (number_c_string == after_end) + { + return false; /* parse_error */ + } + + item->valuedouble = number; + + /* use saturation in case of overflow */ + if (number >= INT_MAX) + { + item->valueint = INT_MAX; + } + else if (number <= (double)INT_MIN) + { + item->valueint = INT_MIN; + } + else + { + item->valueint = (int)number; + } + + item->type = cJSON_Number; + + input_buffer->offset += (size_t)(after_end - number_c_string); + return true; +} + +/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */ +CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number) +{ + if (number >= INT_MAX) + { + object->valueint = INT_MAX; + } + else if (number <= (double)INT_MIN) + { + object->valueint = INT_MIN; + } + else + { + object->valueint = (int)number; + } + + return object->valuedouble = number; +} + +CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring) +{ + char *copy = NULL; + /* if object's type is not cJSON_String or is cJSON_IsReference, it should not set valuestring */ + if ((object == NULL) || !(object->type & cJSON_String) || (object->type & cJSON_IsReference)) + { + return NULL; + } + /* return NULL if the object is corrupted */ + if (object->valuestring == NULL) + { + return NULL; + } + if (strlen(valuestring) <= strlen(object->valuestring)) + { + strcpy(object->valuestring, valuestring); + return object->valuestring; + } + copy = (char*) cJSON_strdup((const unsigned char*)valuestring, &global_hooks); + if (copy == NULL) + { + return NULL; + } + if (object->valuestring != NULL) + { + cJSON_free(object->valuestring); + } + object->valuestring = copy; + + return copy; +} + +typedef struct +{ + unsigned char *buffer; + size_t length; + size_t offset; + size_t depth; /* current nesting depth (for formatted printing) */ + cJSON_bool noalloc; + cJSON_bool format; /* is this print a formatted print */ + internal_hooks hooks; +} printbuffer; + +/* realloc printbuffer if necessary to have at least "needed" bytes more */ +static unsigned char* ensure(printbuffer * const p, size_t needed) +{ + unsigned char *newbuffer = NULL; + size_t newsize = 0; + + if ((p == NULL) || (p->buffer == NULL)) + { + return NULL; + } + + if ((p->length > 0) && (p->offset >= p->length)) + { + /* make sure that offset is valid */ + return NULL; + } + + if (needed > INT_MAX) + { + /* sizes bigger than INT_MAX are currently not supported */ + return NULL; + } + + needed += p->offset + 1; + if (needed <= p->length) + { + return p->buffer + p->offset; + } + + if (p->noalloc) { + return NULL; + } + + /* calculate new buffer size */ + if (needed > (INT_MAX / 2)) + { + /* overflow of int, use INT_MAX if possible */ + if (needed <= INT_MAX) + { + newsize = INT_MAX; + } + else + { + return NULL; + } + } + else + { + newsize = needed * 2; + } + + if (p->hooks.reallocate != NULL) + { + /* reallocate with realloc if available */ + newbuffer = (unsigned char*)p->hooks.reallocate(p->buffer, newsize); + if (newbuffer == NULL) + { + p->hooks.deallocate(p->buffer); + p->length = 0; + p->buffer = NULL; + + return NULL; + } + } + else + { + /* otherwise reallocate manually */ + newbuffer = (unsigned char*)p->hooks.allocate(newsize); + if (!newbuffer) + { + p->hooks.deallocate(p->buffer); + p->length = 0; + p->buffer = NULL; + + return NULL; + } + + memcpy(newbuffer, p->buffer, p->offset + 1); + p->hooks.deallocate(p->buffer); + } + p->length = newsize; + p->buffer = newbuffer; + + return newbuffer + p->offset; +} + +/* calculate the new length of the string in a printbuffer and update the offset */ +static void update_offset(printbuffer * const buffer) +{ + const unsigned char *buffer_pointer = NULL; + if ((buffer == NULL) || (buffer->buffer == NULL)) + { + return; + } + buffer_pointer = buffer->buffer + buffer->offset; + + buffer->offset += strlen((const char*)buffer_pointer); +} + +/* securely comparison of floating-point variables */ +static cJSON_bool compare_double(double a, double b) +{ + double maxVal = fabs(a) > fabs(b) ? fabs(a) : fabs(b); + return (fabs(a - b) <= maxVal * DBL_EPSILON); +} + +/* Render the number nicely from the given item into a string. */ +static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + double d = item->valuedouble; + int length = 0; + size_t i = 0; + unsigned char number_buffer[26] = {0}; /* temporary buffer to print the number into */ + unsigned char decimal_point = get_decimal_point(); + double test = 0.0; + + if (output_buffer == NULL) + { + return false; + } + + /* This checks for NaN and Infinity */ + if (isnan(d) || isinf(d)) + { + length = sprintf((char*)number_buffer, "null"); + } + else if(d == (double)item->valueint) + { + length = sprintf((char*)number_buffer, "%d", item->valueint); + } + else + { + /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */ + length = sprintf((char*)number_buffer, "%1.15g", d); + + /* Check whether the original double can be recovered */ + if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || !compare_double((double)test, d)) + { + /* If not, print with 17 decimal places of precision */ + length = sprintf((char*)number_buffer, "%1.17g", d); + } + } + + /* sprintf failed or buffer overrun occurred */ + if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1))) + { + return false; + } + + /* reserve appropriate space in the output */ + output_pointer = ensure(output_buffer, (size_t)length + sizeof("")); + if (output_pointer == NULL) + { + return false; + } + + /* copy the printed number to the output and replace locale + * dependent decimal point with '.' */ + for (i = 0; i < ((size_t)length); i++) + { + if (number_buffer[i] == decimal_point) + { + output_pointer[i] = '.'; + continue; + } + + output_pointer[i] = number_buffer[i]; + } + output_pointer[i] = '\0'; + + output_buffer->offset += (size_t)length; + + return true; +} + +/* parse 4 digit hexadecimal number */ +static unsigned parse_hex4(const unsigned char * const input) +{ + unsigned int h = 0; + size_t i = 0; + + for (i = 0; i < 4; i++) + { + /* parse digit */ + if ((input[i] >= '0') && (input[i] <= '9')) + { + h += (unsigned int) input[i] - '0'; + } + else if ((input[i] >= 'A') && (input[i] <= 'F')) + { + h += (unsigned int) 10 + input[i] - 'A'; + } + else if ((input[i] >= 'a') && (input[i] <= 'f')) + { + h += (unsigned int) 10 + input[i] - 'a'; + } + else /* invalid */ + { + return 0; + } + + if (i < 3) + { + /* shift left to make place for the next nibble */ + h = h << 4; + } + } + + return h; +} + +/* converts a UTF-16 literal to UTF-8 + * A literal can be one or two sequences of the form \uXXXX */ +static unsigned char utf16_literal_to_utf8(const unsigned char * const input_pointer, const unsigned char * const input_end, unsigned char **output_pointer) +{ + long unsigned int codepoint = 0; + unsigned int first_code = 0; + const unsigned char *first_sequence = input_pointer; + unsigned char utf8_length = 0; + unsigned char utf8_position = 0; + unsigned char sequence_length = 0; + unsigned char first_byte_mark = 0; + + if ((input_end - first_sequence) < 6) + { + /* input ends unexpectedly */ + goto fail; + } + + /* get the first utf16 sequence */ + first_code = parse_hex4(first_sequence + 2); + + /* check that the code is valid */ + if (((first_code >= 0xDC00) && (first_code <= 0xDFFF))) + { + goto fail; + } + + /* UTF16 surrogate pair */ + if ((first_code >= 0xD800) && (first_code <= 0xDBFF)) + { + const unsigned char *second_sequence = first_sequence + 6; + unsigned int second_code = 0; + sequence_length = 12; /* \uXXXX\uXXXX */ + + if ((input_end - second_sequence) < 6) + { + /* input ends unexpectedly */ + goto fail; + } + + if ((second_sequence[0] != '\\') || (second_sequence[1] != 'u')) + { + /* missing second half of the surrogate pair */ + goto fail; + } + + /* get the second utf16 sequence */ + second_code = parse_hex4(second_sequence + 2); + /* check that the code is valid */ + if ((second_code < 0xDC00) || (second_code > 0xDFFF)) + { + /* invalid second half of the surrogate pair */ + goto fail; + } + + + /* calculate the unicode codepoint from the surrogate pair */ + codepoint = 0x10000 + (((first_code & 0x3FF) << 10) | (second_code & 0x3FF)); + } + else + { + sequence_length = 6; /* \uXXXX */ + codepoint = first_code; + } + + /* encode as UTF-8 + * takes at maximum 4 bytes to encode: + * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */ + if (codepoint < 0x80) + { + /* normal ascii, encoding 0xxxxxxx */ + utf8_length = 1; + } + else if (codepoint < 0x800) + { + /* two bytes, encoding 110xxxxx 10xxxxxx */ + utf8_length = 2; + first_byte_mark = 0xC0; /* 11000000 */ + } + else if (codepoint < 0x10000) + { + /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */ + utf8_length = 3; + first_byte_mark = 0xE0; /* 11100000 */ + } + else if (codepoint <= 0x10FFFF) + { + /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */ + utf8_length = 4; + first_byte_mark = 0xF0; /* 11110000 */ + } + else + { + /* invalid unicode codepoint */ + goto fail; + } + + /* encode as utf8 */ + for (utf8_position = (unsigned char)(utf8_length - 1); utf8_position > 0; utf8_position--) + { + /* 10xxxxxx */ + (*output_pointer)[utf8_position] = (unsigned char)((codepoint | 0x80) & 0xBF); + codepoint >>= 6; + } + /* encode first byte */ + if (utf8_length > 1) + { + (*output_pointer)[0] = (unsigned char)((codepoint | first_byte_mark) & 0xFF); + } + else + { + (*output_pointer)[0] = (unsigned char)(codepoint & 0x7F); + } + + *output_pointer += utf8_length; + + return sequence_length; + +fail: + return 0; +} + +/* Parse the input text into an unescaped cinput, and populate item. */ +static cJSON_bool parse_string(cJSON * const item, parse_buffer * const input_buffer) +{ + const unsigned char *input_pointer = buffer_at_offset(input_buffer) + 1; + const unsigned char *input_end = buffer_at_offset(input_buffer) + 1; + unsigned char *output_pointer = NULL; + unsigned char *output = NULL; + + /* not a string */ + if (buffer_at_offset(input_buffer)[0] != '\"') + { + goto fail; + } + + { + /* calculate approximate size of the output (overestimate) */ + size_t allocation_length = 0; + size_t skipped_bytes = 0; + while (((size_t)(input_end - input_buffer->content) < input_buffer->length) && (*input_end != '\"')) + { + /* is escape sequence */ + if (input_end[0] == '\\') + { + if ((size_t)(input_end + 1 - input_buffer->content) >= input_buffer->length) + { + /* prevent buffer overflow when last input character is a backslash */ + goto fail; + } + skipped_bytes++; + input_end++; + } + input_end++; + } + if (((size_t)(input_end - input_buffer->content) >= input_buffer->length) || (*input_end != '\"')) + { + goto fail; /* string ended unexpectedly */ + } + + /* This is at most how much we need for the output */ + allocation_length = (size_t) (input_end - buffer_at_offset(input_buffer)) - skipped_bytes; + output = (unsigned char*)input_buffer->hooks.allocate(allocation_length + sizeof("")); + if (output == NULL) + { + goto fail; /* allocation failure */ + } + } + + output_pointer = output; + /* loop through the string literal */ + while (input_pointer < input_end) + { + if (*input_pointer != '\\') + { + *output_pointer++ = *input_pointer++; + } + /* escape sequence */ + else + { + unsigned char sequence_length = 2; + if ((input_end - input_pointer) < 1) + { + goto fail; + } + + switch (input_pointer[1]) + { + case 'b': + *output_pointer++ = '\b'; + break; + case 'f': + *output_pointer++ = '\f'; + break; + case 'n': + *output_pointer++ = '\n'; + break; + case 'r': + *output_pointer++ = '\r'; + break; + case 't': + *output_pointer++ = '\t'; + break; + case '\"': + case '\\': + case '/': + *output_pointer++ = input_pointer[1]; + break; + + /* UTF-16 literal */ + case 'u': + sequence_length = utf16_literal_to_utf8(input_pointer, input_end, &output_pointer); + if (sequence_length == 0) + { + /* failed to convert UTF16-literal to UTF-8 */ + goto fail; + } + break; + + default: + goto fail; + } + input_pointer += sequence_length; + } + } + + /* zero terminate the output */ + *output_pointer = '\0'; + + item->type = cJSON_String; + item->valuestring = (char*)output; + + input_buffer->offset = (size_t) (input_end - input_buffer->content); + input_buffer->offset++; + + return true; + +fail: + if (output != NULL) + { + input_buffer->hooks.deallocate(output); + } + + if (input_pointer != NULL) + { + input_buffer->offset = (size_t)(input_pointer - input_buffer->content); + } + + return false; +} + +/* Render the cstring provided to an escaped version that can be printed. */ +static cJSON_bool print_string_ptr(const unsigned char * const input, printbuffer * const output_buffer) +{ + const unsigned char *input_pointer = NULL; + unsigned char *output = NULL; + unsigned char *output_pointer = NULL; + size_t output_length = 0; + /* numbers of additional characters needed for escaping */ + size_t escape_characters = 0; + + if (output_buffer == NULL) + { + return false; + } + + /* empty string */ + if (input == NULL) + { + output = ensure(output_buffer, sizeof("\"\"")); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "\"\""); + + return true; + } + + /* set "flag" to 1 if something needs to be escaped */ + for (input_pointer = input; *input_pointer; input_pointer++) + { + switch (*input_pointer) + { + case '\"': + case '\\': + case '\b': + case '\f': + case '\n': + case '\r': + case '\t': + /* one character escape sequence */ + escape_characters++; + break; + default: + if (*input_pointer < 32) + { + /* UTF-16 escape sequence uXXXX */ + escape_characters += 5; + } + break; + } + } + output_length = (size_t)(input_pointer - input) + escape_characters; + + output = ensure(output_buffer, output_length + sizeof("\"\"")); + if (output == NULL) + { + return false; + } + + /* no characters have to be escaped */ + if (escape_characters == 0) + { + output[0] = '\"'; + memcpy(output + 1, input, output_length); + output[output_length + 1] = '\"'; + output[output_length + 2] = '\0'; + + return true; + } + + output[0] = '\"'; + output_pointer = output + 1; + /* copy the string */ + for (input_pointer = input; *input_pointer != '\0'; (void)input_pointer++, output_pointer++) + { + if ((*input_pointer > 31) && (*input_pointer != '\"') && (*input_pointer != '\\')) + { + /* normal character, copy */ + *output_pointer = *input_pointer; + } + else + { + /* character needs to be escaped */ + *output_pointer++ = '\\'; + switch (*input_pointer) + { + case '\\': + *output_pointer = '\\'; + break; + case '\"': + *output_pointer = '\"'; + break; + case '\b': + *output_pointer = 'b'; + break; + case '\f': + *output_pointer = 'f'; + break; + case '\n': + *output_pointer = 'n'; + break; + case '\r': + *output_pointer = 'r'; + break; + case '\t': + *output_pointer = 't'; + break; + default: + /* escape and print as unicode codepoint */ + sprintf((char*)output_pointer, "u%04x", *input_pointer); + output_pointer += 4; + break; + } + } + } + output[output_length + 1] = '\"'; + output[output_length + 2] = '\0'; + + return true; +} + +/* Invoke print_string_ptr (which is useful) on an item. */ +static cJSON_bool print_string(const cJSON * const item, printbuffer * const p) +{ + return print_string_ptr((unsigned char*)item->valuestring, p); +} + +/* Predeclare these prototypes. */ +static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer); +static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer); +static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer); + +/* Utility to jump whitespace and cr/lf */ +static parse_buffer *buffer_skip_whitespace(parse_buffer * const buffer) +{ + if ((buffer == NULL) || (buffer->content == NULL)) + { + return NULL; + } + + if (cannot_access_at_index(buffer, 0)) + { + return buffer; + } + + while (can_access_at_index(buffer, 0) && (buffer_at_offset(buffer)[0] <= 32)) + { + buffer->offset++; + } + + if (buffer->offset == buffer->length) + { + buffer->offset--; + } + + return buffer; +} + +/* skip the UTF-8 BOM (byte order mark) if it is at the beginning of a buffer */ +static parse_buffer *skip_utf8_bom(parse_buffer * const buffer) +{ + if ((buffer == NULL) || (buffer->content == NULL) || (buffer->offset != 0)) + { + return NULL; + } + + if (can_access_at_index(buffer, 4) && (strncmp((const char*)buffer_at_offset(buffer), "\xEF\xBB\xBF", 3) == 0)) + { + buffer->offset += 3; + } + + return buffer; +} + +CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated) +{ + size_t buffer_length; + + if (NULL == value) + { + return NULL; + } + + /* Adding null character size due to require_null_terminated. */ + buffer_length = strlen(value) + sizeof(""); + + return cJSON_ParseWithLengthOpts(value, buffer_length, return_parse_end, require_null_terminated); +} + +/* Parse an object - create a new root, and populate. */ +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated) +{ + parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } }; + cJSON *item = NULL; + + /* reset error position */ + global_error.json = NULL; + global_error.position = 0; + + if (value == NULL || 0 == buffer_length) + { + goto fail; + } + + buffer.content = (const unsigned char*)value; + buffer.length = buffer_length; + buffer.offset = 0; + buffer.hooks = global_hooks; + + item = cJSON_New_Item(&global_hooks); + if (item == NULL) /* memory fail */ + { + goto fail; + } + + if (!parse_value(item, buffer_skip_whitespace(skip_utf8_bom(&buffer)))) + { + /* parse failure. ep is set. */ + goto fail; + } + + /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */ + if (require_null_terminated) + { + buffer_skip_whitespace(&buffer); + if ((buffer.offset >= buffer.length) || buffer_at_offset(&buffer)[0] != '\0') + { + goto fail; + } + } + if (return_parse_end) + { + *return_parse_end = (const char*)buffer_at_offset(&buffer); + } + + return item; + +fail: + if (item != NULL) + { + cJSON_Delete(item); + } + + if (value != NULL) + { + error local_error; + local_error.json = (const unsigned char*)value; + local_error.position = 0; + + if (buffer.offset < buffer.length) + { + local_error.position = buffer.offset; + } + else if (buffer.length > 0) + { + local_error.position = buffer.length - 1; + } + + if (return_parse_end != NULL) + { + *return_parse_end = (const char*)local_error.json + local_error.position; + } + + global_error = local_error; + } + + return NULL; +} + +/* Default options for cJSON_Parse */ +CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value) +{ + return cJSON_ParseWithOpts(value, 0, 0); +} + +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length) +{ + return cJSON_ParseWithLengthOpts(value, buffer_length, 0, 0); +} + +#define cjson_min(a, b) (((a) < (b)) ? (a) : (b)) + +static unsigned char *print(const cJSON * const item, cJSON_bool format, const internal_hooks * const hooks) +{ + static const size_t default_buffer_size = 256; + printbuffer buffer[1]; + unsigned char *printed = NULL; + + memset(buffer, 0, sizeof(buffer)); + + /* create buffer */ + buffer->buffer = (unsigned char*) hooks->allocate(default_buffer_size); + buffer->length = default_buffer_size; + buffer->format = format; + buffer->hooks = *hooks; + if (buffer->buffer == NULL) + { + goto fail; + } + + /* print the value */ + if (!print_value(item, buffer)) + { + goto fail; + } + update_offset(buffer); + + /* check if reallocate is available */ + if (hooks->reallocate != NULL) + { + printed = (unsigned char*) hooks->reallocate(buffer->buffer, buffer->offset + 1); + if (printed == NULL) { + goto fail; + } + buffer->buffer = NULL; + } + else /* otherwise copy the JSON over to a new buffer */ + { + printed = (unsigned char*) hooks->allocate(buffer->offset + 1); + if (printed == NULL) + { + goto fail; + } + memcpy(printed, buffer->buffer, cjson_min(buffer->length, buffer->offset + 1)); + printed[buffer->offset] = '\0'; /* just to be sure */ + + /* free the buffer */ + hooks->deallocate(buffer->buffer); + } + + return printed; + +fail: + if (buffer->buffer != NULL) + { + hooks->deallocate(buffer->buffer); + } + + if (printed != NULL) + { + hooks->deallocate(printed); + } + + return NULL; +} + +/* Render a cJSON item/entity/structure to text. */ +CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item) +{ + return (char*)print(item, true, &global_hooks); +} + +CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item) +{ + return (char*)print(item, false, &global_hooks); +} + +CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt) +{ + printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; + + if (prebuffer < 0) + { + return NULL; + } + + p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer); + if (!p.buffer) + { + return NULL; + } + + p.length = (size_t)prebuffer; + p.offset = 0; + p.noalloc = false; + p.format = fmt; + p.hooks = global_hooks; + + if (!print_value(item, &p)) + { + global_hooks.deallocate(p.buffer); + return NULL; + } + + return (char*)p.buffer; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format) +{ + printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; + + if ((length < 0) || (buffer == NULL)) + { + return false; + } + + p.buffer = (unsigned char*)buffer; + p.length = (size_t)length; + p.offset = 0; + p.noalloc = true; + p.format = format; + p.hooks = global_hooks; + + return print_value(item, &p); +} + +/* Parser core - when encountering text, process appropriately. */ +static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer) +{ + if ((input_buffer == NULL) || (input_buffer->content == NULL)) + { + return false; /* no input */ + } + + /* parse the different types of values */ + /* null */ + if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "null", 4) == 0)) + { + item->type = cJSON_NULL; + input_buffer->offset += 4; + return true; + } + /* false */ + if (can_read(input_buffer, 5) && (strncmp((const char*)buffer_at_offset(input_buffer), "false", 5) == 0)) + { + item->type = cJSON_False; + input_buffer->offset += 5; + return true; + } + /* true */ + if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "true", 4) == 0)) + { + item->type = cJSON_True; + item->valueint = 1; + input_buffer->offset += 4; + return true; + } + /* string */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '\"')) + { + return parse_string(item, input_buffer); + } + /* number */ + if (can_access_at_index(input_buffer, 0) && ((buffer_at_offset(input_buffer)[0] == '-') || ((buffer_at_offset(input_buffer)[0] >= '0') && (buffer_at_offset(input_buffer)[0] <= '9')))) + { + return parse_number(item, input_buffer); + } + /* array */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '[')) + { + return parse_array(item, input_buffer); + } + /* object */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '{')) + { + return parse_object(item, input_buffer); + } + + return false; +} + +/* Render a value to text. */ +static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output = NULL; + + if ((item == NULL) || (output_buffer == NULL)) + { + return false; + } + + switch ((item->type) & 0xFF) + { + case cJSON_NULL: + output = ensure(output_buffer, 5); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "null"); + return true; + + case cJSON_False: + output = ensure(output_buffer, 6); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "false"); + return true; + + case cJSON_True: + output = ensure(output_buffer, 5); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "true"); + return true; + + case cJSON_Number: + return print_number(item, output_buffer); + + case cJSON_Raw: + { + size_t raw_length = 0; + if (item->valuestring == NULL) + { + return false; + } + + raw_length = strlen(item->valuestring) + sizeof(""); + output = ensure(output_buffer, raw_length); + if (output == NULL) + { + return false; + } + memcpy(output, item->valuestring, raw_length); + return true; + } + + case cJSON_String: + return print_string(item, output_buffer); + + case cJSON_Array: + return print_array(item, output_buffer); + + case cJSON_Object: + return print_object(item, output_buffer); + + default: + return false; + } +} + +/* Build an array from input text. */ +static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer) +{ + cJSON *head = NULL; /* head of the linked list */ + cJSON *current_item = NULL; + + if (input_buffer->depth >= CJSON_NESTING_LIMIT) + { + return false; /* to deeply nested */ + } + input_buffer->depth++; + + if (buffer_at_offset(input_buffer)[0] != '[') + { + /* not an array */ + goto fail; + } + + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ']')) + { + /* empty array */ + goto success; + } + + /* check if we skipped to the end of the buffer */ + if (cannot_access_at_index(input_buffer, 0)) + { + input_buffer->offset--; + goto fail; + } + + /* step back to character in front of the first element */ + input_buffer->offset--; + /* loop through the comma separated array elements */ + do + { + /* allocate next item */ + cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); + if (new_item == NULL) + { + goto fail; /* allocation failure */ + } + + /* attach next item to list */ + if (head == NULL) + { + /* start the linked list */ + current_item = head = new_item; + } + else + { + /* add to the end and advance */ + current_item->next = new_item; + new_item->prev = current_item; + current_item = new_item; + } + + /* parse next value */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_value(current_item, input_buffer)) + { + goto fail; /* failed to parse value */ + } + buffer_skip_whitespace(input_buffer); + } + while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ',')); + + if (cannot_access_at_index(input_buffer, 0) || buffer_at_offset(input_buffer)[0] != ']') + { + goto fail; /* expected end of array */ + } + +success: + input_buffer->depth--; + + if (head != NULL) { + head->prev = current_item; + } + + item->type = cJSON_Array; + item->child = head; + + input_buffer->offset++; + + return true; + +fail: + if (head != NULL) + { + cJSON_Delete(head); + } + + return false; +} + +/* Render an array to text */ +static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + size_t length = 0; + cJSON *current_element = item->child; + + if (output_buffer == NULL) + { + return false; + } + + /* Compose the output array. */ + /* opening square bracket */ + output_pointer = ensure(output_buffer, 1); + if (output_pointer == NULL) + { + return false; + } + + *output_pointer = '['; + output_buffer->offset++; + output_buffer->depth++; + + while (current_element != NULL) + { + if (!print_value(current_element, output_buffer)) + { + return false; + } + update_offset(output_buffer); + if (current_element->next) + { + length = (size_t) (output_buffer->format ? 2 : 1); + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ','; + if(output_buffer->format) + { + *output_pointer++ = ' '; + } + *output_pointer = '\0'; + output_buffer->offset += length; + } + current_element = current_element->next; + } + + output_pointer = ensure(output_buffer, 2); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ']'; + *output_pointer = '\0'; + output_buffer->depth--; + + return true; +} + +/* Build an object from the text. */ +static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer) +{ + cJSON *head = NULL; /* linked list head */ + cJSON *current_item = NULL; + + if (input_buffer->depth >= CJSON_NESTING_LIMIT) + { + return false; /* to deeply nested */ + } + input_buffer->depth++; + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '{')) + { + goto fail; /* not an object */ + } + + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '}')) + { + goto success; /* empty object */ + } + + /* check if we skipped to the end of the buffer */ + if (cannot_access_at_index(input_buffer, 0)) + { + input_buffer->offset--; + goto fail; + } + + /* step back to character in front of the first element */ + input_buffer->offset--; + /* loop through the comma separated array elements */ + do + { + /* allocate next item */ + cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); + if (new_item == NULL) + { + goto fail; /* allocation failure */ + } + + /* attach next item to list */ + if (head == NULL) + { + /* start the linked list */ + current_item = head = new_item; + } + else + { + /* add to the end and advance */ + current_item->next = new_item; + new_item->prev = current_item; + current_item = new_item; + } + + /* parse the name of the child */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_string(current_item, input_buffer)) + { + goto fail; /* failed to parse name */ + } + buffer_skip_whitespace(input_buffer); + + /* swap valuestring and string, because we parsed the name */ + current_item->string = current_item->valuestring; + current_item->valuestring = NULL; + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != ':')) + { + goto fail; /* invalid object */ + } + + /* parse the value */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_value(current_item, input_buffer)) + { + goto fail; /* failed to parse value */ + } + buffer_skip_whitespace(input_buffer); + } + while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ',')); + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '}')) + { + goto fail; /* expected end of object */ + } + +success: + input_buffer->depth--; + + if (head != NULL) { + head->prev = current_item; + } + + item->type = cJSON_Object; + item->child = head; + + input_buffer->offset++; + return true; + +fail: + if (head != NULL) + { + cJSON_Delete(head); + } + + return false; +} + +/* Render an object to text. */ +static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + size_t length = 0; + cJSON *current_item = item->child; + + if (output_buffer == NULL) + { + return false; + } + + /* Compose the output: */ + length = (size_t) (output_buffer->format ? 2 : 1); /* fmt: {\n */ + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + + *output_pointer++ = '{'; + output_buffer->depth++; + if (output_buffer->format) + { + *output_pointer++ = '\n'; + } + output_buffer->offset += length; + + while (current_item) + { + if (output_buffer->format) + { + size_t i; + output_pointer = ensure(output_buffer, output_buffer->depth); + if (output_pointer == NULL) + { + return false; + } + for (i = 0; i < output_buffer->depth; i++) + { + *output_pointer++ = '\t'; + } + output_buffer->offset += output_buffer->depth; + } + + /* print key */ + if (!print_string_ptr((unsigned char*)current_item->string, output_buffer)) + { + return false; + } + update_offset(output_buffer); + + length = (size_t) (output_buffer->format ? 2 : 1); + output_pointer = ensure(output_buffer, length); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ':'; + if (output_buffer->format) + { + *output_pointer++ = '\t'; + } + output_buffer->offset += length; + + /* print value */ + if (!print_value(current_item, output_buffer)) + { + return false; + } + update_offset(output_buffer); + + /* print comma if not last */ + length = ((size_t)(output_buffer->format ? 1 : 0) + (size_t)(current_item->next ? 1 : 0)); + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + if (current_item->next) + { + *output_pointer++ = ','; + } + + if (output_buffer->format) + { + *output_pointer++ = '\n'; + } + *output_pointer = '\0'; + output_buffer->offset += length; + + current_item = current_item->next; + } + + output_pointer = ensure(output_buffer, output_buffer->format ? (output_buffer->depth + 1) : 2); + if (output_pointer == NULL) + { + return false; + } + if (output_buffer->format) + { + size_t i; + for (i = 0; i < (output_buffer->depth - 1); i++) + { + *output_pointer++ = '\t'; + } + } + *output_pointer++ = '}'; + *output_pointer = '\0'; + output_buffer->depth--; + + return true; +} + +/* Get Array size/item / object item. */ +CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array) +{ + cJSON *child = NULL; + size_t size = 0; + + if (array == NULL) + { + return 0; + } + + child = array->child; + + while(child != NULL) + { + size++; + child = child->next; + } + + /* FIXME: Can overflow here. Cannot be fixed without breaking the API */ + + return (int)size; +} + +static cJSON* get_array_item(const cJSON *array, size_t index) +{ + cJSON *current_child = NULL; + + if (array == NULL) + { + return NULL; + } + + current_child = array->child; + while ((current_child != NULL) && (index > 0)) + { + index--; + current_child = current_child->next; + } + + return current_child; +} + +CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index) +{ + if (index < 0) + { + return NULL; + } + + return get_array_item(array, (size_t)index); +} + +static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive) +{ + cJSON *current_element = NULL; + + if ((object == NULL) || (name == NULL)) + { + return NULL; + } + + current_element = object->child; + if (case_sensitive) + { + while ((current_element != NULL) && (current_element->string != NULL) && (strcmp(name, current_element->string) != 0)) + { + current_element = current_element->next; + } + } + else + { + while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0)) + { + current_element = current_element->next; + } + } + + if ((current_element == NULL) || (current_element->string == NULL)) { + return NULL; + } + + return current_element; +} + +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string) +{ + return get_object_item(object, string, false); +} + +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string) +{ + return get_object_item(object, string, true); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string) +{ + return cJSON_GetObjectItem(object, string) ? 1 : 0; +} + +/* Utility for array list handling. */ +static void suffix_object(cJSON *prev, cJSON *item) +{ + prev->next = item; + item->prev = prev; +} + +/* Utility for handling references. */ +static cJSON *create_reference(const cJSON *item, const internal_hooks * const hooks) +{ + cJSON *reference = NULL; + if (item == NULL) + { + return NULL; + } + + reference = cJSON_New_Item(hooks); + if (reference == NULL) + { + return NULL; + } + + memcpy(reference, item, sizeof(cJSON)); + reference->string = NULL; + reference->type |= cJSON_IsReference; + reference->next = reference->prev = NULL; + return reference; +} + +static cJSON_bool add_item_to_array(cJSON *array, cJSON *item) +{ + cJSON *child = NULL; + + if ((item == NULL) || (array == NULL) || (array == item)) + { + return false; + } + + child = array->child; + /* + * To find the last item in array quickly, we use prev in array + */ + if (child == NULL) + { + /* list is empty, start new one */ + array->child = item; + item->prev = item; + item->next = NULL; + } + else + { + /* append to the end */ + if (child->prev) + { + suffix_object(child->prev, item); + array->child->prev = item; + } + } + + return true; +} + +/* Add item to array/object. */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item) +{ + return add_item_to_array(array, item); +} + +#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) + #pragma GCC diagnostic push +#endif +#ifdef __GNUC__ +#pragma GCC diagnostic ignored "-Wcast-qual" +#endif +/* helper function to cast away const */ +static void* cast_away_const(const void* string) +{ + return (void*)string; +} +#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) + #pragma GCC diagnostic pop +#endif + + +static cJSON_bool add_item_to_object(cJSON * const object, const char * const string, cJSON * const item, const internal_hooks * const hooks, const cJSON_bool constant_key) +{ + char *new_key = NULL; + int new_type = cJSON_Invalid; + + if ((object == NULL) || (string == NULL) || (item == NULL) || (object == item)) + { + return false; + } + + if (constant_key) + { + new_key = (char*)cast_away_const(string); + new_type = item->type | cJSON_StringIsConst; + } + else + { + new_key = (char*)cJSON_strdup((const unsigned char*)string, hooks); + if (new_key == NULL) + { + return false; + } + + new_type = item->type & ~cJSON_StringIsConst; + } + + if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) + { + hooks->deallocate(item->string); + } + + item->string = new_key; + item->type = new_type; + + return add_item_to_array(object, item); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item) +{ + return add_item_to_object(object, string, item, &global_hooks, false); +} + +/* Add an item to an object with constant string as key */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item) +{ + return add_item_to_object(object, string, item, &global_hooks, true); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) +{ + if (array == NULL) + { + return false; + } + + return add_item_to_array(array, create_reference(item, &global_hooks)); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item) +{ + if ((object == NULL) || (string == NULL)) + { + return false; + } + + return add_item_to_object(object, string, create_reference(item, &global_hooks), &global_hooks, false); +} + +CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name) +{ + cJSON *null = cJSON_CreateNull(); + if (add_item_to_object(object, name, null, &global_hooks, false)) + { + return null; + } + + cJSON_Delete(null); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name) +{ + cJSON *true_item = cJSON_CreateTrue(); + if (add_item_to_object(object, name, true_item, &global_hooks, false)) + { + return true_item; + } + + cJSON_Delete(true_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name) +{ + cJSON *false_item = cJSON_CreateFalse(); + if (add_item_to_object(object, name, false_item, &global_hooks, false)) + { + return false_item; + } + + cJSON_Delete(false_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean) +{ + cJSON *bool_item = cJSON_CreateBool(boolean); + if (add_item_to_object(object, name, bool_item, &global_hooks, false)) + { + return bool_item; + } + + cJSON_Delete(bool_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number) +{ + cJSON *number_item = cJSON_CreateNumber(number); + if (add_item_to_object(object, name, number_item, &global_hooks, false)) + { + return number_item; + } + + cJSON_Delete(number_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string) +{ + cJSON *string_item = cJSON_CreateString(string); + if (add_item_to_object(object, name, string_item, &global_hooks, false)) + { + return string_item; + } + + cJSON_Delete(string_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw) +{ + cJSON *raw_item = cJSON_CreateRaw(raw); + if (add_item_to_object(object, name, raw_item, &global_hooks, false)) + { + return raw_item; + } + + cJSON_Delete(raw_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name) +{ + cJSON *object_item = cJSON_CreateObject(); + if (add_item_to_object(object, name, object_item, &global_hooks, false)) + { + return object_item; + } + + cJSON_Delete(object_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name) +{ + cJSON *array = cJSON_CreateArray(); + if (add_item_to_object(object, name, array, &global_hooks, false)) + { + return array; + } + + cJSON_Delete(array); + return NULL; +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item) +{ + if ((parent == NULL) || (item == NULL)) + { + return NULL; + } + + if (item != parent->child) + { + /* not the first element */ + item->prev->next = item->next; + } + if (item->next != NULL) + { + /* not the last element */ + item->next->prev = item->prev; + } + + if (item == parent->child) + { + /* first element */ + parent->child = item->next; + } + else if (item->next == NULL) + { + /* last element */ + parent->child->prev = item->prev; + } + + /* make sure the detached item doesn't point anywhere anymore */ + item->prev = NULL; + item->next = NULL; + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which) +{ + if (which < 0) + { + return NULL; + } + + return cJSON_DetachItemViaPointer(array, get_array_item(array, (size_t)which)); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which) +{ + cJSON_Delete(cJSON_DetachItemFromArray(array, which)); +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string) +{ + cJSON *to_detach = cJSON_GetObjectItem(object, string); + + return cJSON_DetachItemViaPointer(object, to_detach); +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string) +{ + cJSON *to_detach = cJSON_GetObjectItemCaseSensitive(object, string); + + return cJSON_DetachItemViaPointer(object, to_detach); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string) +{ + cJSON_Delete(cJSON_DetachItemFromObject(object, string)); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string) +{ + cJSON_Delete(cJSON_DetachItemFromObjectCaseSensitive(object, string)); +} + +/* Replace array/object items with new ones. */ +CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem) +{ + cJSON *after_inserted = NULL; + + if (which < 0 || newitem == NULL) + { + return false; + } + + after_inserted = get_array_item(array, (size_t)which); + if (after_inserted == NULL) + { + return add_item_to_array(array, newitem); + } + + if (after_inserted != array->child && newitem->prev == NULL) { + /* return false if after_inserted is a corrupted array item */ + return false; + } + + newitem->next = after_inserted; + newitem->prev = after_inserted->prev; + after_inserted->prev = newitem; + if (after_inserted == array->child) + { + array->child = newitem; + } + else + { + newitem->prev->next = newitem; + } + return true; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement) +{ + if ((parent == NULL) || (parent->child == NULL) || (replacement == NULL) || (item == NULL)) + { + return false; + } + + if (replacement == item) + { + return true; + } + + replacement->next = item->next; + replacement->prev = item->prev; + + if (replacement->next != NULL) + { + replacement->next->prev = replacement; + } + if (parent->child == item) + { + if (parent->child->prev == parent->child) + { + replacement->prev = replacement; + } + parent->child = replacement; + } + else + { /* + * To find the last item in array quickly, we use prev in array. + * We can't modify the last item's next pointer where this item was the parent's child + */ + if (replacement->prev != NULL) + { + replacement->prev->next = replacement; + } + if (replacement->next == NULL) + { + parent->child->prev = replacement; + } + } + + item->next = NULL; + item->prev = NULL; + cJSON_Delete(item); + + return true; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem) +{ + if (which < 0) + { + return false; + } + + return cJSON_ReplaceItemViaPointer(array, get_array_item(array, (size_t)which), newitem); +} + +static cJSON_bool replace_item_in_object(cJSON *object, const char *string, cJSON *replacement, cJSON_bool case_sensitive) +{ + if ((replacement == NULL) || (string == NULL)) + { + return false; + } + + /* replace the name in the replacement */ + if (!(replacement->type & cJSON_StringIsConst) && (replacement->string != NULL)) + { + cJSON_free(replacement->string); + } + replacement->string = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks); + if (replacement->string == NULL) + { + return false; + } + + replacement->type &= ~cJSON_StringIsConst; + + return cJSON_ReplaceItemViaPointer(object, get_object_item(object, string, case_sensitive), replacement); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem) +{ + return replace_item_in_object(object, string, newitem, false); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, cJSON *newitem) +{ + return replace_item_in_object(object, string, newitem, true); +} + +/* Create basic types: */ +CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_NULL; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_True; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_False; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = boolean ? cJSON_True : cJSON_False; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_Number; + item->valuedouble = num; + + /* use saturation in case of overflow */ + if (num >= INT_MAX) + { + item->valueint = INT_MAX; + } + else if (num <= (double)INT_MIN) + { + item->valueint = INT_MIN; + } + else + { + item->valueint = (int)num; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_String; + item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks); + if(!item->valuestring) + { + cJSON_Delete(item); + return NULL; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) + { + item->type = cJSON_String | cJSON_IsReference; + item->valuestring = (char*)cast_away_const(string); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) { + item->type = cJSON_Object | cJSON_IsReference; + item->child = (cJSON*)cast_away_const(child); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child) { + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) { + item->type = cJSON_Array | cJSON_IsReference; + item->child = (cJSON*)cast_away_const(child); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_Raw; + item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks); + if(!item->valuestring) + { + cJSON_Delete(item); + return NULL; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type=cJSON_Array; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item) + { + item->type = cJSON_Object; + } + + return item; +} + +/* Create Arrays: */ +CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for(i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber(numbers[i]); + if (!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for(i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber((double)numbers[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for(i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber(numbers[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (strings == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for (i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateString(strings[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p,n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +/* Duplication */ +CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse) +{ + cJSON *newitem = NULL; + cJSON *child = NULL; + cJSON *next = NULL; + cJSON *newchild = NULL; + + /* Bail on bad ptr */ + if (!item) + { + goto fail; + } + /* Create new item */ + newitem = cJSON_New_Item(&global_hooks); + if (!newitem) + { + goto fail; + } + /* Copy over all vars */ + newitem->type = item->type & (~cJSON_IsReference); + newitem->valueint = item->valueint; + newitem->valuedouble = item->valuedouble; + if (item->valuestring) + { + newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks); + if (!newitem->valuestring) + { + goto fail; + } + } + if (item->string) + { + newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks); + if (!newitem->string) + { + goto fail; + } + } + /* If non-recursive, then we're done! */ + if (!recurse) + { + return newitem; + } + /* Walk the ->next chain for the child. */ + child = item->child; + while (child != NULL) + { + newchild = cJSON_Duplicate(child, true); /* Duplicate (with recurse) each item in the ->next chain */ + if (!newchild) + { + goto fail; + } + if (next != NULL) + { + /* If newitem->child already set, then crosswire ->prev and ->next and move on */ + next->next = newchild; + newchild->prev = next; + next = newchild; + } + else + { + /* Set newitem->child and move to it */ + newitem->child = newchild; + next = newchild; + } + child = child->next; + } + if (newitem && newitem->child) + { + newitem->child->prev = newchild; + } + + return newitem; + +fail: + if (newitem != NULL) + { + cJSON_Delete(newitem); + } + + return NULL; +} + +static void skip_oneline_comment(char **input) +{ + *input += static_strlen("//"); + + for (; (*input)[0] != '\0'; ++(*input)) + { + if ((*input)[0] == '\n') { + *input += static_strlen("\n"); + return; + } + } +} + +static void skip_multiline_comment(char **input) +{ + *input += static_strlen("/*"); + + for (; (*input)[0] != '\0'; ++(*input)) + { + if (((*input)[0] == '*') && ((*input)[1] == '/')) + { + *input += static_strlen("*/"); + return; + } + } +} + +static void minify_string(char **input, char **output) { + (*output)[0] = (*input)[0]; + *input += static_strlen("\""); + *output += static_strlen("\""); + + + for (; (*input)[0] != '\0'; (void)++(*input), ++(*output)) { + (*output)[0] = (*input)[0]; + + if ((*input)[0] == '\"') { + (*output)[0] = '\"'; + *input += static_strlen("\""); + *output += static_strlen("\""); + return; + } else if (((*input)[0] == '\\') && ((*input)[1] == '\"')) { + (*output)[1] = (*input)[1]; + *input += static_strlen("\""); + *output += static_strlen("\""); + } + } +} + +CJSON_PUBLIC(void) cJSON_Minify(char *json) +{ + char *into = json; + + if (json == NULL) + { + return; + } + + while (json[0] != '\0') + { + switch (json[0]) + { + case ' ': + case '\t': + case '\r': + case '\n': + json++; + break; + + case '/': + if (json[1] == '/') + { + skip_oneline_comment(&json); + } + else if (json[1] == '*') + { + skip_multiline_comment(&json); + } else { + json++; + } + break; + + case '\"': + minify_string(&json, (char**)&into); + break; + + default: + into[0] = json[0]; + json++; + into++; + } + } + + /* and null-terminate. */ + *into = '\0'; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Invalid; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_False; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xff) == cJSON_True; +} + + +CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & (cJSON_True | cJSON_False)) != 0; +} +CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_NULL; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Number; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_String; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Array; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Object; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Raw; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive) +{ + if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF))) + { + return false; + } + + /* check if type is valid */ + switch (a->type & 0xFF) + { + case cJSON_False: + case cJSON_True: + case cJSON_NULL: + case cJSON_Number: + case cJSON_String: + case cJSON_Raw: + case cJSON_Array: + case cJSON_Object: + break; + + default: + return false; + } + + /* identical objects are equal */ + if (a == b) + { + return true; + } + + switch (a->type & 0xFF) + { + /* in these cases and equal type is enough */ + case cJSON_False: + case cJSON_True: + case cJSON_NULL: + return true; + + case cJSON_Number: + if (compare_double(a->valuedouble, b->valuedouble)) + { + return true; + } + return false; + + case cJSON_String: + case cJSON_Raw: + if ((a->valuestring == NULL) || (b->valuestring == NULL)) + { + return false; + } + if (strcmp(a->valuestring, b->valuestring) == 0) + { + return true; + } + + return false; + + case cJSON_Array: + { + cJSON *a_element = a->child; + cJSON *b_element = b->child; + + for (; (a_element != NULL) && (b_element != NULL);) + { + if (!cJSON_Compare(a_element, b_element, case_sensitive)) + { + return false; + } + + a_element = a_element->next; + b_element = b_element->next; + } + + /* one of the arrays is longer than the other */ + if (a_element != b_element) { + return false; + } + + return true; + } + + case cJSON_Object: + { + cJSON *a_element = NULL; + cJSON *b_element = NULL; + cJSON_ArrayForEach(a_element, a) + { + /* TODO This has O(n^2) runtime, which is horrible! */ + b_element = get_object_item(b, a_element->string, case_sensitive); + if (b_element == NULL) + { + return false; + } + + if (!cJSON_Compare(a_element, b_element, case_sensitive)) + { + return false; + } + } + + /* doing this twice, once on a and b to prevent true comparison if a subset of b + * TODO: Do this the proper way, this is just a fix for now */ + cJSON_ArrayForEach(b_element, b) + { + a_element = get_object_item(a, b_element->string, case_sensitive); + if (a_element == NULL) + { + return false; + } + + if (!cJSON_Compare(b_element, a_element, case_sensitive)) + { + return false; + } + } + + return true; + } + + default: + return false; + } +} + +CJSON_PUBLIC(void *) cJSON_malloc(size_t size) +{ + return global_hooks.allocate(size); +} + +CJSON_PUBLIC(void) cJSON_free(void *object) +{ + global_hooks.deallocate(object); +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/cJSON.h" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/cJSON.h" new file mode 100644 index 00000000..2628d763 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/cJSON.h" @@ -0,0 +1,300 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#ifndef cJSON__h +#define cJSON__h + +#ifdef __cplusplus +extern "C" +{ +#endif + +#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32)) +#define __WINDOWS__ +#endif + +#ifdef __WINDOWS__ + +/* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention. For windows you have 3 define options: + +CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols +CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default) +CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol + +For *nix builds that support visibility attribute, you can define similar behavior by + +setting default visibility to hidden by adding +-fvisibility=hidden (for gcc) +or +-xldscope=hidden (for sun cc) +to CFLAGS + +then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does + +*/ + +#define CJSON_CDECL __cdecl +#define CJSON_STDCALL __stdcall + +/* export symbols by default, this is necessary for copy pasting the C and header file */ +#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS) +#define CJSON_EXPORT_SYMBOLS +#endif + +#if defined(CJSON_HIDE_SYMBOLS) +#define CJSON_PUBLIC(type) type CJSON_STDCALL +#elif defined(CJSON_EXPORT_SYMBOLS) +#define CJSON_PUBLIC(type) __declspec(dllexport) type CJSON_STDCALL +#elif defined(CJSON_IMPORT_SYMBOLS) +#define CJSON_PUBLIC(type) __declspec(dllimport) type CJSON_STDCALL +#endif +#else /* !__WINDOWS__ */ +#define CJSON_CDECL +#define CJSON_STDCALL + +#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY) +#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type +#else +#define CJSON_PUBLIC(type) type +#endif +#endif + +/* project version */ +#define CJSON_VERSION_MAJOR 1 +#define CJSON_VERSION_MINOR 7 +#define CJSON_VERSION_PATCH 16 + +#include + +/* cJSON Types: */ +#define cJSON_Invalid (0) +#define cJSON_False (1 << 0) +#define cJSON_True (1 << 1) +#define cJSON_NULL (1 << 2) +#define cJSON_Number (1 << 3) +#define cJSON_String (1 << 4) +#define cJSON_Array (1 << 5) +#define cJSON_Object (1 << 6) +#define cJSON_Raw (1 << 7) /* raw json */ + +#define cJSON_IsReference 256 +#define cJSON_StringIsConst 512 + +/* The cJSON structure: */ +typedef struct cJSON +{ + /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */ + struct cJSON *next; + struct cJSON *prev; + /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */ + struct cJSON *child; + + /* The type of the item, as above. */ + int type; + + /* The item's string, if type==cJSON_String and type == cJSON_Raw */ + char *valuestring; + /* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */ + int valueint; + /* The item's number, if type==cJSON_Number */ + double valuedouble; + + /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */ + char *string; +} cJSON; + +typedef struct cJSON_Hooks +{ + /* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */ + void *(CJSON_CDECL *malloc_fn)(size_t sz); + void (CJSON_CDECL *free_fn)(void *ptr); +} cJSON_Hooks; + +typedef int cJSON_bool; + +/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them. + * This is to prevent stack overflows. */ +#ifndef CJSON_NESTING_LIMIT +#define CJSON_NESTING_LIMIT 1000 +#endif + +/* returns the version of cJSON as a string */ +CJSON_PUBLIC(const char*) cJSON_Version(void); + +/* Supply malloc, realloc and free functions to cJSON */ +CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks); + +/* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */ +/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */ +CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value); +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length); +/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */ +/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */ +CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated); +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated); + +/* Render a cJSON entity to text for transfer/storage. */ +CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item); +/* Render a cJSON entity to text for transfer/storage without any formatting. */ +CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item); +/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */ +CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt); +/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */ +/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */ +CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format); +/* Delete a cJSON entity and all subentities. */ +CJSON_PUBLIC(void) cJSON_Delete(cJSON *item); + +/* Returns the number of items in an array (or object). */ +CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array); +/* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */ +CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index); +/* Get item "string" from object. Case insensitive. */ +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string); +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string); +CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string); +/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */ +CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void); + +/* Check item type and return its value */ +CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item); +CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item); + +/* These functions check the type of an item */ +CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item); + +/* These calls create a cJSON item of the appropriate type. */ +CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean); +CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num); +CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string); +/* raw json */ +CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw); +CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void); + +/* Create a string where valuestring references a string so + * it will not be freed by cJSON_Delete */ +CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string); +/* Create an object/array that only references it's elements so + * they will not be freed by cJSON_Delete */ +CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child); +CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child); + +/* These utilities create an Array of count items. + * The parameter count cannot be greater than the number of elements in the number array, otherwise array access will be out of bounds.*/ +CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count); + +/* Append item to the specified array/object. */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item); +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item); +/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object. + * WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before + * writing to `item->string` */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item); +/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item); +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item); + +/* Remove/Detach items from Arrays/Objects. */ +CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which); +CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string); +CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string); +CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string); + +/* Update array items. */ +CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */ +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement); +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem); +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem); +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem); + +/* Duplicate a cJSON item */ +CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse); +/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will + * need to be released. With recurse!=0, it will duplicate any children connected to the item. + * The item->next and ->prev pointers are always zero on return from Duplicate. */ +/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal. + * case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */ +CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive); + +/* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from strings. + * The input pointer json cannot point to a read-only address area, such as a string constant, + * but should point to a readable and writable address area. */ +CJSON_PUBLIC(void) cJSON_Minify(char *json); + +/* Helper functions for creating and adding items to an object at the same time. + * They return the added item or NULL on failure. */ +CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean); +CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number); +CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string); +CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw); +CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name); + +/* When assigning an integer value, it needs to be propagated to valuedouble too. */ +#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number)) +/* helper for the cJSON_SetNumberValue macro */ +CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number); +#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number)) +/* Change the valuestring of a cJSON_String object, only takes effect when type of object is cJSON_String */ +CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring); + +/* If the object is not a boolean type this does nothing and returns cJSON_Invalid else it returns the new type*/ +#define cJSON_SetBoolValue(object, boolValue) ( \ + (object != NULL && ((object)->type & (cJSON_False|cJSON_True))) ? \ + (object)->type=((object)->type &(~(cJSON_False|cJSON_True)))|((boolValue)?cJSON_True:cJSON_False) : \ + cJSON_Invalid\ +) + +/* Macro for iterating over an array or object */ +#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next) + +/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */ +CJSON_PUBLIC(void *) cJSON_malloc(size_t size); +CJSON_PUBLIC(void) cJSON_free(void *object); + +#ifdef __cplusplus +} +#endif + +#endif diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/jni/Android.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/jni/Android.mk" new file mode 100644 index 00000000..86e6a38d --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/jni/Android.mk" @@ -0,0 +1,16 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) +LOCAL_MODULE := module_hide_data_dir + +LOCAL_SRC_FILES := ../module_hide_data_dir.cpp ../patch_base.cpp ../patch_filldir64.cpp ../cJSON.cpp + +KERNEL_MODULE_KIT := $(LOCAL_PATH)/../../kernel_module_kit +LOCAL_C_INCLUDES += $(KERNEL_MODULE_KIT)/include +LOCAL_LDFLAGS += $(KERNEL_MODULE_KIT)/lib/libkernel_module_kit_static.a + +include $(LOCAL_PATH)/build_macros.mk + +include $(BUILD_SHARED_LIBRARY) + + diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/jni/Application.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/jni/Application.mk" new file mode 100644 index 00000000..2500a8a7 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/jni/Application.mk" @@ -0,0 +1,2 @@ +APP_ABI := arm64-v8a +APP_STL := c++_static \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/jni/build_macros.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/jni/build_macros.mk" new file mode 100644 index 00000000..a6f31501 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/jni/build_macros.mk" @@ -0,0 +1,21 @@ +COMMON_CPPFLAGS := \ + -std=c++20 \ + -fPIC \ + -fvisibility=hidden \ + -fno-stack-protector \ + -ffunction-sections \ + -fdata-sections \ + -flto=thin + +COMMON_LDFLAGS := \ + -Wl,-O2 \ + -Wl,--gc-sections \ + -Wl,-s \ + -flto=thin + +COMMON_INCLUDES := \ + $(LOCAL_PATH)/../../../ + +LOCAL_CPPFLAGS += $(COMMON_CPPFLAGS) +LOCAL_LDFLAGS += $(COMMON_LDFLAGS) +LOCAL_C_INCLUDES += $(COMMON_INCLUDES) diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/module_hide_data_dir.cpp" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/module_hide_data_dir.cpp" new file mode 100644 index 00000000..19c7abe4 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/module_hide_data_dir.cpp" @@ -0,0 +1,94 @@ +#include + +#include "module_hide_data_dir.h" +#include "patch_filldir64.h" +#include "kernel_module_kit_umbrella.h" + +#include "cJSON.h" + +#define MOD_VER "1.0.4" + +// 把 ["aa","bb","cc"] 解析成 std::set +static std::set parse_json(const std::string& json) { + std::set result; + cJSON* root = cJSON_Parse(json.c_str()); + if (!root) return result; + if (root->type != cJSON_Array) { + cJSON_Delete(root); + return result; + } + int size = cJSON_GetArraySize(root); + for (int i = 0; i < size; ++i) { + cJSON* item = cJSON_GetArrayItem(root, i); + if (!item) continue; + if (item->type != cJSON_String) continue; + if (!item->valuestring) continue; + result.insert(std::string(item->valuestring)); + } + cJSON_Delete(root); + return result; +} + +// 开始修补内核 +static KModErr patch_kernel_handler(const std::set& hide_dir_list) { + kernel_module::SymbolHit filldir64; + RETURN_IF_ERROR(kernel_module::kallsyms_lookup_name("filldir64", kernel_module::SymbolMatchMode::Prefix, filldir64)); + printf("%s, addr: %p\n", filldir64.name, (void*)filldir64.addr); + + PatchBase patchBase; + PatchFilldir64 patchFilldir64(patchBase, filldir64.addr); + KModErr err = patchFilldir64.patch_filldir64(hide_dir_list); + printf("patch filldir64 ret: %s\n", to_string(err).c_str()); + return err; +} + +// SKRoot模块入口函数 +int skroot_module_main(const char* root_key, const char* module_private_dir) { + printf("Hello! module_hide_data_dir!\n"); + + //读取配置文件内容 + std::string json; + kernel_module::read_string_disk_storage("hide_dir_json", json); + std::set hide_dir_list = parse_json(json); + printf("hide dir list (%zd total) :\n", hide_dir_list.size()); + if(hide_dir_list.empty()) return 0; + + for (const auto& item : hide_dir_list) printf("hide dir: %s\n", item.c_str()); + + KModErr err = patch_kernel_handler(hide_dir_list); + printf("patch_kernel_handler ret:%s\n", to_string(err).c_str()); + return 0; +} + + +// WebUI HTTP服务器回调函数 +class MyWebHttpHandler : public kernel_module::WebUIHttpHandler { // HTTP服务器基于civetweb库 +public: + void onPrepareCreate(const char* root_key, const char* module_private_dir, uint32_t port) override { + m_root_key = root_key; + } + + // 这里的Web服务器仅起到读取、保存配置文件的作用。 + bool handlePost(CivetServer* server, struct mg_connection* conn, const std::string& path, const std::string& body) override { + printf("[module_hide_data_dir] POST request\nPath: %s\nBody: %s\n", path.c_str(), body.c_str()); + + std::string resp; + if(path == "/getVersion") resp = MOD_VER; + else if(path == "/getHiddenDirsJson") kernel_module::read_string_disk_storage("hide_dir_json", resp); + else if(path == "/setHiddenDirsJson") resp = is_ok(kernel_module::write_string_disk_storage("hide_dir_json", body.c_str())) ? "OK" : "FAILED"; + + kernel_module::webui::send_text(conn, 200, resp); + return true; + } +private: + std::string m_root_key; +}; + +// SKRoot 模块名片 +SKROOT_MODULE_NAME("隐藏/data目录") +SKROOT_MODULE_VERSION(MOD_VER) +SKROOT_MODULE_DESC("内核级隐藏 /data 指定目录,彻底阻断文件扫描;底层拦截机制,免疫各类基于漏洞的暴力扫盘。") +SKROOT_MODULE_AUTHOR("SKRoot") +SKROOT_MODULE_UUID32("ae12076c010ebabbb233affdd0239c14") +SKROOT_MODULE_WEB_UI(MyWebHttpHandler) +SKROOT_MODULE_UPDATE_JSON("https://abcz316.github.io/SKRoot-linuxKernelRoot/module_hide_data_dir/update.json") \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/module_hide_data_dir.h" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/module_hide_data_dir.h" new file mode 100644 index 00000000..9d96b945 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/module_hide_data_dir.h" @@ -0,0 +1,11 @@ +#pragma once +#include +#include +#include +#include "urlEncodeUtils.h" + +static std::string urlDecodeToStr(std::string str) { + std::vector buf(str.length() + 1); + url_decode(const_cast(str.c_str()), (char*)buf.data()); + return (char*)buf.data(); +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/patch_base.cpp" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/patch_base.cpp" new file mode 100644 index 00000000..e72728fa --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/patch_base.cpp" @@ -0,0 +1,22 @@ +#include "patch_base.h" +using namespace asmjit; +using namespace asmjit::a64; +using namespace asmjit::a64::Predicate; + +PatchBase::PatchBase() {} + +PatchBase::PatchBase(const PatchBase& other) {} + +PatchBase::~PatchBase() {} + +KModErr PatchBase::patch_kernel_before_hook(uint64_t kaddr, const Assembler* a) { + std::vector bytes = aarch64_asm_to_bytes(a); + RETURN_IF_ERROR(kernel_module::install_kernel_function_before_hook(kaddr, bytes)); + return KModErr::OK; +} + +KModErr PatchBase::patch_kernel_after_hook(uint64_t kaddr, const Assembler* a) { + std::vector bytes = aarch64_asm_to_bytes(a); + RETURN_IF_ERROR(kernel_module::install_kernel_function_after_hook(kaddr, bytes)); + return KModErr::OK; +} \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/patch_base.h" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/patch_base.h" new file mode 100644 index 00000000..9413cf75 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/patch_base.h" @@ -0,0 +1,14 @@ +#pragma once +#include +#include +#include "kernel_module_kit_umbrella.h" + +class PatchBase { +public: + PatchBase(); + PatchBase(const PatchBase& other); + ~PatchBase(); +protected: + KModErr patch_kernel_before_hook(uint64_t kaddr, const asmjit::a64::Assembler* a); + KModErr patch_kernel_after_hook(uint64_t kaddr, const asmjit::a64::Assembler* a); +}; diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/patch_filldir64.cpp" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/patch_filldir64.cpp" new file mode 100644 index 00000000..dc5b6f8a --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/patch_filldir64.cpp" @@ -0,0 +1,76 @@ +#include "patch_filldir64.h" +#include +using namespace asmjit; +using namespace asmjit::a64; +using namespace asmjit::a64::Predicate; + +/* +在 AArch64(ARM64)架构中, 根据 AAPCS64 调用约定: + X0–X7:传递参数和返回值 + X8:系统调用号或临时 + X9–X15:调用者易失(caller‑saved)临时寄存器 + X16–X17(IP0/IP1):过程内调用临时寄存器,用于短期跳转代码 + X18:平台保留寄存器(platform register),arm64内核启用SCS时,会x18作为shadow call stack指针 + X19–X28:被调用者保存寄存器(callee‑saved) + X29(FP):帧指针 + X30(LR):链接寄存器 + SP:栈指针 + +在HOOK内核函数中: +1.必须要保存、恢复的寄存器:x0–x7、X19–X28、X29-X30 +2.能自由修改、无需额外保存/恢复的寄存器是:x9–x15 或 x16–x17(IP0/IP1) +3.尽量避开使用的寄存器:x18 + +简而言之:X9到X15之间的寄存器可以随便用,其他寄存器需要先保存再用,用完需恢复。 + +ABI 规定哪些寄存器需要保存? +caller-saved(会被调用者破坏):X0..X17、Q0..Q7 +callee-saved(必须由被调函数保存):X19..X29、Q8..Q15、SP、FP、LR +也就是说,像 get_task_mm 这种标准C函数,它自己保证不会破坏 callee-saved 寄存器。 +*/ + +PatchFilldir64::PatchFilldir64(const PatchBase& patch_base, uint64_t filldir64) : PatchBase(patch_base), m_filldir64(filldir64) {} + +PatchFilldir64::~PatchFilldir64() {} + +KModErr PatchFilldir64::patch_filldir64(const std::set& hide_dir_list) { + GpX x_name_arg = x1; + GpW w_namelen_arg = w2; + + std::vector hide_dirs(hide_dir_list.begin(), hide_dir_list.end()); + + //生成Hook func汇编命令 + aarch64_asm_ctx asm_ctx = init_aarch64_asm(); + auto a = asm_ctx.assembler(); + + kernel_module::arm64_before_hook_start(a); + for (size_t i = 0; i < hide_dirs.size(); ++i) { + Label L_next = a->newLabel(); + + const auto& dir_name = hide_dirs[i]; + aarch64_asm_mov_w(a, w11, dir_name.length()); + a->cmp(w_namelen_arg, w11); + a->b(CondCode::kNE, L_next); //下一个 + + // memcmp key + aarch64_asm_set_x_cstr_ptr(a, x12, dir_name); + { + RegProtectGuard g1(a, x0); + kernel_module::string_ops::kmemcmp(a, x_name_arg, x12, x11); + a->mov(x11, x0); + } + a->cbnz(x11, L_next); //不相等,下一个 + + // 隐藏文件夹的返回 + if (kernel_module::is_kernel_version_less("6.1.0")) { + a->mov(x0, xzr); + } else { + a->mov(x0, Imm(1)); + } + kernel_module::arm64_before_hook_end(a, false); // 直接返回,不跳回原函数 + + a->bind(L_next); + } + kernel_module::arm64_before_hook_end(a, true); // 正常返回 + return patch_kernel_before_hook(m_filldir64, a); +} \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/patch_filldir64.h" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/patch_filldir64.h" new file mode 100644 index 00000000..129c4496 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/patch_filldir64.h" @@ -0,0 +1,14 @@ +#pragma once +#include +#include +#include "patch_base.h" + +class PatchFilldir64 : public PatchBase { +public: + PatchFilldir64(const PatchBase& patch_base, uint64_t filldir64); + ~PatchFilldir64(); + + KModErr patch_filldir64(const std::set& hide_dir_name); +private: + uint64_t m_filldir64 = 0; +}; \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/urlEncodeUtils.h" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/urlEncodeUtils.h" new file mode 100644 index 00000000..0d1482f7 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/urlEncodeUtils.h" @@ -0,0 +1,74 @@ +#ifndef URL_ENCODE_UTILS_H_ +#define URL_ENCODE_UTILS_H_ +#include +#include + +static inline char to_hex(char code) { + static char hex[] = "0123456789ABCDEF"; + return hex[code & 15]; +} +static inline char from_hex(char ch) { + return isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10; +} + +/* +//使用例子 +int main() { + char str[] = "你好,世界"; + char encoded_str[256]; + url_encode(str, encoded_str); + printf("Encoded URL: %s\n", encoded_str); + return 0; +} +*/ +static void url_encode(char *str, char *encoded_str) { + char *pstr = str, *buf = encoded_str; + while (*pstr) { + unsigned char c = *pstr; + if (c <= 0x7F) { // ASCII + if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') { + *buf++ = c; + } else if (c == ' ') { + *buf++ = '+'; + } else { + *buf++ = '%', *buf++ = to_hex(c >> 4), *buf++ = to_hex(c & 15); + } + } else { // Non-ASCII + while (c) { + *buf++ = '%', *buf++ = to_hex(c >> 4), *buf++ = to_hex(c & 15); + c = *(++pstr); + } + continue; + } + pstr++; + } + *buf = '\0'; +} +/* +//使用例子 +int main() { + char url[] = "%E4%BD%A0%E5%A5%BD%EF%BC%8C%E4%B8%96%E7%95%8C"; // "你好,世界"的URL编码 + char decoded_str[256]; + url_decode(url, decoded_str); + printf("Decoded URL: %s\n", decoded_str); + return 0; +} +*/ +static void url_decode(char *str, char *decoded_str) { + char *pstr = str, *buf = decoded_str; + while (*pstr) { + if (*pstr == '%') { + if (pstr[1] && pstr[2]) { + *buf++ = from_hex(pstr[1]) << 4 | from_hex(pstr[2]); + pstr += 2; + } + } else if (*pstr == '+') { + *buf++ = ' '; + } else { + *buf++ = *pstr; + } + pstr++; + } + *buf = '\0'; +} +#endif \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/webroot/index.html" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/webroot/index.html" new file mode 100644 index 00000000..5a24e3d1 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/webroot/index.html" @@ -0,0 +1,46 @@ + + + + + + /data 隐藏目录配置 + + + + +
+
+
/data 隐藏目录
+
请避免与系统目录重名,如 system、vendor、data 等关键词,否则无法开机。
+
提示:请输入 /data 下的目录名称(仅名称,如 myfolder)。目录将被隐藏,但内部程序可正常运行。配置将在重启后生效。
+ +
+ +
+ +
+ + +
+ + +
+ + +
+
+ + +
+ + + + + + + + + diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/webroot/main.js" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/webroot/main.js" new file mode 100644 index 00000000..e64b00b0 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/webroot/main.js" @@ -0,0 +1,161 @@ +// ====== 业务配置 ====== +const FORBIDDEN_KEYWORDS = ['system', 'vendor', 'data', 'app']; // 小写匹配 +const NAME_RULE = /^[A-Za-z0-9._\-+]+$/; +const LS_KEY = 'hidden-folders-v1'; + +// ====== DOM ====== +const $input = document.getElementById('inputName'); +const $btnAdd = document.getElementById('btnAdd'); +const $fabAdd = document.getElementById('fabAdd'); +const $list = document.getElementById('list'); +const $error = document.getElementById('error'); +const $verSpan = document.getElementById('ver'); + +// ====== 状态 ====== +/** @type {string[]} */ +let items = []; + +// ====== 工具 ====== +function showError(msg) { + $error.textContent = msg; + $error.classList.add('show'); + clearTimeout(showError.tid); + showError.tid = setTimeout(() => $error.classList.remove('show'), 2600); +} + +async function save() { + try { + const json = JSON.stringify(items); + const result = await RequestApi.setHiddenDirsJson(json); + if (result !== 'OK') { + alert('保存失败:' + result); + return false; + } + return true; + } catch (err) { + console.error('保存配置失败:', err); + alert('保存失败:' + (err instanceof Error ? err.message : String(err))); + return false; + } +} + +async function load() { + try { + const raw = await RequestApi.getHiddenDirsJson(); + if (!raw) return []; + + const data = JSON.parse(raw); + return /** @type {string[]} */ (data); + } catch (err) { + console.error('读取配置失败:', err); + alert('读取配置失败:' + (err instanceof Error ? err.message : String(err))); + return []; + } +} + + +function sanitizeName(raw) { + const s = (raw || '').trim(); + if (!s) { showError('目录名不能为空'); return null; } + if (!NAME_RULE.test(s)) { + showError('只允许字母/数字/点/下划线/短横线/加号,且不要包含 /'); + return null; + } + const lower = s.toLowerCase(); + if (FORBIDDEN_KEYWORDS.some(k => lower.includes(k))) { + showError(`禁止包含系统关键字:${FORBIDDEN_KEYWORDS.join(', ')}`); + return null; + } + return s; +} + +function exists(name) { + const lower = name.toLowerCase(); + return items.some(n => n.toLowerCase() === lower); +} + +// ====== 渲染 ====== +function render() { + $list.innerHTML = ''; + if (!items.length) { + const empty = document.createElement('div'); + empty.className = 'row'; + empty.innerHTML = + `
+ 暂无数据,点击「+新增」添加要隐藏的目录名 +
`; + $list.appendChild(empty); + return; + } + + items.forEach((name, idx) => { + const row = document.createElement('div'); + row.className = 'row'; + + const left = document.createElement('div'); + left.className = 'name'; + left.innerHTML = `${name}/data/${name}`; + + const del = document.createElement('button'); + del.className = 'del'; + del.textContent = '删除'; + del.addEventListener('click', async () => { + items.splice(idx, 1); + const ok = await save(); + if (ok) { + showToast('删除成功,重启生效', 'danger'); + render(); + } + }); + + row.appendChild(left); + row.appendChild(del); + $list.appendChild(row); + }); +} + +// ====== 事件 ====== +async function doAdd() { + const s = sanitizeName($input.value); + if (!s) return; + if (exists(s)) { + showError('该目录已存在'); + return; + } + + items.push(s); + $input.value = ''; + + const ok = await save(); + if (ok) { + showToast('新增成功,重启生效', 'success'); + render(); + } +} + + +$btnAdd.addEventListener('click', doAdd); +$fabAdd.addEventListener('click', doAdd); +$input.addEventListener('keydown', (e) => { + if (e.key === 'Enter') doAdd(); +}); + +async function initVersion() { + try { + const ver = await RequestApi.getVersion(); + $verSpan.textContent = ver || '未知'; + } catch (err) { + $verSpan.textContent = '读取失败'; + console.error('getVersion 出错:', err); + alert('读取版本失败:' + (err instanceof Error ? err.message : String(err))); + } +} + +// ====== 入口初始化 ====== +async function onReady() { + items = await load(); + render(); + await initVersion(); +} +document.addEventListener('DOMContentLoaded', onReady); + diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/webroot/request.js" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/webroot/request.js" new file mode 100644 index 00000000..0347b9b0 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/webroot/request.js" @@ -0,0 +1,27 @@ +const RequestApi = (() => { + function postText(path, bodyText = "") { + const url = new URL(path, window.location.href); + return fetch(url, { method: 'POST', body: bodyText }); + } + + async function getVersion() { + const resp = await postText('/getVersion'); + return resp.ok ? await resp.text() : ('HTTP ' + resp.status); + } + + async function getHiddenDirsJson() { + const resp = await postText('/getHiddenDirsJson'); + return resp.ok ? await resp.text() : ('HTTP ' + resp.status); + } + + async function setHiddenDirsJson(json) { + const resp = await postText('/setHiddenDirsJson', json); + return resp.ok ? await resp.text() : ('HTTP ' + resp.status); + } + + return { + getVersion, + getHiddenDirsJson, + setHiddenDirsJson + }; +})(); diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/webroot/style.css" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/webroot/style.css" new file mode 100644 index 00000000..7b528b5b --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/webroot/style.css" @@ -0,0 +1,242 @@ +:root { + /* 明亮主题 */ + --bg: #f6f7fb; + --card: #ffffff; + --text: #0b1220; + --muted: #5f6b7a; + --line: #e7eaf0; + --ok: #34c759; + /* iOS 绿色 */ + --danger: #ff3b30; + /* iOS 红 */ + --warn: #ffcc00; + /* iOS 黄 */ + --blue: #0a84ff; + /* iOS 蓝 */ + --radius: 14px; + --shadow: 0 10px 30px rgba(0, 0, 0, .08); +} + +* { + box-sizing: border-box; + -webkit-tap-highlight-color: transparent; +} + +html, +body { + height: 100%; +} + +body { + margin: 0; + background: var(--bg); + color: var(--text); + font: 15px/1.5 -apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", "PingFang SC", "Helvetica Neue", Arial, "Microsoft YaHei", sans-serif; +} + +.wrap { + max-width: 720px; + margin: 0 auto; + padding: env(safe-area-inset-top) 14px calc(64px + env(safe-area-inset-bottom)) 14px; +} + +/* 顶部栏(明亮) */ +.topbar { + position: sticky; + top: 0; + z-index: 10; + margin: 0 -14px 16px; + padding: calc(env(safe-area-inset-top) + 10px) 14px 10px; + background: rgba(255, 255, 255, .85); + backdrop-filter: blur(10px); + border-bottom: 1px solid var(--line); +} + +.title { + font-size: 20px; + font-weight: 700; + letter-spacing: .3px; + display: flex; + align-items: center; + gap: 10px; +} + +.title .dot { + width: 10px; + height: 10px; + border-radius: 50%; + background: linear-gradient(135deg, #0ea5e9, #6366f1); + box-shadow: 0 0 12px rgba(14, 165, 233, .6); +} + +.sub { + margin-top: 8px; + color: var(--muted); + font-size: 13px; +} + +.warn { + display: flex; + align-items: center; + gap: 8px; + margin-top: 10px; + padding: 10px 12px; + background: #fff8e1; + border: 1px solid #ffe08a; + border-radius: 12px; + color: #8a6d00; + font-size: 13px; +} + +/* 面板 */ +.panel { + background: var(--card); + border: 1px solid var(--line); + border-radius: var(--radius); + box-shadow: var(--shadow); + overflow: hidden; +} + +.toolbar { + display: flex; + gap: 10px; + align-items: center; + padding: 12px; + border-bottom: 1px solid var(--line); + background: #fafbff; +} + +.toolbar input { + appearance: none; + outline: none; + flex: 1; + background: #fff; + color: var(--text); + border: 1px solid var(--line); + border-radius: 12px; + padding: 12px 14px; +} + +.toolbar input::placeholder { + color: #9aa5b1; +} + +.btn { + appearance: none; + border: 0; + border-radius: 12px; + padding: 10px 14px; + background: linear-gradient(135deg, #0ea5e9, #6366f1); + color: #fff; + font-weight: 600; + letter-spacing: .2px; + box-shadow: 0 6px 18px rgba(99, 102, 241, .25); +} + +.btn:active { + transform: translateY(1px); + opacity: .95; +} + +/* 列表(表格风) */ +.list { + width: 100%; +} + +.row { + display: grid; + grid-template-columns: 1fr auto auto; + gap: 10px; + align-items: center; + padding: 12px 14px; + border-bottom: 1px dashed var(--line); + background: #fff; +} + +.row:nth-child(odd) { + background: #fbfcff; +} + +.row:last-child { + border-bottom: none; +} + +.name { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-weight: 600; + letter-spacing: .2px; +} + +.badge { + font-size: 11px; + color: var(--muted); + border: 1px solid var(--line); + border-radius: 999px; + padding: 3px 8px; + margin-left: 8px; + background: #f7f9fc; +} + +.del { + appearance: none; + border: 1px solid rgba(255, 59, 48, .35); + background: rgba(255, 59, 48, .06); + color: #d32f2f; + border-radius: 10px; + padding: 6px 10px; + font-weight: 600; +} + +.del:active { + transform: translateY(1px); + opacity: .9; +} + +/* 错误提示(明亮) */ +.error { + margin: 12px; + padding: 10px 12px; + border-radius: 10px; + color: #b00020; + background: #fff1f2; + border: 1px solid #ffcdd2; + display: none; + font-size: 13px; +} + +.error.show { + display: block; +} + +/* 页脚(明亮) */ +.footer { + margin-top: 16px; + padding: 14px; + text-align: center; + color: var(--muted); + font-size: 12px; +} + +.footer a { + color: #0066cc; + text-decoration: underline; +} + +/* 浮动 + */ +.fab { + position: fixed; + right: 18px; + bottom: calc(18px + env(safe-area-inset-bottom)); + width: 56px; + height: 56px; + border-radius: 50%; + border: none; + color: #fff; + font-size: 30px; + line-height: 0; + background: linear-gradient(135deg, #0ea5e9, #6366f1); + box-shadow: 0 12px 30px rgba(99, 102, 241, .28); +} \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/webroot/toast.css" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/webroot/toast.css" new file mode 100644 index 00000000..149a5db6 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/webroot/toast.css" @@ -0,0 +1,36 @@ +/* ====== 中央提示 Toast ====== */ +.toast { + position: fixed; + left: 50%; + top: 50%; + transform: translate(-50%, -50%) translateY(8px); + padding: 10px 18px; + border-radius: 999px; + font-size: 14px; + font-weight: 500; + color: #fff; + background: rgba(15, 23, 42, 0.96); + box-shadow: 0 12px 30px rgba(15, 23, 42, 0.45); + opacity: 0; + pointer-events: none; + z-index: 999; + transition: opacity .26s ease, transform .26s ease; +} + +/* 成功(绿色) */ +.toast--success { + background: rgba(52, 199, 89, 0.96); + /* 对应 --ok */ +} + +/* 删除(红色) */ +.toast--danger { + background: rgba(255, 59, 48, 0.96); + /* 对应 --danger */ +} + +/* 显示状态 */ +.toast--show { + opacity: 1; + transform: translate(-50%, -50%) translateY(0); +} \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/webroot/toast.js" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/webroot/toast.js" new file mode 100644 index 00000000..fdb9dfcf --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_data_dir/webroot/toast.js" @@ -0,0 +1,37 @@ +let toastTimer = null; + +/** + * 居中小提示 + * @param {string} msg 提示文字 + * @param {'success' | 'danger'} type 提示类型 + */ +function showToast(msg, type = 'success') { + let toast = document.getElementById('toast'); + if (!toast) { + toast = document.createElement('div'); + toast.id = 'toast'; + toast.className = 'toast'; + document.body.appendChild(toast); + } + + toast.textContent = msg; + + // 先清掉旧的 class + toast.classList.remove('toast--success', 'toast--danger', 'toast--show'); + + if (type === 'danger') { + toast.classList.add('toast--danger'); + } else { + toast.classList.add('toast--success'); + } + + // 触发重绘(让重新加 show 时动画生效) + void toast.offsetWidth; + + toast.classList.add('toast--show'); + + clearTimeout(toastTimer); + toastTimer = setTimeout(() => { + toast.classList.remove('toast--show'); + }, 2000); // 2000 秒自动消失 +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/idle_killer.cpp" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/idle_killer.cpp" new file mode 100644 index 00000000..002020f0 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/idle_killer.cpp" @@ -0,0 +1,33 @@ +#include "idle_killer.h" + +static int64_t now_ns() { + using namespace std::chrono; + return duration_cast(steady_clock::now().time_since_epoch()).count(); +} +static int64_t to_ns(std::chrono::seconds s) { + using namespace std::chrono; + return duration_cast(s).count(); +} + +void IdleKiller::start(std::chrono::seconds timeout, OnTimeout cb) { + m_timeout_ns = to_ns(timeout); + m_on_timeout = std::move(cb); + touch(); + bool expected = false; + if (!m_started.compare_exchange_strong(expected, true, std::memory_order_acq_rel)) return; + std::thread([this] { + for (;;) { + const auto last = m_last_activity_ns.load(std::memory_order_acquire); + const auto now = now_ns(); + + if (last != 0 && (now - last) > m_timeout_ns.load(std::memory_order_acquire)) { + // 先取出回调再执行,避免回调里 _exit 导致奇怪竞态 + auto cb = m_on_timeout; // copy + if (cb) cb(); + return; + } + std::this_thread::sleep_for(std::chrono::seconds(1)); + } + }).detach(); +} +void IdleKiller::touch() { m_last_activity_ns.store(now_ns(), std::memory_order_release); } diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/idle_killer.h" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/idle_killer.h" new file mode 100644 index 00000000..02b4e2b7 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/idle_killer.h" @@ -0,0 +1,18 @@ +#pragma once +#include +#include +#include +#include +#include + +class IdleKiller { +public: + using OnTimeout = std::function; + void start(std::chrono::seconds timeout, OnTimeout cb); + void touch(); +private: + std::atomic m_started{false}; + std::atomic m_last_activity_ns{0}; + std::atomic m_timeout_ns{0}; + OnTimeout m_on_timeout; +}; \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/jni/Android.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/jni/Android.mk" new file mode 100644 index 00000000..93b9433e --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/jni/Android.mk" @@ -0,0 +1,16 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) +LOCAL_MODULE := module_hide_sh_exec + +LOCAL_SRC_FILES := ../module_hide_sh_exec.cpp ../su_interactive.cpp ../idle_killer.cpp + +KERNEL_MODULE_KIT := $(LOCAL_PATH)/../../kernel_module_kit +LOCAL_C_INCLUDES += $(KERNEL_MODULE_KIT)/include +LOCAL_LDFLAGS += $(KERNEL_MODULE_KIT)/lib/libkernel_module_kit_static.a + +include $(LOCAL_PATH)/build_macros.mk + +include $(BUILD_SHARED_LIBRARY) + + diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/jni/Application.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/jni/Application.mk" new file mode 100644 index 00000000..2500a8a7 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/jni/Application.mk" @@ -0,0 +1,2 @@ +APP_ABI := arm64-v8a +APP_STL := c++_static \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/jni/build_macros.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/jni/build_macros.mk" new file mode 100644 index 00000000..a6f31501 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/jni/build_macros.mk" @@ -0,0 +1,21 @@ +COMMON_CPPFLAGS := \ + -std=c++20 \ + -fPIC \ + -fvisibility=hidden \ + -fno-stack-protector \ + -ffunction-sections \ + -fdata-sections \ + -flto=thin + +COMMON_LDFLAGS := \ + -Wl,-O2 \ + -Wl,--gc-sections \ + -Wl,-s \ + -flto=thin + +COMMON_INCLUDES := \ + $(LOCAL_PATH)/../../../ + +LOCAL_CPPFLAGS += $(COMMON_CPPFLAGS) +LOCAL_LDFLAGS += $(COMMON_LDFLAGS) +LOCAL_C_INCLUDES += $(COMMON_INCLUDES) diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/module_hide_sh_exec.cpp" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/module_hide_sh_exec.cpp" new file mode 100644 index 00000000..8582ce63 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/module_hide_sh_exec.cpp" @@ -0,0 +1,82 @@ +#include "kernel_module_kit_umbrella.h" + +#include "su_interactive.h" +#include "idle_killer.h" + +int skroot_module_main(const char* root_key, const char* module_private_dir) { return 0; } + +static bool pid_alive(pid_t pid) { + if (pid <= 1) return false; + if (::kill(pid, 0) == 0) return true; + return errno == EPERM; +} + +static void wait_parent_exit(const std::string& root_key, pid_t ppid) { + timespec ts{0, 500 * 1000 * 1000}; // 500ms + while (getppid() != 1 && pid_alive(ppid)) { + skroot_env::get_root(root_key.c_str()); + nanosleep(&ts, nullptr); + } +} + +// WebUI HTTP服务器回调函数 +class MyWebHttpHandler : public kernel_module::WebUIHttpHandler { +public: + void onPrepareCreate(const char* root_key, const char* module_private_dir, uint32_t port) override { + m_root_key = root_key; + m_su_interactive.start(); + fork_sh_process_daemon(); + + m_idle_killer.start(std::chrono::seconds(30), [this] { + _exit(0); + }); + + } + + bool handlePost(CivetServer* server, struct mg_connection* conn, const std::string& path, const std::string& body) override { + //printf("[module_hide_sh_exec] POST request\nPath: %s\nBody: %s\n", path.c_str(), body.c_str()); + std::string resp; + if(path == "/sendCommand") { + m_idle_killer.touch(); + m_su_interactive.sendLine(body); + resp = "OK"; + } else if(path == "/getNewOutput") { + m_idle_killer.touch(); + resp = m_su_interactive.takeOutput(); + } + kernel_module::webui::send_text(conn, 200, resp); + return true; + } + + ServerExitAction onBeforeServerExit() override { return ServerExitAction::KeepRunning; } + +private: + void fork_sh_process_daemon() { + pid_t shell_pid = m_su_interactive.get_shell_pid(); + pid_t ppid = getpid(); + pid_t child = fork(); + if(child == 0) { + if (setsid() < 0) { + setpgid(0, 0); + } + signal(SIGPIPE, SIG_IGN); + wait_parent_exit(m_root_key, ppid); + printf("[module_hide_sh_exec] kill sh!\n"); + kill(shell_pid, SIGKILL); + _exit(0); + } + } +private: + std::string m_root_key; + SuInteractive m_su_interactive; + IdleKiller m_idle_killer; +}; + +// SKRoot 模块名片 +SKROOT_MODULE_NAME("隐蔽的系统终端") +SKROOT_MODULE_VERSION("2.0.0") +SKROOT_MODULE_DESC("提供独立隐蔽的 sh 执行通道,彻底替代终端类 App,避免终端类 App 带来的特征暴露。") +SKROOT_MODULE_AUTHOR("SKRoot") +SKROOT_MODULE_UUID32("zse9vkTjLjWXbafvx8Mlh1MTf8SMTUEL") +SKROOT_MODULE_WEB_UI(MyWebHttpHandler) +SKROOT_MODULE_UPDATE_JSON("https://abcz316.github.io/SKRoot-linuxKernelRoot/module_hide_sh_exec/update.json") \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/su_interactive.cpp" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/su_interactive.cpp" new file mode 100644 index 00000000..46dd15cd --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/su_interactive.cpp" @@ -0,0 +1,226 @@ +#include "su_interactive.h" + +#include +#include +#include +#include +#include + +#include +#include +#include + +SuInteractive::SuInteractive() = default; + +SuInteractive::~SuInteractive() { + stop(true); +} + +bool SuInteractive::makePipe(int p[2]) { + if (::pipe(p) != 0) return false; + setCloExec(p[0]); + setCloExec(p[1]); + return true; +} + +void SuInteractive::setCloExec(int fd) { + int flags = ::fcntl(fd, F_GETFD); + if (flags >= 0) ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC); +} + +void SuInteractive::safeClose(int& fd) { + if (fd >= 0) { ::close(fd); fd = -1; } +} + +bool SuInteractive::start() { + stop(true); // 支持重复 start:先清理干净 + + int in_p[2]{-1,-1}; + int out_p[2]{-1,-1}; + if (!makePipe(in_p) || !makePipe(out_p)) { + if (in_p[0] >= 0) ::close(in_p[0]); + if (in_p[1] >= 0) ::close(in_p[1]); + if (out_p[0] >= 0) ::close(out_p[0]); + if (out_p[1] >= 0) ::close(out_p[1]); + return false; + } + + pid_t pid = ::fork(); + if (pid < 0) { + ::close(in_p[0]); ::close(in_p[1]); + ::close(out_p[0]); ::close(out_p[1]); + return false; + } + + if (pid == 0) { + // child: stdin/out/err + ::dup2(in_p[0], STDIN_FILENO); + ::dup2(out_p[1], STDOUT_FILENO); + ::dup2(STDOUT_FILENO, STDERR_FILENO); // stderr 合并到 stdout + + ::close(in_p[0]); ::close(in_p[1]); + ::close(out_p[0]); ::close(out_p[1]); + + // 只用 su + const char* argv[] = {"su", nullptr}; + ::execvp("su", (char* const*)argv); + + // exec failed + const char* msg = "exec su failed\n"; + ::write(STDERR_FILENO, msg, std::strlen(msg)); + _exit(127); + } + + // parent + m_pid = pid; + + ::close(in_p[0]); + ::close(out_p[1]); + + m_in_w = in_p[1]; + m_out_r = out_p[0]; + + { + std::lock_guard lk(m_mu); + m_out.clear(); + } + + m_reader = std::thread([this] { readerLoop_(); }); + return true; +} + +void SuInteractive::readerLoop_() { + // 注意:这里读的是“合并后的输出” + char buf[4096]; + for (;;) { + int fd = m_out_r; + if (fd < 0) break; + + ssize_t n = ::read(fd, buf, sizeof(buf)); + if (n > 0) { + // 1) 实时打印(你要的“持续读取输出”) + // 如果你不想默认打印,把下面这行注释掉即可。 + (void)::write(STDOUT_FILENO, buf, static_cast(n)); + + // 2) 累积到 string(方便你之后一次性取) + { + std::lock_guard lk(m_mu); + m_out.append(buf, static_cast(n)); + } + continue; + } + + if (n == 0) break; // EOF + if (errno == EINTR) continue; // 被信号打断,继续 + // fd 被关闭/其它错误:退出 + break; + } + + // reader 线程退出前确保关闭读端 + safeClose(m_out_r); +} + +bool SuInteractive::send(const std::string& s) { + if (m_in_w < 0) return false; + + const char* p = s.data(); + size_t left = s.size(); + while (left) { + ssize_t n = ::write(m_in_w, p, left); + if (n > 0) { + p += n; + left -= static_cast(n); + continue; + } + if (n < 0 && errno == EINTR) continue; + return false; + } + return true; +} + +bool SuInteractive::sendLine(const std::string& line) { + if (!send(line)) return false; + if (!line.empty() && line.back() == '\n') return true; + return send("\n"); +} + +void SuInteractive::closeInput() { + safeClose(m_in_w); +} + +int SuInteractive::wait() { + if (m_pid <= 0) return -1; + + closeInput(); + + int status = 0; + for (;;) { + pid_t r = ::waitpid(m_pid, &status, 0); + if (r > 0) break; + if (r < 0 && errno == EINTR) continue; + break; + } + + if (m_reader.joinable()) m_reader.join(); + + pid_t old = m_pid; + m_pid = -1; + + if (old <= 0) return -1; + if (WIFEXITED(status)) return WEXITSTATUS(status); + if (WIFSIGNALED(status)) return 128 + WTERMSIG(status); + return -1; +} + +void SuInteractive::stop(bool force) { + // 先关输入,让对端有机会优雅退出 + closeInput(); + + if (m_pid > 0 && force) { + // 先 SIGTERM,再等一会儿,不行再 SIGKILL + ::kill(m_pid, SIGTERM); + + for (int i = 0; i < 30; ++i) { // ~300ms + int status = 0; + pid_t r = ::waitpid(m_pid, &status, WNOHANG); + if (r == m_pid) { + m_pid = -1; + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + + if (m_pid > 0) { + ::kill(m_pid, SIGKILL); + } + } + + // 关闭输出读端,确保 reader 线程 read 能退出 + safeClose(m_out_r); + + // 回收线程 + if (m_reader.joinable()) m_reader.join(); + + // 如果还没回收进程,这里兜底 waitpid 一下(不阻塞太久) + if (m_pid > 0) { + int status = 0; + (void)::waitpid(m_pid, &status, WNOHANG); + m_pid = -1; + } +} + +std::string SuInteractive::output() const { + std::lock_guard lk(m_mu); + return m_out; +} + +std::string SuInteractive::takeOutput() { + std::lock_guard lk(m_mu); + std::string ret = std::move(m_out); + m_out.clear(); + return ret; +} + +pid_t SuInteractive::get_shell_pid() { + return m_pid; +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/su_interactive.h" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/su_interactive.h" new file mode 100644 index 00000000..c898aceb --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/su_interactive.h" @@ -0,0 +1,60 @@ +#pragma once +#include + +#include +#include +#include +#include +#include + +class SuInteractive { +public: + SuInteractive(); + ~SuInteractive(); + + SuInteractive(const SuInteractive&) = delete; + SuInteractive& operator=(const SuInteractive&) = delete; + + // 启动 su;stderr 会合并到 stdout + bool start(); + + // 发送数据/发送一行(自动补 '\n') + bool send(const std::string& s); + bool sendLine(const std::string& line); + + // 关闭输入(让对端收到 EOF) + void closeInput(); + + // 等待子进程退出(返回 exit code;信号:128+sig;失败 -1) + int wait(); + + // 停止并清理: + // force=false:不强杀,只关输入/输出fd并回收线程(对方若不退出可能 wait 会卡) + // force=true :SIGTERM + 短暂等待 + SIGKILL,确保回收 + void stop(bool force = true); + + // 获取累积输出(拷贝) + std::string output() const; + + // 取走并清空累积输出(更适合“增量取日志”) + std::string takeOutput(); + + // 获取shell进程PID + pid_t get_shell_pid(); +private: + static bool makePipe(int p[2]); + static void setCloExec(int fd); + static void safeClose(int& fd); + + void readerLoop_(); + +private: + pid_t m_pid{-1}; + + int m_in_w{-1}; // parent -> child stdin (write end) + int m_out_r{-1}; // child -> parent merged stdout/stderr (read end) + + mutable std::mutex m_mu; + std::string m_out; + std::thread m_reader; +}; diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/webroot/index.html" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/webroot/index.html" new file mode 100644 index 00000000..37f1cf0c --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/webroot/index.html" @@ -0,0 +1,72 @@ + + + + + + 隐蔽的系统终端 + + + +
+
+ +
+
隐蔽的系统终端
+
+ + 连接中 +
+
+ +
+
+ +
+
+
+
#
+ +
+ + +
+ +
+
+ 提示:执行后台脚本时,建议命令下发后关闭本页面;脚本仍可继续在后台运行,同时隐蔽性更高。 +
+ +
+ 查看使用说明 +
+ 本功能并非普通系统终端,而是一个 极其隐蔽 的系统终端。 + 为避免被侦测,交互方式会受到一定限制,部分需要持续交互的命令, + 可能无法像常规终端那样直接操作。若需更稳定的交互,建议自行编写 + sh 脚本进行一层封装后再执行。 + 这是隐蔽性与交互性之间的必要取舍。 +
+
+
+
+
+ +
+
+ + + + + \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/webroot/main.js" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/webroot/main.js" new file mode 100644 index 00000000..7b0ff3ae --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/webroot/main.js" @@ -0,0 +1,149 @@ +(() => { + // ====== UI refs ====== + const out = document.getElementById("out"); + const cmd = document.getElementById("cmd"); + const sendBtn = document.getElementById("sendBtn"); + const connDot = document.getElementById("connDot"); + const connText = document.getElementById("connText"); + + // ====== state ====== + let failCount = 0; + + // ====== stream state ====== + let pending = ""; + let partialRow = null; + + function scrollBottom() { + requestAnimationFrame(() => { + requestAnimationFrame(() => { + out.scrollTop = out.scrollHeight; + }); + }); + } + + function appendLine(text){ + const row = document.createElement("div"); + row.className = "line"; + + const txt = document.createElement("div"); + txt.className = "txt"; + txt.textContent = text; + + row.appendChild(txt); + out.appendChild(row); + + scrollBottom(); + } + + function ensurePartialRow(){ + if (partialRow) return partialRow; + + const row = document.createElement("div"); + row.className = "line"; + const txt = document.createElement("div"); + txt.className = "txt"; + row.appendChild(txt); + out.appendChild(row); + partialRow = row; + + scrollBottom(); + return partialRow; + } + + function setPartialText(text){ + if (!text) { + if (partialRow) { + partialRow.remove(); + partialRow = null; + } + scrollBottom(); + return; + } + const row = ensurePartialRow(); + row.firstChild.textContent = text; + scrollBottom(); + } + + function consumeChunk(chunk){ + if (!chunk) return; + + pending += chunk; + const parts = pending.split("\n"); + pending = parts.pop(); + for (const line of parts) appendLine(line); + setPartialText(pending); + } + + function setConn(ok, text){ + connDot.classList.remove("ok", "bad", "connecting"); + if (ok === true) connDot.classList.add("ok"); + else if (ok === false) connDot.classList.add("bad"); + else connDot.classList.add("connecting"); + connText.textContent = text; + } + + async function sendCommand(){ + const v = (cmd.value || "").trim(); + if (!v) return; + + appendLine("# " + v); + + cmd.value = ""; + cmd.focus(); + + sendBtn.disabled = true; + try { + await RequestApi.sendCommand(v); + } catch(e) { + appendLine("ERR: 发送失败 - " + (e && e.message ? e.message : String(e))); + } finally { + sendBtn.disabled = false; + scrollBottom(); + } + } + + async function pollLogsOnce(){ + const chunk = await RequestApi.getNewOutput(); + if (chunk && chunk.length > 0) { + consumeChunk(chunk); + return true; + } + return false; + } + + async function tick(){ + try{ + await pollLogsOnce(); + failCount = 0; + setConn(true, "在线"); + } catch(e){ + failCount++; + if (failCount >= 2) setConn(false, "异常"); + else setConn(null, "连接中"); + } + } + + + // ====== events ====== + cmd.addEventListener("keydown", (ev) => { + if (ev.key === "Enter") { + ev.preventDefault(); + sendCommand(); + } + }); + sendBtn.addEventListener("click", sendCommand); + + if (window.visualViewport) { + const vv = window.visualViewport; + const onVV = () => scrollBottom(); + vv.addEventListener("resize", onVV); + vv.addEventListener("scroll", onVV); + } + // ====== init ====== + appendLine("#"); + setConn(null, "连接中"); + cmd.focus(); + tick(); + setInterval(tick, 1000); + +})(); diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/webroot/request.js" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/webroot/request.js" new file mode 100644 index 00000000..4055a585 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/webroot/request.js" @@ -0,0 +1,21 @@ +const RequestApi = (() => { + function postText(path, bodyText = "") { + const url = new URL(path, window.location.href); + return fetch(url, { method: 'POST', body: bodyText }); + } + + async function sendCommand(cmd) { + const resp = await postText('/sendCommand', cmd); + return resp.ok ? await resp.text() : ('HTTP ' + resp.status); + } + + async function getNewOutput() { + const resp = await postText('/getNewOutput'); + return resp.ok ? await resp.text() : ('HTTP ' + resp.status); + } + + return { + sendCommand, + getNewOutput + }; +})(); diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/webroot/style.css" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/webroot/style.css" new file mode 100644 index 00000000..af2c1d63 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_hide_sh_exec/webroot/style.css" @@ -0,0 +1,547 @@ +:root{ + --bg:#f6f8fc; + --card:#ffffff; + --text:#0f172a; + --muted:#64748b; + --line:#e6eaf2; + --shadow: 0 18px 60px rgba(15, 23, 42, .10); + --accent:#2563eb; + --accent2:#4f46e5; + --mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; + --sans: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, "Noto Sans"; +} + +*{ box-sizing:border-box; } + +html, body{ + height:100%; + overflow:hidden; +} + +body{ + margin:0; + font-family:var(--sans); + color:var(--text); + background: + radial-gradient(1100px 650px at 15% 10%, #eef3ff, transparent 70%), + linear-gradient(180deg, var(--bg), #ffffff); +} + +.wrap{ + min-height:100%; + display:flex; + align-items:center; + justify-content:center; + padding:16px 12px; +} + +.card{ + width:min(980px, 96vw); + background:var(--card); + border:1px solid var(--line); + border-radius:18px; + box-shadow:var(--shadow); + overflow:hidden; + max-height:92vh; + display:flex; + flex-direction:column; +} + +/* ====== Head ====== */ +.head{ + padding:12px 14px; + border-bottom:1px solid var(--line); + background:linear-gradient(180deg, #ffffff, #fbfcff); + display:flex; + align-items:center; + justify-content:space-between; + gap:12px; +} + +.title{ + font-size:14px; + font-weight:700; + letter-spacing:.2px; + min-width:0; + overflow:hidden; + text-overflow:ellipsis; + white-space:nowrap; +} + +.conn{ + display:inline-flex; + align-items:center; + gap:8px; + font-size:12px; + color:var(--muted); + user-select:none; + white-space:nowrap; + flex:0 0 auto; +} + +.dot{ + width:10px; + height:10px; + border-radius:999px; + background:#f59e0b; + box-shadow:0 0 0 4px rgba(245,158,11,.12); +} + +.dot.ok{ + background:#16a34a; + box-shadow:0 0 0 4px rgba(22,163,74,.12); +} + +.dot.bad{ + background:#ef4444; + box-shadow:0 0 0 4px rgba(239,68,68,.12); +} + +.dot.connecting{ + background:#f59e0b; + box-shadow:0 0 0 4px rgba(245,158,11,.12); +} + +/* ====== Terminal ====== */ +.terminal{ + height:86vh; + flex:1; + max-height:0; + min-height:420px; + display:flex; + flex-direction:column; +} + +.out{ + flex:1; + min-height:0; + overflow:auto; + -webkit-overflow-scrolling:touch; + padding:10px 14px 0 14px; + font-size:12px; + line-height:1.55; + font-family:var(--mono); + white-space:pre-wrap; + word-break:break-word; + background: + radial-gradient(900px 420px at 10% 0%, rgba(37,99,235,.06), transparent 60%), + #ffffff; +} + +.line{ + display:flex; + gap:10px; + padding:2px 0; + align-items:flex-start; +} + +.ts{ + flex:0 0 auto; + color:#94a3b8; + font-size:11px; + margin-top:1px; +} + +.txt{ + flex:1 1 auto; + min-width:0; +} + +/* ====== Composer ====== */ +.composer{ + position:sticky; + bottom:0; + flex:0 0 auto; + padding:12px; + border-top:1px solid var(--line); + background:rgba(255,255,255,.92); + backdrop-filter:blur(10px); +} + +.row{ + display:flex; + gap:10px; + align-items:center; +} + +.input{ + flex:1; + min-width:0; + display:flex; + align-items:center; + gap:10px; + padding:10px 12px; + border-radius:14px; + border:1px solid var(--line); + background:#ffffff; + box-shadow:0 8px 18px rgba(15,23,42,.06); +} + +.prompt{ + flex:0 0 auto; + font-family:var(--mono); + font-size:12px; + color:#64748b; + user-select:none; +} + +input[type="text"]{ + flex:1; + min-width:0; + border:0; + outline:none; + font-family:var(--mono); + font-size:12px; + background:transparent; + color:var(--text); + padding:0; +} + +.btn{ + border:0; + cursor:pointer; + border-radius:14px; + padding:10px 12px; + background:linear-gradient(135deg, var(--accent), var(--accent2)); + color:#ffffff; + box-shadow:0 14px 28px rgba(37,99,235,.18); + display:inline-flex; + align-items:center; + justify-content:center; + gap:8px; + font-weight:650; + letter-spacing:.2px; + user-select:none; + flex:0 0 auto; + white-space:nowrap; +} + +.btn:active{ + transform:translateY(1px); +} + +.btn[disabled]{ + opacity:.6; + cursor:not-allowed; + transform:none; + box-shadow:none; +} + +/* ====== Tips ====== */ +.tip{ + margin-top:8px; + font-size:11px; + color:var(--muted); + line-height:1.45; +} + +.tip-main{ + color:var(--muted); +} + +.tip-more{ + margin-top:6px; +} + +.tip-more summary{ + cursor:pointer; + user-select:none; + list-style:none; + color:#475569; + font-size:11px; + display:inline-flex; + align-items:center; + gap:4px; +} + +.tip-more summary::-webkit-details-marker{ + display:none; +} + +.tip-more summary::before{ + content:"ⓘ"; + font-size:12px; + color:#64748b; + line-height:1; +} + +.tip-more summary::after{ + content:"展开说明"; +} + +.tip-more[open] summary::after{ + content:"收起说明"; +} + +.tip-sub{ + margin-top:6px; + padding-top:6px; + border-top:1px dashed rgba(100,116,139,.22); + color:#55657d; + line-height:1.55; +} + +.tip code{ + font-family:var(--mono); + font-size:11px; + background:rgba(148,163,184,.12); + border:1px solid rgba(148,163,184,.18); + padding:1px 5px; + border-radius:6px; +} + +.tip strong{ + font-weight:700; + color:#334155; +} + +/* ====== Tablet ====== */ +@media (max-width: 768px){ + .wrap{ + padding:10px 8px; + } + + .card{ + width:min(100vw, 100%); + max-height:96vh; + border-radius:14px; + } + + .terminal{ + min-height:360px; + } + + .out{ + padding:8px 10px 0 10px; + font-size:12px; + } + + .composer{ + padding:10px; + } + + .row{ + gap:8px; + } + + .input{ + padding:9px 10px; + border-radius:12px; + } + + .prompt{ + font-size:12px; + } + + input[type="text"]{ + font-size:12px; + } + + .btn{ + padding:9px 10px; + border-radius:12px; + } + + .tip{ + font-size:11px; + } + + .tip-more summary{ + font-size:11px; + } + + .tip-sub{ + font-size:11px; + } +} + +/* ====== Mobile ====== */ +@media (max-width: 520px){ + .wrap{ + padding:8px; + align-items:stretch; + } + + .card{ + width:100%; + height:calc(100vh - 16px); + max-height:calc(100vh - 16px); + border-radius:14px; + box-shadow:0 10px 28px rgba(15,23,42,.08); + } + + .head{ + padding:10px; + gap:8px; + } + + .title{ + font-size:14px; + } + + .conn{ + gap:6px; + font-size:12px; + } + + .dot{ + width:8px; + height:8px; + box-shadow:none; + } + + .terminal{ + height:auto; + min-height:0; + max-height:none; + flex:1; + } + + .out{ + padding:8px 10px 0 10px; + font-size:11px; + line-height:1.5; + } + + .line{ + gap:6px; + padding:1px 0; + } + + .ts{ + font-size:10px; + } + + .composer{ + padding:8px; + } + + .row{ + gap:8px; + } + + .input{ + gap:8px; + padding:8px 10px; + border-radius:12px; + box-shadow:0 6px 14px rgba(15,23,42,.05); + } + + .prompt{ + font-size:12px; + } + + input[type="text"]{ + font-size:12px; + } + + .btn{ + min-width:44px; + padding:8px 10px; + border-radius:12px; + box-shadow:0 10px 20px rgba(37,99,235,.16); + } + + .btn span{ + display:none; + } + + .btn svg{ + width:16px; + height:16px; + } + + .tip{ + margin-top:6px; + font-size:12px; + line-height:1.45; + } + + .tip-main{ + font-size:12px; + } + + .tip-more{ + margin-top:4px; + } + + .tip-more summary{ + font-size:12px; + } + + .tip-more summary::before{ + font-size:12px; + } + + .tip-sub{ + font-size:12px; + line-height:1.5; + } + + .tip code{ + font-size:11px; + padding:0 4px; + border-radius:5px; + } +} + +/* ====== Very small mobile ====== */ +@media (max-width: 380px){ + .head{ + padding:8px; + } + + .title{ + font-size:13px; + } + + .conn{ + font-size:11px; + } + + .out{ + font-size:11px; + } + + .ts{ + font-size:10px; + } + + .input{ + padding:7px 9px; + } + + .prompt{ + font-size:11px; + } + + input[type="text"]{ + font-size:11px; + } + + .btn{ + padding:7px 9px; + } + + .tip{ + font-size:11px; + line-height:1.4; + } + + .tip-main{ + font-size:11px; + } + + .tip-more summary{ + font-size:11px; + } + + .tip-sub{ + font-size:11px; + line-height:1.45; + } + + .tip code{ + font-size:10px; + } +} \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_install_uninstall_cb_demo/jni/Android.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_install_uninstall_cb_demo/jni/Android.mk" new file mode 100644 index 00000000..bc6348c6 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_install_uninstall_cb_demo/jni/Android.mk" @@ -0,0 +1,17 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) +LOCAL_MODULE := module_install_uninstall_cb_demo + +LOCAL_SRC_FILES := \ + $(LOCAL_PATH)/../module_install_uninstall_cb_demo.cpp\ + +KERNEL_MODULE_KIT := $(LOCAL_PATH)/../../kernel_module_kit +LOCAL_C_INCLUDES += $(KERNEL_MODULE_KIT)/include +LOCAL_LDFLAGS += $(KERNEL_MODULE_KIT)/lib/libkernel_module_kit_static.a + +include $(LOCAL_PATH)/build_macros.mk + +include $(BUILD_SHARED_LIBRARY) + + diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_install_uninstall_cb_demo/jni/Application.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_install_uninstall_cb_demo/jni/Application.mk" new file mode 100644 index 00000000..2500a8a7 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_install_uninstall_cb_demo/jni/Application.mk" @@ -0,0 +1,2 @@ +APP_ABI := arm64-v8a +APP_STL := c++_static \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_install_uninstall_cb_demo/jni/build_macros.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_install_uninstall_cb_demo/jni/build_macros.mk" new file mode 100644 index 00000000..a6f31501 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_install_uninstall_cb_demo/jni/build_macros.mk" @@ -0,0 +1,21 @@ +COMMON_CPPFLAGS := \ + -std=c++20 \ + -fPIC \ + -fvisibility=hidden \ + -fno-stack-protector \ + -ffunction-sections \ + -fdata-sections \ + -flto=thin + +COMMON_LDFLAGS := \ + -Wl,-O2 \ + -Wl,--gc-sections \ + -Wl,-s \ + -flto=thin + +COMMON_INCLUDES := \ + $(LOCAL_PATH)/../../../ + +LOCAL_CPPFLAGS += $(COMMON_CPPFLAGS) +LOCAL_LDFLAGS += $(COMMON_LDFLAGS) +LOCAL_C_INCLUDES += $(COMMON_INCLUDES) diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_install_uninstall_cb_demo/module_install_uninstall_cb_demo.cpp" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_install_uninstall_cb_demo/module_install_uninstall_cb_demo.cpp" new file mode 100644 index 00000000..a376692b --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_install_uninstall_cb_demo/module_install_uninstall_cb_demo.cpp" @@ -0,0 +1,27 @@ +#include +#include "kernel_module_kit_umbrella.h" + +int skroot_module_main(const char* root_key, const char* module_private_dir) { + printf("[module_cb_demo] hello!\n"); + return 0; +} + +std::string module_on_install(const char* root_key, const char* module_private_dir) { + printf("[module_cb_demo] on install!!!\n"); + return ""; +} + +void module_on_uninstall(const char* root_key, const char* module_private_dir) { + printf("[module_cb_demo] on uninstall!!!\n"); +} + +// SKRoot 模块名片 +SKROOT_MODULE_NAME("安装/卸载回调 Demo") +SKROOT_MODULE_VERSION("0.0.1") +SKROOT_MODULE_DESC("演示模块安装、卸载回调") +SKROOT_MODULE_AUTHOR("SKRoot") +SKROOT_MODULE_UUID32("b7e4d333fd4689044b58b59e631a40e5") + +SKROOT_MODULE_ON_INSTALL(module_on_install) // 配置安装模块回调 +SKROOT_MODULE_ON_UNINSTALL(module_on_uninstall) // 配置卸载模块回调 + diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/android_packages_list_utils.h" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/android_packages_list_utils.h" new file mode 100644 index 00000000..723d0584 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/android_packages_list_utils.h" @@ -0,0 +1,165 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include + +namespace android_pkgmap { + +namespace detail { + inline void trim_inplace(std::string& s) { + auto issp = [](unsigned char c){ return std::isspace(c) != 0; }; + size_t l = 0, r = s.size(); + while (l < r && issp(static_cast(s[l]))) ++l; + while (r > l && issp(static_cast(s[r-1]))) --r; + if (l == 0 && r == s.size()) return; + s.assign(s.begin() + static_cast(l), + s.begin() + static_cast(r)); + } + + // 解析一行:取前两列 ;可选检测是否包含 "@system" + inline bool parse_line_pkg_uid(const std::string& line, + std::string& out_pkg, + uint32_t& out_uid, + bool* out_is_system = nullptr) { + if (out_is_system) *out_is_system = false; + + std::string work = line; + // 去掉 # 注释 + if (auto pos = work.find('#'); pos != std::string::npos) work.resize(pos); + trim_inplace(work); + if (work.empty()) return false; + + std::istringstream iss(work); + std::string pkg; + unsigned long uid_ul = 0; + if (!(iss >> pkg >> uid_ul)) return false; + + out_pkg = std::move(pkg); + out_uid = static_cast(uid_ul); + + // 扫描剩余列,判断是否有 "@system" + if (out_is_system) { + std::string tok; + while (iss >> tok) { + if (tok == "@system") { + *out_is_system = true; + break; + } + } + } + return true; + } + +} + +/** + * 把给定包名列表映射为UID。未命中置为0。 + * @param pkgs 待查询包名列表 + * @param path packages.list 路径(默认 /data/system/packages.list) + * @return {包名 -> uid} 映射,未命中的值为0。文件打不开也返回全0。 + */ +inline std::unordered_map +read_pkg_uids_from_packages_list(const std::vector& pkgs, + const std::string& path = "/data/system/packages.list") +{ + std::unordered_map result; + result.reserve(pkgs.size()); + for (const auto& p : pkgs) result.emplace(p, 0); // 先默认0 + + std::unordered_set targets(pkgs.begin(), pkgs.end()); + if (targets.empty()) return result; + + std::ifstream fin(path); + if (!fin.is_open()) { + // 无权限/文件不存在:直接返回默认0 + return result; + } + + std::string line, pkg; + uint32_t uid = 0; + size_t remaining = targets.size(); + + while (std::getline(fin, line)) { + if (!detail::parse_line_pkg_uid(line, pkg, uid)) continue; + + if (auto it = targets.find(pkg); it != targets.end()) { + result[pkg] = uid; + targets.erase(it); + if (--remaining == 0) break; // 都找到了,提前结束 + } + } + return result; +} + +/** + * 读取整个 packages.list,返回全量 {包名->uid} 映射。 + * @param path packages.list 路径 + * @return 若文件不可读,返回空map。 + */ +inline std::unordered_map +read_all_pkg_uids(const std::string& path = "/data/system/packages.list") +{ + std::unordered_map map; + std::ifstream fin(path); + if (!fin.is_open()) return map; + + std::string line, pkg; + uint32_t uid = 0; + // 若同一包名出现多次,后出现的覆盖前者(通常不会发生) + while (std::getline(fin, line)) { + if (detail::parse_line_pkg_uid(line, pkg, uid)) { + map[pkg] = uid; + } + } + return map; +} + +/** + * 读取整个 packages.list,排除system应用,返回全量 {包名->uid} 映射。 + * @param path packages.list 路径 + * @return 若文件不可读,返回空map。 + */ +inline std::unordered_map +read_all_pkg_uids_exclude_system(const std::string& path = "/data/system/packages.list") +{ + std::unordered_map map; + std::ifstream fin(path); + if (!fin.is_open()) return map; + + std::string line, pkg; + uint32_t uid = 0; + bool is_system = false; + + while (std::getline(fin, line)) { + if (!detail::parse_line_pkg_uid(line, pkg, uid, &is_system)) continue; + if (is_system) continue; + map[pkg] = uid; + } + return map; +} + +/** + * 查询单个包名对应UID;未命中/文件不可读返回0。 + */ +inline uint32_t get_uid_for_package(const std::string& pkg, + const std::string& path = "/data/system/packages.list") +{ + if (pkg.empty()) return 0; + std::ifstream fin(path); + if (!fin.is_open()) return 0; + + std::string line, name; + uint32_t uid = 0; + while (std::getline(fin, line)) { + if (!detail::parse_line_pkg_uid(line, name, uid)) continue; + if (name == pkg) return uid; + } + return 0; +} + +} // namespace android_pkgmap \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/file_utils.h" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/file_utils.h" new file mode 100644 index 00000000..f704a8f8 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/file_utils.h" @@ -0,0 +1,91 @@ +#pragma once +#include +#include +#include +#include +#include +#include + +namespace file_utils { + +static bool file_exists(const std::filesystem::path& p) { + std::error_code ec; + return std::filesystem::exists(p, ec); +} + +static bool read_file_bytes(const char* path, std::vector& out) { + std::ifstream f(path, std::ios::binary); + if (!f) return false; + + f.seekg(0, std::ios::end); + std::streamsize n = f.tellg(); + if (n < 0) return false; + + f.seekg(0, std::ios::beg); + out.resize(static_cast(n)); + return static_cast(f.read(reinterpret_cast(out.data()), n)); +} + +static bool write_file_bytes(const char* path, const void* data, size_t size) { + if (!path) return false; + std::ofstream f(path, std::ios::binary | std::ios::out | std::ios::trunc); + if (!f) return false; + if (data && size > 0) { + f.write(static_cast(data), + static_cast(size)); + } + return f.good(); +} + +static bool read_text_file(const char* target_path, std::string& text) { + std::vector buf; + if(!read_file_bytes(target_path, buf)) return false; + text.assign(buf.begin(), buf.end()); + return true; +} + +static bool write_text_file(const char* target_path, std::string_view text) { + if (!target_path) return false; + std::ofstream file(target_path, std::ios::out | std::ios::trunc); + if (!file.is_open()) return false; + file << text; + return file.good(); +} + +static inline bool create_empty_file(const char* target_path) { + std::ofstream file(target_path, std::ios::binary | std::ios::out | std::ios::trunc); + if (!file.is_open()) return false; + file.close(); + return true; +} + +static bool make_dirs(const std::filesystem::path& p) { + std::error_code ec; + return std::filesystem::create_directories(p, ec); +} + +static bool create_directory_if_not_exists(const char* dir_path) { + if (!file_exists(dir_path)) { + make_dirs(dir_path); + } + return file_exists(dir_path); +} + +static bool delete_path(const std::filesystem::path& dir_path) { + std::error_code ec; + std::filesystem::remove_all(dir_path, ec); + return !file_exists(dir_path); +} + +static bool copy_dir(const std::filesystem::path& src, const std::filesystem::path& dst) { + std::error_code ec; + std::filesystem::create_directories(dst, ec); + if (ec) return false; + std::filesystem::copy(src, dst, + std::filesystem::copy_options::recursive | + std::filesystem::copy_options::overwrite_existing, + ec); + return !ec; +} + +} // namespace file_utils diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/jni/Android.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/jni/Android.mk" new file mode 100644 index 00000000..722e7519 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/jni/Android.mk" @@ -0,0 +1,16 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) +LOCAL_MODULE := module_tricky_store + +LOCAL_SRC_FILES := $(LOCAL_PATH)/../module_tricky_store.cpp + +KERNEL_MODULE_KIT := $(LOCAL_PATH)/../../kernel_module_kit +LOCAL_C_INCLUDES += $(KERNEL_MODULE_KIT)/include +LOCAL_LDFLAGS += $(KERNEL_MODULE_KIT)/lib/libkernel_module_kit_static.a + +include $(LOCAL_PATH)/build_macros.mk + +include $(BUILD_SHARED_LIBRARY) + + diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/jni/Application.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/jni/Application.mk" new file mode 100644 index 00000000..2500a8a7 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/jni/Application.mk" @@ -0,0 +1,2 @@ +APP_ABI := arm64-v8a +APP_STL := c++_static \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/jni/build_macros.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/jni/build_macros.mk" new file mode 100644 index 00000000..a6f31501 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/jni/build_macros.mk" @@ -0,0 +1,21 @@ +COMMON_CPPFLAGS := \ + -std=c++20 \ + -fPIC \ + -fvisibility=hidden \ + -fno-stack-protector \ + -ffunction-sections \ + -fdata-sections \ + -flto=thin + +COMMON_LDFLAGS := \ + -Wl,-O2 \ + -Wl,--gc-sections \ + -Wl,-s \ + -flto=thin + +COMMON_INCLUDES := \ + $(LOCAL_PATH)/../../../ + +LOCAL_CPPFLAGS += $(COMMON_CPPFLAGS) +LOCAL_LDFLAGS += $(COMMON_LDFLAGS) +LOCAL_C_INCLUDES += $(COMMON_INCLUDES) diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/module_tricky_store.cpp" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/module_tricky_store.cpp" new file mode 100644 index 00000000..477e480e --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/module_tricky_store.cpp" @@ -0,0 +1,202 @@ +#include +#include +#include +#include +#include +#include "module_tricky_store.h" + +#include "kernel_module_kit_umbrella.h" + +#include "file_utils.h" +#include "android_packages_list_utils.h" +#include "tricky_store_daemon.h" + +#define MOD_VER "1.4.1-r5" + +#define TARGET_TS_DIR "/data/adb/" +#define TARGET_TXT "/data/adb/tricky_store/target.txt" +#define KEYBOX_XML "/data/adb/tricky_store/keybox.xml" +#define TEE_STATUS "/data/adb/tricky_store/tee_status" +#define SERVICE_SH "/data/adb/modules/tricky_store/service.sh" +#define SERVICE_BASE "/data/adb/modules/tricky_store/" + +#define HIDE_BOOTLOADER_SH "hide_bootloader.sh" + +using namespace file_utils; +using namespace android_pkgmap; + +static bool write_target_txt_applist() { + std::unordered_map packages = read_all_pkg_uids_exclude_system(); + printf("thrid package count: %zu\n", packages.size()); + std::stringstream sstr; + for(auto & pkg : packages) sstr << pkg.first << "\n"; + return write_text_file(TARGET_TXT, sstr.str()); +} + +static bool get_auto_third_app_toggle() { + bool enable = false; + kernel_module::read_bool_disk_storage("auto_third_app_toggle", enable); + return enable; +} + +static bool set_target_txt(const std::string& text); +static bool set_auto_third_app_toggle(bool enable) { + if(enable) { + write_target_txt_applist(); + } else { + set_target_txt(""); + } + return is_ok(kernel_module::write_bool_disk_storage("auto_third_app_toggle", enable)); +} + +static bool get_fix_tee_toggle() { + std::string text; + read_text_file(TEE_STATUS, text); + return text == "teeBroken=true"; +} + +static bool set_fix_tee_toggle(bool enable) { + return write_text_file(TEE_STATUS, enable ? "teeBroken=true" : "teeBroken=false"); +} + +static bool get_hide_bootloader_toggle() { + bool enable = true; + kernel_module::read_bool_disk_storage("hide_bootloader_toggle", enable); + return enable; +} + +static bool set_hide_bootloader_toggle(bool enable) { + return is_ok(kernel_module::write_bool_disk_storage("hide_bootloader_toggle", enable)); +} + +static std::string get_target_txt() { + std::string text; + read_text_file(TARGET_TXT, text); + return text; +} + +static bool set_target_txt(const std::string& text) { + return write_text_file(TARGET_TXT, text); +} + +static std::string get_keybox_xml() { + std::string text; + read_text_file(KEYBOX_XML, text); + return text; +} + +static bool set_keybox_xml(const std::string& text) { + return write_text_file(KEYBOX_XML, text); +} + +static std::string get_hide_bootloader_script(const std::string& module_private_dir) { + std::string path = module_private_dir + HIDE_BOOTLOADER_SH; + std::string script; + read_text_file(path.c_str(), script); + return script; +} + +static bool set_hide_bootloader_script(const std::string& module_private_dir, const std::string & script) { + std::string path = module_private_dir + HIDE_BOOTLOADER_SH; + return write_text_file(path.c_str(), script); +} + +int skroot_module_main(const char* root_key, const char* module_private_dir) { + printf("Hello! module_tricky_store!\n"); + + bool auto_third_app_toggle = get_auto_third_app_toggle(); + bool tee_fix_toggle = get_fix_tee_toggle(); + bool hide_bootloader_toggle = get_hide_bootloader_toggle(); + printf("auto_third_app_toggle: %d\n", !!auto_third_app_toggle); + printf("tee_fix_toggle: %d\n", !!tee_fix_toggle); + printf("hide_bootloader_toggle: %d\n", !!hide_bootloader_toggle); + + spawn_delayed_task(7, [=] { + if (auto_third_app_toggle) { + bool ok = write_target_txt_applist(); + printf("[module_tricky_store] write target.txt applist: %s\n", ok ? "success" : "failed"); + } + printf("[module_tricky_store] run_script: %s\n", SERVICE_SH); + // run_script(SERVICE_SH); // DO NOT USE! + // prevent the sh process from remaining in the background. + start_tricky_store_daemon_loop(SERVICE_BASE); + }); + + if (hide_bootloader_toggle) { + spawn_delayed_task(9, [=] { + std::printf("[module_tricky_store] run hide_bootloader_sh\n"); + run_script(HIDE_BOOTLOADER_SH); + }); + } + return 0; +} + +static void clear_tricky_store_history_dir() { + delete_path("/data/adb/tricky_store"); + delete_path("/data/adb/modules"); + ::chmod("/data/adb", 0700); +} + +std::string module_on_install(const char* root_key, const char* module_private_dir) { + printf("[module_tricky_store] on install\n"); + clear_tricky_store_history_dir(); + std::string my_ts_path = std::string(module_private_dir) + "TS/"; + copy_dir(my_ts_path, TARGET_TS_DIR); + ::sync(); + return ""; +} + +void module_on_uninstall(const char* root_key, const char* module_private_dir) { + printf("[module_tricky_store] on uninstall\n"); + clear_tricky_store_history_dir(); + ::sync(); +} + +static std::string get_all_props() { + return run_cmd("resetprop"); +} + +// WebUI HTTP服务器回调函数 +class MyWebHttpHandler : public kernel_module::WebUIHttpHandler { // HTTP服务器基于civetweb库 +public: + void onPrepareCreate(const char* root_key, const char* module_private_dir, uint32_t port) override { + m_module_private_dir = module_private_dir; + } + + bool handlePost(CivetServer* server, struct mg_connection* conn, const std::string& path, const std::string& body) override { + printf("[module_tricky_store] POST request\nPath: %s\nBody: %s\n", path.c_str(), body.c_str()); + + std::string resp; + if(path == "/getVersion") resp = MOD_VER; + else if(path == "/getAutoThirdAppToggle") resp = get_auto_third_app_toggle() ? "1" : "0"; + else if(path == "/setAutoThirdAppToggle") resp = set_auto_third_app_toggle(body == "1") ? "OK" : "FAILED"; + else if(path == "/getFixTeeToggle") resp = get_fix_tee_toggle() ? "1" : "0"; + else if(path == "/setFixTeeToggle") resp = set_fix_tee_toggle(body == "1") ? "OK" : "FAILED"; + else if(path == "/getHideBootloaderToggle") resp = get_hide_bootloader_toggle() ? "1" : "0"; + else if(path == "/setHideBootloaderToggle") resp = set_hide_bootloader_toggle(body == "1") ? "OK" : "FAILED"; + else if(path == "/getTargetTxt") resp = get_target_txt(); + else if(path == "/setTargetTxt") resp = set_target_txt(body) ? "OK" : "FAILED"; + else if(path == "/getKeyboxXml") resp = get_keybox_xml(); + else if(path == "/setKeyboxXml") resp = set_keybox_xml(body) ? "OK" : "FAILED"; + else if(path == "/getBootloaderScript") resp = get_hide_bootloader_script(m_module_private_dir); + else if(path == "/setBootloaderScript") resp = set_hide_bootloader_script(m_module_private_dir, body) ? "OK" : "FAILED"; + else if(path == "/getAllProps") resp = get_all_props(); + + kernel_module::webui::send_text(conn, 200, resp); + return true; + } +private: + std::string m_module_private_dir; +}; + +// SKRoot 模块名片 +SKROOT_MODULE_NAME("Tricky Store") +SKROOT_MODULE_VERSION(MOD_VER) +SKROOT_MODULE_DESC("提供系统证书接管与 TEE 状态修复能力。") +SKROOT_MODULE_AUTHOR("5ec1cff, aviraxp, Cyberenchanter and topjohnwu") +SKROOT_MODULE_UUID32("c3a70f603b48380a611131d29c50aac3") +SKROOT_MODULE_WEB_UI(MyWebHttpHandler) +SKROOT_MODULE_ON_INSTALL(module_on_install) +SKROOT_MODULE_ON_UNINSTALL(module_on_uninstall) +SKROOT_MODULE_UPDATE_JSON("https://abcz316.github.io/SKRoot-linuxKernelRoot/module_tricky_store/update.json") + diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/module_tricky_store.h" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/module_tricky_store.h" new file mode 100644 index 00000000..beaccc5a --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/module_tricky_store.h" @@ -0,0 +1,55 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include + +static std::string run_cmd(const std::string& cmd) { + std::string cmd_add_err_info = cmd; + cmd_add_err_info += " 2>&1"; + FILE * fp = popen(cmd_add_err_info.c_str(), "r"); + if(!fp) return {}; + int pip = fileno(fp); + + std::string result; + while(true) { + char rbuf[1024] = {0}; + ssize_t r = read(pip, rbuf, sizeof(rbuf)); + if (r == -1 && errno == EAGAIN) continue; + else if(r > 0) { std::string str_convert(rbuf, r); result += str_convert; } + else break; + } + pclose(fp); + return result; +} + +static void run_script(const char* script) { + const char* sh = "/system/bin/sh"; + char* const argv[] = { + (char*)sh, + (char*)script, + nullptr + }; + execve(sh, argv, environ); +} + +template +static pid_t spawn_delayed_task(unsigned delay_sec, Fn&& fn) { + using F = std::decay_t; + F f = std::forward(fn); + + pid_t pid = ::fork(); + if (pid < 0) { + std::printf("fork failed: %s\n", std::strerror(errno)); + return -1; + } + if (pid == 0) { + ::sleep(delay_sec); + f(); + _exit(127); + } + return pid; +} \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/modules/tricky_store/daemon" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/modules/tricky_store/daemon" new file mode 100644 index 00000000..66490887 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/modules/tricky_store/daemon" @@ -0,0 +1,3 @@ +#!/system/bin/sh + +exec /system/bin/app_process -Djava.class.path=./service.apk / --nice-name=TrickyStore io.github.a13e300.tricky_store.MainKt "$@" diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/modules/tricky_store/libtricky_store.so" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/modules/tricky_store/libtricky_store.so" new file mode 100644 index 00000000..f72810e7 Binary files /dev/null and "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/modules/tricky_store/libtricky_store.so" differ diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/modules/tricky_store/machikado" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/modules/tricky_store/machikado" new file mode 100644 index 00000000..6285f678 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/modules/tricky_store/machikado" @@ -0,0 +1 @@ +/2 `mdR2LY Ohxvκ1ہi壟 V`ӵMk6Z%M[W \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/modules/tricky_store/mazoku" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/modules/tricky_store/mazoku" new file mode 100644 index 00000000..cbfc7631 Binary files /dev/null and "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/modules/tricky_store/mazoku" differ diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/modules/tricky_store/module.prop" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/modules/tricky_store/module.prop" new file mode 100644 index 00000000..82838b64 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/modules/tricky_store/module.prop" @@ -0,0 +1,7 @@ +id=tricky_store +name=Tricky Store +version=v1.4.1 (245-72b2e84-release) +versionCode=245 +author=5ec1cff, aviraxp and Cyberenchanter +description=A trick of keystore +updateJson=https://5ec1cff.github.io/TrickyStore/update.json diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/modules/tricky_store/post-fs-data.sh" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/modules/tricky_store/post-fs-data.sh" new file mode 100644 index 00000000..08eb3644 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/modules/tricky_store/post-fs-data.sh" @@ -0,0 +1 @@ +MODDIR=${0%/*} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/modules/tricky_store/sepolicy.rule" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/modules/tricky_store/sepolicy.rule" new file mode 100644 index 00000000..04c5338b --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/modules/tricky_store/sepolicy.rule" @@ -0,0 +1 @@ +allow crash_dump keystore process * diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/modules/tricky_store/service.apk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/modules/tricky_store/service.apk" new file mode 100644 index 00000000..aaeb5f6d Binary files /dev/null and "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/modules/tricky_store/service.apk" differ diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/modules/tricky_store/service.sh" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/modules/tricky_store/service.sh" new file mode 100644 index 00000000..c52cfe8a --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/modules/tricky_store/service.sh" @@ -0,0 +1,16 @@ +DEBUG=false + +MODDIR=${0%/*} + +cd $MODDIR + +( +while [ true ]; do + ./daemon + if [ $? -ne 0 ]; then + exit 1 + fi + # ensure keystore initialized + sleep 2 +done +) & diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/tricky_store/key_db/keystore.db" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/tricky_store/key_db/keystore.db" new file mode 100644 index 00000000..c7f16a38 Binary files /dev/null and "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/tricky_store/key_db/keystore.db" differ diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/tricky_store/key_db/keystore.db-shm" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/tricky_store/key_db/keystore.db-shm" new file mode 100644 index 00000000..1457eb45 Binary files /dev/null and "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/tricky_store/key_db/keystore.db-shm" differ diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/tricky_store/key_db/keystore.db-wal" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/tricky_store/key_db/keystore.db-wal" new file mode 100644 index 00000000..607c2576 Binary files /dev/null and "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/tricky_store/key_db/keystore.db-wal" differ diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/tricky_store/keybox.xml" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/tricky_store/keybox.xml" new file mode 100644 index 00000000..34d1277c --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/tricky_store/keybox.xml" @@ -0,0 +1,215 @@ + + +1 + + +-----BEGIN EC PRIVATE KEY----- +MHcCAQEEIMOfE3URnnCd+HjNf6XNUwJyQV9WSvP128Y49SqzDRJboAoGCCqGSM49 +AwEHoUQDQgAECm6WbU7ETodTvW8Yl/MuenyPcCN/Op/5UswtuPeydRGUju/KLyQE +MgQ5F+SBIQwIjZailXl17R2LT9JzQhltsQ== +-----END EC PRIVATE KEY----- + +3 +-----BEGIN CERTIFICATE----- +MIIB8zCCAXmgAwIBAgIQTVljecgb+3C6abB73Fjz8jAKBggqhkjOPQQDAjA5MQww +CgYDVQQMDANURUUxKTAnBgNVBAUTIDNmYjZlNjMwOTFkZTI2Yjg1OWVkOWI0M2Q5 +ZDg0ZWZkMB4XDTIyMDMyMDE5MTQwNFoXDTMyMDMxNzE5MTQwNFowOTEMMAoGA1UE +DAwDVEVFMSkwJwYDVQQFEyAxZWQ3NGI1YTQ0NGQxMjJkYzdkNTM4NDVkYzhiNmU2 +MTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABApulm1OxE6HU71vGJfzLnp8j3Aj +fzqf+VLMLbj3snURlI7vyi8kBDIEORfkgSEMCI2WopV5de0di0/Sc0IZbbGjYzBh +MB0GA1UdDgQWBBRlw5ENM76tLCCWnMzSV49zwWNV1TAfBgNVHSMEGDAWgBSpHV4y +SNJCjQKus9dlFl5hNP2hsjAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIC +BDAKBggqhkjOPQQDAgNoADBlAjBUtfGW9GqnzI8UdHicOZtM21QCg5DOVqZqDwjI +mY4+l+yRoqUMK6SoPBIsO1k9ljkCMQDa4MdV3KzHbt4iwTduUPl7rHoy932pDx6+ +wygrFl6VXAaTWRzfS1Pdbz46EplOc7s= +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDkzCCAXugAwIBAgIQO4Pwzf7CV71nL+WCsaL7szANBgkqhkiG9w0BAQsFADAb +MRkwFwYDVQQFExBmOTIwMDllODUzYjZiMDQ1MB4XDTIyMDMyMDE5MTIwNloXDTMy +MDMxNzE5MTIwNlowOTEMMAoGA1UEDAwDVEVFMSkwJwYDVQQFEyAzZmI2ZTYzMDkx +ZGUyNmI4NTllZDliNDNkOWQ4NGVmZDB2MBAGByqGSM49AgEGBSuBBAAiA2IABNX0 +VF+CMtTaAcj04PKHea0wqDVQWBjax/x4XSY+yhsO14mscnT4XBLdXZIz/ScehVRO +s9LeJui1pje6yzaSQTjYzzKWYdqW9yDRmSlPrFJsoGT2QzgODPL17tzvViXL0qNj +MGEwHQYDVR0OBBYEFKkdXjJI0kKNAq6z12UWXmE0/aGyMB8GA1UdIwQYMBaAFDZh +4QB8iAUJUYtEbEf/GkzJ6k8SMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQD +AgIEMA0GCSqGSIb3DQEBCwUAA4ICAQAr47ZQaBcTwDbgnNwY/6MXenw+4qIzMxOZ +ibLjalrcAWUoucnHNwkeVAo5oQk4RcqKOeAXObMSgOlYDgh78fD2zLjOiFRVoerP +aVlzm0lY8fVLZGBVQA6R69d627Jp7hS8W3A24pgfKQ9QJnlxL+USLp9bKv94Oe5Z +xsNBXnP/ugKf7Hkk3b9zE9UniMSnyZmkdnxi48NpNdUcJf4eckGYHv8MW/xlF0Xx +yoLEd+Gv5AjqNjnc/ckVUZvy/8EWcwoLfzK6MyselEg9SyQEo/WuNd4U2Fk2VS7w +XVyoT8sGmtAA/ZSL3mH9C05m7SJcL7DzTEI256K/lz9e09RSgWQZItBTKrI6wNgl +0zSGdHbYeTzF8O0G87dQI5+PzWC3l20B4JtTH+Eu0HnzsnfbbMOacCJ40iqGLmE+ +5RFAyueZ0XxrArth84FHUrNgYFOkReDwR+1nq5nMBDvNAfeutsz6mFZ3RQvnNx+y +3Nrr2RYQHd33ujlKhG9esI+i9v6WQ73XW9a7QqoHOI7y51f7qhP4i+ybx8ZqecJL +z1RcOTvlo6V5ktLY9RgYWPFefR+skvj/Q+qc0KgdjGhR+I2ukMwMaZA8wMWBiWJr +Dv6gABr1r/qQguzy2mDDiSjKEAEbM86i2DNC1m7FjduqRjTv6oZX/YbgC45eyy8U +fVsW0/PnUg== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIFHDCCAwSgAwIBAgIJAPHBcqaZ6vUdMA0GCSqGSIb3DQEBCwUAMBsxGTAXBgNV +BAUTEGY5MjAwOWU4NTNiNmIwNDUwHhcNMjIwMzIwMTgwNzQ4WhcNNDIwMzE1MTgw +NzQ4WjAbMRkwFwYDVQQFExBmOTIwMDllODUzYjZiMDQ1MIICIjANBgkqhkiG9w0B +AQEFAAOCAg8AMIICCgKCAgEAr7bHgiuxpwHsK7Qui8xUFmOr75gvMsd/dTEDDJdS +Sxtf6An7xyqpRR90PL2abxM1dEqlXnf2tqw1Ne4Xwl5jlRfdnJLmN0pTy/4lj4/7 +tv0Sk3iiKkypnEUtR6WfMgH0QZfKHM1+di+y9TFRtv6y//0rb+T+W8a9nsNL/ggj +nar86461qO0rOs2cXjp3kOG1FEJ5MVmFmBGtnrKpa73XpXyTqRxB/M0n1n/W9nGq +C4FSYa04T6N5RIZGBN2z2MT5IKGbFlbC8UrW0DxW7AYImQQcHtGl/m00QLVWutHQ +oVJYnFPlXTcHYvASLu+RhhsbDmxMgJJ0mcDpvsC4PjvB+TxywElgS70vE0XmLD+O +JtvsBslHZvPBKCOdT0MS+tgSOIfga+z1Z1g7+DVagf7quvmag8jfPioyKvxnK/Eg +sTUVi2ghzq8wm27ud/mIM7AY2qEORR8Go3TVB4HzWQgpZrt3i5MIlCaY504LzSRi +igHCzAPlHws+W0rB5N+er5/2pJKnfBSDiCiFAVtCLOZ7gLiMm0jhO2B6tUXHI/+M +RPjy02i59lINMRRev56GKtcd9qO/0kUJWdZTdA2XoS82ixPvZtXQpUpuL12ab+9E +aDK8Z4RHJYYfCT3Q5vNAXaiWQ+8PTWm2QgBR/bkwSWc+NpUFgNPN9PvQi8WEg5Um +AGMCAwEAAaNjMGEwHQYDVR0OBBYEFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMB8GA1Ud +IwQYMBaAFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMA8GA1UdEwEB/wQFMAMBAf8wDgYD +VR0PAQH/BAQDAgIEMA0GCSqGSIb3DQEBCwUAA4ICAQB8cMqTllHc8U+qCrOlg3H7 +174lmaCsbo/bJ0C17JEgMLb4kvrqsXZs01U3mB/qABg/1t5Pd5AORHARs1hhqGIC +W/nKMav574f9rZN4PC2ZlufGXb7sIdJpGiO9ctRhiLuYuly10JccUZGEHpHSYM2G +tkgYbZba6lsCPYAAP83cyDV+1aOkTf1RCp/lM0PKvmxYN10RYsK631jrleGdcdkx +oSK//mSQbgcWnmAEZrzHoF1/0gso1HZgIn0YLzVhLSA/iXCX4QT2h3J5z3znluKG +1nv8NQdxei2DIIhASWfu804CA96cQKTTlaae2fweqXjdN1/v2nqOhngNyz1361mF +mr4XmaKH/ItTwOe72NI9ZcwS1lVaCvsIkTDCEXdm9rCNPAY10iTunIHFXRh+7KPz +lHGewCq/8TOohBRn0/NNfh7uRslOSZ/xKbN9tMBtw37Z8d2vvnXq/YWdsm1+JLVw +n6yYD/yacNJBlwpddla8eaVMjsF6nBnIgQOf9zKSe06nSTqvgwUHosgOECZJZ1Eu +zbH4yswbt02tKtKEFhx+v+OTge/06V+jGsqTWLsfrOCNLuA8H++z+pUENmpqnnHo +vaI47gC+TNpkgYGkkBT6B/m/U01BuOBBTzhIlMEZq9qkDWuM2cA5kW5V3FJUcfHn +w1IdYIg2Wxg7yHcQZemFQg== +-----END CERTIFICATE----- + + + +-----BEGIN RSA PRIVATE KEY----- +MIIG4gIBAAKCAYEAyYwuhlRzYhDBe3qn18FZHAp2x2bpwngWAvPVKn1FLciitxnY +l/bfgWIwnA+COeBspRD+HLwnS5K5AvIobIzR+arJKqlimMjs4PY/dd/Rzj+HbChl +HlGIEdTErIMrbxmVpLw2teQTjOkDYe50VY7Wj/5dS6eCR9eGPR8RgH1GjxOSJn3U +JvqpF+ZxP2BEhy48BDFMlkluFnaSZZ5Jhz4k3uOVVH+jBaSMhQEntkQ68vwzhVqS +gMjQG3V3MbBiYLeBg7lcEO/VFlvhhFpXmHCHh8dAirsOgQqOBo4bg+WWdPQr92zI +0hJzkwnVSJSJW9Cej6sPLMdPe03Lf4YzCHpDNK3XMyQZVF+ZlmaeFZDDo3ylR42e +GJDV0Kki+qHUThNqxf44faiWQsFGHeobc1qACY1ggKL0xBdd3yWH4TvisEe0A7GN +w9x+MSWW0dvB3jhkB6t/Zxyj2p1T6l0lER3F9LHSfQ6D25dlyZwcNFce2jHtpWkX +yTxyFT6x3hbIKcJ3AgMBAAECggGBALDIMJbKxFoj8FHqiAYLJaoe04ibkDZvNn9o +eHVIY8GA1phcJ0tD00+dXJ3GTKePXjx65yk1MBJto7Idza9I5XRkhQbShBUXSA8a +bxdpNpH9zz7jP66UPRHG2qumchaFDmjsXeC1KSDT0Y+4pHnXTAQJTLPrPa7eMHS0 +J5nYSGd+9xakD84Q1viLvJGmUvVvbF0REOhRiCpT3p0bdcsWiyil3nm7arasWkTf +eoG43yv6YwZ5Jz+m5ELxiZcf62qCCZrwDNB1l4I01KBPGCi7v44kwaOrnEiGh06S +eJHsqZSX3gqpd5Tt/zuEcXuL+MfgCJN1AIPKmN1ipbZ/abpLCsGWp6UlvRCGrBwj +68m3PMhjEru3Dd7mdGRp28llKp1ZJ0fzvdFBoX4fg/R0dVujxoAlcJ80c33AxhZB +mwabk4NM4p8pv8DjN89TsOt8TCenpsiPrQ/7rsNLy1nSMNazvb/xZPMW4jKgvm3u +c9ObmkOc2PKkfb7ne/UTR8E86yTXAQKBwQD+zNWQnFHO6EbAp3137Vx4envCX9Sk +0BoyAnf4+w5O2KCYqlU89pLOf4i7CDteALjBrC6eAvFf1RpSz1IaXMb8ji0ja9P4 +dRP9slD38FOeWYuBZOh3yuXIQLlU4FCD6gENx0MeNL7tWZWu5SzgGFBRC6spfjdr +uanyFRDWZWsrwjSZWjPIMbYKXk5ErNAUP6g2juO5dEwE8az888sqaPAhCrWqr1Bq +T7mVgJ9e89UX54IQAE44c5LL5/dO9HSEluECgcEAyn8mko6DA0b3/vvVH0QNmvmv +0GcN8vIu54JTfH/ZGzeNtdW70u7ct6B0a3/sNoby4dU/LiZW+1+Yvz6VADFOoZwf +b7qvCZCT8RhzLRxx8hO/zX2DYoNV5XcbqaKSi8eGLk5EyBw0G7O+hj8V3yhPu3I5 +kXp7iB+NPTWVPEtwjroXxn1VxG56wfSVGbW5ZCG/ZX0P0yt5mJgLlcwQBiUYSnlB +mtRkJ/a0dQjB9YtFfLbrs6H3q4R5DSrr2OEuNfxXAoHAFSZrk9Vl9QbS2KsOfyX0 +xwtjun655/ReOEh8LO6qAWF58zIwYR8WkI2FjADi7Kqiq3Dfbb5QyuOli7op1oZc +/hnPJWGN9tHBFw32Kp6IUlycd+EoasksybKVr7Xu+QQzkjE4IQm/z3PgOORNFUzv +XcraKlePwiFnOfEFtMY2Xyt/sjsKkVOPCM1LMegmXYfrLpwtyvccWEy3T0ftVVfg +lt2Mtt5WjnyPqxlCIV+cEJ/m6+0akRUG2mYm4SbphRgBAoG/af4kMpJmAVEkflNT +OwpkFLqdTHik1IXwBz4wdPp2qchqZMN7jO16mqNiTOKoweHhQFRevclTvkBLs88O +LwugHPebfOA6vsbuqUQjBXneKtgrjWQlYWtdir7Nu/1ct824boSJfDVHETkEgUCE +MkrncTZY680w3A+n3mItu2HBiPPffgYc3rT1jJB5evukDsWbaYQMxHv9KeJsLfyi +ZpUEIfdWX7TMuB5qVtg+rkg4Fw+oUF53RVASDNJqoRs9FQUCgcB9/qMhbq2wJVyi +bYczWpLwwnMfw9YJrdtnyzME9i5i1VOCPkSnf9j1OQpU7iU4jlKLWJfoWqRcdMD0 +oNnUJ6Rl0lNTEUDy1rPNRxGAP/RdDOJykfaeccQ17EgYRMglLX2A0Ryiuqn34h/4 +T2LtYoTn35a5fCQj9ZsKx85U3iglUq1Wi2EJS+hEOBAY/b4R55N1pr1ln0A012BR +kbM/qi6/c4isoMVC4OjyJiEtIxUwr27zxaBnYkRb/YYAHTdG5eE= +-----END RSA PRIVATE KEY----- + +3 +-----BEGIN CERTIFICATE----- +MIIE4DCCAsigAwIBAgIRAJO2eaKl6bPJMS5zlaESC3AwDQYJKoZIhvcNAQELBQAw +OTEMMAoGA1UEDAwDVEVFMSkwJwYDVQQFEyAzZmI2ZTYzMDkxZGUyNmI4NTllZDli +NDNkOWQ4NGVmZDAeFw0yMjAzMjAxOTE0MDRaFw0zMjAzMTcxOTE0MDRaMDkxDDAK +BgNVBAwMA1RFRTEpMCcGA1UEBRMgMWVkNzRiNWE0NDRkMTIyZGM3ZDUzODQ1ZGM4 +YjZlNjEwggGiMA0GCSqGSIb3DQEBAQUAA4IBjwAwggGKAoIBgQDJjC6GVHNiEMF7 +eqfXwVkcCnbHZunCeBYC89UqfUUtyKK3GdiX9t+BYjCcD4I54GylEP4cvCdLkrkC +8ihsjNH5qskqqWKYyOzg9j9139HOP4dsKGUeUYgR1MSsgytvGZWkvDa15BOM6QNh +7nRVjtaP/l1Lp4JH14Y9HxGAfUaPE5ImfdQm+qkX5nE/YESHLjwEMUyWSW4WdpJl +nkmHPiTe45VUf6MFpIyFASe2RDry/DOFWpKAyNAbdXcxsGJgt4GDuVwQ79UWW+GE +WleYcIeHx0CKuw6BCo4GjhuD5ZZ09Cv3bMjSEnOTCdVIlIlb0J6Pqw8sx097Tct/ +hjMIekM0rdczJBlUX5mWZp4VkMOjfKVHjZ4YkNXQqSL6odROE2rF/jh9qJZCwUYd +6htzWoAJjWCAovTEF13fJYfhO+KwR7QDsY3D3H4xJZbR28HeOGQHq39nHKPanVPq +XSURHcX0sdJ9DoPbl2XJnBw0Vx7aMe2laRfJPHIVPrHeFsgpwncCAwEAAaNjMGEw +HQYDVR0OBBYEFKcua8nAUFaoWjNzfxkL6q8SVLI3MB8GA1UdIwQYMBaAFLHDuuso +t/iqm0BNQ8+1V1xM4wmyMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgIE +MA0GCSqGSIb3DQEBCwUAA4ICAQCQ2QeswZjN/AuZFRenF7RHsoVp9Ywdx3imv6aP +RQY9/TIeLYl1QCn8Q4hLZhn8YZTOznCluqFwwA7Y1fXS9V9gm5SrHDxtzUvgDL/g +tenx5gtE8+z0lWwBjCwhqAzyG6AuY6Ynfm9gjCbCr78etw0tKn+jnH5cei7vUkZt +lYXjTubAVUsbG8h1qO/+DdB3P/ujS+YJfAio8YPv4c5Z1EOvTmnA1umkF/IRuUnP +WXeRfmwLvKTM52Qq9tv/y/so2B6ohRSykUY5rjfyAsNP9mtiisvk+MDPdlqiD+2D +iN9hLz1qGK7tuTZYGet/ihl0QIZHQjtU23uhDOLa68sEzr9PMOQCXDMIQkcRkFF6 +zAIoz+xWWoPfJYqE6md/zo6xCqgHyQ7D2XZyorK7KrNNbEiT5YNRyqNMTjEAat8q +QQ/fTdvpOFHI77klgLLaIzXrKEDCIweKCRWOVtx3T1GgmLNnybYEjKwOo4pkjigg +6MfCteNn/8rf02Q4z3GhjKmwCitTdcXzls+BLbjLVLbwAfxxjVLbo7OAonDjD3t5 +qJNAVjKiVHxfwD2FKwGkw5YXvftyZjY0kjn//DOCokvUCKUy7u5W7PYqThojsAMj +/JlUEdWBeqd7cgOFWWVP59CChk484YsvWta4v05+6TZA1xsZWA1qLH0w+s5YtlaL +evE2Cg== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIFQjCCAyqgAwIBAgIRAKOxxs11Vb1Hgwt4oANMwLQwDQYJKoZIhvcNAQELBQAw +GzEZMBcGA1UEBRMQZjkyMDA5ZTg1M2I2YjA0NTAeFw0yMjAzMjAxOTExNDlaFw0z +MjAzMTcxOTExNDlaMDkxDDAKBgNVBAwMA1RFRTEpMCcGA1UEBRMgM2ZiNmU2MzA5 +MWRlMjZiODU5ZWQ5YjQzZDlkODRlZmQwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAw +ggIKAoICAQDeoz4iPWI/c3ZAf+XfepmbzaTCTj2RZN1dE3Lrrw3xJ76dz9763sXg +KFL6vMTzO6kqVJzKlWY76GYWyXj5cwUz1Kg476kd1JhADA27s57MLutOez5obXsN +ASQTOJ8ngb5wza2TZPR/vORuD+s0fuJlA3nveCzfKbjds1aHdS2rR6XYkzBy03bm +rdQI2kb+2PAAZtbm2mCI67yeHbn+XkbEowBzYnG+SoKVxXGszAIjOVzzzqvIMs7c +J8458Dpdc34cPhQ0XfdN8hZPNQt6hDxZt8BbEHXdm0/dUosryLA+nKcb++MAm4Ff +m8lwIK+31aqyIm/AIYL09fm1NN2fnzyEmX/KOGxHKY1FVIMwSQrZACvc+icCNCOo +xNrO8ahpd3uhACx7cqtnTP4hgZxNrkRxVFmbFy75TXcmL7nVGt3HmELPVEAZM/8I +cB0ztrRWC5+Woc3i8Znqb/I/E698Uk47v03/iM0VaXkPpcTIKNQZdS51+KTu7NEw +TOaPo0iW30pkRJPAfnXWvvQa0qfGoqMJsm45Yapr4cm6EzxM6XFDxPwslFhbz1e7 +M+gkq4J4UgHYMHM4spEqs9O7F2zUJLKWW9n2JTz1LGcEyVFS5QrkCdEQTeWlwnB6 +HAzErP+ObSaMWH6UVeNEtbP4VpXRYiNBzTGKK3qfbSXsXzVI7pbuqQIDAQABo2Mw +YTAdBgNVHQ4EFgQUscO66yi3+KqbQE1Dz7VXXEzjCbIwHwYDVR0jBBgwFoAUNmHh +AHyIBQlRi0RsR/8aTMnqTxIwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC +AgQwDQYJKoZIhvcNAQELBQADggIBAFdt0IxxNe5hkTrLnGZGG1f+NtWn+m9iU8GY +ZTvT4zvyF96v/5hte9pmwhLc2jGm/UOm5qDNMq1JvrFejr6VQVh1zTS5BGaDVK8D +iHosqRTxD/O2qULwGMpwBXoDeRDW3egVE/SUkYH9qAgQ211uZsLJQ4mNq0rPDDxl +jxjl7cCIErwgx66jWUEfOVIl9VTaR1V/nOtmfpVfveR4kxvQzm6NSsOZg/pl1yUq +Vxttml8emFiboVNY+BYe29wu++DpzR3KET+bBVXGFLQw+mk5GwJ9YI1FiwTexlJA +w326CJcTRO4gBU15xrceapnVu/sK9NeJX3ybdxLmgh0cZ/jCf7yBUW5YMHYcFpEX +3RzQSnRCA/gh6TUeWzyxx3YpgIXynRS1iSw2xGZV95wX6krXjnwPIZILAQPWI8tj +6IFlQt/lSRrJltYoWMncoTOiGaD/WBeKv4qXWBp18GmoSYYQTZFT4TWKQ2MhgNmA +18kw/riW2XKwMO6NzsAgOyH6AwDiiaFqZt9o2UGqlRfgmZrbUPq4Qgeuvnc4jXaK +bszmAg1TG4b+wP9xaczIaCIDPNFDTbpnveZDw5ZSxIC54X+GHKHdYhIM79P4zZOl +DX/Vit/iXXOMx2TBEiZZw5kQc7L2jvE8cc7qrKv1cjNhzZvBz7I0UmjjtsRoj3SD +gAs9PxVc +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIFHDCCAwSgAwIBAgIJAPHBcqaZ6vUdMA0GCSqGSIb3DQEBCwUAMBsxGTAXBgNV +BAUTEGY5MjAwOWU4NTNiNmIwNDUwHhcNMjIwMzIwMTgwNzQ4WhcNNDIwMzE1MTgw +NzQ4WjAbMRkwFwYDVQQFExBmOTIwMDllODUzYjZiMDQ1MIICIjANBgkqhkiG9w0B +AQEFAAOCAg8AMIICCgKCAgEAr7bHgiuxpwHsK7Qui8xUFmOr75gvMsd/dTEDDJdS +Sxtf6An7xyqpRR90PL2abxM1dEqlXnf2tqw1Ne4Xwl5jlRfdnJLmN0pTy/4lj4/7 +tv0Sk3iiKkypnEUtR6WfMgH0QZfKHM1+di+y9TFRtv6y//0rb+T+W8a9nsNL/ggj +nar86461qO0rOs2cXjp3kOG1FEJ5MVmFmBGtnrKpa73XpXyTqRxB/M0n1n/W9nGq +C4FSYa04T6N5RIZGBN2z2MT5IKGbFlbC8UrW0DxW7AYImQQcHtGl/m00QLVWutHQ +oVJYnFPlXTcHYvASLu+RhhsbDmxMgJJ0mcDpvsC4PjvB+TxywElgS70vE0XmLD+O +JtvsBslHZvPBKCOdT0MS+tgSOIfga+z1Z1g7+DVagf7quvmag8jfPioyKvxnK/Eg +sTUVi2ghzq8wm27ud/mIM7AY2qEORR8Go3TVB4HzWQgpZrt3i5MIlCaY504LzSRi +igHCzAPlHws+W0rB5N+er5/2pJKnfBSDiCiFAVtCLOZ7gLiMm0jhO2B6tUXHI/+M +RPjy02i59lINMRRev56GKtcd9qO/0kUJWdZTdA2XoS82ixPvZtXQpUpuL12ab+9E +aDK8Z4RHJYYfCT3Q5vNAXaiWQ+8PTWm2QgBR/bkwSWc+NpUFgNPN9PvQi8WEg5Um +AGMCAwEAAaNjMGEwHQYDVR0OBBYEFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMB8GA1Ud +IwQYMBaAFDZh4QB8iAUJUYtEbEf/GkzJ6k8SMA8GA1UdEwEB/wQFMAMBAf8wDgYD +VR0PAQH/BAQDAgIEMA0GCSqGSIb3DQEBCwUAA4ICAQB8cMqTllHc8U+qCrOlg3H7 +174lmaCsbo/bJ0C17JEgMLb4kvrqsXZs01U3mB/qABg/1t5Pd5AORHARs1hhqGIC +W/nKMav574f9rZN4PC2ZlufGXb7sIdJpGiO9ctRhiLuYuly10JccUZGEHpHSYM2G +tkgYbZba6lsCPYAAP83cyDV+1aOkTf1RCp/lM0PKvmxYN10RYsK631jrleGdcdkx +oSK//mSQbgcWnmAEZrzHoF1/0gso1HZgIn0YLzVhLSA/iXCX4QT2h3J5z3znluKG +1nv8NQdxei2DIIhASWfu804CA96cQKTTlaae2fweqXjdN1/v2nqOhngNyz1361mF +mr4XmaKH/ItTwOe72NI9ZcwS1lVaCvsIkTDCEXdm9rCNPAY10iTunIHFXRh+7KPz +lHGewCq/8TOohBRn0/NNfh7uRslOSZ/xKbN9tMBtw37Z8d2vvnXq/YWdsm1+JLVw +n6yYD/yacNJBlwpddla8eaVMjsF6nBnIgQOf9zKSe06nSTqvgwUHosgOECZJZ1Eu +zbH4yswbt02tKtKEFhx+v+OTge/06V+jGsqTWLsfrOCNLuA8H++z+pUENmpqnnHo +vaI47gC+TNpkgYGkkBT6B/m/U01BuOBBTzhIlMEZq9qkDWuM2cA5kW5V3FJUcfHn +w1IdYIg2Wxg7yHcQZemFQg== +-----END CERTIFICATE----- + + + + diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/tricky_store/target.txt" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/tricky_store/target.txt" new file mode 100644 index 00000000..e69de29b diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/tricky_store/tee_status" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/tricky_store/tee_status" new file mode 100644 index 00000000..ec9076c0 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/TS/tricky_store/tee_status" @@ -0,0 +1 @@ +teeBroken=false \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/hide_bootloader.sh" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/hide_bootloader.sh" new file mode 100644 index 00000000..7d144545 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/hide_bootloader.sh" @@ -0,0 +1,48 @@ +#!/system/bin/sh +check_reset_prop() { + local NAME=$1 + local EXPECTED=$2 + local VALUE=$(resetprop $NAME) + [ -z $VALUE ] || [ $VALUE = $EXPECTED ] || resetprop $NAME $EXPECTED +} + +contains_reset_prop() { + local NAME=$1 + local CONTAINS=$2 + local NEWVAL=$3 + [[ "$(resetprop $NAME)" = *"$CONTAINS"* ]] && resetprop $NAME $NEWVAL +} + +resetprop -w sys.boot_completed 0 +check_reset_prop "ro.boot.vbmeta.device_state" "locked" +check_reset_prop "ro.boot.verifiedbootstate" "green" +check_reset_prop "ro.boot.flash.locked" "1" +check_reset_prop "ro.boot.veritymode" "enforcing" +check_reset_prop "ro.boot.warranty_bit" "0" +check_reset_prop "ro.warranty_bit" "0" +check_reset_prop "ro.debuggable" "0" +check_reset_prop "ro.force.debuggable" "0" +check_reset_prop "ro.secure" "1" +check_reset_prop "ro.adb.secure" "1" +check_reset_prop "ro.build.type" "user" +check_reset_prop "ro.build.tags" "release-keys" +check_reset_prop "ro.vendor.boot.warranty_bit" "0" +check_reset_prop "ro.vendor.warranty_bit" "0" +check_reset_prop "vendor.boot.vbmeta.device_state" "locked" +check_reset_prop "vendor.boot.verifiedbootstate" "green" +check_reset_prop "sys.oem_unlock_allowed" "0" + +# MIUI specific +check_reset_prop "ro.secureboot.lockstate" "locked" + +# Realme specific +check_reset_prop "ro.boot.realmebootstate" "green" +check_reset_prop "ro.boot.realme.lockstate" "1" + +# ASUS specific +check_reset_prop "ro.boot.asusverifiedstate" "PASS" + +# Hide that we booted from recovery when magisk is in recovery mode +contains_reset_prop "ro.bootmode" "recovery" "unknown" +contains_reset_prop "ro.boot.bootmode" "recovery" "unknown" +contains_reset_prop "vendor.boot.bootmode" "recovery" "unknown" \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/resetprop" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/resetprop" new file mode 100644 index 00000000..feeb0284 Binary files /dev/null and "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/resetprop" differ diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/webroot/index.html" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/webroot/index.html" new file mode 100644 index 00000000..803dde52 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/webroot/index.html" @@ -0,0 +1,188 @@ + + + + + + Tricky Store 模块控制台 + + + + + + +
+ + +
+
+

Tricky Store

+ 模块控制台 +
+ +

+ Android 证书增强模块 · 提供系统证书接管与 TEE 状态修复能力。 +

+ +
+ 版本:加载中 +
+
+ 作者:5ec1cff, aviraxp, Cyberenchanter and topjohnwu +
+
+ + +
+

功能开关

+ +
+
+
开机自动接管系统外应用
+
+ 设备重启后,自动将所有系统外应用加入生效列表。 +
+
+ +
+ +
+
+
修复 TEE 状态异常
+
+ 检测到 TEE 相关状态异常时,尝试自动修复。 +
+
+ +
+ +
+
+
隐藏 Bootloader 状态
+
+ 伪装锁定状态,并重置 VerifiedBoot State 等属性。 +
+
+ +
+ +
+ +
+

target.txt 配置

+

+ target.txt 逐行存放每个 App 的包名(一个包名一行)。修改后请保存。 +

+ + + +
+ + +
+ + + +
+ target.txt 修改需要重启设备后才生效。 +
+
+ +
+

keybox.xml 配置

+

+ 这里展示当前 keybox.xml 内容,仅在充分理解配置含义的情况下再修改。 +

+ + + +
+ + + +
+ + + +
+ keybox.xml 修改需要重启设备后才生效。 +
+
+ +
+
+

Bootloader 属性覆写

+ +
+

+ 自定义用于隐藏 Bootloader 状态的 Shell 脚本逻辑。 +

+ + + +
+ + + +
+ + + +
+ 脚本修改需要重启设备后才生效。 +
+
+ +
+ + + + +
+ + + + + + + \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/webroot/main.js" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/webroot/main.js" new file mode 100644 index 00000000..067765bb --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/webroot/main.js" @@ -0,0 +1,275 @@ +// ====== DOM ====== +const $verSpan = document.getElementById('module-version'); + +const $autoThirdAppToggle = document.getElementById("toggle-auto-third-app"); +const $fixTeeToggle = document.getElementById("toggle-fix-tee"); +const $hideBootloaderToggle = document.getElementById("toggle-hide-bl"); + +const $targetEditor = document.getElementById("target-editor"); +const $btnCopyTarget = document.getElementById("btn-copy-target"); +const $btnPasteTarget = document.getElementById("btn-paste-target"); +const $btnSaveTarget = document.getElementById("btn-save-target"); + +const $keyboxEditor = document.getElementById("keybox-editor"); +const $btnCopyKeybox = document.getElementById("btn-copy-keybox"); +const $btnPasteKeybox = document.getElementById("btn-paste-keybox"); +const $btnSaveKeybox = document.getElementById("btn-save-keybox"); + +const $bootloaderScriptEditor = document.getElementById("bl-script-editor"); +const $btnDebug = document.getElementById('btn-debug-props'); + +const $btnCopyBootloader = document.getElementById("btn-copy-bl"); +const $btnPasteBootloader = document.getElementById("btn-paste-bl"); +const $btnSaveBootloader = document.getElementById("btn-save-bl"); + +async function loadSettings() { + try { + $autoThirdAppToggle.checked = (await RequestApi.getAutoThirdAppToggle()) == "1"; + $fixTeeToggle.checked = (await RequestApi.getFixTeeToggle()) == "1"; + $hideBootloaderToggle.checked = (await RequestApi.getHideBootloaderToggle()) == "1"; + + } catch (err) { + console.error('读取配置失败:', err); + alert('读取配置失败:' + (err instanceof Error ? err.message : String(err))); + } +} + +async function saveSettings() { + try { + if ((await RequestApi.setAutoThirdAppToggle($autoThirdAppToggle.checked ? "1" : "0")) !== 'OK') throw new Error(result); + if ((await RequestApi.setFixTeeToggle($fixTeeToggle.checked ? "1" : "0")) !== 'OK') throw new Error(result); + if ((await RequestApi.setHideBootloaderToggle($hideBootloaderToggle.checked ? "1" : "0")) !== 'OK') throw new Error(result); + + showToast("设置成功,重启生效"); + return true; + } catch (err) { + console.error('保存配置失败:', err); + alert('保存失败:' + (err instanceof Error ? err.message : String(err))); + } +} + +async function loadTargetTxt() { + try { + $targetEditor.value = await RequestApi.getTargetTxt(); + } catch (err) { + console.error('读取target.txt失败:', err); + alert('读取target.txt失败:' + (err instanceof Error ? err.message : String(err))); + } +} + +async function saveTargetTxt() { + try { + const result = await RequestApi.setTargetTxt($targetEditor.value); + if (result !== 'OK') { + alert('保存失败:' + result); + return false; + } + showToast("已保存,重启生效"); + return true; + } catch (err) { + console.error('保存target.txt失败:', err); + alert('保存target.txt失败:' + (err instanceof Error ? err.message : String(err))); + return false; + } +} + +async function loadKeyboxXml() { + try { + $keyboxEditor.value = await RequestApi.getKeyboxXml(); + } catch (err) { + console.error('读取keybox.xml失败:', err); + alert('读取keybox.xml失败:' + (err instanceof Error ? err.message : String(err))); + } +} + +async function saveKeyboxXml() { + try { + const result = await RequestApi.setKeyboxXml($keyboxEditor.value); + if (result !== 'OK') { + alert('保存失败:' + result); + return false; + } + showToast("已保存,重启生效"); + return true; + } catch (err) { + console.error('保存keybox.xml失败:', err); + alert('保存keybox.xml失败:' + (err instanceof Error ? err.message : String(err))); + return false; + } +} + +async function loadBootloaderScript() { + try { + $bootloaderScriptEditor.value = await RequestApi.getBootloaderScript(); + } catch (err) { + console.error('读取脚本失败:', err); + alert('读取脚本失败:' + (err instanceof Error ? err.message : String(err))); + } +} + +async function saveBootloaderScript() { + try { + const result = await RequestApi.setBootloaderScript($bootloaderScriptEditor.value); + if (result !== 'OK') { + alert('保存失败:' + result); + return false; + } + showToast("已保存,重启生效"); + return true; + } catch (err) { + console.error('保存脚本失败:', err); + alert('保存脚本失败:' + (err instanceof Error ? err.message : String(err))); + return false; + } +} + +async function showAllPropsModal() { + const modal = document.getElementById('debug-modal'); + const btnCloseModal = document.getElementById('btn-close-modal'); + const btnCopyDebug = document.getElementById('btn-copy-debug'); + const debugOutput = document.getElementById('debug-output'); + + debugOutput.value = "正在读取系统属性 (Running getprop)..."; + modal.classList.remove('hidden'); + + const closeModal = () => { + modal.classList.add('hidden'); + }; + btnCloseModal.addEventListener('click', closeModal); + modal.addEventListener('click', (e) => { + if (e.target === modal) closeModal(); + }); + + btnCopyDebug.addEventListener('click', () => { + copyToClipboard(debugOutput.value); + showToast("已复制"); + }); + + try { + debugOutput.value = await RequestApi.getAllProps(); + } catch (err) { + debugOutput.value = "获取属性失败:\n" + (err instanceof Error ? err.message : String(err)); + } +} + +function copyToClipboard(text) { + let tempTextarea = document.createElement('textarea'); + document.body.appendChild(tempTextarea); + tempTextarea.value = text; + tempTextarea.select(); + document.execCommand('copy'); + document.body.removeChild(tempTextarea); +} + +async function readClipboardText() { + try { + if (!navigator.clipboard || !navigator.clipboard.readText) return null; + // 很多环境需要安全上下文 + if (!window.isSecureContext) return null; + return await navigator.clipboard.readText(); + } catch (e) { + console.error("readClipboardText failed:", e); + return null; + } +} + +function render() { + $autoThirdAppToggle.addEventListener("change", async function () { + const ok = await saveSettings(); + if(ok) loadTargetTxt(); + }); + + $fixTeeToggle.addEventListener("change", async function () { + await saveSettings(); + }); + + $hideBootloaderToggle.addEventListener("change", async function () { + await saveSettings(); + }); + + $btnCopyTarget.addEventListener("click", function () { + copyToClipboard($targetEditor.value); + showToast("已复制"); + }); + + $btnPasteTarget.addEventListener("click", async () => { + const text = await readClipboardText(); + if (typeof text === "string" && text.length) { + if (!confirm("将剪贴板内容覆盖全文?")) return; + $targetEditor.value = text; + } else { + alert("当前浏览器限制,无法读取剪贴板,请长按文本框手动粘贴。"); + $targetEditor.focus(); + } + }); + + $btnSaveTarget.addEventListener("click", async function () { + await saveTargetTxt(); + }); + + $btnCopyKeybox.addEventListener("click", async function () { + copyToClipboard($keyboxEditor.value); + showToast("已复制"); + }); + + $btnPasteKeybox.addEventListener("click", async () => { + const text = await readClipboardText(); + if (typeof text === "string" && text.length) { + if (!confirm("将剪贴板内容覆盖全文?")) return; + $keyboxEditor.value = text; + } else { + alert("当前浏览器限制,无法读取剪贴板,请长按文本框手动粘贴。"); + $keyboxEditor.focus(); + } + }); + + $btnSaveKeybox.addEventListener("click", async function () { + await saveKeyboxXml(); + }); + + $btnCopyBootloader.addEventListener("click", async function () { + copyToClipboard($bootloaderScriptEditor.value); + showToast("已复制"); + }); + + $btnPasteBootloader.addEventListener("click", async () => { + const text = await readClipboardText(); + if (typeof text === "string" && text.length) { + if (!confirm("将剪贴板内容覆盖全文?")) return; + $bootloaderScriptEditor.value = text; + } else { + alert("当前浏览器限制,无法读取剪贴板,请长按文本框手动粘贴。"); + $bootloaderScriptEditor.focus(); + } + }); + + $btnSaveBootloader.addEventListener("click", async function () { + await saveBootloaderScript(); + }); + + $btnDebug.addEventListener('click', async () => { + showAllPropsModal(); + }); +} + +async function initVersion() { + try { + const ver = await RequestApi.getVersion(); + $verSpan.textContent = ver || '未知'; + } catch (err) { + $verSpan.textContent = '读取失败'; + console.error('getVersion 出错:', err); + alert('读取版本失败:' + (err instanceof Error ? err.message : String(err))); + } +} + +// ====== 入口初始化 ====== +async function onReady() { + await initVersion(); + await loadSettings(); + await loadTargetTxt(); + await loadKeyboxXml(); + await loadBootloaderScript(); + render(); +} +document.addEventListener('DOMContentLoaded', onReady); \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/webroot/request.js" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/webroot/request.js" new file mode 100644 index 00000000..bced9dea --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/webroot/request.js" @@ -0,0 +1,93 @@ +const RequestApi = (() => { + function postText(path, bodyText = "") { + const url = new URL(path, window.location.href); + return fetch(url, { method: 'POST', body: bodyText }); + } + + async function getVersion() { + const resp = await postText('/getVersion'); + return resp.ok ? await resp.text() : ('HTTP ' + resp.status); + } + + async function getAutoThirdAppToggle() { + const resp = await postText('/getAutoThirdAppToggle'); + return resp.ok ? await resp.text() : ('HTTP ' + resp.status); + } + + async function setAutoThirdAppToggle(content) { + const resp = await postText('/setAutoThirdAppToggle', content); + return resp.ok ? await resp.text() : ('HTTP ' + resp.status); + } + + async function getFixTeeToggle() { + const resp = await postText('/getFixTeeToggle'); + return resp.ok ? await resp.text() : ('HTTP ' + resp.status); + } + + async function setFixTeeToggle(content) { + const resp = await postText('/setFixTeeToggle', content); + return resp.ok ? await resp.text() : ('HTTP ' + resp.status); + } + + async function getHideBootloaderToggle() { + const resp = await postText('/getHideBootloaderToggle'); + return resp.ok ? await resp.text() : ('HTTP ' + resp.status); + } + + async function setHideBootloaderToggle(content) { + const resp = await postText('/setHideBootloaderToggle', content); + return resp.ok ? await resp.text() : ('HTTP ' + resp.status); + } + + async function getTargetTxt() { + const resp = await postText('/getTargetTxt'); + return resp.ok ? await resp.text() : ('HTTP ' + resp.status); + } + + async function setTargetTxt(content) { + const resp = await postText('/setTargetTxt', content); + return resp.ok ? await resp.text() : ('HTTP ' + resp.status); + } + + async function getKeyboxXml() { + const resp = await postText('/getKeyboxXml'); + return resp.ok ? await resp.text() : ('HTTP ' + resp.status); + } + + async function setKeyboxXml(content) { + const resp = await postText('/setKeyboxXml', content); + return resp.ok ? await resp.text() : ('HTTP ' + resp.status); + } + + async function getBootloaderScript() { + const resp = await postText('/getBootloaderScript'); + return resp.ok ? await resp.text() : ('HTTP ' + resp.status); + } + + async function setBootloaderScript(content) { + const resp = await postText('/setBootloaderScript', content); + return resp.ok ? await resp.text() : ('HTTP ' + resp.status); + } + + async function getAllProps() { + const resp = await postText('/getAllProps'); + return resp.ok ? await resp.text() : ('HTTP ' + resp.status); + } + + return { + getVersion, + getAutoThirdAppToggle, + setAutoThirdAppToggle, + getFixTeeToggle, + setFixTeeToggle, + getHideBootloaderToggle, + setHideBootloaderToggle, + getTargetTxt, + setTargetTxt, + getKeyboxXml, + setKeyboxXml, + getBootloaderScript, + setBootloaderScript, + getAllProps, + }; +})(); diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/webroot/style.css" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/webroot/style.css" new file mode 100644 index 00000000..c3cfaab7 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/webroot/style.css" @@ -0,0 +1,406 @@ +* { + box-sizing: border-box; + -webkit-tap-highlight-color: transparent; +} + +body { + margin: 0; + font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", + "Segoe UI", Roboto, "Helvetica Neue", Arial, + "PingFang SC", "Microsoft YaHei", sans-serif; + background: #e5e7eb; /* 整体浅灰,不是一片死白 */ + color: #0f172a; +} + +.page { + max-width: 520px; + margin: 0 auto; + padding: 12px 14px 24px; + min-height: 100vh; +} + +.card { + border-radius: 18px; + box-shadow: 0 8px 22px rgba(15, 23, 42, 0.08); + margin-bottom: 12px; +} + +/* 顶部深色模块头 */ +.header { + background: #020617; + color: #e5e7eb; + padding: 16px 16px 14px; +} + +.header-title-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; +} + +.title { + margin: 0; + font-size: 20px; + font-weight: 700; + letter-spacing: 0.03em; +} + +.badge { + font-size: 11px; + padding: 4px 10px; + border-radius: 999px; + border: 1px solid rgba(148, 163, 184, 0.55); + color: #e5e7eb; + white-space: nowrap; +} + +.subtitle { + margin: 6px 0 8px; + font-size: 12px; + color: #9ca3af; +} + +.meta-line { + font-size: 11px; + color: #9ca3af; +} + +.meta-line + .meta-line { + margin-top: 2px; +} + +/* section 通用卡片 */ +.section { + background: #ffffff; + padding: 12px 14px 14px; +} + +/* 第二块略微变色,色调隔开一点 */ +.section-alt { + background: #f9fafb; +} + +.section-title { + margin: 0 0 4px; + font-size: 14px; + font-weight: 600; + color: #111827; +} + +.section-desc { + margin: 0 0 8px; + font-size: 12px; + color: #6b7280; +} + +/* 功能开关行 */ +.row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; + padding: 10px 0; +} + +.row + .row { + border-top: 1px solid #e5e7eb; +} + +.row-text { + flex: 1; + min-width: 0; +} + +.row-title { + font-size: 14px; + font-weight: 500; + color: #111827; +} + +.row-desc { + margin-top: 3px; + font-size: 12px; + color: #6b7280; + line-height: 1.35; +} + +/* iOS 风格 switch */ +.switch { + position: relative; + display: inline-block; + width: 46px; + height: 26px; + flex-shrink: 0; +} + +.switch input { + opacity: 0; + width: 0; + height: 0; +} + +.slider { + position: absolute; + cursor: pointer; + inset: 0; + background-color: #d1d5db; + transition: 0.22s; + border-radius: 999px; +} + +.slider::before { + content: ""; + position: absolute; + height: 20px; + width: 20px; + left: 3px; + top: 3px; + background-color: #ffffff; + border-radius: 999px; + box-shadow: 0 1px 3px rgba(15, 23, 42, 0.30); + transition: 0.22s; +} + +.switch input:checked + .slider { + background-color: #22c55e; +} + +.switch input:checked + .slider::before { + transform: translateX(18px); +} + +@media (max-width: 360px) { + .page { + padding-inline: 10px; + } +} + +/* keybox 文本域 + 按钮 */ +.keybox-textarea { + margin-top: 6px; + width: 100%; + min-height: 170px; + resize: vertical; + border-radius: 10px; + border: 1px solid #e5e7eb; + padding: 8px 9px; + font-family: "SF Mono", "Roboto Mono", Menlo, Consolas, monospace; + font-size: 12px; + line-height: 1.4; + background: #f9fafb; + color: #111827; + outline: none; +} + +.keybox-textarea:focus { + border-color: #22c55e; + box-shadow: 0 0 0 1px rgba(34, 197, 94, 0.18); + background: #ffffff; +} +.keybox-toolbar{ + display:flex; + gap:10px; + margin-top:8px; +} + +.tool-btn{ + flex:1; + height:38px; + border-radius:999px; + border:1px solid #e5e7eb; + background:#ffffff; + color:#111827; + font-size:13px; + font-weight:600; + cursor:pointer; + box-shadow:0 6px 14px rgba(15, 23, 42, 0.06); +} + +.tool-btn:active{ + transform: translateY(1px); + box-shadow:0 3px 10px rgba(15, 23, 42, 0.05); +} + +.tool-btn.tool-warn{ + border-color: rgba(245, 158, 11, 0.45); + background: rgba(245, 158, 11, 0.10); + color:#92400e; +} + +.btn-primary { + width: 100%; + margin-top: 12px; + padding: 10px 0; + border: none; + border-radius: 999px; + font-size: 14px; + font-weight: 600; + background: #22c55e; + color: #ffffff; + cursor: pointer; + box-shadow: 0 8px 18px rgba(34, 197, 94, 0.35); +} + +.btn-primary:active { + transform: translateY(1px); + box-shadow: 0 4px 10px rgba(34, 197, 94, 0.30); +} + +.tip { + margin-top: 6px; + font-size: 11px; + color: #9ca3af; + text-align: center; +} + +/* 让 textarea 明显出现滚动条(内容很长时) */ +.keybox-textarea{ + overflow: auto; + scrollbar-gutter: stable; + /* Firefox */ + scrollbar-width: auto; /* 可改 thin/auto */ + scrollbar-color: rgba(100,116,139,.7) rgba(226,232,240,.9); +} + +/* Chrome / Edge / Android WebView */ +.keybox-textarea::-webkit-scrollbar{ + width: 10px; + height: 10px; +} +.keybox-textarea::-webkit-scrollbar-track{ + background: rgba(226,232,240,.9); + border-radius: 999px; +} +.keybox-textarea::-webkit-scrollbar-thumb{ + background: rgba(100,116,139,.7); + border-radius: 999px; + border: 2px solid rgba(226,232,240,.9); +} +.keybox-textarea::-webkit-scrollbar-thumb:hover{ + background: rgba(71,85,105,.85); +} + +/* --- Bootloader 模拟脚本 --- */ +.section-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 4px; +} + +.section-header .section-title { + margin: 0; +} + +/* --- 查看本机属性按钮 --- */ +.btn-ghost { + background: transparent; + border: none; + color: #9ca3af; + font-size: 12px; + padding: 4px 8px; + border-radius: 6px; + cursor: pointer; + transition: all 0.2s; + font-weight: 500; +} + +.btn-ghost:hover { + background: rgba(107, 114, 128, 0.1); + color: #4b5563; +} + +.btn-ghost:active { + transform: scale(0.96); +} + +/* --- 调试弹窗 (Modal) --- */ +.modal-overlay { + position: fixed; + inset: 0; + background: rgba(0, 0, 0, 0.4); + backdrop-filter: blur(2px); + z-index: 1000; + display: flex; + align-items: center; + justify-content: center; + padding: 20px; + opacity: 1; + transition: opacity 0.2s; +} + +.modal-overlay.hidden { + opacity: 0; + pointer-events: none; + visibility: hidden; +} + +.modal-card { + background: #fff; + width: 100%; + max-width: 500px; + height: 80vh; /* 占据屏幕高度的80% */ + border-radius: 16px; + box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1); + display: flex; + flex-direction: column; + overflow: hidden; + transform: scale(1); + transition: transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1); +} + +.modal-overlay.hidden .modal-card { + transform: scale(0.95); +} + +.modal-header { + padding: 16px; + border-bottom: 1px solid #e5e7eb; + display: flex; + justify-content: space-between; + align-items: center; +} + +.modal-header h3 { + margin: 0; + font-size: 16px; + color: #111827; +} + +.btn-close { + background: transparent; + border: none; + font-size: 24px; + line-height: 1; + color: #6b7280; + cursor: pointer; + padding: 0 8px; +} + +.modal-body { + flex: 1; + overflow: auto; + padding: 0; + background: #f9fafb; +} + +#debug-output { + width: 100%; + height: 100%; + border: none; + background: transparent; + padding: 12px; + font-family: "SF Mono", "Roboto Mono", monospace; + font-size: 11px; + line-height: 1.5; + color: #374151; + resize: none; + outline: none; +} + +.modal-footer { + padding: 12px; + border-top: 1px solid #e5e7eb; + background: #fff; +} \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/webroot/toast.css" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/webroot/toast.css" new file mode 100644 index 00000000..0f376bef --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/webroot/toast.css" @@ -0,0 +1,25 @@ +.toast { + position: fixed; + left: 50%; + top: 50%; + transform: translate(-50%, -50%) translateY(8px); + padding: 10px 20px; + border-radius: 16px; + font-size: 13px; + font-weight: 500; + color: #ffffff; + + background: rgba(52, 199, 89, 0.96); + box-shadow: 0 12px 30px rgba(52, 199, 89, 0.45); + + opacity: 0; + pointer-events: none; + z-index: 9999; + transition: opacity .26s ease, transform .26s ease; + white-space: normal; +} + +.toast.show { + opacity: 1; + transform: translate(-50%, -50%) translateY(0); +} \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/webroot/toast.js" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/webroot/toast.js" new file mode 100644 index 00000000..52e886df --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/resources/webroot/toast.js" @@ -0,0 +1,18 @@ +let toastTimer = null; + +function showToast(message) { + const toast = document.getElementById("toast"); + if (!toast) return; + + toast.textContent = message; + toast.classList.add("show"); + + // 清理之前的定时器 + if (toastTimer) { + clearTimeout(toastTimer); + } + + toastTimer = setTimeout(() => { + toast.classList.remove("show"); + }, 1800); +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/tricky_store_daemon.h" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/tricky_store_daemon.h" new file mode 100644 index 00000000..4db5e40c --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_tricky_store/tricky_store_daemon.h" @@ -0,0 +1,39 @@ +#pragma once +#include +#include +#include + +extern char **environ; + +static void redirect_stdio_to_devnull(void) { + int fd = open("/dev/null", O_WRONLY); + if (fd < 0) return; + dup2(fd, STDOUT_FILENO); // 1 -> /dev/null + dup2(fd, STDERR_FILENO); // 2 -> /dev/null + close(fd); +} + +static void start_tricky_store_daemon_loop(const char* moddir) { + setsid(); + redirect_stdio_to_devnull(); + if (chdir(moddir) != 0) _exit(1); + for (;;) { + pid_t pid = fork(); + if (pid < 0) _exit(1); + + if (pid == 0) { + char *const argv[] = { (char*)"./daemon", NULL }; + execve("./daemon", argv, environ); + _exit(127); + } + + int st = 0; + if (waitpid(pid, &st, 0) < 0) _exit(1); + + int code = 1; + if (WIFEXITED(st)) code = WEXITSTATUS(st); + else if (WIFSIGNALED(st)) code = 128 + WTERMSIG(st); + if (code != 0) _exit(1); + sleep(2); + } +} diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_update_demo/jni/Android.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_update_demo/jni/Android.mk" new file mode 100644 index 00000000..4d379026 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_update_demo/jni/Android.mk" @@ -0,0 +1,17 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) +LOCAL_MODULE := module_update_demo + +LOCAL_SRC_FILES := \ + $(LOCAL_PATH)/../module_update_demo.cpp\ + +KERNEL_MODULE_KIT := $(LOCAL_PATH)/../../kernel_module_kit +LOCAL_C_INCLUDES += $(KERNEL_MODULE_KIT)/include +LOCAL_LDFLAGS += $(KERNEL_MODULE_KIT)/lib/libkernel_module_kit_static.a + +include $(LOCAL_PATH)/build_macros.mk + +include $(BUILD_SHARED_LIBRARY) + + diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_update_demo/jni/Application.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_update_demo/jni/Application.mk" new file mode 100644 index 00000000..2500a8a7 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_update_demo/jni/Application.mk" @@ -0,0 +1,2 @@ +APP_ABI := arm64-v8a +APP_STL := c++_static \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_update_demo/jni/build_macros.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_update_demo/jni/build_macros.mk" new file mode 100644 index 00000000..a6f31501 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_update_demo/jni/build_macros.mk" @@ -0,0 +1,21 @@ +COMMON_CPPFLAGS := \ + -std=c++20 \ + -fPIC \ + -fvisibility=hidden \ + -fno-stack-protector \ + -ffunction-sections \ + -fdata-sections \ + -flto=thin + +COMMON_LDFLAGS := \ + -Wl,-O2 \ + -Wl,--gc-sections \ + -Wl,-s \ + -flto=thin + +COMMON_INCLUDES := \ + $(LOCAL_PATH)/../../../ + +LOCAL_CPPFLAGS += $(COMMON_CPPFLAGS) +LOCAL_LDFLAGS += $(COMMON_LDFLAGS) +LOCAL_C_INCLUDES += $(COMMON_INCLUDES) diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_update_demo/module_update_demo.cpp" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_update_demo/module_update_demo.cpp" new file mode 100644 index 00000000..ac31d2b9 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_update_demo/module_update_demo.cpp" @@ -0,0 +1,39 @@ +#include +#include "kernel_module_kit_umbrella.h" + +int skroot_module_main(const char* root_key, const char* module_private_dir) { + printf("[module_update] starting... \n"); + printf("[module_update] root_key len=%zu\n", strlen(root_key)); + printf("[module_update] module_private_dir=%s\n", module_private_dir); + return 0; +} + +// SKRoot 模块名片 +SKROOT_MODULE_NAME("URL 配置更新 Demo") +SKROOT_MODULE_VERSION("0.0.1") +SKROOT_MODULE_DESC("演示配置更新 JSON") +SKROOT_MODULE_AUTHOR("SKRoot") +SKROOT_MODULE_UUID32("62027df1409d6109da7e153d04915074") + +/* +========================== + 更新 JSON 示例与说明书 +========================== +SKRoot App 会定期检查该 JSON,并在发现新版本时向用户提示更新。 + +示例 JSON 内容如下: +{ + "version": "0.0.1", + "zipUrl": "https://example.com/demo.zip", + "changelog": "https://example.com/changelog.txt" +} + +字段说明: +- version : 最新模块版本号。 +- zipUrl : 模块更新包(ZIP 文件)下载地址。 +- changelog : 更新说明文件,用于展示更新内容。 +*/ + +// 在线更新 JSON 配置(演示用 example.com) +SKROOT_MODULE_UPDATE_JSON("https://example.com/update.json") + diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_web_ui_example/jni/Android.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_web_ui_example/jni/Android.mk" new file mode 100644 index 00000000..17c90d77 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_web_ui_example/jni/Android.mk" @@ -0,0 +1,17 @@ +LOCAL_PATH := $(call my-dir) + +include $(CLEAR_VARS) +LOCAL_MODULE := module_web_ui_example + +LOCAL_SRC_FILES := \ + $(LOCAL_PATH)/../module_web_ui_example.cpp + +KERNEL_MODULE_KIT := $(LOCAL_PATH)/../../kernel_module_kit +LOCAL_C_INCLUDES += $(KERNEL_MODULE_KIT)/include +LOCAL_LDFLAGS += $(KERNEL_MODULE_KIT)/lib/libkernel_module_kit_static.a + +include $(LOCAL_PATH)/build_macros.mk + +include $(BUILD_SHARED_LIBRARY) + + diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_web_ui_example/jni/Application.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_web_ui_example/jni/Application.mk" new file mode 100644 index 00000000..2500a8a7 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_web_ui_example/jni/Application.mk" @@ -0,0 +1,2 @@ +APP_ABI := arm64-v8a +APP_STL := c++_static \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_web_ui_example/jni/build_macros.mk" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_web_ui_example/jni/build_macros.mk" new file mode 100644 index 00000000..a6f31501 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_web_ui_example/jni/build_macros.mk" @@ -0,0 +1,21 @@ +COMMON_CPPFLAGS := \ + -std=c++20 \ + -fPIC \ + -fvisibility=hidden \ + -fno-stack-protector \ + -ffunction-sections \ + -fdata-sections \ + -flto=thin + +COMMON_LDFLAGS := \ + -Wl,-O2 \ + -Wl,--gc-sections \ + -Wl,-s \ + -flto=thin + +COMMON_INCLUDES := \ + $(LOCAL_PATH)/../../../ + +LOCAL_CPPFLAGS += $(COMMON_CPPFLAGS) +LOCAL_LDFLAGS += $(COMMON_LDFLAGS) +LOCAL_C_INCLUDES += $(COMMON_INCLUDES) diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_web_ui_example/module_web_ui_example.cpp" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_web_ui_example/module_web_ui_example.cpp" new file mode 100644 index 00000000..9e906a9c --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_web_ui_example/module_web_ui_example.cpp" @@ -0,0 +1,55 @@ +#include "kernel_module_kit_umbrella.h" + +// SKRoot模块入口函数 +int skroot_module_main(const char* root_key, const char* module_private_dir) { + printf("[module_web_ui_example] starting... \n"); + printf("[module_web_ui_example] root_key len=%zu\n", strlen(root_key)); + printf("[module_web_ui_example] module_private_dir=%s\n", module_private_dir); + + //读取配置文件内容 + std::string value; + KModErr err = kernel_module::read_string_disk_storage("myKey", value); + if(is_ok(err)) { + printf("[module_web_ui_example] read storage succeed: value: %s\n", value.c_str()); + } else { + printf("[module_web_ui_example] read storage failed: %s\n", to_string(err).c_str()); + } + return 0; +} + + +// WebUI HTTP服务器回调函数 +class MyWebHttpHandler : public kernel_module::WebUIHttpHandler { // HTTP服务器基于civetweb库 +public: + void onPrepareCreate(const char* root_key, const char* module_private_dir, uint32_t port) override { + printf("[module_web_ui_example] MyHttpHandler root_key len=%zu\n", strlen(root_key)); + printf("[module_web_ui_example] MyHttpHandler module_private_dir=%s\n", module_private_dir); + printf("[module_web_ui_example] MyHttpHandler port=%d\n", port); + } + + bool handleGet(CivetServer* server, struct mg_connection* conn, const std::string& path, const std::string& query) override { + printf("GET request\nPath: %s\nQuery: %s\n", path.c_str(), query.c_str()); + return false; + } + + bool handlePost(CivetServer* server, struct mg_connection* conn, const std::string& path, const std::string& body) override { + printf("POST request\nPath: %s\nBody: %s\n", path.c_str(), body.c_str()); + + std::string resp; + if(path == "/getPid") resp = std::to_string(getpid()); + else if(path == "/getUid") resp = std::to_string(getuid()); + else if(path == "/getValue") kernel_module::read_string_disk_storage("myKey", resp); + else if(path == "/setValue") resp = is_ok(kernel_module::write_string_disk_storage("myKey", body.c_str())) ? "OK" : "FAILED"; + + kernel_module::webui::send_text(conn, 200, resp); + return true; + } +}; + +// SKRoot 模块名片 +SKROOT_MODULE_NAME("内置 WebUI Demo") +SKROOT_MODULE_VERSION("1.0.0") +SKROOT_MODULE_DESC("演示在模块中使用WebUI页面") +SKROOT_MODULE_AUTHOR("SKRoot") +SKROOT_MODULE_UUID32("6080b19fb2db26c534af3051103f541f") +SKROOT_MODULE_WEB_UI(MyWebHttpHandler) \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_web_ui_example/webroot/index.html" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_web_ui_example/webroot/index.html" new file mode 100644 index 00000000..8b89f0f5 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/module_web_ui_example/webroot/index.html" @@ -0,0 +1,56 @@ + + + + + 演示模块HTTP管理页面 + + + + +

当前进程信息

+
+

上次的值

+
+

设置新值

+

+ + + +

+ + \ No newline at end of file diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/\346\250\241\345\235\227\346\211\223\345\214\205\347\244\272\344\276\213/module_fake_system_file.zip" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/\346\250\241\345\235\227\346\211\223\345\214\205\347\244\272\344\276\213/module_fake_system_file.zip" new file mode 100644 index 00000000..44c2e4cf Binary files /dev/null and "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/\346\250\241\345\235\227\346\211\223\345\214\205\347\244\272\344\276\213/module_fake_system_file.zip" differ diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/\346\250\241\345\235\227\346\211\223\345\214\205\347\244\272\344\276\213/module_hello_world.zip" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/\346\250\241\345\235\227\346\211\223\345\214\205\347\244\272\344\276\213/module_hello_world.zip" new file mode 100644 index 00000000..65fe024f Binary files /dev/null and "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/\346\250\241\345\235\227\346\211\223\345\214\205\347\244\272\344\276\213/module_hello_world.zip" differ diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/\346\250\241\345\235\227\346\211\223\345\214\205\347\244\272\344\276\213/module_hide_data_dir.zip" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/\346\250\241\345\235\227\346\211\223\345\214\205\347\244\272\344\276\213/module_hide_data_dir.zip" new file mode 100644 index 00000000..278d86cd Binary files /dev/null and "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/\346\250\241\345\235\227\346\211\223\345\214\205\347\244\272\344\276\213/module_hide_data_dir.zip" differ diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/\346\250\241\345\235\227\346\211\223\345\214\205\347\244\272\344\276\213/module_web_ui_example.zip" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/\346\250\241\345\235\227\346\211\223\345\214\205\347\244\272\344\276\213/module_web_ui_example.zip" new file mode 100644 index 00000000..0fa32f29 Binary files /dev/null and "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/\346\250\241\345\235\227\346\211\223\345\214\205\347\244\272\344\276\213/module_web_ui_example.zip" differ diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/\347\233\256\345\275\225\346\270\205\345\215\225.txt" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/\347\233\256\345\275\225\346\270\205\345\215\225.txt" new file mode 100644 index 00000000..618d2ea9 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/testModule/\347\233\256\345\275\225\346\270\205\345\215\225.txt" @@ -0,0 +1,22 @@ +testModule 模块目录清单: +────────────────────────────── +• SKRoot 内核模块开发 SDK .................. kernel_module_kit +• SDK 全接口回归测试工程(源码) .......... kernel_module_kit_test + +模块示例: +────────────────────────────── +• Hello World Demo (源码)............... module_hello_world +• 内置 WebUI Demo (源码)................ module_web_ui_example +• 安装/卸载回调 Demo (源码)............. module_install_uninstall_cb_demo +• URL 配置更新 Demo (源码).............. module_update_demo +• 系统文件伪造 Demo (源码).............. module_fake_system_file + +功能模块: +────────────────────────────── +• 隐藏 /data 路径功能模块(源码)........ module_hide_data_dir +• 清理 USB 调试痕迹模块(源码).......... module_clear_usb_trace +• 隐蔽的系统终端 模块(源码)......................module_hide_sh_exec +• TrickyStore 集成模块(源码).............. module_tricky_store +• 伪装机型模块(源码)........................... module_fake_device +• 温控解除模块(源码)........................... module_fake_thermal +────────────────────────────── diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/\345\267\245\347\250\213\347\233\256\345\275\225\350\257\264\346\230\216.txt" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/\345\267\245\347\250\213\347\233\256\345\275\225\350\257\264\346\230\216.txt" new file mode 100644 index 00000000..438f7779 --- /dev/null +++ "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/src/\345\267\245\347\250\213\347\233\256\345\275\225\350\257\264\346\230\216.txt" @@ -0,0 +1,7 @@ +SKRoot (Pro) 工程目录说明: +────────────────────────────── +1. 内核修补工具 .................... patch_kernel_sk +2. 环境安装管理 APP ............... PermissionManager +3. 环境安装 JNI 程序 .............. testInstall +4. 内核模块示例 ..................... testModule +────────────────────────────── diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/\345\212\237\350\203\275\346\210\252\345\233\276/1.png" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/\345\212\237\350\203\275\346\210\252\345\233\276/1.png" new file mode 100644 index 00000000..7bf04644 Binary files /dev/null and "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/\345\212\237\350\203\275\346\210\252\345\233\276/1.png" differ diff --git "a/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/\345\212\237\350\203\275\346\210\252\345\233\276/2.png" "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/\345\212\237\350\203\275\346\210\252\345\233\276/2.png" new file mode 100644 index 00000000..3cb6e7b6 Binary files /dev/null and "b/Pro(\344\274\227\346\265\213\345\274\200\346\224\276\344\270\255)/\345\212\237\350\203\275\346\210\252\345\233\276/2.png" differ diff --git a/README.md b/README.md new file mode 100644 index 00000000..84a70506 --- /dev/null +++ b/README.md @@ -0,0 +1,108 @@ +# SkRoot - Linux 内核级完美隐藏 Root 方案 + +新一代 SkRoot,完美隐藏Root功能,挑战全网Root检测手段,实现**SELinux零触碰、无挂载**,通杀所有内核,**不需要内核源码**,直接 Patch 内核,兼容安卓 APP 直接JNI调用,稳定不闪退。 + +## 版本对比 + +| 对比项 | 🟢 SkRoot (Lite) | 🚀 SkRoot (Pro) | +| :--- | :--- | :--- | +| **隐蔽性** | **完美隐藏 Root**、**SELinux 零触碰、无挂载** | **完美隐藏 Root**、**SELinux 零触碰、无挂载** | +| **用途** | 面向基础 Root 场景,稳定性最佳。 | 主力版本,拥有更强的控制能力。 | +| **功能** | 仅提供基础 Root 支持。 | 支持 **授权管理** + **内核模块**。 | +| **进阶** | - | 隐藏目录、隐蔽执行sh、解除温控、系统文件无痕伪造等。 | +| **模块能力** | - | 支持内核热修改Hook,**最多10万个Hook位置、无性能损耗**,单模块跨内核通用运行。 | + +## 功能列表: +1.测试ROOT权限 + +2.执行ROOT命令 + +3.以ROOT执行程序 + +4.安装部署su + +5.注入su到指定进程 + +6.完全卸载清理su + +7.寄生目标APP +## 效果: +* 实验设备包括:红米K20\K30\K40\K50\K60、小米8\9\10\11\12\13、小米平板5\6、红魔5\6\7、联想、三星、一加、ROG2\3等,支持型号非常多。测试结果显示,SkRoot能够在设备上**非常稳定**的运行。 +* **过市面上所有主流App的Root检测,如农业XX、交X12123等...** +* **不需要Linux内核源码、不编译内核,直接修补内核,保留原厂内核优化** +* **支持Linux内核版本:3.10~6.12** + +![image](https://github.com/abcz316/SKRoot-linuxKernelRoot/blob/master/Lite_version/%E5%8A%9F%E8%83%BD%E6%88%AA%E5%9B%BE/1.png) +![image](https://github.com/abcz316/SKRoot-linuxKernelRoot/blob/master/Lite_version/%E5%8A%9F%E8%83%BD%E6%88%AA%E5%9B%BE/2.png) +![image](https://github.com/abcz316/SKRoot-linuxKernelRoot/blob/master/Lite_version/%E5%8A%9F%E8%83%BD%E6%88%AA%E5%9B%BE/3.png) + +## 功能备注: +1. APP应用程序得到Root权限的唯一方法就是得到Root密匙,此密匙为48位的随机字符串,安全可靠。 + +2. 其中【**注入su到指定进程**】**只支持授权su到64位的APP**,老式32位App不再进行支持。 + +## SkRoot(Lite) 使用流程: +1.下载源码编译或**下载编译产物**: [patch_kernel_root.exe](https://github.com/abcz316/SKRoot-linuxKernelRoot/blob/master/Lite_version/patch_kernel_root(2026-3-11).exe)、 [PermissionManager.apk](https://github.com/abcz316/SKRoot-linuxKernelRoot/blob/master/Lite_version/SKRoot-Lite-(2026-3-8).apk) + +2.将内核kernel文件拖拽置`patch_kernel_root.exe`即可一键自动化流程补丁内核,同时会自动生成Root密匙。 + +3.安装并启动`PermissionManager.apk`或者`testRoot`,输入Root密匙值,即可正常使用SkRoot。 + +## SkRoot(Pro) 使用流程: +*已全部开发完成,其中 “SkRootPro 模块开发 SDK” 已公开,其余组件将在稳定后逐步公开。* + +*目前正在众测中。如想加入测试组织,请关注TG频道:https://t.me/skrootabc* + +## 更新日志: +2026-3: + * 1.修复部分Linux6.12无法解析的问题。 + * 2.修复Linux 5.15会睡死的问题。 + * 3.增强寄生App功能的稳定性。 + +2026-2: + * 1.修复su无法独立后台运行的问题。 + * 2.修复Linux 4.4无法解析的问题。 + +2026-1: + * 1.修复审计日志残留痕迹。 + +2025: + * 1.适配Linux6.12。 + * 2.修复su部分命令无法执行的问题。 + * 3.修复su进程切后台会被系统冻结的BUG。 + * 4.修复su进程不能退出有残留的问题。 + * 5.修复部分Linux 4.x会死机、无法解析的问题。 + * 6.修复Linux 6.1、6.6及以上无法解析问题。 + * 7.新增内核隐藏su路径(抵御安卓漏洞)。 + * 8.新增以Root身份直接执行程序功能。 + +2024: + * 1.新增永久授权su功能。 + +2023: + * 1.新增seccomp补丁代码。 + * 2.新增寄生目标功能。 + * 3.新增一键自动化流程补丁内核功能。 + * 4.修复Linux 3.X老内核兼容问题。 + * 5.修复Linux 5.10、5.15无法开机问题。 + +## 问题排查: +1、如遇到Linux 6.0以上内核无法开机,请阅读: +* **请不要使用Android.Image.Kitchen进行打包,该工具不支持Linux 6.0以上内核!** +* **可使用magiskboot进行打包。** +* **magiskboot的快速获取方式:使用7z解压[Magisk.apk](https://github.com/topjohnwu/Magisk/releases),把lib/x86_64文件夹里的libmagiskboot.so直接改名magiskboot即可使用。因为这是个Linux可执行文件,并不是动态库,不要被名字带so字样所迷惑。** +* **magiskboot官方没有提供Windows版本,请安装Linux系统使用它。不建议使用非官方的Windows版本,因为代码版本可能太旧。** +* **解包命令:./magiskboot unpack boot.img** +* **打包命令:./magiskboot repack boot.img** + +2、如发现第三方应用程序依然有侦测行为,请按照以下步骤进行排查: +* **内核必须保证是基于官方原版进行修改,而非自行编译或使用第三方源码编译。** +* **如果你曾经使用过Magisk,你应该先将手机完全刷机,因为Magisk可能会残留日志文件等信息。** +* **不要安装需要Root权限的工具,或涉及系统环境检测的应用,如冰箱、黑洞、momo和密匙认证等。这些应用的存在可能会被用作证据,推断你的设备已获取Root权限。若需使用,请在使用后立即卸载。** +* **App可能会被特征检测。这里的App只是演示功能写法。在实际使用中,请尽量隐藏App。例如使用寄生功能,寄生到其他无害的App内,以免被侦测。** +* **如果在解锁BL后手机会发出警报,你需要自行解决这个问题,因为它与SkRoot无关。** +* **如果对方是检测BL锁,而不是Root权限。你应该安装SkRoot的隐藏BL锁模块。** +* **请检查SELinux状态是否被恶意软件禁用。** + +3、耗电风险须知: +* **我们不提倡任何自行编译内核的行为,可能会造成续航缩短、发烫等问题,因其丢失了原厂的功耗管理策略。SkRoot则是在原厂内核上进行修补,保留原厂调教,无任何耗电问题。** diff --git a/testRoot/README.md b/testRoot/README.md deleted file mode 100644 index 117e997d..00000000 --- a/testRoot/README.md +++ /dev/null @@ -1,13 +0,0 @@ - printf( - "======================================================\n" - "本工具名称: Linux ARM64 完美隐藏ROOT演示\n" - "本工具功能列表:\n" - "\t1.显示自身权限信息\n" - "\t2.获取ROOT权限\n" - "\t3.绕过SELinux\n" - "\t4.还原SELinux\n" - "\t5.执行ROOT权限级别的Shell命令\n" - "\t6.赋予ADB最高级别权限\n" - "\t新一代root,跟面具完全不同思路,摆脱面具被检测的弱点,完美隐藏root功能,挑战全网root检测手段,兼容安卓APP直接JNI调用,稳定、流畅、不闪退。\n" - "======================================================\n" - ); diff --git a/testRoot/jni/Android.mk b/testRoot/jni/Android.mk deleted file mode 100644 index f1a70c67..00000000 --- a/testRoot/jni/Android.mk +++ /dev/null @@ -1,11 +0,0 @@ -LOCAL_PATH := $(call my-dir) - -include $(CLEAR_VARS) -LOCAL_CPPFLAGS += -std=c++1y -LOCAL_CFLAGS += -fPIE -LOCAL_CFLAGS += -fvisibility=hidden -LOCAL_LDFLAGS += -fPIE -pie -LOCAL_DISABLE_FATAL_LINKER_WARNINGS := true -LOCAL_MODULE := testRoot.out -LOCAL_SRC_FILES := ../main.cpp ../adb_inject.cpp ../ptrace_arm64_utils.cpp -include $(BUILD_EXECUTABLE) diff --git a/testRoot/main.cpp b/testRoot/main.cpp deleted file mode 100644 index ca905fee..00000000 --- a/testRoot/main.cpp +++ /dev/null @@ -1,147 +0,0 @@ -#include -#include - -#include "super_root.h" -#include "adb_inject.h" -#define ROOT_KEY 0x7F6766F8 - -void show_capability_info() -{ - struct __user_cap_header_struct cap_header_data; - cap_user_header_t cap_header = &cap_header_data; - - struct __user_cap_data_struct cap_data_data; - cap_user_data_t cap_data = &cap_data_data; - - cap_header->pid = getpid(); - cap_header->version = _LINUX_CAPABILITY_VERSION_3; //_1、_2、_3 - - if (capget(cap_header, cap_data) < 0) { - perror("FAILED capget()"); - exit(1); - } - - printf("Cap data 0x%x, 0x%x, 0x%x\n", cap_data->effective, cap_data->permitted, cap_data->inheritable); - printf("now getuid()=%d,geteuid()=%d,getgid()=%d,getegid()=%d\n", getuid(), geteuid(), getgid(), getegid()); - - FILE * fp = popen("getenforce", "r"); - if (fp) - { - char cmd[512] = { 0 }; - fread(cmd, 1, sizeof(cmd), fp); - pclose(fp); - - printf("SELinux status: %s\n", cmd); - } -} -void test_root() -{ - show_capability_info(); - - printf("get_root ret:%d\n", get_root(ROOT_KEY)); - - show_capability_info(); - - //system("id"); - //system("/data/local/tmp/getmyinfo"); - //system("insmod /sdcard/rwProcMem37.ko ; echo $?"); - //system("cat /proc/1/maps"); - //system("ls /proc"); - //system("screencap -p /sdcard/temp.png"); - return; -} - -void test_disable_selinux() -{ - int ret = disable_selinux(ROOT_KEY); - printf("disable_selinux ret:%d\n", ret); - printf("done.\n"); - return; -} - -void test_enable_selinux() -{ - int ret = enable_selinux(ROOT_KEY); - printf("enable_selinux ret:%d\n", ret); - printf("done.\n"); - return; -} - - -void test_run_cmd(char * cmd, bool bKeepAdbRoot = false) { - printf("inject_cmd_remote_process(%s)\n", cmd); - char szResult[0x1000] = { 0 }; - ssize_t ret = safe_inject_adb_process_run_cmd_wrapper(ROOT_KEY, cmd, bKeepAdbRoot, szResult, sizeof(szResult)); - printf("inject_cmd_remote_process ret val:%zd\n", ret); - printf("inject_cmd_remote_process result:%s\n", szResult); -} - -int main(int argc, char *argv[]) -{ - printf( - "======================================================\n" - "本工具名称: Linux ARM64 完美隐藏ROOT演示\n" - "本工具功能列表:\n" - "\t1.显示自身权限信息\n" - "\t2.获取ROOT权限\n" - "\t3.绕过SELinux\n" - "\t4.还原SELinux\n" - "\t5.执行ROOT权限级别的Shell命令\n" - "\t6.赋予ADB最高级别权限\n" - "\t新一代root,跟面具完全不同思路,摆脱面具被检测的弱点,完美隐藏root功能,挑战全网root检测手段,兼容安卓APP直接JNI调用,稳定、流畅、不闪退。\n" - "======================================================\n" - ); - - - ++argv; - --argc; - - - int cmdc; - char *cmdv[6]; - - while (argc) { - // Clean up - cmdc = 0; - memset(cmdv, 0, sizeof(cmdv)); - - // Split the commands - for (char *tok = strtok(argv[0], " "); tok; tok = strtok(nullptr, " ")) - { - cmdv[cmdc++] = tok; - if (cmdc == 0) - { - continue; - } - } - - - if (strcmp(cmdv[0], "show") == 0) { - show_capability_info(); - } - else if (strcmp(cmdv[0], "root") == 0) { - test_root(); - } - else if (strcmp(cmdv[0], "disable") == 0) { - test_disable_selinux(); - } - else if (strcmp(cmdv[0], "enable") == 0) { - test_enable_selinux(); - } - else if (strcmp(cmdv[0], "cmd") == 0) { - test_run_cmd("id"); - //test_run_cmd("id > /sdcard/run.txt"); - //test_run_cmd("insmod rwProcMem37.ko > /sdcard/run.txt"); - } - else if (strcmp(cmdv[0], "adb") == 0) { - test_run_cmd("id", true); - } - else { - return 1; - } - - --argc; - ++argv; - } - return 0; -} \ No newline at end of file diff --git a/testRoot/testRoot.vcxproj b/testRoot/testRoot.vcxproj deleted file mode 100644 index 87beb8d5..00000000 --- a/testRoot/testRoot.vcxproj +++ /dev/null @@ -1,94 +0,0 @@ - - - - - Debug - ARM - - - Release - ARM - - - Debug - ARM64 - - - Release - ARM64 - - - Debug - x86 - - - Release - x86 - - - Debug - x64 - - - Release - x64 - - - - {2a287d40-5742-4389-a623-50f6bcea2a0f} - Linux - testRoot - 15.0 - Linux - 1.0 - Generic - {D51BCBC9-82E9-4017-911E-C93873C4EA2B} - - - - true - - - false - - - true - - - false - - - true - - - false - - - false - - - true - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/testRoot/testRoot.vcxproj.filters b/testRoot/testRoot.vcxproj.filters deleted file mode 100644 index 52b27543..00000000 --- a/testRoot/testRoot.vcxproj.filters +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - {4f0b16e1-e05c-44ce-8377-35b973d209f5} - - - - - jni - - - jni - - - - - - - - \ No newline at end of file diff --git a/testRoot/testRoot.vcxproj.user b/testRoot/testRoot.vcxproj.user deleted file mode 100644 index 6e2aec7a..00000000 --- a/testRoot/testRoot.vcxproj.user +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file