diff --git a/appdata-sandbox-app.json b/appdata-sandbox-app.json index 3a82aa3a97ad234e4c03170140436ba5d306fb65..15d5876d18e3f851eb600a0421bb51310f395dae 100644 --- a/appdata-sandbox-app.json +++ b/appdata-sandbox-app.json @@ -162,9 +162,6 @@ }, { "src-path" : "/data/app/el1//aot_compiler/ark_profile/", "sandbox-path" : "/data/storage/ark-profile" - }, { - "src-path" : "/data/app/el1//shader_cache/", - "sandbox-path" : "/data/storage/shader_cache/local" }, { "src-path" : "/data/app/el1/public/shader_cache/cloud/", "sandbox-path" : "/data/storage/shader_cache/cloud" @@ -465,6 +462,11 @@ "sandbox-path": "/data/storage/el2/base/files/mediadata/", "sandbox-flags": ["bind", "rec"] }] + }, { + "name": "ohos.permission.ACCESS_DFX_LOG_DIR", + "sandbox-switch": "ON", + "gids": ["log"], + "mount-paths": [] }], "spawn-flag": [{ "name": "START_FLAGS_BACKUP", diff --git a/appdata-sandbox-gpu.json b/appdata-sandbox-gpu.json index d80ed7e1c776c976cda5cff0fb4c0bcbc78d7f32..6b8d3c820e751660da2d28d8b01eb383e79e14a2 100644 --- a/appdata-sandbox-gpu.json +++ b/appdata-sandbox-gpu.json @@ -77,8 +77,8 @@ "src-path" : "/module_update/ArkWebCore/app/", "sandbox-path" : "/module_update/ArkWebCore/app/" }, { - "src-path" : "/data/app/el1//shader_cache/", - "sandbox-path" : "/data/storage/shader_cache/local" + "src-path" : "/data/app/el1//system_optimize//shader_cache", + "sandbox-path" : "/data/storage/system_optimize/shader_cache" }, { "src-path" : "/data/app/el1/public/shader_cache/cloud/", "sandbox-path" : "/data/storage/shader_cache/cloud" diff --git a/appdata-sandbox.json b/appdata-sandbox.json index 9504f3745d109c89cbc98b159176246cb6b5a297..38115a046400a6fac9ef7f7669fbc1904101b47c 100755 --- a/appdata-sandbox.json +++ b/appdata-sandbox.json @@ -163,11 +163,6 @@ "sandbox-path" : "/data/storage/ark-profile", "sandbox-flags" : [ "bind", "rec" ], "check-action-status": "false" - }, { - "src-path" : "/data/app/el1//shader_cache/", - "sandbox-path" : "/data/storage/shader_cache/local", - "sandbox-flags" : [ "bind", "rec" ], - "check-action-status": "false" }, { "src-path" : "/data/app/el1/public/shader_cache/cloud/", "sandbox-path" : "/data/storage/shader_cache/cloud", @@ -652,8 +647,8 @@ "sandbox-flags" : [ "bind", "rec" ], "check-action-status": "false" }, { - "src-path" : "/data/app/el1//shader_cache/", - "sandbox-path" : "/data/storage/shader_cache/local", + "src-path" : "/data/app/el1//system_optimize//shader_cache", + "sandbox-path" : "/data/storage/system_optimize/shader_cache", "sandbox-flags" : [ "bind", "rec" ], "check-action-status": "false" }, { @@ -767,30 +762,14 @@ }, { "src-path": "/mnt/user//sharefs/docs", - "sandbox-path": "/mnt/storage/Users", - "sandbox-flags": [ "bind", "rec" ] - }, - { - "src-path": "/mnt/sandbox///mnt/storage/Users", "sandbox-path": "/storage/Users", - "sandbox-flags-customized": [ "MS_NODEV"], - "dac-override-sensitive": "true", - "fs-type": "sharefs", - "options": "override" + "sandbox-flags": [ "bind", "rec" ] }, { "src-path": "/mnt/data//userExternal", - "sandbox-path": "/mnt/storage/userExternal", + "sandbox-path": "/storage/userExternal", "sandbox-flags": [ "bind", "rec" ], "check-action-status": "false" - }, - { - "src-path": "/mnt/sandbox///mnt/storage/userExternal", - "sandbox-path": "/storage/userExternal", - "sandbox-flags-customized": [ "MS_NODEV" ], - "dac-override-sensitive": "true", - "fs-type": "sharefs", - "options": "override_support_delete" } ] }], @@ -950,7 +929,7 @@ "src-path" : "", "sandbox-path" : "", "sandbox-flags" : [], - "dec-paths": [ "/mnt/data/fuse" ] + "dec-paths": [ "/mnt/data/fuse", "/mnt/sandbox/*//storage/Users/currentUser" ] } ] }], @@ -1087,25 +1066,7 @@ "ohos.permission.READ_WRITE_USER_FILE":[{ "sandbox-switch": "ON", "gids": [1006], - "mount-paths": [{ - "src-path": "/storage/media//local/files/Docs", - "sandbox-path": "/storage/Users/", - "sandbox-flags": [ "bind", "rec" ], - "check-action-status": "false" - }, - { - "src-path": "/mnt/data/external", - "sandbox-path": "/storage/External", - "sandbox-flags": ["bind", "rec"], - "check-action-status": "false" - }, - { - "src-path": "/mnt/data//hmdfs", - "sandbox-path": "/storage/hmdfs", - "sandbox-flags": ["bind", "rec"], - "check-action-status": "false" - } - ] + "mount-paths": [] }], "ohos.permission.ACCESS_APP_CLONE_DIR":[{ "sandbox-switch": "ON", @@ -1126,6 +1087,11 @@ "sandbox-flags": ["bind", "rec"] } ] + }], + "ohos.permission.ACCESS_DFX_LOG_DIR":[{ + "sandbox-switch": "ON", + "gids":[1007], + "mount-paths": [] }] }] } diff --git a/appspawn.gni b/appspawn.gni index 3e32920ed534648b226c8ce02f59bb96280166ba..cdc3fa6221e99175a10e1b48b7bb60399871282b 100644 --- a/appspawn.gni +++ b/appspawn.gni @@ -36,8 +36,10 @@ declare_args() { appspawn_support_code_signature = true appspawn_allow_internet_permission = false appspawn_custom_sandbox = false + appspawn_support_nosharefs = false appspawn_support_local_debugger = false appspawn_hitrace_option = true + appspawn_napi_preload_path = "../appspawn_preload.json" } if (!defined(global_parts_info) || diff --git a/bundle.json b/bundle.json index ac0f60c472116c1cf504ec817af0306477021232..7b73228e1092dfbfdf64c7765a12639c85050992 100644 --- a/bundle.json +++ b/bundle.json @@ -29,7 +29,9 @@ "appspawn_support_code_signature", "appspawn_allow_internet_permission", "appspawn_custom_sandbox", - "appspawn_support_local_debugger" + "appspawn_support_nosharefs", + "appspawn_support_local_debugger", + "appspawn_napi_preload_path" ], "rom": "296KB", "ram": "13125KB", diff --git a/etc/BUILD.gn b/etc/BUILD.gn index b23fdfc13f3d8226ea4f50236ae343a692f91a7f..961814940dfed7e0643cf439b403ac7d35a071cd 100644 --- a/etc/BUILD.gn +++ b/etc/BUILD.gn @@ -73,7 +73,7 @@ if (defined(appspawn_sandbox_new) && appspawn_sandbox_new) { } ohos_prebuilt_etc("appspawn_preload.json") { - source = "../appspawn_preload.json" + source = appspawn_napi_preload_path part_name = "${part_name}" module_install_dir = "etc/appspawn" } diff --git a/modules/ace_adapter/ace_adapter.cpp b/modules/ace_adapter/ace_adapter.cpp index 37da3a22e9b2e6340837e24f64e2999ff8d9286b..1b00fe42a0d013d1913e92d26b1c167b6d9ec1f3 100644 --- a/modules/ace_adapter/ace_adapter.cpp +++ b/modules/ace_adapter/ace_adapter.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2024 Huawei Device Co., Ltd. + * Copyright (c) 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -49,6 +49,7 @@ static const bool DEFAULT_PRELOAD_VALUE = false; #else static const bool DEFAULT_PRELOAD_VALUE = true; #endif +static const bool DEFAULT_PRELOAD_ETS_VALUE = false; static const std::string PRELOAD_JSON_CONFIG("/appspawn_preload.json"); typedef struct TagParseJsonContext { @@ -84,11 +85,17 @@ static int GetModuleSet(const cJSON *root, ParseJsonContext *context) static void PreloadModule(void) { + bool preloadEts = OHOS::system::GetBoolParameter("persist.appspawn.preloadets", DEFAULT_PRELOAD_ETS_VALUE); + APPSPAWN_LOGI("LoadExtendLib: preloadets param value is %{public}s", preloadEts ? "true" : "false"); + OHOS::AbilityRuntime::Runtime::Options options; - options.lang = OHOS::AbilityRuntime::Runtime::Language::JS; options.loadAce = true; options.preload = true; - + if (preloadEts) { + options.lang = OHOS::AbilityRuntime::Runtime::Language::ETS; + } else { + options.lang = OHOS::AbilityRuntime::Runtime::Language::JS; + } auto runtime = OHOS::AbilityRuntime::Runtime::Create(options); if (!runtime) { APPSPAWN_LOGE("LoadExtendLib: Failed to create runtime"); @@ -108,7 +115,7 @@ static void PreloadModule(void) static void LoadExtendLib(void) { const char *acelibdir = OHOS::Ace::AceForwardCompatibility::GetAceLibName(); - APPSPAWN_LOGI("LoadExtendLib: Start calling dlopen acelibdir."); + APPSPAWN_LOGI("LoadExtendLib: Start calling dlopen acelibdir"); void *aceAbilityLib = dlopen(acelibdir, RTLD_NOW | RTLD_LOCAL); APPSPAWN_CHECK(aceAbilityLib != nullptr, return, "Fail to dlopen %{public}s, [%{public}s]", acelibdir, dlerror()); APPSPAWN_LOGI("LoadExtendLib: Success to dlopen %{public}s", acelibdir); @@ -116,22 +123,23 @@ static void LoadExtendLib(void) OHOS::AppExecFwk::MainThread::PreloadExtensionPlugin(); bool preload = OHOS::system::GetBoolParameter("persist.appspawn.preload", DEFAULT_PRELOAD_VALUE); if (!preload) { - APPSPAWN_LOGI("LoadExtendLib: Do not preload JS VM"); + APPSPAWN_LOGI("LoadExtendLib: Do not preload VM"); return; } - APPSPAWN_LOGI("LoadExtendLib: Start preload JS VM"); + APPSPAWN_LOGI("LoadExtendLib: Start preload VM"); SetTraceDisabled(true); PreloadModule(); SetTraceDisabled(false); + APPSPAWN_LOGI("LoadExtendLib: Start reclaim file cache"); OHOS::Ace::AceForwardCompatibility::ReclaimFileCache(getpid()); Resource::ResourceManager *systemResMgr = Resource::GetSystemResourceManagerNoSandBox(); APPSPAWN_CHECK(systemResMgr != nullptr, return, "Fail to get system resource manager"); - APPSPAWN_LOGI("LoadExtendLib: End preload JS VM"); + APPSPAWN_LOGI("LoadExtendLib: End preload VM"); } -APPSPAWN_STATIC void PreloadCJLibs(void) +static void PreloadCJLibs(void) { const char* cjEnvLibName = "libcj_environment.z.so"; const char* cjEnvInitName = "OHOS_InitSpawnEnv"; @@ -147,7 +155,7 @@ APPSPAWN_STATIC void PreloadCJLibs(void) initSpawnEnv(); } -APPSPAWN_STATIC void LoadExtendCJLib(void) +static void LoadExtendCJLib(void) { const char *acelibdir = OHOS::Ace::AceForwardCompatibility::GetAceLibName(); APPSPAWN_LOGI("LoadExtendLib: Start calling dlopen acelibdir."); @@ -160,7 +168,7 @@ APPSPAWN_STATIC void LoadExtendCJLib(void) PreloadCJLibs(); } -APPSPAWN_STATIC int BuildFdInfoMap(const AppSpawnMsgNode *message, std::map &fdMap, int isColdRun) +static int BuildFdInfoMap(const AppSpawnMsgNode *message, std::map &fdMap, int isColdRun) { APPSPAWN_CHECK_ONLY_EXPER(message != NULL && message->buffer != NULL, return -1); APPSPAWN_CHECK_ONLY_EXPER(message->tlvOffset != NULL, return -1); @@ -206,7 +214,7 @@ APPSPAWN_STATIC int BuildFdInfoMap(const AppSpawnMsgNode *message, std::map> BITLEN32); capData[0].permitted = (__u32)(permitted); @@ -157,6 +190,10 @@ static int SetCapabilities(const AppSpawnMgr *content, const AppSpawningCtx *pro // set capabilities isRet = capset(&capHeader, &capData[0]) != 0; APPSPAWN_CHECK(!isRet, return -errno, "Failed to capset errno: %{public}d", errno); +#ifdef APPSPAWN_SUPPORT_NOSHAREFS + isRet = SetAmbientCapabilities(property); + APPSPAWN_CHECK(!isRet, return -1, "Failed to set ambient"); +#endif return 0; } @@ -516,7 +553,7 @@ static int SpawnSetProperties(AppSpawnMgr *content, AppSpawningCtx *property) ret = SetCapabilities(content, property); APPSPAWN_CHECK_ONLY_EXPER(ret == 0, return ret); - ret = SetSelinuxCon(content, property) == -1; + ret = SetSelinuxCon(content, property); APPSPAWN_CHECK_ONLY_EXPER(ret == 0, return ret); ret = WaitForDebugger(property); diff --git a/modules/common/appspawn_encaps.c b/modules/common/appspawn_encaps.c index 3236e976b732994cb36379af9d3ed501616e3088..6d492d80bf6d7f015836519a07155f0a6a53b6a4 100644 --- a/modules/common/appspawn_encaps.c +++ b/modules/common/appspawn_encaps.c @@ -25,45 +25,44 @@ #include "appspawn_hook.h" #include "appspawn_manager.h" #include "appspawn_utils.h" +#include "appspawn_encaps.h" #define APP_ENCAPS "encaps" #define APP_OHOS_ENCAPS_COUNT_KEY "ohos.encaps.count" #define APP_OHOS_ENCAPS_FORK_KEY "ohos.encaps.fork.count" +#define APP_OHOS_ENCAPS_PERMISSIONS_KEY "permissions" #define MSG_EXT_NAME_MAX_DECIMAL 10 #define OH_APP_MAX_PIDS_NUM 512 #define OH_ENCAPS_PROC_TYPE_BASE 0x18 -#define OH_ENCAPS_PERMISSION_TYPE_BASE 0x1A +#define OH_ENCAPS_PERMISSION_TYPE_BASE 0x1E #define OH_ENCAPS_MAGIC 'E' #define OH_PROC_HAP 4 #define OH_ENCAPS_DEFAULT_FLAG 0 #define OH_ENCAPS_DEFAULT_STR "" +// permission value max len is 512 +#define OH_ENCAPS_VALUE_MAX_LEN 512 +// encapsCount max count is 64 +#define OH_ENCAPS_MAX_COUNT 64 #define SET_ENCAPS_PROC_TYPE_CMD _IOW(OH_ENCAPS_MAGIC, OH_ENCAPS_PROC_TYPE_BASE, uint32_t) -#define SET_ENCAPS_PERMISSION_TYPE_CMD _IOW(OH_ENCAPS_MAGIC, OH_ENCAPS_PERMISSION_TYPE_BASE, char *) +#define SET_ENCAPS_PERMISSION_TYPE_CMD _IOW(OH_ENCAPS_MAGIC, OH_ENCAPS_PERMISSION_TYPE_BASE, UserEncaps) -typedef enum { - ENCAPS_PROC_TYPE_MODE, // enable the encaps attribute of a process - ENCAPS_PERMISSION_TYPE_MODE, // set the encaps permission of a process - ENCAPS_MAX_TYPE_MODE -} AppSpawnEncapsBaseType; - -static int OpenEncapsFile(void) +APPSPAWN_STATIC int OpenEncapsFile(void) { int fd = 0; - fd = open("dev/encaps", O_RDWR); + fd = open("/dev/encaps", O_RDWR); if (fd < 0) { APPSPAWN_LOGW("Failed to open encaps file errno: %{public}d", errno); } return fd; } -static int WriteEncapsInfo(int fd, AppSpawnEncapsBaseType encapsType, const char *encapsInfo, uint32_t flag) +APPSPAWN_STATIC int WriteEncapsInfo(int fd, AppSpawnEncapsBaseType encapsType, const void *encapsInfo, uint32_t flag) { if (encapsInfo == NULL) { return APPSPAWN_ARG_INVALID; } - APPSPAWN_LOGV("root object: %{public}s", encapsInfo); int ret = 0; switch (encapsType) { @@ -74,10 +73,11 @@ static int WriteEncapsInfo(int fd, AppSpawnEncapsBaseType encapsType, const char ret = ioctl(fd, SET_ENCAPS_PERMISSION_TYPE_CMD, encapsInfo); break; default: + ret = APPSPAWN_ARG_INVALID; break; } if (ret != 0) { - APPSPAWN_LOGE("Encaps the setup failed ret: %{public}d fd: %{public}d maxPid: %{public}s", ret, fd, encapsInfo); + APPSPAWN_LOGE("Encaps the setup failed ret: %{public}d fd: %{public}d", ret, fd); return ret; } return 0; @@ -89,7 +89,7 @@ APPSPAWN_STATIC int EnableEncapsForProc(int encapsFileFd) return WriteEncapsInfo(encapsFileFd, ENCAPS_PROC_TYPE_MODE, OH_ENCAPS_DEFAULT_STR, flag); } -static uint32_t SpawnGetMaxPids(AppSpawnMgr *content, AppSpawningCtx *property) +APPSPAWN_STATIC uint32_t SpawnGetMaxPids(AppSpawningCtx *property) { uint32_t len = 0; char *pidMaxStr = GetAppPropertyExt(property, MSG_EXT_NAME_MAX_CHILD_PROCCESS_MAX, &len); @@ -108,26 +108,6 @@ static uint32_t SpawnGetMaxPids(AppSpawnMgr *content, AppSpawningCtx *property) return 0; } -/* set ohos.encaps.fork.count to encaps */ -static int SpawnSetMaxPids(AppSpawnMgr *content, AppSpawningCtx *property, cJSON *encaps) -{ - uint32_t maxPidCount = 0; - if (GetAppSpawnMsgType(property) != MSG_SPAWN_NATIVE_PROCESS) { - maxPidCount = SpawnGetMaxPids(content, property); - } - if (maxPidCount == 0 || maxPidCount > OH_APP_MAX_PIDS_NUM) { - APPSPAWN_LOGV("Don't need to set pid max count. Use default pid max"); - return APPSPAWN_PIDMGR_DEFAULT_PID_MAX; - } - - if (cJSON_AddNumberToObject(encaps, APP_OHOS_ENCAPS_FORK_KEY, maxPidCount) == NULL) { - APPSPAWN_LOGV("Add number to object failed.(ignore)"); - return APPSPAWN_PIDMGR_DEFAULT_PID_MAX; - } - - return 0; -} - static inline cJSON *GetJsonObjFromExtInfo(const AppSpawningCtx *property, const char *name) { uint32_t size = 0; @@ -141,196 +121,266 @@ static inline cJSON *GetJsonObjFromExtInfo(const AppSpawningCtx *property, const return extInfoJson; } -APPSPAWN_STATIC int AddPermissionArrayToItem(cJSON *encaps, const char *key, cJSON *permissionItemArr) +APPSPAWN_STATIC int AddPermissionStrToValue(const char *valueStr, UserEncap *encap) { - cJSON *arrayItem = permissionItemArr->child; - cJSON *newArray = cJSON_CreateArray(); - if (newArray == NULL) { - return APPSPAWN_ERROR_UTILS_CREATE_JSON_FAIL; + APPSPAWN_CHECK(valueStr != NULL, return APPSPAWN_ARG_INVALID, "Invalid string value"); + uint32_t valueLen = strlen(valueStr) + 1; + APPSPAWN_CHECK(valueLen > 1 && valueLen <= OH_ENCAPS_VALUE_MAX_LEN, return APPSPAWN_ARG_INVALID, + "String value len is invalied, len: %{public}u", valueLen); + char *value = (char *)calloc(1, valueLen); + APPSPAWN_CHECK(value != NULL, return APPSPAWN_SYSTEM_ERROR, "Failed to calloc value"); + + int ret = strcpy_s(value, valueLen, valueStr); + APPSPAWN_CHECK(ret == EOK, free(value); + return APPSPAWN_SYSTEM_ERROR, "Failed to copy string value"); + + encap->value.ptrValue = (void *)value; + encap->valueLen = valueLen; + encap->type = ENCAPS_CHAR_ARRAY; + return 0; +} + +APPSPAWN_STATIC int AddPermissionIntArrayToValue(cJSON *arrayItem, UserEncap *encap, int arraySize) +{ + uint32_t valueLen = sizeof(int) * arraySize; + APPSPAWN_CHECK(valueLen <= OH_ENCAPS_VALUE_MAX_LEN, return APPSPAWN_ARG_INVALID, + "Int array len too long, len: %{public}u", valueLen); + int *value = (int *)calloc(1, valueLen); + APPSPAWN_CHECK(value != NULL, return APPSPAWN_SYSTEM_ERROR, "Failed to calloc int array value"); + + cJSON *arrayItemTemp = arrayItem; + for (int index = 0; index < arraySize; index++) { + if (arrayItemTemp == NULL || !cJSON_IsNumber(arrayItemTemp)) { + free(value); + APPSPAWN_LOGE("Invalid int array item type"); + return APPSPAWN_ARG_INVALID; + } + value[index] = arrayItemTemp->valueint; + arrayItemTemp = arrayItemTemp->next; } - if (!cJSON_AddItemToObject(encaps, key, newArray)) { - cJSON_Delete(newArray); - return APPSPAWN_ERROR_UTILS_ADD_JSON_FAIL; + encap->value.ptrValue = (void *)value; + encap->valueLen = valueLen; + encap->type = ENCAPS_INT_ARRAY; + return 0; +} + +APPSPAWN_STATIC int AddPermissionBoolArrayToValue(cJSON *arrayItem, UserEncap *encap, int arraySize) +{ + uint32_t valueLen = sizeof(bool) * arraySize; + APPSPAWN_CHECK(valueLen <= OH_ENCAPS_VALUE_MAX_LEN, return APPSPAWN_ARG_INVALID, + "Bool array len too long, len: %{public}u", valueLen); + bool *value = (bool *)calloc(1, valueLen); + APPSPAWN_CHECK(value != NULL, return APPSPAWN_SYSTEM_ERROR, "Failed to calloc bool array value"); + + cJSON *arrayItemTemp = arrayItem; + for (int index = 0; index < arraySize; index++) { + if (arrayItemTemp == NULL || !cJSON_IsBool(arrayItemTemp)) { + free(value); + APPSPAWN_LOGE("Invalid bool array item type"); + return APPSPAWN_ARG_INVALID; + } + value[index] = cJSON_IsTrue(arrayItemTemp) ? true : false; + arrayItemTemp = arrayItemTemp->next; } + encap->value.ptrValue = (void *)value; + encap->valueLen = valueLen; + encap->type = ENCAPS_BOOL_ARRAY; + return 0; +} - while (arrayItem) { - cJSON *newItem = NULL; - if (cJSON_IsNumber(arrayItem)) { - newItem = cJSON_CreateNumber(arrayItem->valueint); - } else if (cJSON_IsString(arrayItem)) { - newItem = cJSON_CreateString(arrayItem->valuestring); - } else if (cJSON_IsBool(arrayItem)) { - newItem = cJSON_CreateBool(arrayItem->valueint); +APPSPAWN_STATIC int AddPermissionStrArrayToValue(cJSON *arrayItem, UserEncap *encap) +{ + uint32_t valueLen = 0; + for (cJSON *arrayItemTemp = arrayItem; arrayItemTemp != NULL; arrayItemTemp = arrayItemTemp->next) { + if (!cJSON_IsString(arrayItemTemp) || arrayItemTemp->valuestring == NULL) { + APPSPAWN_LOGE("Invalid string array item type"); + return APPSPAWN_ARG_INVALID; } + uint32_t tempLen = strlen(arrayItemTemp->valuestring); + APPSPAWN_CHECK(tempLen > 0, return APPSPAWN_ARG_INVALID, "String array value is invalied"); + valueLen += tempLen + 1; + } + + APPSPAWN_CHECK(valueLen > 0 && valueLen <= OH_ENCAPS_VALUE_MAX_LEN, return APPSPAWN_ARG_INVALID, + "String array len is invalied, len: %{public}u", valueLen); + char *value = (char *)calloc(1, valueLen); + APPSPAWN_CHECK(value != NULL, return APPSPAWN_SYSTEM_ERROR, "Failed to calloc string array value"); + + char *valuePtr = value; + for (cJSON *arrayItemTemp = arrayItem; arrayItemTemp != NULL; arrayItemTemp = arrayItemTemp->next) { + int len = strlen(arrayItemTemp->valuestring) + 1; + int ret = strcpy_s(valuePtr, len, arrayItemTemp->valuestring); + APPSPAWN_CHECK(ret == EOK, free(value); + return APPSPAWN_SYSTEM_ERROR, "Failed to copy string value"); + valuePtr += len; + } + encap->value.ptrValue = (void *)value; + encap->valueLen = valueLen; + encap->type = ENCAPS_CHAR_ARRAY; + return 0; +} - if (newItem == NULL || !cJSON_AddItemToArray(newArray, newItem)) { - cJSON_Delete(newItem); - return APPSPAWN_ERROR_UTILS_ADD_JSON_FAIL; +APPSPAWN_STATIC int AddPermissionArrayToValue(cJSON *permissionItemArr, UserEncap *encap) +{ + int arraySize = cJSON_GetArraySize(permissionItemArr); + if (arraySize == 0) { + return APPSPAWN_ARG_INVALID; + } + + // check first item type + cJSON *arrayItem = permissionItemArr->child; + if (cJSON_IsNumber(arrayItem)) { + if (AddPermissionIntArrayToValue(arrayItem, encap, arraySize) != 0) { + return APPSPAWN_ARG_INVALID; + } + } else if (cJSON_IsString(arrayItem)) { + if (AddPermissionStrArrayToValue(arrayItem, encap) != 0) { + return APPSPAWN_ARG_INVALID; + } + } else if (cJSON_IsBool(arrayItem)) { + if (AddPermissionBoolArrayToValue(arrayItem, encap, arraySize) != 0) { + return APPSPAWN_ARG_INVALID; } - arrayItem = arrayItem->next; + } else { + APPSPAWN_LOGW("Invalid array item type"); + return APPSPAWN_ARG_INVALID; } return 0; } -APPSPAWN_STATIC int AddPermissionItemToEncaps(cJSON *encaps, cJSON *permissionItem) +APPSPAWN_STATIC int AddPermissionItemToEncapsInfo(UserEncap *encap, cJSON *permissionItem) { - const char *key = permissionItem->string; + // copy json key + char *key = permissionItem->string; + if (key == NULL || strcpy_s(encap->key, OH_ENCAPS_KEY_MAX_LEN, key) != EOK) { + APPSPAWN_LOGE("Failed to copy json key"); + return APPSPAWN_SYSTEM_ERROR; + } + if (cJSON_IsNumber(permissionItem)) { - if (!cJSON_AddNumberToObject(encaps, key, permissionItem->valueint)) { - return APPSPAWN_ERROR_UTILS_ADD_JSON_FAIL; - } - } else if (cJSON_IsString(permissionItem)) { - if (!cJSON_AddStringToObject(encaps, key, permissionItem->valuestring)) { - return APPSPAWN_ERROR_UTILS_ADD_JSON_FAIL; - } + encap->type = ENCAPS_INT; + encap->value.intValue = (uint64_t)permissionItem->valueint; + encap->valueLen = sizeof(permissionItem->valueint); } else if (cJSON_IsBool(permissionItem)) { - if (!cJSON_AddBoolToObject(encaps, key, permissionItem->valueint)) { - return APPSPAWN_ERROR_UTILS_ADD_JSON_FAIL; + encap->type = ENCAPS_BOOL; + bool value = cJSON_IsTrue(permissionItem) ? true : false; + encap->value.intValue = (uint64_t)value; + encap->valueLen = sizeof(value); + } else if (cJSON_IsString(permissionItem)) { + if (AddPermissionStrToValue(permissionItem->valuestring, encap) != 0) { + return APPSPAWN_ARG_INVALID; } - } else if (cJSON_IsArray(permissionItem)) { - if (AddPermissionArrayToItem(encaps, key, permissionItem) != 0) { - return APPSPAWN_ERROR_UTILS_ADD_JSON_FAIL; + } else if (cJSON_IsArray(permissionItem)) { + if (AddPermissionArrayToValue(permissionItem, encap) != 0) { + return APPSPAWN_ARG_INVALID; } + } else { + APPSPAWN_LOGW("Invalid permission item type"); + return APPSPAWN_ARG_INVALID; } return 0; } -APPSPAWN_STATIC int AddPermissionToEncaps(cJSON *extInfoJson, cJSON *encaps, uint32_t *permissionCount) +APPSPAWN_STATIC int AddMembersToEncapsInfo(cJSON *extInfoJson, UserEncaps *encapsInfo) { // Get ohos.encaps.count - cJSON *countJson = cJSON_GetObjectItem(extInfoJson, "ohos.encaps.count"); - int encapsCount = 0; - if (cJSON_IsNumber(countJson)) { - encapsCount = countJson->valueint; - } + cJSON *countJson = cJSON_GetObjectItem(extInfoJson, APP_OHOS_ENCAPS_COUNT_KEY); + APPSPAWN_CHECK(countJson != NULL && cJSON_IsNumber(countJson), return APPSPAWN_ARG_INVALID, "Invalid countJson"); + int encapsCount = countJson->valueint; // Check input count and permissions size - cJSON *permissions = cJSON_GetObjectItemCaseSensitive(extInfoJson, "permissions"); - int count = cJSON_GetArraySize(permissions); - if (encapsCount != count) { - APPSPAWN_LOGE("Invalid args, encaps count: %{public}d, permission count: %{public}d", encapsCount, count); - return APPSPAWN_ARG_INVALID; - } + cJSON *permissionsJson = cJSON_GetObjectItemCaseSensitive(extInfoJson, APP_OHOS_ENCAPS_PERMISSIONS_KEY); + APPSPAWN_CHECK(permissionsJson != NULL && cJSON_IsArray(permissionsJson), return APPSPAWN_ARG_INVALID, + "Invalid permissionsJson"); + int count = cJSON_GetArraySize(permissionsJson); + APPSPAWN_CHECK(count > 0 && count <= OH_ENCAPS_MAX_COUNT && encapsCount == count, return APPSPAWN_ARG_INVALID, + "Invalid args, encaps count: %{public}d, permission count: %{public}d", encapsCount, count); + + encapsInfo->encap = (UserEncap *)calloc(count + 1, sizeof(UserEncap)); + APPSPAWN_CHECK(encapsInfo->encap != NULL, return APPSPAWN_SYSTEM_ERROR, "Failed to calloc encap"); - // If permissionName and permissionValue are obtained, they need to be written - // in the {"permissionName1":"permissionValue1", "permissionName2":"permissionValue2", ...} in the encaps. for (int i = 0; i < count; i++) { - // get single permission, such as {"permissionName1":"permissionValue1"} - cJSON *permission = cJSON_GetArrayItem(permissions, i); - if (permission == NULL) { - APPSPAWN_LOGE("encaps get single permission failed."); - return APPSPAWN_ERROR_UTILS_DECODE_JSON_FAIL; - } + cJSON *permission = cJSON_GetArrayItem(permissionsJson, i); + APPSPAWN_CHECK(permission != NULL, return APPSPAWN_ERROR_UTILS_DECODE_JSON_FAIL, + "Encaps get single permission failed") - // only one object in {}. So we only need to get first object. - // such as key:"permissionName1", value:"permissionValue1" cJSON *permissionItem = permission->child; - if (permissionItem == NULL) { - APPSPAWN_LOGE("encaps get permission item failed."); - return APPSPAWN_ERROR_UTILS_DECODE_JSON_FAIL; - } + APPSPAWN_CHECK(permissionItem != NULL, return APPSPAWN_ERROR_UTILS_DECODE_JSON_FAIL, + "Encaps get permission item failed") - if (AddPermissionItemToEncaps(encaps, permissionItem) != 0) { - APPSPAWN_LOGV("Add permission to object failed.(ignore)"); + if (AddPermissionItemToEncapsInfo(&encapsInfo->encap[i], permissionItem) != 0) { + APPSPAWN_LOGE("Add permission to encap failed"); return APPSPAWN_ERROR_UTILS_ADD_JSON_FAIL; } + encapsInfo->encapsCount++; } - *permissionCount += count; return 0; } -static int SpawnSetPermissions(AppSpawnMgr *content, AppSpawningCtx *property, cJSON *encaps, uint32_t *count) +APPSPAWN_STATIC void FreeEncapsInfo(UserEncaps *encapsInfo) { - cJSON *extInfoJson = GetJsonObjFromExtInfo(property, MSG_EXT_NAME_JIT_PERMISSIONS); - if (extInfoJson == NULL) { - return APPSPAWN_ARG_INVALID; - } - - int ret = AddPermissionToEncaps(extInfoJson, encaps, count); - if (ret != 0) { - APPSPAWN_LOGW("Add permission to object failed.(ignore), ret: %{public}d", ret); + APPSPAWN_CHECK_ONLY_EXPER(encapsInfo != NULL, return); + + if (encapsInfo->encap != NULL) { + for (uint32_t i = 0; i < encapsInfo->encapsCount; i++) { + if (encapsInfo->encap[i].type > ENCAPS_AS_ARRAY) { + free(encapsInfo->encap[i].value.ptrValue); + encapsInfo->encap[i].value.ptrValue = NULL; + } + } + free(encapsInfo->encap); + encapsInfo->encap = NULL; } - - cJSON_Delete(extInfoJson); - return ret; } -static int AddMembersToEncaps(AppSpawnMgr *content, AppSpawningCtx *property, cJSON *encaps) +/* set ohos.encaps.fork.count to encaps */ +static int SpawnSetMaxPids(AppSpawningCtx *property, UserEncaps *encapsInfo) { - uint32_t encapsPermissionCount = 0; - // need set ohos.encaps.count to encaps firstly - if (cJSON_AddNumberToObject(encaps, APP_OHOS_ENCAPS_COUNT_KEY, encapsPermissionCount) == NULL) { - APPSPAWN_LOGV("Set ohos.encaps.count to object failed.(ignore)"); - return APPSPAWN_ERROR_UTILS_ADD_JSON_FAIL; - } - - int ret = SpawnSetMaxPids(content, property, encaps); - if (ret != 0) { - APPSPAWN_LOGV("Can't set max pids to encaps object.(ignore), ret: %{public}d", ret); - } else { - encapsPermissionCount += 1; - } - - uint32_t count = 0; - ret = SpawnSetPermissions(content, property, encaps, &count); - if (ret != 0) { - APPSPAWN_LOGV("Can't set JIT permission to encaps object.(ignore), ret: %{public}d", ret); - } else { - encapsPermissionCount += count; + uint32_t maxPidCount = 0; + if (GetAppSpawnMsgType(property) != MSG_SPAWN_NATIVE_PROCESS) { + maxPidCount = SpawnGetMaxPids(property); } - if (encapsPermissionCount == 0) { - return APPSPAWN_ERROR_UTILS_ADD_JSON_FAIL; // Don't need set permission - } + APPSPAWN_CHECK(maxPidCount > 0 && maxPidCount < OH_APP_MAX_PIDS_NUM, return 0, + "Don't need to set pid max count %{public}u. Use default pid max", maxPidCount); + APPSPAWN_CHECK(encapsInfo->encapsCount < OH_ENCAPS_MAX_COUNT, + return APPSPAWN_ARG_INVALID, "Encaps count is more than 64, cannot set permissions"); - cJSON *encapsCountItem = cJSON_GetObjectItem(encaps, APP_OHOS_ENCAPS_COUNT_KEY); - if (encapsCountItem != NULL) { - cJSON_SetNumberValue(encapsCountItem, encapsPermissionCount); - } + int count = encapsInfo->encapsCount; + int ret = strcpy_s(encapsInfo->encap[count].key, OH_ENCAPS_KEY_MAX_LEN, APP_OHOS_ENCAPS_FORK_KEY); + APPSPAWN_CHECK_ONLY_EXPER(ret == EOK, return APPSPAWN_SYSTEM_ERROR); + encapsInfo->encap[count].value.intValue = (uint64_t)maxPidCount; + encapsInfo->encap[count].valueLen = sizeof(maxPidCount); + encapsInfo->encap[count].type = ENCAPS_INT; + encapsInfo->encapsCount++; return 0; } -static int SpawnBuildEncaps(AppSpawnMgr *content, AppSpawningCtx *property, char **encapsInfoStr) +APPSPAWN_STATIC int SpawnSetPermissions(AppSpawningCtx *property, UserEncaps *encapsInfo) { - // Create root object - cJSON *root = cJSON_CreateObject(); - if (root == NULL) { - return APPSPAWN_ERROR_UTILS_CREATE_JSON_FAIL; - } - - // Create encaps object - cJSON *encaps = cJSON_CreateObject(); - if (encaps == NULL) { - cJSON_Delete(root); - return APPSPAWN_ERROR_UTILS_CREATE_JSON_FAIL; + // Get Permissions obejct + cJSON *extInfoJson = GetJsonObjFromExtInfo(property, MSG_EXT_NAME_JIT_PERMISSIONS); + if (extInfoJson == NULL) { + APPSPAWN_LOGW("GetJsonObjFromExtInfo failed"); + return APPSPAWN_ARG_INVALID; } - int ret = AddMembersToEncaps(content, property, encaps); + int ret = AddMembersToEncapsInfo(extInfoJson, encapsInfo); if (ret != 0) { - APPSPAWN_LOGW("Add members to encaps object failed.(ignore), ret: %{public}d", ret); - cJSON_Delete(root); - cJSON_Delete(encaps); + APPSPAWN_LOGW("Add member to encaps failed, ret: %{public}d", ret); + cJSON_Delete(extInfoJson); return ret; } - if (cJSON_AddItemToObject(root, APP_ENCAPS, encaps) != true) { // add encaps object to root - cJSON_Delete(root); - cJSON_Delete(encaps); - APPSPAWN_LOGW("Add encaps object to root failed.(ignore)"); - return APPSPAWN_ERROR_UTILS_ADD_JSON_FAIL; - } - - *encapsInfoStr = cJSON_PrintUnformatted(root); // need to free - if (*encapsInfoStr == NULL) { - cJSON_Delete(root); - return APPSPAWN_ERROR_UTILS_DECODE_JSON_FAIL; - } + ret = SpawnSetMaxPids(property, encapsInfo); + APPSPAWN_CHECK(ret == 0, cJSON_Delete(extInfoJson); + return ret, "Set max pids count to encaps failed"); - cJSON_Delete(root); + cJSON_Delete(extInfoJson); return 0; } @@ -356,19 +406,19 @@ APPSPAWN_STATIC int SpawnSetEncapsPermissions(AppSpawnMgr *content, AppSpawningC return 0; // Can't enable encaps ability } - char *encapsInfoStr = NULL; - ret = SpawnBuildEncaps(content, property, &encapsInfoStr); + UserEncaps encapsInfo = {0}; + ret = SpawnSetPermissions(property, &encapsInfo); if (ret != 0) { close(encapsFileFd); - APPSPAWN_LOGW("Build encaps object failed, ret: %{public}d", ret); + FreeEncapsInfo(&encapsInfo); + APPSPAWN_LOGW("Build encaps info failed, ret: %{public}d", ret); return 0; // Can't set permission encpas ability } - (void)WriteEncapsInfo(encapsFileFd, ENCAPS_PERMISSION_TYPE_MODE, encapsInfoStr, OH_ENCAPS_DEFAULT_FLAG); + (void)WriteEncapsInfo(encapsFileFd, ENCAPS_PERMISSION_TYPE_MODE, &encapsInfo, OH_ENCAPS_DEFAULT_FLAG); + APPSPAWN_LOGV("Set encaps info finish"); - if (encapsInfoStr != NULL) { - free(encapsInfoStr); - } + FreeEncapsInfo(&encapsInfo); close(encapsFileFd); return 0; diff --git a/modules/common/appspawn_encaps.h b/modules/common/appspawn_encaps.h new file mode 100644 index 0000000000000000000000000000000000000000..70d3e9beedb32545ea48ad0c0b589ff0ed61df1f --- /dev/null +++ b/modules/common/appspawn_encaps.h @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2025-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APPSPAWN_ENCAPS_CPP +#define APPSPAWN_ENCAPS_CPP + +#ifdef __cplusplus +extern "C" { +#endif + +#define OH_ENCAPS_KEY_MAX_LEN 64 + +typedef enum { + ENCAPS_PROC_TYPE_MODE, // enable the encaps attribute of a process + ENCAPS_PERMISSION_TYPE_MODE, // set the encaps permission of a process + ENCAPS_MAX_TYPE_MODE +} AppSpawnEncapsBaseType; + +typedef enum { + ENCAPS_BOOL, + ENCAPS_INT, + ENCAPS_AS_ARRAY = 10, + ENCAPS_BOOL_ARRAY, + ENCAPS_INT_ARRAY, + ENCAPS_CHAR_ARRAY +} EncapsType; + +typedef struct { + char key[OH_ENCAPS_KEY_MAX_LEN]; + EncapsType type; + union { + uint64_t intValue; + void *ptrValue; + } value; + uint32_t valueLen; // valueLen < 512 +} UserEncap; + +typedef struct { + UserEncap *encap; + uint32_t encapsCount; +} UserEncaps; + +#ifdef __cplusplus +} +#endif +#endif diff --git a/modules/common/appspawn_namespace.c b/modules/common/appspawn_namespace.c index 8122410fee0cb3f3690732b197a201110b930bca..e128c4ae55627b5ed4c655c4882a9e69fb6a0323 100644 --- a/modules/common/appspawn_namespace.c +++ b/modules/common/appspawn_namespace.c @@ -39,7 +39,7 @@ typedef struct TagAppSpawnNamespace { } AppSpawnNamespace; APPSPAWN_STATIC pid_t GetPidByName(const char *name); -static int AppSpawnExtDataCompareDataId(ListNode *node, void *data) +APPSPAWN_STATIC int AppSpawnExtDataCompareDataId(ListNode *node, void *data) { AppSpawnExtData *extData = (AppSpawnExtData *)ListEntry(node, AppSpawnExtData, node); return extData->dataId - *(uint32_t *)data; @@ -223,7 +223,7 @@ APPSPAWN_STATIC int PreLoadEnablePidNs(AppSpawnMgr *content) } // after calling setns, new process will be in the same pid namespace of the input pid -static int SetPidNamespace(int nsPidFd, int nsType) +APPSPAWN_STATIC int SetPidNamespace(int nsPidFd, int nsType) { APPSPAWN_LOGI("SetPidNamespace 0x%{public}x", nsType); #ifndef APPSPAWN_TEST diff --git a/modules/sandbox/BUILD.gn b/modules/sandbox/BUILD.gn index 5464f7a9e83f882089086abb78695b72fc260a94..4d1226efe0635ea06f64fd022dfce046945fa94e 100644 --- a/modules/sandbox/BUILD.gn +++ b/modules/sandbox/BUILD.gn @@ -12,23 +12,12 @@ # limitations under the License. import("//base/startup/appspawn/appspawn.gni") +import("//base/startup/appspawn/modules/sandbox/sandbox.gni") import("//build/ohos.gni") if (defined(appspawn_sandbox_new) && appspawn_sandbox_new) { ohos_shared_library("appspawn_sandbox") { - sources = [ - "appspawn_mount_template.c", - "appspawn_permission.c", - "appspawn_sandbox.c", - "sandbox_adapter.cpp", - "sandbox_cfgvar.c", - "sandbox_debug_mode.c", - "sandbox_dec.c", - "sandbox_expand.c", - "sandbox_load.c", - "sandbox_manager.c", - "sandbox_shared.c", - ] + sources += appspawn_sandbox_src include_dirs = [ ".", @@ -36,6 +25,8 @@ if (defined(appspawn_sandbox_new) && appspawn_sandbox_new) { "${appspawn_path}/standard", ] + include_dirs += appspawn_sandbox_inc + configs = [ "${appspawn_path}:appspawn_config" ] defines = [ "APPSPAWN_SANDBOX_NEW" ] @@ -80,11 +71,8 @@ if (defined(appspawn_sandbox_new) && appspawn_sandbox_new) { ohos_shared_library("appspawn_sandbox") { sources = [ "${appspawn_innerkits_path}/permission/appspawn_mount_permission.c", - "appspawn_permission.c", - "sandbox_dec.c", - "sandbox_shared_mount.cpp", - "sandbox_utils.cpp", ] + sources += appspawn_sandbox_src include_dirs = [ ".", @@ -93,6 +81,7 @@ if (defined(appspawn_sandbox_new) && appspawn_sandbox_new) { "${appspawn_innerkits_path}/client", "${appspawn_innerkits_path}/permission", ] + include_dirs += appspawn_sandbox_inc configs = [ "${appspawn_path}:appspawn_config" ] @@ -125,6 +114,9 @@ if (defined(appspawn_sandbox_new) && appspawn_sandbox_new) { include_dirs += [ "${appspawn_path}/modules/sysevent" ] sources += [ "${appspawn_path}/modules/sysevent/hisysevent_adapter.cpp" ] } + if (appspawn_support_nosharefs) { + defines += [ "APPSPAWN_SUPPORT_NOSHAREFS" ] + } subsystem_name = "${subsystem_name}" part_name = "${part_name}" diff --git a/modules/sandbox/appspawn_mount_template.c b/modules/sandbox/modern/appspawn_mount_template.c similarity index 100% rename from modules/sandbox/appspawn_mount_template.c rename to modules/sandbox/modern/appspawn_mount_template.c diff --git a/modules/sandbox/appspawn_sandbox.c b/modules/sandbox/modern/appspawn_sandbox.c similarity index 100% rename from modules/sandbox/appspawn_sandbox.c rename to modules/sandbox/modern/appspawn_sandbox.c diff --git a/modules/sandbox/appspawn_sandbox.h b/modules/sandbox/modern/appspawn_sandbox.h similarity index 100% rename from modules/sandbox/appspawn_sandbox.h rename to modules/sandbox/modern/appspawn_sandbox.h diff --git a/modules/sandbox/sandbox_adapter.cpp b/modules/sandbox/modern/sandbox_adapter.cpp similarity index 100% rename from modules/sandbox/sandbox_adapter.cpp rename to modules/sandbox/modern/sandbox_adapter.cpp diff --git a/modules/sandbox/sandbox_adapter.h b/modules/sandbox/modern/sandbox_adapter.h similarity index 100% rename from modules/sandbox/sandbox_adapter.h rename to modules/sandbox/modern/sandbox_adapter.h diff --git a/modules/sandbox/sandbox_cfgvar.c b/modules/sandbox/modern/sandbox_cfgvar.c similarity index 100% rename from modules/sandbox/sandbox_cfgvar.c rename to modules/sandbox/modern/sandbox_cfgvar.c diff --git a/modules/sandbox/sandbox_debug_mode.c b/modules/sandbox/modern/sandbox_debug_mode.c similarity index 100% rename from modules/sandbox/sandbox_debug_mode.c rename to modules/sandbox/modern/sandbox_debug_mode.c diff --git a/modules/sandbox/sandbox_expand.c b/modules/sandbox/modern/sandbox_expand.c similarity index 100% rename from modules/sandbox/sandbox_expand.c rename to modules/sandbox/modern/sandbox_expand.c diff --git a/modules/sandbox/sandbox_load.c b/modules/sandbox/modern/sandbox_load.c similarity index 100% rename from modules/sandbox/sandbox_load.c rename to modules/sandbox/modern/sandbox_load.c diff --git a/modules/sandbox/sandbox_manager.c b/modules/sandbox/modern/sandbox_manager.c similarity index 100% rename from modules/sandbox/sandbox_manager.c rename to modules/sandbox/modern/sandbox_manager.c diff --git a/modules/sandbox/sandbox_shared.c b/modules/sandbox/modern/sandbox_shared.c similarity index 100% rename from modules/sandbox/sandbox_shared.c rename to modules/sandbox/modern/sandbox_shared.c diff --git a/modules/sandbox/sandbox_shared.h b/modules/sandbox/modern/sandbox_shared.h similarity index 100% rename from modules/sandbox/sandbox_shared.h rename to modules/sandbox/modern/sandbox_shared.h diff --git a/modules/sandbox/normal/appspawn_sandbox_manager.cpp b/modules/sandbox/normal/appspawn_sandbox_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..aa9224b2ef4d99e07f92103d057074915253d9c5 --- /dev/null +++ b/modules/sandbox/normal/appspawn_sandbox_manager.cpp @@ -0,0 +1,161 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "securec.h" +#include "appspawn_hook.h" +#include "appspawn_manager.h" +#include "appspawn_utils.h" +#include "sandbox_core.h" + +#define USER_ID_SIZE 16 +#define DIR_MODE 0711 + +int32_t SetAppSandboxProperty(AppSpawnMgr *content, AppSpawningCtx *property) +{ + APPSPAWN_CHECK(property != nullptr, return -1, "Invalid appspawn client"); + APPSPAWN_CHECK(content != nullptr, return -1, "Invalid appspawn content"); + // clear g_mountInfo in the child process + std::map* mapPtr = static_cast*>(GetEl1BundleMountCount()); + if (mapPtr == nullptr) { + APPSPAWN_LOGE("Get el1 bundle mount count failed"); + return APPSPAWN_ARG_INVALID; + } + mapPtr->clear(); + int ret = 0; + // no sandbox + if (CheckAppMsgFlagsSet(property, APP_FLAGS_NO_SANDBOX)) { + return 0; + } + if ((content->content.sandboxNsFlags & CLONE_NEWPID) == CLONE_NEWPID) { + ret = getprocpid(); + if (ret < 0) { + return ret; + } + } + uint32_t sandboxNsFlags = CLONE_NEWNS; + + if (OHOS::AppSpawn::SandboxCore::NeedNetworkIsolated(property)) { + sandboxNsFlags |= content->content.sandboxNsFlags & CLONE_NEWNET ? CLONE_NEWNET : 0; + } + + APPSPAWN_LOGV("SetAppSandboxProperty sandboxNsFlags 0x%{public}x", sandboxNsFlags); + + if (IsNWebSpawnMode(content)) { + ret = OHOS::AppSpawn::SandboxCore::SetAppSandboxPropertyNweb(property, sandboxNsFlags); + } else { + ret = OHOS::AppSpawn::SandboxCore::SetAppSandboxProperty(property, sandboxNsFlags); + } + // for module test do not create sandbox, use APP_FLAGS_IGNORE_SANDBOX to ignore sandbox result + if (CheckAppMsgFlagsSet(property, APP_FLAGS_IGNORE_SANDBOX)) { + APPSPAWN_LOGW("Do not care sandbox result %{public}d", ret); + return 0; + } + return ret; +} + +static int SpawnMountDirToShared(AppSpawnMgr *content, AppSpawningCtx *property) +{ +#ifndef APPSPAWN_SANDBOX_NEW + if (!IsNWebSpawnMode(content)) { + // mount dynamic directory + MountToShared(content, property); + } +#endif + return 0; +} + +static int UninstallDebugSandbox(AppSpawnMgr *content, AppSpawningCtx *property) +{ + APPSPAWN_CHECK(property != nullptr && content != nullptr, return -1, + "Invalid appspawn client or property"); + return OHOS::AppSpawn::SandboxCore::UninstallDebugSandbox(content, property); +} + +static int InstallDebugSandbox(AppSpawnMgr *content, AppSpawningCtx *property) +{ + APPSPAWN_CHECK(property != nullptr && content != nullptr, return -1, + "Invalid appspawn client or property"); + return OHOS::AppSpawn::SandboxCore::InstallDebugSandbox(content, property); +} + +static void UmountDir(const char *rootPath, const char *targetPath, const AppSpawnedProcessInfo *appInfo) +{ + size_t allPathSize = strlen(rootPath) + USER_ID_SIZE + strlen(appInfo->name) + strlen(targetPath) + 2; + char *path = reinterpret_cast(malloc(sizeof(char) * (allPathSize))); + APPSPAWN_CHECK(path != nullptr, return, "Failed to malloc path"); + + int ret = sprintf_s(path, allPathSize, "%s%u/%s%s", rootPath, appInfo->uid / UID_BASE, + appInfo->name, targetPath); + APPSPAWN_CHECK(ret > 0 && ((size_t)ret < allPathSize), free(path); + return, "Failed to get sandbox path errno %{public}d", errno); + + ret = umount2(path, MNT_DETACH); + if (ret == 0) { + APPSPAWN_LOGI("Umount2 sandbox path %{public}s success", path); + } else { + APPSPAWN_LOGW("Failed to umount2 sandbox path %{public}s errno %{public}d", path, errno); + } + free(path); +} + +static int UmountSandboxPath(const AppSpawnMgr *content, const AppSpawnedProcessInfo *appInfo) +{ + APPSPAWN_CHECK(content != nullptr && appInfo != nullptr && appInfo->name != NULL, + return -1, "Invalid content or appInfo"); + if (!IsAppSpawnMode(content)) { + return 0; + } + APPSPAWN_LOGV("UmountSandboxPath name %{public}s pid %{public}d", appInfo->name, appInfo->pid); + const char rootPath[] = "/mnt/sandbox/"; + const char el1Path[] = "/data/storage/el1/bundle"; + + std::string varBundleName = std::string(appInfo->name); + if (appInfo->appIndex > 0) { + varBundleName = "+clone-" + std::to_string(appInfo->appIndex) + "+" + varBundleName; + } + + uint32_t userId = appInfo->uid / UID_BASE; + std::string key = std::to_string(userId) + "-" + varBundleName; + std::map *el1BundleCountMap = static_cast*>(GetEl1BundleMountCount()); + if (el1BundleCountMap == nullptr || el1BundleCountMap->find(key) == el1BundleCountMap->end()) { + return 0; + } + (*el1BundleCountMap)[key]--; + if ((*el1BundleCountMap)[key] == 0) { + APPSPAWN_LOGV("no app %{public}s use it in userId %{public}u, need umount", appInfo->name, userId); + UmountDir(rootPath, el1Path, appInfo); + el1BundleCountMap->erase(key); + } else { + APPSPAWN_LOGV("app %{public}s use it mount times %{public}d in userId %{public}u, not need umount", + appInfo->name, (*el1BundleCountMap)[key], userId); + } + return 0; +} + +#ifndef APPSPAWN_SANDBOX_NEW +MODULE_CONSTRUCTOR(void) +{ + APPSPAWN_LOGV("Load sandbox module ..."); + (void)AddServerStageHook(STAGE_SERVER_PRELOAD, HOOK_PRIO_SANDBOX, + OHOS::AppSpawn::SandboxCommon::LoadAppSandboxConfigCJson); + (void)AddAppSpawnHook(STAGE_PARENT_PRE_FORK, HOOK_PRIO_COMMON, SpawnMountDirToShared); + (void)AddAppSpawnHook(STAGE_CHILD_EXECUTE, HOOK_PRIO_SANDBOX, SetAppSandboxProperty); + (void)AddAppSpawnHook(STAGE_PARENT_UNINSTALL, HOOK_PRIO_SANDBOX, UninstallDebugSandbox); + (void)AddAppSpawnHook(STAGE_PARENT_PRE_FORK, HOOK_PRIO_SANDBOX, InstallDebugSandbox); + (void)AddProcessMgrHook(STAGE_SERVER_APP_UMOUNT, HOOK_PRIO_SANDBOX, UmountSandboxPath); + (void)AddServerStageHook(STAGE_SERVER_EXIT, HOOK_PRIO_SANDBOX, + OHOS::AppSpawn::SandboxCommon::FreeAppSandboxConfigCJson); +} +#endif \ No newline at end of file diff --git a/modules/sandbox/normal/sandbox_common.cpp b/modules/sandbox/normal/sandbox_common.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7f8c9e87c201ca02c7db31cc00dffcac60f177d2 --- /dev/null +++ b/modules/sandbox/normal/sandbox_common.cpp @@ -0,0 +1,1008 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "sandbox_common.h" + +#include +#include +#include +#include +#include +#include +#include "appspawn_manager.h" +#include "appspawn_utils.h" +#include "sandbox_def.h" +#include "parameters.h" +#include "init_param.h" +#include "init_utils.h" +#include "parameter.h" +#include "config_policy_utils.h" + +#ifdef WITH_SELINUX +#include "hap_restorecon.h" +#ifdef APPSPAWN_MOUNT_TMPSHM +#include "policycoreutils.h" +#endif // APPSPAWN_MOUNT_TMPSHM +#endif // WITH_SELINUX + +namespace OHOS { +namespace AppSpawn { + +int32_t SandboxCommon::deviceTypeEnable_ = -1; +std::map> SandboxCommon::appSandboxCJsonConfig_ = {}; + +// 加载配置文件 +uint32_t SandboxCommon::GetSandboxNsFlags(bool isNweb) +{ + uint32_t nsFlags = 0; + if (!IsTotalSandboxEnabled(nullptr)) { + return nsFlags; + } + + const std::map NamespaceFlagsMap = { {"pid", CLONE_NEWPID}, + {"net", CLONE_NEWNET} }; + const char *prefixStr = + isNweb ? SandboxCommonDef::g_privatePrefix : SandboxCommonDef::g_commonPrefix; + const char *baseStr = isNweb ? SandboxCommonDef::g_ohosRender.c_str() : SandboxCommonDef::g_appBase; + + auto processor = [&baseStr, &NamespaceFlagsMap, &nsFlags](cJSON *item) { + cJSON *internal = cJSON_GetObjectItemCaseSensitive(item, baseStr); + if (!internal || !cJSON_IsArray(internal)) { + return 0; + } + + // 获取数组中第一个元素 + cJSON *firstElem = cJSON_GetArrayItem(internal, 0); + if (!firstElem) { + return 0; + } + + // 获取 "sandbox-ns-flags" 数组 + cJSON *nsFlagsJson = cJSON_GetObjectItemCaseSensitive(firstElem, SandboxCommonDef::g_sandBoxNsFlags); + if (!nsFlagsJson || !cJSON_IsArray(nsFlagsJson)) { + return 0; + } + cJSON *nsIte = nullptr; + cJSON_ArrayForEach(nsIte, nsFlagsJson) { + const char *sandboxNs = cJSON_GetStringValue(nsIte); + if (sandboxNs == nullptr) { + continue; + } + std::string sandboxNsStr = sandboxNs; + if (!NamespaceFlagsMap.count(sandboxNsStr)) { + continue; + } + nsFlags |= NamespaceFlagsMap.at(sandboxNsStr); + } + return 0; + }; + + for (auto& config : GetCJsonConfig(SandboxCommonDef::SANDBOX_APP_JSON_CONFIG)) { + // 获取 "individual" 数组 + cJSON *individual = cJSON_GetObjectItemCaseSensitive(config, prefixStr); + if (!individual || !cJSON_IsArray(individual)) { + return nsFlags; + } + (void)HandleArrayForeach(individual, processor); + } + + if (!nsFlags) { + APPSPAWN_LOGE("config is not found %{public}s ns config", isNweb ? "Nweb" : "App"); + } + return nsFlags; +} + +bool SandboxCommon::AppSandboxPidNsIsSupport(void) +{ + char buffer[10] = {0}; + uint32_t buffSize = sizeof(buffer); + + if (SystemGetParameter("const.sandbox.pidns.support", buffer, &buffSize) != 0) { + return true; + } + if (!strcmp(buffer, "false")) { + return false; + } + return true; +} + +void SandboxCommon::StoreCJsonConfig(cJSON *root, SandboxCommonDef::SandboxConfigType type) +{ + appSandboxCJsonConfig_[type].push_back(root); +} + +int32_t SandboxCommon::HandleArrayForeach(cJSON *arrayJson, ArrayItemProcessor processor) +{ + if (!arrayJson || !cJSON_IsArray(arrayJson) || !processor) { + return APPSPAWN_ERROR_UTILS_DECODE_JSON_FAIL; + } + + int ret = 0; + cJSON *item; + cJSON_ArrayForEach(item, arrayJson) { + ret = processor(item); + if (ret != 0) { + return ret; + } + } + return ret; +} + +int SandboxCommon::LoadAppSandboxConfigCJson(AppSpawnMgr *content) +{ + // load sandbox config + cJSON *sandboxCJsonRoot; + CfgFiles *files = GetCfgFiles("etc/sandbox"); + for (int i = 0; (files != nullptr) && (i < MAX_CFG_POLICY_DIRS_CNT); ++i) { + if (files->paths[i] == nullptr) { + continue; + } + std::string path = files->paths[i]; + std::string appPath = path + SandboxCommonDef::APP_JSON_CONFIG; + APPSPAWN_LOGI("LoadAppSandboxConfig %{public}s", appPath.c_str()); + sandboxCJsonRoot = GetJsonObjFromFile(appPath.c_str()); + APPSPAWN_CHECK((sandboxCJsonRoot != nullptr && cJSON_IsObject(sandboxCJsonRoot)), continue, + "Failed to load app data sandbox config %{public}s", appPath.c_str()); + StoreCJsonConfig(sandboxCJsonRoot, SandboxCommonDef::SANDBOX_APP_JSON_CONFIG); + + std::string isolatedPath = path + SandboxCommonDef::APP_ISOLATED_JSON_CONFIG; + APPSPAWN_LOGI("LoadAppSandboxConfig %{public}s", isolatedPath.c_str()); + sandboxCJsonRoot = GetJsonObjFromFile(isolatedPath.c_str()); + APPSPAWN_CHECK((sandboxCJsonRoot != nullptr && cJSON_IsObject(sandboxCJsonRoot)), continue, + "Failed to load app data sandbox config %{public}s", isolatedPath.c_str()); + StoreCJsonConfig(sandboxCJsonRoot, SandboxCommonDef::SANDBOX_ISOLATED_JSON_CONFIG); + } + FreeCfgFiles(files); + + bool isNweb = IsNWebSpawnMode(content); + if (!isNweb && !AppSandboxPidNsIsSupport()) { + return 0; + } + content->content.sandboxNsFlags = GetSandboxNsFlags(isNweb); + return 0; +} + +int SandboxCommon::FreeAppSandboxConfigCJson(AppSpawnMgr *content) +{ + UNUSED(content); + std::vector &normalJsonVec = GetCJsonConfig(SandboxCommonDef::SANDBOX_APP_JSON_CONFIG); + for (auto& normal : normalJsonVec) { + if (normal == nullptr) { + continue; + } + cJSON_Delete(normal); + normal = nullptr; + } + normalJsonVec.clear(); + + std::vector &isolatedJsonVec = GetCJsonConfig(SandboxCommonDef::SANDBOX_ISOLATED_JSON_CONFIG); + for (auto& isolated : isolatedJsonVec) { + if (isolated == nullptr) { + continue; + } + cJSON_Delete(isolated); + isolated = nullptr; + } + isolatedJsonVec.clear(); + return 0; +} + +std::vector &SandboxCommon::GetCJsonConfig(SandboxCommonDef::SandboxConfigType type) +{ + return appSandboxCJsonConfig_[type]; +} + +// 获取应用信息 +std::string SandboxCommon::GetExtraInfoByType(const AppSpawningCtx *appProperty, const std::string &type) +{ + uint32_t len = 0; + char *info = reinterpret_cast(GetAppPropertyExt(appProperty, type.c_str(), &len)); + if (info == nullptr) { + return ""; + } + return std::string(info, len); +} + +std::string SandboxCommon::GetSandboxRootPath(const AppSpawningCtx *appProperty, cJSON *config) +{ + AppSpawnMsgDacInfo *dacInfo = reinterpret_cast(GetAppProperty(appProperty, TLV_DAC_INFO)); + if (dacInfo == nullptr) { + return ""; + } + + std::string sandboxRoot = ""; + std::string isolatedFlagText = CheckAppMsgFlagsSet(appProperty, APP_FLAGS_ISOLATED_SANDBOX_TYPE) ? "isolated/" : ""; + AppSpawnMsgBundleInfo *bundleInfo = + reinterpret_cast(GetAppProperty(appProperty, TLV_BUNDLE_INFO)); + if (bundleInfo == nullptr) { + return ""; + } + std::string tmpBundlePath = bundleInfo->bundleName; + std::ostringstream variablePackageName; + if (CheckAppSpawnMsgFlag(appProperty->message, TLV_MSG_FLAGS, APP_FLAGS_CLONE_ENABLE)) { + variablePackageName << "+clone-" << bundleInfo->bundleIndex << "+" << bundleInfo->bundleName; + tmpBundlePath = variablePackageName.str(); + } + const std::string variableSandboxRoot = SandboxCommonDef::g_sandBoxRootDir + + std::to_string(dacInfo->uid / UID_BASE) + "/" + isolatedFlagText.c_str() + tmpBundlePath; + + const char *sandboxRootChr = GetStringFromJsonObj(config, SandboxCommonDef::g_sandboxRootPrefix); + if (sandboxRootChr != nullptr) { + sandboxRoot = sandboxRootChr; + if (sandboxRoot == SandboxCommonDef::g_originSandboxPath || + sandboxRoot == SandboxCommonDef::g_sandboxRootPathTemplate) { + sandboxRoot = variableSandboxRoot; + } else { + sandboxRoot = ConvertToRealPath(appProperty, sandboxRoot); + APPSPAWN_LOGV("set sandbox-root name is %{public}s", sandboxRoot.c_str()); + } + } else { + sandboxRoot = variableSandboxRoot; + APPSPAWN_LOGV("set sandbox-root to default rootapp name is %{public}s", GetBundleName(appProperty)); + } + + return sandboxRoot; +} + +int SandboxCommon::CreateDirRecursive(const std::string &path, mode_t mode) +{ + return MakeDirRec(path.c_str(), mode, 1); +} + +void SandboxCommon::CreateDirRecursiveWithClock(const std::string &path, mode_t mode) +{ + size_t size = path.size(); + if (size == 0) { + return; + } +#ifdef APPSPAWN_HISYSEVENT + struct timespec startClock = {0}; + clock_gettime(CLOCK_MONOTONIC, &startClock); +#endif + size_t index = 0; + do { + size_t pathIndex = path.find_first_of('/', index); + index = pathIndex == std::string::npos ? size : pathIndex + 1; + std::string dir = path.substr(0, index); +#ifndef APPSPAWN_TEST + APPSPAWN_CHECK(!(access(dir.c_str(), F_OK) < 0 && mkdir(dir.c_str(), mode) < 0), + return, "errno is %{public}d, mkdir %{public}s failed", errno, dir.c_str()); +#endif + } while (index < size); + +#ifdef APPSPAWN_HISYSEVENT + struct timespec endClock = {0}; + clock_gettime(CLOCK_MONOTONIC, &endClock); + uint64_t diff = DiffTime(&startClock, &endClock); + + APPSPAWN_CHECK_ONLY_EXPER(diff < FUNC_REPORT_DURATION, + ReportAbnormalDuration("MakeDirRecursive", diff)); +#endif +} + +bool SandboxCommon::VerifyDirRecursive(const std::string &path) +{ + size_t size = path.size(); + if (size == 0) { + return false; + } + size_t index = 0; + do { + size_t pathIndex = path.find_first_of('/', index); + index = pathIndex == std::string::npos ? size : pathIndex + 1; + std::string dir = path.substr(0, index); +#ifndef APPSPAWN_TEST + APPSPAWN_CHECK(access(dir.c_str(), F_OK) == 0, + return false, "check dir %{public}s failed, strerror: %{public}s", dir.c_str(), strerror(errno)); +#endif + } while (index < size); + return true; +} + +void SandboxCommon::CreateFileIfNotExist(const char *file) +{ + if (access(file, F_OK) == 0) { + APPSPAWN_LOGI("file %{public}s already exist", file); + return; + } + std::string path = file; + auto pos = path.find_last_of('/'); + APPSPAWN_CHECK(pos != std::string::npos, return, "file %{public}s error", file); + std::string dir = path.substr(0, pos); + (void)CreateDirRecursive(dir, SandboxCommonDef::FILE_MODE); + int fd = open(file, O_CREAT, SandboxCommonDef::FILE_MODE); + if (fd < 0) { + APPSPAWN_LOGW("failed create %{public}s, err=%{public}d", file, errno); + } else { + close(fd); + } + return; +} + +void SandboxCommon::SetSandboxPathChmod(cJSON *jsonConfig, std::string &sandboxRoot) +{ + const std::map modeMap = {{"S_IRUSR", S_IRUSR}, {"S_IWUSR", S_IWUSR}, {"S_IXUSR", S_IXUSR}, + {"S_IRGRP", S_IRGRP}, {"S_IWGRP", S_IWGRP}, {"S_IXGRP", S_IXGRP}, + {"S_IROTH", S_IROTH}, {"S_IWOTH", S_IWOTH}, {"S_IXOTH", S_IXOTH}, + {"S_IRWXU", S_IRWXU}, {"S_IRWXG", S_IRWXG}, {"S_IRWXO", S_IRWXO}}; + const char *fileMode = GetStringFromJsonObj(jsonConfig, SandboxCommonDef::g_destMode); + if (fileMode == nullptr) { + return; + } + + mode_t mode = 0; + std::string fileModeStr = fileMode; + std::vector modeVec = SplitString(fileModeStr, "|"); + for (unsigned int i = 0; i < modeVec.size(); i++) { + if (modeMap.count(modeVec[i])) { + mode |= modeMap.at(modeVec[i]); + } + } + + chmod(sandboxRoot.c_str(), mode); +} + +// 获取挂载配置参数信息 +unsigned long SandboxCommon::GetMountFlagsFromConfig(const std::vector &vec) +{ + const std::map MountFlagsMap = { {"rec", MS_REC}, {"MS_REC", MS_REC}, + {"bind", MS_BIND}, {"MS_BIND", MS_BIND}, + {"move", MS_MOVE}, {"MS_MOVE", MS_MOVE}, + {"slave", MS_SLAVE}, {"MS_SLAVE", MS_SLAVE}, + {"rdonly", MS_RDONLY}, {"MS_RDONLY", MS_RDONLY}, + {"shared", MS_SHARED}, {"MS_SHARED", MS_SHARED}, + {"unbindable", MS_UNBINDABLE}, + {"MS_UNBINDABLE", MS_UNBINDABLE}, + {"remount", MS_REMOUNT}, {"MS_REMOUNT", MS_REMOUNT}, + {"nosuid", MS_NOSUID}, {"MS_NOSUID", MS_NOSUID}, + {"nodev", MS_NODEV}, {"MS_NODEV", MS_NODEV}, + {"noexec", MS_NOEXEC}, {"MS_NOEXEC", MS_NOEXEC}, + {"noatime", MS_NOATIME}, {"MS_NOATIME", MS_NOATIME}, + {"lazytime", MS_LAZYTIME}, {"MS_LAZYTIME", MS_LAZYTIME}}; + + unsigned long mountFlags = 0; + for (unsigned int i = 0; i < vec.size(); i++) { + if (MountFlagsMap.count(vec[i])) { + mountFlags |= MountFlagsMap.at(vec[i]); + } + } + return mountFlags; +} + +bool SandboxCommon::IsDacOverrideEnabled(cJSON *config) // GetSandboxDacOverrideEnable +{ + return GetBoolValueFromJsonObj(config, SandboxCommonDef::g_dacOverrideSensitive, false); +} + +bool SandboxCommon::GetSwitchStatus(cJSON *config) // GetSbxSwitchStatusByConfig +{ + // if not find sandbox-switch node, default switch status is true + return GetBoolValueFromJsonObj(config, SandboxCommonDef::g_sandBoxSwitchPrefix, true); +} + +uint32_t SandboxCommon::ConvertFlagStr(const std::string &flagStr) +{ + const std::map flagsMap = {{"0", 0}, {"START_FLAGS_BACKUP", 1}, + {"DLP_MANAGER", 2}, + {"DEVELOPER_MODE", 17}, + {"PREINSTALLED_HAP", 29}, + {"CUSTOM_SANDBOX_HAP", 31}}; + + if (flagsMap.count(flagStr)) { + return 1 << flagsMap.at(flagStr); + } + return 0; +} + +unsigned long SandboxCommon::GetMountFlags(cJSON *config) // GetSandboxMountFlags +{ + unsigned long mountFlags = SandboxCommonDef::BASIC_MOUNT_FLAGS; + std::vector vec; + cJSON *customizedFlags = IsDacOverrideEnabled(config) ? + cJSON_GetObjectItemCaseSensitive(config, SandboxCommonDef::g_sandBoxFlagsCustomized) : + cJSON_GetObjectItemCaseSensitive(config, SandboxCommonDef::g_sandBoxFlags); + + if (!customizedFlags) { + customizedFlags = cJSON_GetObjectItemCaseSensitive(config, SandboxCommonDef::g_sandBoxFlags); + } + if (customizedFlags == nullptr || !cJSON_IsArray(customizedFlags)) { + return mountFlags; + } + + auto processor = [&vec](cJSON *item) { + const char *strItem = cJSON_GetStringValue(item); + if (strItem == nullptr) { + return -1; + } + vec.emplace_back(strItem); + return 0; + }; + + if (HandleArrayForeach(customizedFlags, processor) != 0) { + return mountFlags; + } + return GetMountFlagsFromConfig(vec); +} + +std::string SandboxCommon::GetFsType(cJSON *config) // GetSandboxFsType +{ + std::string fsType = ""; + const char *fsTypeChr = GetStringFromJsonObj(config, SandboxCommonDef::g_fsType); + if (fsTypeChr == nullptr) { + return fsType; + } + fsType = fsTypeChr; + return fsType; +} + +std::string SandboxCommon::GetOptions(const AppSpawningCtx *appProperty, cJSON *config) // GetSandboxOptions +{ + AppSpawnMsgDacInfo *dacInfo = reinterpret_cast(GetAppProperty(appProperty, TLV_DAC_INFO)); + if (dacInfo == nullptr) { + return ""; + } + + std::string options = ""; + const char *optionsChr = GetStringFromJsonObj(config, SandboxCommonDef::g_sandBoxOptions); + if (optionsChr == nullptr) { + return options; + } + options = optionsChr; + options += ",user_id=" + std::to_string(dacInfo->uid / UID_BASE); + return options; +} + +std::vector SandboxCommon::GetDecPath(const AppSpawningCtx *appProperty, cJSON *config) // GetSandboxDecPath +{ + AppSpawnMsgDacInfo *dacInfo = reinterpret_cast(GetAppProperty(appProperty, TLV_DAC_INFO)); + if (dacInfo == nullptr) { + return {}; + } + + std::vector decPaths = {}; + cJSON *decPathJson = cJSON_GetObjectItemCaseSensitive(config, SandboxCommonDef::g_sandBoxDecPath); + if (decPathJson == nullptr || !cJSON_IsArray(decPathJson)) { + return {}; + } + + auto processor = [&appProperty, &decPaths](cJSON *item) { + const char *strItem = cJSON_GetStringValue(item); + if (strItem == nullptr) { + return -1; + } + std::string decPath = ConvertToRealPath(appProperty, strItem); + decPaths.emplace_back(std::move(decPath)); + return 0; + }; + if (HandleArrayForeach(decPathJson, processor) != 0) { + return {}; + } + return decPaths; +} + +bool SandboxCommon::IsCreateSandboxPathEnabled(cJSON *json, std::string srcPath) // GetCreateSandboxPath +{ + bool isRet = GetBoolValueFromJsonObj(json, SandboxCommonDef::CREATE_SANDBOX_PATH, false); + if (isRet && access(srcPath.c_str(), F_OK) != 0) { + return false; + } + return true; +} + +bool SandboxCommon::IsTotalSandboxEnabled(const AppSpawningCtx *appProperty) // CheckTotalSandboxSwitchStatus +{ + SandboxCommonDef::SandboxConfigType type = CheckAppMsgFlagsSet(appProperty, APP_FLAGS_ISOLATED_SANDBOX_TYPE) ? + SandboxCommonDef::SANDBOX_ISOLATED_JSON_CONFIG : SandboxCommonDef::SANDBOX_APP_JSON_CONFIG; + + for (auto& wholeConfig : GetCJsonConfig(type)) { + // 获取 "common" 数组 + cJSON *common = cJSON_GetObjectItemCaseSensitive(wholeConfig, SandboxCommonDef::g_commonPrefix); + if (!common || !cJSON_IsArray(common)) { + continue; + } + // 获取第一个字段 + cJSON *firstCommon = cJSON_GetArrayItem(common, 0); + if (!firstCommon) { + continue; + } + return GetBoolValueFromJsonObj(firstCommon, SandboxCommonDef::g_topSandBoxSwitchPrefix, true); + } + // default sandbox switch is on + return true; +} + +bool SandboxCommon::IsAppSandboxEnabled(const AppSpawningCtx *appProperty) // CheckAppSandboxSwitchStatus +{ + SandboxCommonDef::SandboxConfigType type = CheckAppMsgFlagsSet(appProperty, APP_FLAGS_ISOLATED_SANDBOX_TYPE) ? + SandboxCommonDef::SANDBOX_ISOLATED_JSON_CONFIG : SandboxCommonDef::SANDBOX_APP_JSON_CONFIG; + + bool ret = true; + for (auto& wholeConfig : GetCJsonConfig(type)) { + // 获取 "individual" 数组 + cJSON *individual = cJSON_GetObjectItemCaseSensitive(wholeConfig, SandboxCommonDef::g_privatePrefix); + if (!individual || !cJSON_IsArray(individual)) { + continue; + } + cJSON *bundleNameInfo = cJSON_GetObjectItemCaseSensitive(individual, GetBundleName(appProperty)); + if (!bundleNameInfo || !cJSON_IsArray(bundleNameInfo)) { + continue; + } + // 获取第一个字段 + cJSON *firstCommon = cJSON_GetArrayItem(bundleNameInfo, 0); + if (!firstCommon) { + continue; + } + ret = GetSwitchStatus(firstCommon); + if (ret) { + break; + } + } + // default sandbox switch is on + return ret; +} + +void SandboxCommon::GetSandboxMountConfig(const AppSpawningCtx *appProperty, const std::string §ion, + cJSON *mntPoint, SandboxMountConfig &mountConfig) +{ + if (section.compare(SandboxCommonDef::g_permissionPrefix) == 0 || + section.compare(SandboxCommonDef::g_flagePoint) == 0 || + section.compare(SandboxCommonDef::g_debughap) == 0) { + mountConfig.optionsPoint = GetOptions(appProperty, mntPoint); + mountConfig.fsType = GetFsType(mntPoint); + mountConfig.decPaths = GetDecPath(appProperty, mntPoint); + } else { + mountConfig.fsType = GetFsType(mntPoint); + mountConfig.optionsPoint = ""; + mountConfig.decPaths = {}; + } + return; +} + +// 校验操作 +bool SandboxCommon::IsNeededCheckPathStatus(const AppSpawningCtx *appProperty, const char *path) +{ + if (strstr(path, "data/app/el1/") || strstr(path, "data/app/el2/")) { + return true; + } + if ((strstr(path, "data/app/el3/") || strstr(path, "data/app/el4/") || strstr(path, "data/app/el5/")) && + CheckAppMsgFlagsSet(appProperty, APP_FLAGS_UNLOCKED_STATUS)) { + return true; + } + return false; +} + +void SandboxCommon::CheckMountStatus(const std::string &path) +{ + std::ifstream file("/proc/self/mountinfo"); + if (!file.is_open()) { + APPSPAWN_LOGE("Failed to open /proc/self/mountinfo errno %{public}d", errno); + return; + } + + bool flag = false; + std::string line; + while (std::getline(file, line)) { + if (line.find(path) != std::string::npos) { + flag = true; + APPSPAWN_LOGI("Current mountinfo %{public}s", line.c_str()); + } + } + file.close(); + APPSPAWN_CHECK_ONLY_LOG(flag, "Mountinfo not contains %{public}s", path.c_str()); +} + +bool SandboxCommon::HasPrivateInBundleName(const std::string &bundleName) // CheckBundleNameForPrivate +{ + if (bundleName.find(SandboxCommonDef::g_internal) != std::string::npos) { + return false; + } + return true; +} + +bool SandboxCommon::IsMountSuccessful(cJSON *mntPoint) // GetCheckStatus +{ + // default false + return GetBoolValueFromJsonObj(mntPoint, SandboxCommonDef::g_actionStatuc, false); +} + +int SandboxCommon::CheckBundleName(const std::string &bundleName) +{ + if (bundleName.empty() || bundleName.size() > APP_LEN_BUNDLE_NAME) { + return -1; + } + if (bundleName.find('\\') != std::string::npos || bundleName.find('/') != std::string::npos) { + return -1; + } + return 0; +} + +int32_t SandboxCommon::CheckAppFullMountEnable() +{ + if (deviceTypeEnable_ != -1) { + return deviceTypeEnable_; + } + + char value[] = "false"; + int32_t ret = GetParameter("const.filemanager.full_mount.enable", "false", value, sizeof(value)); + if (ret > 0 && (strcmp(value, "true")) == 0) { + deviceTypeEnable_ = SandboxCommonDef::FILE_CROSS_APP_STATUS; + } else if (ret > 0 && (strcmp(value, "false")) == 0) { + deviceTypeEnable_ = SandboxCommonDef::FILE_ACCESS_COMMON_DIR_STATUS; + } else { + deviceTypeEnable_ = -1; + } + + return deviceTypeEnable_; +} + +bool SandboxCommon::IsPrivateSharedStatus(const std::string &bundleName, AppSpawningCtx *appProperty) +{ + bool result = false; + SandboxCommonDef::SandboxConfigType type = CheckAppMsgFlagsSet(appProperty, APP_FLAGS_ISOLATED_SANDBOX_TYPE) ? + SandboxCommonDef::SANDBOX_ISOLATED_JSON_CONFIG : SandboxCommonDef::SANDBOX_APP_JSON_CONFIG; + + for (auto& config : GetCJsonConfig(type)) { + // 获取 "individual" 数组 + cJSON *individual = cJSON_GetObjectItemCaseSensitive(config, SandboxCommonDef::g_privatePrefix); + if (!individual || !cJSON_IsArray(individual)) { + return result; + } + cJSON *bundleNameInfo = cJSON_GetObjectItemCaseSensitive(individual, bundleName.c_str()); + if (!bundleNameInfo || !cJSON_IsArray(bundleNameInfo)) { + return result; + } + result = GetBoolValueFromJsonObj(bundleNameInfo, SandboxCommonDef::g_sandBoxShared, false); + } + return result; +} + +bool SandboxCommon::IsValidMountConfig(cJSON *mntPoint, const AppSpawningCtx *appProperty, bool checkFlag) +{ + const char *srcPath = GetStringFromJsonObj(mntPoint, SandboxCommonDef::g_srcPath); + const char *sandboxPath = GetStringFromJsonObj(mntPoint, SandboxCommonDef::g_sandBoxPath); + cJSON *customizedFlags = cJSON_GetObjectItemCaseSensitive(mntPoint, SandboxCommonDef::g_sandBoxFlagsCustomized); + cJSON *flags = cJSON_GetObjectItemCaseSensitive(mntPoint, SandboxCommonDef::g_sandBoxFlags); + if (srcPath == nullptr || sandboxPath == nullptr || (customizedFlags == nullptr && flags == nullptr)) { + APPSPAWN_LOGE("read mount config failed, app name is %{public}s", GetBundleName(appProperty)); + return false; + } + + AppSpawnMsgDomainInfo *info = + reinterpret_cast(GetAppProperty(appProperty, TLV_DOMAIN_INFO)); + APPSPAWN_CHECK(info != nullptr, return false, "Filed to get domain info %{public}s", GetBundleName(appProperty)); + const char *appAplName = GetStringFromJsonObj(mntPoint, SandboxCommonDef::g_appAplName); + if (appAplName != nullptr) { + if (!strcmp(appAplName, info->apl)) { + return false; + } + } + + const std::string configSrcPath = srcPath; + // special handle wps and don't use /data/app/xxx/ config + if (checkFlag && (configSrcPath.find("/data/app") != std::string::npos && + (configSrcPath.find("/base") != std::string::npos || + configSrcPath.find("/database") != std::string::npos + ) && configSrcPath.find(SandboxCommonDef::g_packageName) != std::string::npos)) { + return false; + } + + return true; +} + +// 路径处理 +std::string SandboxCommon::ReplaceAllVariables(std::string str, const std::string& from, const std::string& to) +{ + while (true) { + std::string::size_type pos(0); + if ((pos = str.find(from)) != std::string::npos) { + str.replace(pos, from.length(), to); + } else { + break; + } + } + return str; +} + +std::vector SandboxCommon::SplitString(std::string &str, const std::string &delimiter) +{ + std::string::size_type pos; + std::vector result; + str += delimiter; + size_t size = str.size(); + for (unsigned int i = 0; i < size; i++) { + pos = str.find(delimiter, i); + if (pos < size) { + std::string s = str.substr(i, pos - i); + result.push_back(s); + i = pos + delimiter.size() - 1; + } + } + + return result; +} + +void SandboxCommon::MakeAtomicServiceDir(const AppSpawningCtx *appProperty, std::string path, + std::string variablePackageName) +{ + AppSpawnMsgDacInfo *dacInfo = reinterpret_cast(GetAppProperty(appProperty, TLV_DAC_INFO)); + APPSPAWN_CHECK(dacInfo != nullptr, return, "No dac info in msg app property"); + if (path.find("/mnt/share") != std::string::npos) { + path = "/data/service/el2/" + std::to_string(dacInfo->uid / UID_BASE) + "/share/" + variablePackageName; + } + struct stat st = {}; + if (stat(path.c_str(), &st) == 0 && S_ISDIR(st.st_mode)) { + return; + } + + int ret = mkdir(path.c_str(), S_IRWXU); + APPSPAWN_CHECK(ret == 0, return, "mkdir %{public}s failed, errno %{public}d", path.c_str(), errno); + + if (path.find("/database") != std::string::npos || path.find("/data/service/el2") != std::string::npos) { + ret = chmod(path.c_str(), S_IRWXU | S_IRWXG | S_ISGID); + } else if (path.find("/log") != std::string::npos) { + ret = chmod(path.c_str(), S_IRWXU | S_IRWXG); + } + APPSPAWN_CHECK(ret == 0, return, "chmod %{public}s failed, errno %{public}d", path.c_str(), errno); + +#ifdef WITH_SELINUX + AppSpawnMsgDomainInfo *msgDomainInfo = + reinterpret_cast(GetAppProperty(appProperty, TLV_DOMAIN_INFO)); + APPSPAWN_CHECK(msgDomainInfo != nullptr, return, "No domain info for %{public}s", GetProcessName(appProperty)); + HapContext hapContext; + HapFileInfo hapFileInfo; + hapFileInfo.pathNameOrig.push_back(path); + hapFileInfo.apl = msgDomainInfo->apl; + hapFileInfo.packageName = GetBundleName(appProperty); + hapFileInfo.hapFlags = msgDomainInfo->hapFlags; + if (CheckAppMsgFlagsSet(appProperty, APP_FLAGS_DEBUGGABLE)) { + hapFileInfo.hapFlags |= SELINUX_HAP_DEBUGGABLE; + } + if ((path.find("/base") != std::string::npos) || (path.find("/database") != std::string::npos)) { + ret = hapContext.HapFileRestorecon(hapFileInfo); + APPSPAWN_CHECK(ret == 0, return, "set dir %{public}s selinuxLabel failed, apl %{public}s, ret %{public}d", + path.c_str(), hapFileInfo.apl.c_str(), ret); + } +#endif + if (path.find("/base") != std::string::npos || path.find("/data/service/el2") != std::string::npos) { + ret = chown(path.c_str(), dacInfo->uid, dacInfo->gid); + } else if (path.find("/database") != std::string::npos) { + ret = chown(path.c_str(), dacInfo->uid, DecodeGid("ddms")); + } else if (path.find("/log") != std::string::npos) { + ret = chown(path.c_str(), dacInfo->uid, DecodeGid("log")); + } + APPSPAWN_CHECK(ret == 0, return, "chown %{public}s failed, errno %{public}d", path.c_str(), errno); + return; +} + +std::string SandboxCommon::ReplaceVariablePackageName(const AppSpawningCtx *appProperty, const std::string &path) +{ + std::string tmpSandboxPath = path; + AppSpawnMsgBundleInfo *bundleInfo = + reinterpret_cast(GetAppProperty(appProperty, TLV_BUNDLE_INFO)); + APPSPAWN_CHECK(bundleInfo != nullptr, return "", "No bundle info in msg %{public}s", GetBundleName(appProperty)); + + char *extension; + uint32_t flags = CheckAppSpawnMsgFlag(appProperty->message, TLV_MSG_FLAGS, APP_FLAGS_ATOMIC_SERVICE) ? 0x4 : 0; + if (flags == 0) { + flags = (CheckAppSpawnMsgFlag(appProperty->message, TLV_MSG_FLAGS, APP_FLAGS_CLONE_ENABLE) && + bundleInfo->bundleIndex > 0) ? 0x1 : 0; + flags |= CheckAppSpawnMsgFlag(appProperty->message, TLV_MSG_FLAGS, APP_FLAGS_EXTENSION_SANDBOX) ? 0x2 : 0; + extension = reinterpret_cast( + GetAppSpawnMsgExtInfo(appProperty->message, MSG_EXT_NAME_APP_EXTENSION, nullptr)); + } + std::ostringstream variablePackageName; + switch (flags) { + case SANDBOX_PACKAGENAME_DEFAULT: // 0 default + variablePackageName << bundleInfo->bundleName; + break; + case SANDBOX_PACKAGENAME_CLONE: // 1 +clone-bundleIndex+packageName + variablePackageName << "+clone-" << bundleInfo->bundleIndex << "+" << bundleInfo->bundleName; + break; + case SANDBOX_PACKAGENAME_EXTENSION: { // 2 +extension-+packageName + APPSPAWN_CHECK(extension != nullptr, return "", "Invalid extension data "); + variablePackageName << "+extension-" << extension << "+" << bundleInfo->bundleName; + break; + } + case SANDBOX_PACKAGENAME_CLONE_AND_EXTENSION: { // 3 +clone-bundleIndex+extension-+packageName + APPSPAWN_CHECK(extension != nullptr, return "", "Invalid extension data "); + variablePackageName << "+clone-" << bundleInfo->bundleIndex << "+extension" << "-" << + extension << "+" << bundleInfo->bundleName; + break; + } + case SANDBOX_PACKAGENAME_ATOMIC_SERVICE: { // 4 +auid-+packageName + std::string accountId = GetExtraInfoByType(appProperty, MSG_EXT_NAME_ACCOUNT_ID); + variablePackageName << "+auid-" << accountId << "+" << bundleInfo->bundleName; + std::string atomicServicePath = path; + atomicServicePath = ReplaceAllVariables(atomicServicePath, SandboxCommonDef::g_variablePackageName, + variablePackageName.str()); + MakeAtomicServiceDir(appProperty, atomicServicePath, variablePackageName.str()); + break; + } + default: + variablePackageName << bundleInfo->bundleName; + break; + } + tmpSandboxPath = ReplaceAllVariables(tmpSandboxPath, SandboxCommonDef::g_variablePackageName, variablePackageName.str()); + APPSPAWN_LOGV("tmpSandboxPath %{public}s", tmpSandboxPath.c_str()); + return tmpSandboxPath; +} + +std::string SandboxCommon::ReplaceHostUserId(const AppSpawningCtx *appProperty, const std::string &path) +{ + std::string tmpSandboxPath = path; + int32_t uid = 0; + const char *userId = + (const char *)(GetAppSpawnMsgExtInfo(appProperty->message, MSG_EXT_NAME_PARENT_UID, nullptr)); + if (userId != nullptr) { + uid = atoi(userId); + } + tmpSandboxPath = ReplaceAllVariables(tmpSandboxPath, SandboxCommonDef::g_hostUserId, + std::to_string(uid / UID_BASE)); + APPSPAWN_LOGV("tmpSandboxPath %{public}s", tmpSandboxPath.c_str()); + return tmpSandboxPath; +} + +std::string SandboxCommon::ReplaceClonePackageName(const AppSpawningCtx *appProperty, const std::string &path) +{ + std::string tmpSandboxPath = path; + AppSpawnMsgBundleInfo *bundleInfo = + reinterpret_cast(GetAppProperty(appProperty, TLV_BUNDLE_INFO)); + APPSPAWN_CHECK(bundleInfo != nullptr, return "", "No bundle info in msg %{public}s", GetBundleName(appProperty)); + + std::string tmpBundlePath = bundleInfo->bundleName; + std::ostringstream variablePackageName; + if (CheckAppSpawnMsgFlag(appProperty->message, TLV_MSG_FLAGS, APP_FLAGS_CLONE_ENABLE)) { + variablePackageName << "+clone-" << bundleInfo->bundleIndex << "+" << bundleInfo->bundleName; + tmpBundlePath = variablePackageName.str(); + } + + tmpSandboxPath = ReplaceAllVariables(tmpSandboxPath, SandboxCommonDef::g_clonePackageName, tmpBundlePath); + APPSPAWN_LOGV("tmpSandboxPath %{public}s", tmpSandboxPath.c_str()); + return tmpSandboxPath; +} + +const std::string& SandboxCommon::GetArkWebPackageName(void) +{ + static std::string arkWebPackageName; + if (arkWebPackageName.empty()) { + arkWebPackageName = system::GetParameter(SandboxCommonDef::ARK_WEB_PERSIST_PACKAGE_NAME, ""); + } + return arkWebPackageName; +} + +std::string SandboxCommon::ConvertToRealPathWithPermission(const AppSpawningCtx *appProperty, std::string path) +{ + AppSpawnMsgBundleInfo *info = + reinterpret_cast(GetAppProperty(appProperty, TLV_BUNDLE_INFO)); + if (info == nullptr) { + return ""; + } + if (path.find(SandboxCommonDef::g_packageNameIndex) != std::string::npos) { + std::string bundleNameWithIndex = info->bundleName; + if (info->bundleIndex != 0) { + bundleNameWithIndex = std::to_string(info->bundleIndex) + "_" + bundleNameWithIndex; + } + path = ReplaceAllVariables(path, SandboxCommonDef::g_packageNameIndex, bundleNameWithIndex); + } + + if (path.find(SandboxCommonDef::g_packageName) != std::string::npos) { + path = ReplaceAllVariables(path, SandboxCommonDef::g_packageName, info->bundleName); + } + + if (path.find(SandboxCommonDef::g_userId) != std::string::npos) { + if (deviceTypeEnable_ == SandboxCommonDef::FILE_CROSS_APP_STATUS) { + path = ReplaceAllVariables(path, SandboxCommonDef::g_userId, "currentUser"); + } else if (deviceTypeEnable_ == SandboxCommonDef::FILE_ACCESS_COMMON_DIR_STATUS) { + path = ReplaceAllVariables(path, SandboxCommonDef::g_userId, "currentUser"); + } else { + return ""; + } + } + return path; +} + +std::string SandboxCommon::ConvertToRealPath(const AppSpawningCtx *appProperty, std::string path) +{ + AppSpawnMsgBundleInfo *info = + reinterpret_cast(GetAppProperty(appProperty, TLV_BUNDLE_INFO)); + AppSpawnMsgDacInfo *dacInfo = reinterpret_cast(GetAppProperty(appProperty, TLV_DAC_INFO)); + if (info == nullptr || dacInfo == nullptr) { + return ""; + } + if (path.find(SandboxCommonDef::g_packageNameIndex) != std::string::npos) { + std::string bundleNameWithIndex = info->bundleName; + if (info->bundleIndex != 0) { + bundleNameWithIndex = std::to_string(info->bundleIndex) + "_" + bundleNameWithIndex; + } + path = ReplaceAllVariables(path, SandboxCommonDef::g_packageNameIndex, bundleNameWithIndex); + } + + if (path.find(SandboxCommonDef::g_packageName) != std::string::npos) { + path = ReplaceAllVariables(path, SandboxCommonDef::g_packageName, info->bundleName); + } + + if (path.find(SandboxCommonDef::g_userId) != std::string::npos) { + path = ReplaceAllVariables(path, SandboxCommonDef::g_userId, std::to_string(dacInfo->uid / UID_BASE)); + } + + if (path.find(SandboxCommonDef::g_hostUserId) != std::string::npos) { + path = ReplaceHostUserId(appProperty, path); + } + + if (path.find(SandboxCommonDef::g_variablePackageName) != std::string::npos) { + path = ReplaceVariablePackageName(appProperty, path); + } + + if (path.find(SandboxCommonDef::g_clonePackageName) != std::string::npos) { + path = ReplaceClonePackageName(appProperty, path); + } + + if (path.find(SandboxCommonDef::g_arkWebPackageName) != std::string::npos) { + path = ReplaceAllVariables(path, SandboxCommonDef::g_arkWebPackageName, GetArkWebPackageName()); + APPSPAWN_LOGV("arkWeb sandbox, path %{public}s, package:%{public}s", + path.c_str(), GetArkWebPackageName().c_str()); + } + + return path; +} + +// 挂载操作 +int32_t SandboxCommon::DoAppSandboxMountOnce(const AppSpawningCtx *appProperty, const SharedMountArgs *arg) +{ + if (!(arg && arg->srcPath && arg->destPath && arg->srcPath[0] != '\0' && arg->destPath[0] != '\0')) { + return 0; + } + if (strstr(arg->srcPath, "system/etc/hosts") != nullptr || strstr(arg->srcPath, "system/etc/profile") != nullptr) { + CreateFileIfNotExist(arg->destPath); + } else { + (void)CreateDirRecursive(arg->destPath, SandboxCommonDef::FILE_MODE); + } + + int ret = 0; + // to mount fs and bind mount files or directory + struct timespec mountStart = {0}; + clock_gettime(CLOCK_MONOTONIC_COARSE, &mountStart); + APPSPAWN_LOGV("Bind mount %{public}s to %{public}s '%{public}s' '%{public}lu' '%{public}s' '%{public}u'", + arg->srcPath, arg->destPath, arg->fsType, arg->mountFlags, arg->options, arg->mountSharedFlag); + ret = mount(arg->srcPath, arg->destPath, arg->fsType, arg->mountFlags, arg->options); + struct timespec mountEnd = {0}; + clock_gettime(CLOCK_MONOTONIC_COARSE, &mountEnd); + uint64_t diff = DiffTime(&mountStart, &mountEnd); + APPSPAWN_CHECK_ONLY_LOG(diff < SandboxCommonDef::MAX_MOUNT_TIME, "mount %{public}s time %{public}" PRId64 " us", arg->srcPath, diff); +#ifdef APPSPAWN_HISYSEVENT + APPSPAWN_CHECK_ONLY_EXPER(diff < FUNC_REPORT_DURATION, ReportAbnormalDuration("MOUNT", diff)); +#endif + if (ret != 0) { + APPSPAWN_LOGI("errno is: %{public}d, bind mount %{public}s to %{public}s", errno, arg->srcPath, arg->destPath); + if (errno == ENOENT && IsNeededCheckPathStatus(appProperty, arg->srcPath)) { + VerifyDirRecursive(arg->srcPath); + } + return ret; + } + + ret = mount(nullptr, arg->destPath, nullptr, arg->mountSharedFlag, nullptr); + if (ret != 0) { + APPSPAWN_LOGI("errno is: %{public}d, private mount to %{public}s '%{public}u' failed", + errno, arg->destPath, arg->mountSharedFlag); + if (errno == EINVAL) { + CheckMountStatus(arg->destPath); + } + return ret; + } + return 0; +} + +} // namespace AppSpawn +} // namespace OHOS \ No newline at end of file diff --git a/modules/sandbox/normal/sandbox_common.h b/modules/sandbox/normal/sandbox_common.h new file mode 100644 index 0000000000000000000000000000000000000000..2bdee646c61f5ca81d95077fc6234c55d2904707 --- /dev/null +++ b/modules/sandbox/normal/sandbox_common.h @@ -0,0 +1,146 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SANDBOX_COMMON_H +#define SANDBOX_COMMON_H + +#include +#include +#include +#include +#include "sandbox_def.h" +#include "appspawn_msg.h" +#include "appspawn_server.h" +#include "appspawn_manager.h" +#include "sandbox_shared_mount.h" +#include "json_utils.h" + +namespace OHOS { +namespace AppSpawn { + +// 挂载选项 +typedef struct SandboxMountConfig { + unsigned long mountFlags; + std::string optionsPoint; + std::string fsType; + std::string sandboxPath; + std::vector decPaths; +} SandboxMountConfig; + +typedef struct MountPointProcessParams { + const AppSpawningCtx *appProperty; // 引用属性 + bool checkFlag; // 检查标志 + std::string section; // 分区名称 + std::string sandboxRoot; // 沙箱根路径 + std::string bundleName; // 包名 +} MountPointProcessParams; + +using ArrayItemProcessor = std::function; + +class SandboxCommon { + +public: + // 加载配置文件 + static int LoadAppSandboxConfigCJson(AppSpawnMgr *content); + static int FreeAppSandboxConfigCJson(AppSpawnMgr *content); + static void StoreJsonConfig(cJSON *appSandboxConfig, SandboxCommonDef::SandboxConfigType type); + static std::vector &GetCJsonConfig(SandboxCommonDef::SandboxConfigType type); // GetJsonConfig + + static int32_t HandleArrayForeach(cJSON *arrayJson, ArrayItemProcessor processor); + + // 获取应用信息 + static std::string GetExtraInfoByType(const AppSpawningCtx *appProperty, const std::string &type); + static std::string GetSandboxRootPath(const AppSpawningCtx *appProperty, cJSON *config); // GetSbxPathByConfig + + // 文件操作 + static int CreateDirRecursive(const std::string &path, mode_t mode); // MakeDirRecursive + static void CreateDirRecursiveWithClock(const std::string &path, mode_t mode); // MakeDirRecursiveWithClock + static void SetSandboxPathChmod(cJSON *jsonConfig, std::string &sandboxRoot); // DoSandboxChmod + + // 获取挂载配置参数信息 + static uint32_t ConvertFlagStr(const std::string &flagStr); + static unsigned long GetMountFlags(cJSON *config); // GetSandboxMountFlags + static bool IsCreateSandboxPathEnabled(cJSON *json, std::string srcPath); // GetCreateSandboxPath + static bool IsTotalSandboxEnabled(const AppSpawningCtx *appProperty); // CheckTotalSandboxSwitchStatus + static bool IsAppSandboxEnabled(const AppSpawningCtx *appProperty); // CheckAppSandboxSwitchStatus + static void GetSandboxMountConfig(const AppSpawningCtx *appProperty, const std::string §ion, + cJSON *mntPoint, SandboxMountConfig &mountConfig); + + // 校验操作 + static bool HasPrivateInBundleName(const std::string &bundleName); // CheckBundleNameForPrivate + static bool IsMountSuccessful(cJSON *mntPoint); // GetCheckStatus + static int CheckBundleName(const std::string &bundleName); + static bool IsValidMountConfig(cJSON *mntPoint, const AppSpawningCtx *appProperty, + bool checkFlag); // CheckMountConfig + static bool IsPrivateSharedStatus(const std::string &bundleName, + AppSpawningCtx *appProperty); // GetSandboxPrivateSharedStatus + static int32_t CheckAppFullMountEnable(); + + // 路径处理 + static std::vector SplitString(std::string &str, const std::string &delimiter); // split + static std::string ReplaceAllVariables(std::string str, const std::string& from, + const std::string& to); // replace_all + static std::string ConvertToRealPath(const AppSpawningCtx *appProperty, std::string path); + static std::string ConvertToRealPathWithPermission(const AppSpawningCtx *appProperty, std::string path); + + // 挂载操作 + static int32_t DoAppSandboxMountOnce(const AppSpawningCtx *appProperty, const SharedMountArgs *arg); + +private: + // 加载配置文件 + static uint32_t GetSandboxNsFlags(bool isNweb); + static bool AppSandboxPidNsIsSupport(void); + static void StoreCJsonConfig(cJSON *root, SandboxCommonDef::SandboxConfigType type); + + // 文件操作 + static bool VerifyDirRecursive(const std::string &path); // CheckDirRecursive + static void CreateFileIfNotExist(const char *file); // CheckAndCreatFile + + // 获取挂载配置参数信息 + static bool GetSwitchStatus(cJSON *config); // GetSbxSwitchStatusByConfig + static unsigned long GetMountFlagsFromConfig(const std::vector &vec); + static bool IsDacOverrideEnabled(cJSON *config); // GetSandboxDacOverrideEnable + static std::string GetFsType(cJSON *config); // GetSandboxFsType + static std::string GetOptions(const AppSpawningCtx *appProperty, cJSON *config); // GetSandboxOptions + static std::vector GetDecPath(const AppSpawningCtx *appProperty, cJSON *config); // GetSandboxDecPath + + // 校验操作 + static bool IsNeededCheckPathStatus(const AppSpawningCtx *appProperty, const char *path); + static void CheckMountStatus(const std::string &path); + + // 路径处理 + static std::string ReplaceVariablePackageName(const AppSpawningCtx *appProperty, const std::string &path); + static void MakeAtomicServiceDir(const AppSpawningCtx *appProperty, std::string path, + std::string variablePackageName); + static std::string ReplaceHostUserId(const AppSpawningCtx *appProperty, const std::string &path); + static std::string ReplaceClonePackageName(const AppSpawningCtx *appProperty, const std::string &path); + static const std::string &GetArkWebPackageName(void); + +private: + static int32_t deviceTypeEnable_; + static std::map> appSandboxCJsonConfig_; + typedef enum { + SANDBOX_PACKAGENAME_DEFAULT = 0, + SANDBOX_PACKAGENAME_CLONE, + SANDBOX_PACKAGENAME_EXTENSION, + SANDBOX_PACKAGENAME_CLONE_AND_EXTENSION, + SANDBOX_PACKAGENAME_ATOMIC_SERVICE, + } SandboxVarPackageNameType; +}; + +} // namespace AppSpawn +} // namespace OHOS + +#endif // SANDBOX_COMMON_H \ No newline at end of file diff --git a/modules/sandbox/normal/sandbox_core.cpp b/modules/sandbox/normal/sandbox_core.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ebecabb8ecb3cd3d238fc771d2c884a50cc9a3e6 --- /dev/null +++ b/modules/sandbox/normal/sandbox_core.cpp @@ -0,0 +1,1452 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "sandbox_core.h" + +#include +#include +#include +#include +#include +#include +#include "securec.h" +#include "appspawn_manager.h" +#include "appspawn_trace.h" +#include "appspawn_utils.h" +#include "sandbox_dec.h" +#include "sandbox_def.h" +#ifdef APPSPAWN_HISYSEVENT +#include "hisysevent_adapter.h" +#endif + +#ifdef WITH_DLP +#include "dlp_fuse_fd.h" +#endif + +namespace OHOS { +namespace AppSpawn { + +bool SandboxCore::NeedNetworkIsolated(AppSpawningCtx *property) +{ + int developerMode = IsDeveloperModeOpen(); + if (CheckAppMsgFlagsSet(property, APP_FLAGS_ISOLATED_SANDBOX) && !developerMode) { + return true; + } + + if (CheckAppMsgFlagsSet(property, APP_FLAGS_ISOLATED_NETWORK)) { + std::string extensionType = SandboxCommon::GetExtraInfoByType(property, MSG_EXT_NAME_EXTENSION_TYPE); + if (extensionType.length() == 0 || !developerMode) { + return true; + } + } + + return false; +} + +int SandboxCore::EnableSandboxNamespace(AppSpawningCtx *appProperty, uint32_t sandboxNsFlags) +{ +#ifdef APPSPAWN_HISYSEVENT + struct timespec startClock = {0}; + clock_gettime(CLOCK_MONOTONIC, &startClock); +#endif + int rc = unshare(sandboxNsFlags); +#ifdef APPSPAWN_HISYSEVENT + struct timespec endClock = {0}; + clock_gettime(CLOCK_MONOTONIC, &endClock); + uint64_t diff = DiffTime(&startClock, &endClock); + APPSPAWN_CHECK_ONLY_EXPER(diff < FUNC_REPORT_DURATION, ReportAbnormalDuration("unshare", diff)); +#endif + APPSPAWN_CHECK(rc == 0, return rc, "unshare %{public}s failed, err %{public}d", GetBundleName(appProperty), errno); + + if ((sandboxNsFlags & CLONE_NEWNET) == CLONE_NEWNET) { + rc = EnableNewNetNamespace(); + APPSPAWN_CHECK(rc == 0, return rc, "Set %{public}s new netnamespace failed", GetBundleName(appProperty)); + } + return 0; +} + +uint32_t SandboxCore::GetAppMsgFlags(const AppSpawningCtx *property) +{ + APPSPAWN_CHECK(property != nullptr && property->message != nullptr, + return 0, "Invalid property for name %{public}u", TLV_MSG_FLAGS); + AppSpawnMsgFlags *msgFlags = (AppSpawnMsgFlags *)GetAppSpawnMsgInfo(property->message, TLV_MSG_FLAGS); + APPSPAWN_CHECK(msgFlags != nullptr, + return 0, "No TLV_MSG_FLAGS in msg %{public}s", property->message->msgHeader.processName); + return msgFlags->flags[0]; +} + +bool SandboxCore::CheckMountFlag(const AppSpawningCtx *appProperty, const std::string bundleName, + cJSON *appConfig) +{ + const char *flagChr = GetStringFromJsonObj(appConfig, SandboxCommonDef::g_flags); + if (flagChr == nullptr) { + return false; + } + std::string flagStr(flagChr); + if (((SandboxCommon::ConvertFlagStr(flagStr) & GetAppMsgFlags(appProperty)) != 0) && + bundleName.find("wps") != std::string::npos) { + return true; + } + return false; +} + +void SandboxCore::UpdateMsgFlagsWithPermission(AppSpawningCtx *appProperty) +{ + int32_t processIndex = GetPermissionIndex(nullptr, SandboxCommonDef::GET_ALL_PROCESSES_MODE.c_str()); + if ((CheckAppPermissionFlagSet(appProperty, static_cast(processIndex)) == 0)) { + APPSPAWN_LOGV("Don't need set GET_ALL_PROCESSES_MODE flag"); + return; + } + + int ret = SetAppSpawnMsgFlag(appProperty->message, TLV_MSG_FLAGS, APP_FLAGS_GET_ALL_PROCESSES); + if (ret != 0) { + APPSPAWN_LOGV("Set GET_ALL_PROCESSES_MODE flag failed"); + } +} + +int32_t SandboxCore::UpdatePermissionFlags(AppSpawningCtx *appProperty) +{ + int32_t index = 0; + int32_t appFullMountStatus = SandboxCommon::CheckAppFullMountEnable(); + if (appFullMountStatus == SandboxCommonDef::FILE_CROSS_APP_STATUS) { + index = GetPermissionIndex(nullptr, SandboxCommonDef::FILE_CROSS_APP_MODE.c_str()); + } else if (appFullMountStatus == SandboxCommonDef::FILE_ACCESS_COMMON_DIR_STATUS) { + index = GetPermissionIndex(nullptr, SandboxCommonDef::FILE_ACCESS_COMMON_DIR_MODE.c_str()); + } + int32_t fileMgrIndex = GetPermissionIndex(nullptr, SandboxCommonDef::FILE_ACCESS_MANAGER_MODE.c_str()); + if (index > 0 && (CheckAppPermissionFlagSet(appProperty, static_cast(fileMgrIndex)) == 0)) { + return SetAppPermissionFlags(appProperty, index); + } + return 0; +} + +std::string SandboxCore::GetSandboxPath(const AppSpawningCtx *appProperty, cJSON *mntPoint, + const std::string §ion, std::string sandboxRoot) +{ + std::string sandboxPath = ""; + const char *tmpSandboxPathChr = GetStringFromJsonObj(mntPoint, SandboxCommonDef::g_sandBoxPath); + if (tmpSandboxPathChr == nullptr) { + return ""; + } + std::string tmpSandboxPath(tmpSandboxPathChr); + if (section.compare(SandboxCommonDef::g_permissionPrefix) == 0) { + sandboxPath = sandboxRoot + SandboxCommon::ConvertToRealPathWithPermission(appProperty, tmpSandboxPath); + } else { + sandboxPath = sandboxRoot + SandboxCommon::ConvertToRealPath(appProperty, tmpSandboxPath); + } + return sandboxPath; +} + +int32_t SandboxCore::DoDlpAppMountStrategy(const AppSpawningCtx *appProperty, const std::string &srcPath, + const std::string &sandboxPath, const std::string &fsType, unsigned long mountFlags) +{ + AppSpawnMsgDacInfo *dacInfo = reinterpret_cast(GetAppProperty(appProperty, TLV_DAC_INFO)); + if (dacInfo == nullptr) { + return -1; + } + + // umount fuse path, make sure that sandbox path is not a mount point + umount2(sandboxPath.c_str(), MNT_DETACH); + + int fd = open("/dev/fuse", O_RDWR); + APPSPAWN_CHECK(fd != -1, return -EINVAL, "open /dev/fuse failed, errno is %{public}d", errno); + + char options[SandboxCommonDef::OPTIONS_MAX_LEN]; + (void)sprintf_s(options, sizeof(options), "fd=%d," + "rootmode=40000,user_id=%u,group_id=%u,allow_other," + "context=\"u:object_r:dlp_fuse_file:s0\"," + "fscontext=u:object_r:dlp_fuse_file:s0", + fd, dacInfo->uid, dacInfo->gid); + + // To make sure destinationPath exist + (void)SandboxCommon::CreateDirRecursive(sandboxPath, SandboxCommonDef::FILE_MODE); + + int ret = 0; +#ifndef APPSPAWN_TEST + APPSPAWN_LOGV("Bind mount %{public}s to %{public}s '%{public}s' '%{public}lu' '%{public}s'", + srcPath.c_str(), sandboxPath.c_str(), fsType.c_str(), mountFlags, options); + ret = mount(srcPath.c_str(), sandboxPath.c_str(), fsType.c_str(), mountFlags, options); + APPSPAWN_CHECK(ret == 0, close(fd); + return ret, "DoDlpAppMountStrategy failed, bind mount %{public}s to %{public}s failed %{public}d", + srcPath.c_str(), sandboxPath.c_str(), errno); + + ret = mount(nullptr, sandboxPath.c_str(), nullptr, MS_SHARED, nullptr); + APPSPAWN_CHECK(ret == 0, close(fd); + return ret, "errno is: %{public}d, private mount to %{public}s failed", errno, sandboxPath.c_str()); +#endif + /* set DLP_FUSE_FD */ +#ifdef WITH_DLP + SetDlpFuseFd(fd); +#endif + return fd; +} + +int32_t SandboxCore::HandleSpecialAppMount(const AppSpawningCtx *appProperty, const std::string &srcPath, + const std::string &sandboxPath, const std::string &fsType, unsigned long mountFlags) +{ + std::string bundleName = GetBundleName(appProperty); + std::string processName = GetProcessName(appProperty); + /* dlp application mount strategy */ + /* dlp is an example, we should change to real bundle name later */ + if (bundleName.find(SandboxCommonDef::g_dlpBundleName) != std::string::npos && + processName.compare(SandboxCommonDef::g_dlpBundleName) == 0) { + if (!fsType.empty()) { + return DoDlpAppMountStrategy(appProperty, srcPath, sandboxPath, fsType, mountFlags); + } + } + return -1; +} + +cJSON *SandboxCore::GetPrivateJsonInfo(const AppSpawningCtx *appProperty, cJSON *wholeConfig) +{ + cJSON *firstPrivate = GetFirstCommonConfig(wholeConfig, SandboxCommonDef::g_privatePrefix); + if (!firstPrivate) { + return nullptr; + } + + const char *bundleName = GetBundleName(appProperty); + return GetFirstSubConfig(firstPrivate, bundleName); +} + +int32_t SandboxCore::DoSandboxFilePrivateBind(const AppSpawningCtx *appProperty, cJSON *wholeConfig) +{ + cJSON *bundleNameInfo = GetPrivateJsonInfo(appProperty, wholeConfig); + if (bundleNameInfo == nullptr) { + return 0; + } + (void)DoAddGid((AppSpawningCtx *)appProperty, bundleNameInfo, "", SandboxCommonDef::g_privatePrefix); + return DoAllMntPointsMount(appProperty, bundleNameInfo, nullptr, SandboxCommonDef::g_privatePrefix); +} + +int32_t SandboxCore::DoSandboxFilePrivateSymlink(const AppSpawningCtx *appProperty, cJSON *wholeConfig) +{ + cJSON *bundleNameInfo = GetPrivateJsonInfo(appProperty, wholeConfig); + if (bundleNameInfo == nullptr) { + return 0; + } + return DoAllSymlinkPointslink(appProperty, bundleNameInfo); +} + +int32_t SandboxCore::DoSandboxFilePrivateFlagsPointHandle(const AppSpawningCtx *appProperty, cJSON *wholeConfig) +{ + cJSON *bundleNameInfo = GetPrivateJsonInfo(appProperty, wholeConfig); + if (bundleNameInfo == nullptr) { + return 0; + } + return HandleFlagsPoint(appProperty, bundleNameInfo); +} + +int32_t SandboxCore::SetPrivateAppSandboxProperty_(const AppSpawningCtx *appProperty, cJSON *config) +{ + int ret = DoSandboxFilePrivateBind(appProperty, config); + APPSPAWN_CHECK(ret == 0, return ret, "DoSandboxFilePrivateBind failed"); + + ret = DoSandboxFilePrivateSymlink(appProperty, config); + APPSPAWN_CHECK_ONLY_LOG(ret == 0, "DoSandboxFilePrivateSymlink failed"); + + ret = DoSandboxFilePrivateFlagsPointHandle(appProperty, config); + APPSPAWN_CHECK_ONLY_LOG(ret == 0, "DoSandboxFilePrivateFlagsPointHandle failed"); + + return ret; +} + +int32_t SandboxCore::DoSandboxFilePermissionBind(AppSpawningCtx *appProperty, cJSON *wholeConfig) +{ + cJSON *permission = cJSON_GetObjectItemCaseSensitive(wholeConfig, SandboxCommonDef::g_permissionPrefix); + if (!permission || !cJSON_IsArray(permission)) { + return 0; + } + + auto processor = [&appProperty](cJSON *item) { + cJSON *permissionChild = item->child; + while (permissionChild != nullptr) { + int index = GetPermissionIndex(nullptr, permissionChild->string); + APPSPAWN_LOGV("DoSandboxFilePermissionBind %{public}s index %{public}d", permissionChild->string, index); + if (CheckAppPermissionFlagSet(appProperty, static_cast(index)) == 0) { + permissionChild = permissionChild->next; + continue; + } + DoAddGid(appProperty, permissionChild, permissionChild->string, SandboxCommonDef::g_permissionPrefix); + cJSON *permissionMountPaths = cJSON_GetArrayItem(permissionChild, 0); + if (!permissionMountPaths) { + permissionChild = permissionChild->next; + continue; + } + DoAddGid(appProperty, permissionMountPaths, permissionChild->string, SandboxCommonDef::g_permissionPrefix); + DoAllMntPointsMount(appProperty, permissionMountPaths, permissionChild->string, + SandboxCommonDef::g_permissionPrefix); + + permissionChild = permissionChild->next; + } + return 0; + }; + + return SandboxCommon::HandleArrayForeach(permission, processor); +} + +int32_t SandboxCore::SetPermissionAppSandboxProperty_(AppSpawningCtx *appProperty, cJSON *config) +{ + int ret = DoSandboxFilePermissionBind(appProperty, config); + APPSPAWN_CHECK(ret == 0, return ret, "DoSandboxFilePermissionBind failed"); + return ret; +} + +cJSON *SandboxCore::GetFirstCommonConfig(cJSON *wholeConfig, const char *prefix) +{ + cJSON *commonConfig = cJSON_GetObjectItemCaseSensitive(wholeConfig, prefix); + if (!commonConfig || !cJSON_IsArray(commonConfig)) { + return nullptr; + } + + return cJSON_GetArrayItem(commonConfig, 0); +} + +cJSON *SandboxCore::GetFirstSubConfig(cJSON *parent, const char *key) +{ + cJSON *config = cJSON_GetObjectItemCaseSensitive(parent, key); + if (!config || !cJSON_IsArray(config)) { + return nullptr; + } + + return cJSON_GetArrayItem(config, 0); +} + +int32_t SandboxCore::DoSandboxFileCommonBind(const AppSpawningCtx *appProperty, cJSON *wholeConfig) +{ + cJSON *firstCommon = GetFirstCommonConfig(wholeConfig, SandboxCommonDef::g_commonPrefix); + if (!firstCommon) { + return 0; + } + + cJSON *appBaseConfig = GetFirstSubConfig(firstCommon, SandboxCommonDef::g_appBase); + if (!appBaseConfig) { + return 0; + } + + int ret = DoAllMntPointsMount(appProperty, appBaseConfig, nullptr, SandboxCommonDef::g_appBase); + if (ret) { + return ret; + } + + cJSON *appResourcesConfig = GetFirstSubConfig(firstCommon, SandboxCommonDef::g_appResources); + if (!appResourcesConfig) { + return 0; + } + ret = DoAllMntPointsMount(appProperty, appResourcesConfig, nullptr, SandboxCommonDef::g_appResources); + return ret; +} + +int32_t SandboxCore::DoSandboxFileCommonSymlink(const AppSpawningCtx *appProperty, cJSON *wholeConfig) +{ + cJSON *firstCommon = GetFirstCommonConfig(wholeConfig, SandboxCommonDef::g_commonPrefix); + if (!firstCommon) { + return 0; + } + + cJSON *appBaseConfig = GetFirstSubConfig(firstCommon, SandboxCommonDef::g_appBase); + if (!appBaseConfig) { + return 0; + } + + int ret = DoAllSymlinkPointslink(appProperty, appBaseConfig); + if (ret) { + return ret; + } + + cJSON *appResourcesConfig = GetFirstSubConfig(firstCommon, SandboxCommonDef::g_appResources); + if (!appResourcesConfig) { + return 0; + } + ret = DoAllSymlinkPointslink(appProperty, appResourcesConfig); + return ret; +} + +int32_t SandboxCore::DoSandboxFileCommonFlagsPointHandle(const AppSpawningCtx *appProperty, cJSON *wholeConfig) +{ + cJSON *firstCommon = GetFirstCommonConfig(wholeConfig, SandboxCommonDef::g_commonPrefix); + if (!firstCommon) { + return 0; + } + + cJSON *appResoucesConfig = GetFirstSubConfig(firstCommon, SandboxCommonDef::g_appResources); + if (!appResoucesConfig) { + return 0; + } + + return HandleFlagsPoint(appProperty, appResoucesConfig); +} + +int32_t SandboxCore::SetCommonAppSandboxProperty_(const AppSpawningCtx *appProperty, cJSON *config) +{ + int rc = 0; + rc = DoSandboxFileCommonBind(appProperty, config); + APPSPAWN_CHECK(rc == 0, return rc, "DoSandboxFileCommonBind failed, %{public}s", GetBundleName(appProperty)); + + // if sandbox switch is off, don't do symlink work again + if (SandboxCommon::IsAppSandboxEnabled(appProperty) == true && + (SandboxCommon::IsTotalSandboxEnabled(appProperty) == true)) { + rc = DoSandboxFileCommonSymlink(appProperty, config); + APPSPAWN_CHECK(rc == 0, return rc, "DoSandboxFileCommonSymlink failed, %{public}s", GetBundleName(appProperty)); + } + + rc = DoSandboxFileCommonFlagsPointHandle(appProperty, config); + APPSPAWN_CHECK_ONLY_LOG(rc == 0, "DoSandboxFilePrivateFlagsPointHandle failed"); + + return rc; +} + +static inline bool CheckPath(const std::string& name) +{ + return !name.empty() && name != "." && name != ".." && name.find("/") == std::string::npos; +} + +static inline cJSON *GetJsonObjFromProperty(const AppSpawningCtx *appProperty, const char *name) +{ + uint32_t size = 0; + const char *extInfo = (char *)(GetAppSpawnMsgExtInfo(appProperty->message, name, &size)); + if (size == 0 || extInfo == nullptr) { + return nullptr; + } + APPSPAWN_LOGV("Get json name %{public}s value %{public}s", name, extInfo); + cJSON *root = cJSON_Parse(extInfo); + APPSPAWN_CHECK(root != nullptr, return nullptr, "Invalid ext info %{public}s for %{public}s", extInfo, name); + return root; +} + +int32_t SandboxCore::MountAllHsp(const AppSpawningCtx *appProperty, std::string &sandboxPackagePath) +{ + if (appProperty == nullptr || sandboxPackagePath == "") { + return 0; + } + int ret = 0; + cJSON *hspRoot = GetJsonObjFromProperty(appProperty, SandboxCommonDef::HSPLIST_SOCKET_TYPE.c_str()); + APPSPAWN_CHECK_ONLY_EXPER(hspRoot != nullptr && cJSON_IsObject(hspRoot), return 0); + + cJSON *bundles = cJSON_GetObjectItemCaseSensitive(hspRoot, "bundles"); + cJSON *modules = cJSON_GetObjectItemCaseSensitive(hspRoot, "modules"); + cJSON *versions = cJSON_GetObjectItemCaseSensitive(hspRoot, "versions"); + APPSPAWN_CHECK(bundles != nullptr && cJSON_IsArray(bundles), return -1, "MountAllHsp: invalid bundles"); + APPSPAWN_CHECK(modules != nullptr && cJSON_IsArray(modules), return -1, "MountAllHsp: invalid modules"); + APPSPAWN_CHECK(versions != nullptr && cJSON_IsArray(versions), return -1, "MountAllHsp: invalid versions"); + int count = cJSON_GetArraySize(bundles); + APPSPAWN_CHECK(count == cJSON_GetArraySize(modules), return -1, "MountAllHsp: sizes are not same"); + APPSPAWN_CHECK(count == cJSON_GetArraySize(versions), return -1, "MountAllHsp: sizes are not same"); + + APPSPAWN_LOGI("MountAllHsp app: %{public}s, count: %{public}d", GetBundleName(appProperty), count); + for (int i = 0; i < count; i++) { + if (!(cJSON_IsString(cJSON_GetArrayItem(bundles, i)) && cJSON_IsString(cJSON_GetArrayItem(modules, i)) && + cJSON_IsString(cJSON_GetArrayItem(versions, i)))) { + return -1; + } + const char *libBundleName = cJSON_GetStringValue(cJSON_GetArrayItem(bundles, i)); + const char *libModuleName = cJSON_GetStringValue(cJSON_GetArrayItem(modules, i)); + const char *libVersion = cJSON_GetStringValue(cJSON_GetArrayItem(versions, i)); + APPSPAWN_CHECK(libBundleName != nullptr && libModuleName != nullptr && libVersion != nullptr, + return -1, "MountAllHsp: config error"); + APPSPAWN_CHECK(CheckPath(libBundleName) && CheckPath(libModuleName) && CheckPath(libVersion), + return -1, "MountAllHsp: path error"); + + std::string libPhysicalPath = SandboxCommonDef::g_physicalAppInstallPath + libBundleName + "/" + + libVersion + "/" + libModuleName; + std::string mntPath = + sandboxPackagePath + SandboxCommonDef::g_sandboxHspInstallPath + libBundleName + "/" + libModuleName; + SharedMountArgs arg = { + .srcPath = libPhysicalPath.c_str(), + .destPath = mntPath.c_str() + }; + ret = SandboxCommon::DoAppSandboxMountOnce(appProperty, &arg); + APPSPAWN_CHECK(ret == 0, return 0, "mount library failed %{public}d", ret); + } + cJSON_Delete(hspRoot); + return 0; +} + +int32_t SandboxCore::MountAllGroup(const AppSpawningCtx *appProperty, std::string &sandboxPackagePath) +{ + if (appProperty == nullptr || sandboxPackagePath == "") { + return 0; + } + cJSON *dataGroupRoot = GetJsonObjFromProperty(appProperty, SandboxCommonDef::DATA_GROUP_SOCKET_TYPE.c_str()); + APPSPAWN_CHECK_ONLY_EXPER(dataGroupRoot != nullptr, return 0); + + mode_t mountSharedFlag = MS_SLAVE; + if (CheckAppMsgFlagsSet(appProperty, APP_FLAGS_ISOLATED_SANDBOX)) { + APPSPAWN_LOGV("Data group flags is isolated"); + mountSharedFlag |= MS_REMOUNT | MS_NODEV | MS_RDONLY | MS_BIND; + } + + auto processor = [&appProperty, &sandboxPackagePath, &mountSharedFlag](cJSON *item) { + APPSPAWN_CHECK(IsValidDataGroupItem(item), return -1, "MountAllGroup: data group item error"); + const char *srcPathChr = GetStringFromJsonObj(item, SandboxCommonDef::g_groupList_key_dir.c_str()); + if (srcPathChr == nullptr) { + return 0; + } + std::string srcPath(srcPathChr); + APPSPAWN_CHECK(!CheckPath(srcPath), return -1, "MountAllGroup: path error"); + const char *uuidChr = GetStringFromJsonObj(item, SandboxCommonDef::g_groupList_key_uuid.c_str()); + if (uuidChr == nullptr) { + return 0; + } + std::string uuidStr(uuidChr); + + int elxValue = GetElxInfoFromDir(srcPath.c_str()); + APPSPAWN_CHECK((elxValue >= EL2 && elxValue < ELX_MAX), return -1, "Get elx value failed"); + + const DataGroupSandboxPathTemplate *templateItem = GetDataGroupArgTemplate(elxValue); + APPSPAWN_CHECK(templateItem != nullptr, return -1, "Get data group arg template failed"); + + // If permission isn't null, need check permission flag + if (templateItem->permission != nullptr) { + int index = GetPermissionIndex(nullptr, templateItem->permission); + APPSPAWN_LOGV("mount dir no lock mount permission flag %{public}d", index); + if (CheckAppPermissionFlagSet(appProperty, static_cast(index)) == 0) { + return 0; + } + } + + std::string mntPath = sandboxPackagePath + templateItem->sandboxPath + uuidStr; + SharedMountArgs arg = { + .srcPath = srcPath.c_str(), + .destPath = mntPath.c_str(), + .mountSharedFlag = mountSharedFlag + }; + int result = SandboxCommon::DoAppSandboxMountOnce(appProperty, &arg); + if (result != 0) { + APPSPAWN_LOGE("mount el%{public}d datagroup failed", elxValue); + } + return 0; + }; + int ret = SandboxCommon::HandleArrayForeach(dataGroupRoot, processor); + cJSON_Delete(dataGroupRoot); + return ret; +} + +int32_t SandboxCore::ProcessMountPoint(cJSON *mntPoint, MountPointProcessParams ¶ms) +{ + APPSPAWN_CHECK_ONLY_EXPER(SandboxCommon::IsValidMountConfig(mntPoint, params.appProperty, params.checkFlag), + return 0); + const char *srcPathChr = GetStringFromJsonObj(mntPoint, SandboxCommonDef::g_srcPath); + const char *sandboxPathChr = GetStringFromJsonObj(mntPoint, SandboxCommonDef::g_sandBoxPath); + if (srcPathChr == nullptr || sandboxPathChr == nullptr) { + return 0; + } + std::string srcPath(srcPathChr); + std::string sandboxPath(sandboxPathChr); + srcPath = SandboxCommon::ConvertToRealPath(params.appProperty, srcPath); + APPSPAWN_CHECK_ONLY_EXPER(SandboxCommon::IsCreateSandboxPathEnabled(mntPoint, srcPath), return 0); + sandboxPath = GetSandboxPath(params.appProperty, mntPoint, params.section, params.sandboxRoot); + SandboxMountConfig mountConfig = {0}; + SandboxCommon::GetSandboxMountConfig(params.appProperty, params.section, mntPoint, mountConfig); + SharedMountArgs arg = { + .srcPath = srcPath.c_str(), + .destPath = sandboxPath.c_str(), + .fsType = mountConfig.fsType.c_str(), + .mountFlags = SandboxCommon::GetMountFlags(mntPoint), + .options = mountConfig.optionsPoint.c_str(), + .mountSharedFlag = + GetBoolValueFromJsonObj(mntPoint, SandboxCommonDef::g_mountSharedFlag, false) ? MS_SHARED : MS_SLAVE + }; + + /* if app mount failed for special strategy, we need deal with common mount config */ + int ret = HandleSpecialAppMount(params.appProperty, arg.srcPath, arg.destPath, arg.fsType, arg.mountFlags); + if (ret < 0) { + ret = SandboxCommon::DoAppSandboxMountOnce(params.appProperty, &arg); + } + APPSPAWN_CHECK(ret == 0 || !SandboxCommon::IsMountSuccessful(mntPoint), +#ifdef APPSPAWN_HISYSEVENT + ReportMountFail(params.bundleName.c_str(), arg.srcPath, arg.destPath, errno); + ret = APPSPAWN_SANDBOX_MOUNT_FAIL; +#endif + return ret, + "DoAppSandboxMountOnce section %{public}s failed, %{public}s", params.section.c_str(), arg.destPath); + SetDecPolicyWithPermission(params.appProperty, mountConfig); + SandboxCommon::SetSandboxPathChmod(mntPoint, params.sandboxRoot); + return 0; +} + +int32_t SandboxCore::DoAllMntPointsMount(const AppSpawningCtx *appProperty, cJSON *appConfig, + const char *typeName, const std::string §ion) +{ + std::string bundleName = GetBundleName(appProperty); + cJSON *mountPoints = cJSON_GetObjectItemCaseSensitive(appConfig, SandboxCommonDef::g_mountPrefix); + if (mountPoints == nullptr || !cJSON_IsArray(mountPoints)) { + APPSPAWN_LOGI("mount config is not found in %{public}s, app name is %{public}s", + section.c_str(), bundleName.c_str()); + return 0; + } + + std::string sandboxRoot = SandboxCommon::GetSandboxRootPath(appProperty, appConfig); + bool checkFlag = CheckMountFlag(appProperty, bundleName, appConfig); + MountPointProcessParams mountPointParams = { + .appProperty = appProperty, + .checkFlag = checkFlag, + .section = section, + .sandboxRoot = sandboxRoot, + .bundleName = bundleName + }; + + auto processor = [&mountPointParams](cJSON *mntPoint) { + return ProcessMountPoint(mntPoint, mountPointParams); + }; + + return SandboxCommon::HandleArrayForeach(mountPoints, processor); +} + +int32_t SandboxCore::DoAddGid(AppSpawningCtx *appProperty, cJSON *appConfig, + const char *permissionName, const std::string §ion) +{ + AppSpawnMsgDacInfo *dacInfo = reinterpret_cast(GetAppProperty(appProperty, TLV_DAC_INFO)); + if (dacInfo == nullptr) { + return 0; + } + + cJSON *mountPoints = cJSON_GetObjectItemCaseSensitive(appConfig, SandboxCommonDef::g_gidPrefix); + if (mountPoints == nullptr || !cJSON_IsArray(mountPoints)) { + return 0; + } + + std::string bundleName = GetBundleName(appProperty); + auto processor = [&dacInfo](cJSON *item) { + gid_t gid = 0; + if (cJSON_IsNumber(item)) { + gid = (gid_t)cJSON_GetNumberValue(item); + } + if (gid <= 0) { + return 0; + } + if (dacInfo->gidCount < APP_MAX_GIDS) { + dacInfo->gidTable[dacInfo->gidCount++] = gid; + } + return 0; + }; + + return SandboxCommon::HandleArrayForeach(mountPoints, processor); +} + +int32_t SandboxCore::DoAllSymlinkPointslink(const AppSpawningCtx *appProperty, cJSON *appConfig) +{ + cJSON *symlinkPoints = cJSON_GetObjectItemCaseSensitive(appConfig, SandboxCommonDef::g_symlinkPrefix); + if (symlinkPoints == nullptr || !cJSON_IsArray(symlinkPoints)) { + APPSPAWN_LOGV("symlink config is not found"); + return 0; + } + + std::string sandboxRoot = SandboxCommon::GetSandboxRootPath(appProperty, appConfig); + auto processor = [&appProperty, &sandboxRoot](cJSON *item) { + const char *targetNameChr = GetStringFromJsonObj(item, SandboxCommonDef::g_targetName); + const char *linkNameChr = GetStringFromJsonObj(item, SandboxCommonDef::g_linkName); + if (targetNameChr == nullptr || linkNameChr == nullptr) { + return 0; + } + std::string targetName(targetNameChr); + std::string linkName(linkNameChr); + targetName = SandboxCommon::ConvertToRealPath(appProperty, targetName); + linkName = sandboxRoot + SandboxCommon::ConvertToRealPath(appProperty, linkName); + int ret = symlink(targetName.c_str(), linkName.c_str()); + if (ret && errno != EEXIST && SandboxCommon::IsMountSuccessful(item)) { + APPSPAWN_LOGE("errno is %{public}d, symlink failed, %{public}s", errno, linkName.c_str()); + return -1; + } + SandboxCommon::SetSandboxPathChmod(item, sandboxRoot); + return 0; + }; + + return SandboxCommon::HandleArrayForeach(symlinkPoints, processor); +} + +int32_t SandboxCore::DoSandboxRootFolderCreateAdapt(std::string &sandboxPackagePath) +{ +#ifndef APPSPAWN_TEST + int rc = mount(nullptr, "/", nullptr, MS_REC | MS_SLAVE, nullptr); + APPSPAWN_CHECK(rc == 0, return rc, "set propagation slave failed"); +#endif + (void)SandboxCommon::CreateDirRecursive(sandboxPackagePath, SandboxCommonDef::FILE_MODE); + + // bind mount "/" to /mnt/sandbox// path + // rootfs: to do more resources bind mount here to get more strict resources constraints +#ifndef APPSPAWN_TEST + rc = mount("/", sandboxPackagePath.c_str(), nullptr, SandboxCommonDef::BASIC_MOUNT_FLAGS, nullptr); + APPSPAWN_CHECK(rc == 0, return rc, "mount bind / failed, %{public}d", errno); +#endif + return 0; +} + +int32_t SandboxCore::DoSandboxRootFolderCreate(const AppSpawningCtx *appProperty, std::string &sandboxPackagePath) +{ +#ifndef APPSPAWN_TEST + int rc = mount(nullptr, "/", nullptr, MS_REC | MS_SLAVE, nullptr); + if (rc) { + return rc; + } +#endif + SharedMountArgs arg = { + .srcPath = sandboxPackagePath.c_str(), + .destPath = sandboxPackagePath.c_str() + }; + SandboxCommon::DoAppSandboxMountOnce(appProperty, &arg); + + return 0; +} + +int32_t SandboxCore::HandleFlagsPoint(const AppSpawningCtx *appProperty, cJSON *appConfig) +{ + cJSON *flagsPoints = cJSON_GetObjectItemCaseSensitive(appConfig, SandboxCommonDef::g_flagePoint); + if (flagsPoints == nullptr || !cJSON_IsArray(flagsPoints)) { + APPSPAWN_LOGV("flag points config is not found"); + return 0; + } + + auto processor = [&appProperty](cJSON *item) { + const char *flagsChr = GetStringFromJsonObj(item, SandboxCommonDef::g_flags); + if (flagsChr == nullptr) { + return 0; + } + std::string flagsStr(flagsChr); + uint32_t flag = SandboxCommon::ConvertFlagStr(flagsStr); + if ((GetAppMsgFlags(appProperty) & flag) == 0) { + return 0; + } + return DoAllMntPointsMount(appProperty, item, nullptr, SandboxCommonDef::g_flagePoint); + }; + return SandboxCommon::HandleArrayForeach(flagsPoints, processor); +} + +int32_t SandboxCore::SetOverlayAppSandboxProperty(const AppSpawningCtx *appProperty, std::string &sandboxPackagePath) +{ + int ret = 0; + if (!CheckAppMsgFlagsSet(appProperty, APP_FLAGS_OVERLAY)) { + return ret; + } + + std::string overlayInfo = SandboxCommon::GetExtraInfoByType(appProperty, SandboxCommonDef::OVERLAY_SOCKET_TYPE); + std::set mountedSrcSet; + std::vector splits = SandboxCommon::SplitString(overlayInfo, SandboxCommonDef::g_overlayDecollator); + std::string sandboxOverlayPath = sandboxPackagePath + SandboxCommonDef::g_overlayPath; + for (auto hapPath : splits) { + size_t pathIndex = hapPath.find_last_of(SandboxCommonDef::g_fileSeparator); + if (pathIndex == std::string::npos) { + continue; + } + std::string srcPath = hapPath.substr(0, pathIndex); + if (mountedSrcSet.find(srcPath) != mountedSrcSet.end()) { + APPSPAWN_LOGV("%{public}s have mounted before, no need to mount twice.", srcPath.c_str()); + continue; + } + + auto bundleNameIndex = srcPath.find_last_of(SandboxCommonDef::g_fileSeparator); + std::string destPath = sandboxOverlayPath + srcPath.substr(bundleNameIndex + 1, srcPath.length()); + SharedMountArgs arg = { + .srcPath = srcPath.c_str(), + .destPath = destPath.c_str() + }; + int32_t retMount = SandboxCommon::DoAppSandboxMountOnce(appProperty, &arg); + if (retMount != 0) { + APPSPAWN_LOGE("fail to mount overlay path, src is %{public}s.", hapPath.c_str()); + ret = retMount; + } + + mountedSrcSet.emplace(srcPath); + } + return ret; +} + +int32_t SandboxCore::SetBundleResourceAppSandboxProperty(const AppSpawningCtx *appProperty, + std::string &sandboxPackagePath) +{ + if (!CheckAppMsgFlagsSet(appProperty, APP_FLAGS_BUNDLE_RESOURCES)) { + return 0; + } + + std::string destPath = sandboxPackagePath + SandboxCommonDef::g_bundleResourceDestPath; + SharedMountArgs arg = { + .srcPath = SandboxCommonDef::g_bundleResourceSrcPath.c_str(), + .destPath = destPath.c_str() + }; + return SandboxCommon::DoAppSandboxMountOnce(appProperty, &arg); +} + +int32_t SandboxCore::SetCommonAppSandboxProperty(const AppSpawningCtx *appProperty, std::string &sandboxPackagePath) +{ + int ret = 0; + SandboxCommonDef::SandboxConfigType type = CheckAppMsgFlagsSet(appProperty, APP_FLAGS_ISOLATED_SANDBOX_TYPE) ? + SandboxCommonDef::SANDBOX_ISOLATED_JSON_CONFIG : SandboxCommonDef::SANDBOX_APP_JSON_CONFIG; + + for (auto& jsonConfig : SandboxCommon::GetCJsonConfig(type)) { + ret = SetCommonAppSandboxProperty_(appProperty, jsonConfig); + APPSPAWN_CHECK(ret == 0, return ret, + "parse appdata config for common failed, %{public}s", sandboxPackagePath.c_str()); + } + + ret = MountAllHsp(appProperty, sandboxPackagePath); + APPSPAWN_CHECK(ret == 0, return ret, "mount extraInfo failed, %{public}s", sandboxPackagePath.c_str()); + + ret = MountAllGroup(appProperty, sandboxPackagePath); + APPSPAWN_CHECK(ret == 0, return ret, "mount groupList failed, %{public}s", sandboxPackagePath.c_str()); + + AppSpawnMsgDomainInfo *info = + reinterpret_cast(GetAppProperty(appProperty, TLV_DOMAIN_INFO)); + APPSPAWN_CHECK(info != nullptr, return -1, "No domain info %{public}s", sandboxPackagePath.c_str()); + if (strcmp(info->apl, SandboxCommonDef::APL_SYSTEM_BASIC.data()) == 0 || + strcmp(info->apl, SandboxCommonDef::APL_SYSTEM_CORE.data()) == 0 || + CheckAppMsgFlagsSet(appProperty, APP_FLAGS_ACCESS_BUNDLE_DIR)) { + // need permission check for system app here + std::string destbundlesPath = sandboxPackagePath + SandboxCommonDef::g_dataBundles; + SharedMountArgs arg = { + .srcPath = SandboxCommonDef::g_physicalAppInstallPath.c_str(), + .destPath = destbundlesPath.c_str() + }; + SandboxCommon::DoAppSandboxMountOnce(appProperty, &arg); + } + + return 0; +} + +int32_t SandboxCore::SetPrivateAppSandboxProperty(const AppSpawningCtx *appProperty) +{ + int ret = 0; + SandboxCommonDef::SandboxConfigType type = CheckAppMsgFlagsSet(appProperty, APP_FLAGS_ISOLATED_SANDBOX_TYPE) ? + SandboxCommonDef::SANDBOX_ISOLATED_JSON_CONFIG : SandboxCommonDef::SANDBOX_APP_JSON_CONFIG; + + for (auto& config : SandboxCommon::GetCJsonConfig(type)) { + ret = SetPrivateAppSandboxProperty_(appProperty, config); + APPSPAWN_CHECK(ret == 0, return ret, "parse adddata-sandbox config failed"); + } + return ret; +} + +int32_t SandboxCore::SetPermissionAppSandboxProperty(AppSpawningCtx *appProperty) +{ + int ret = 0; + SandboxCommonDef::SandboxConfigType type = CheckAppMsgFlagsSet(appProperty, APP_FLAGS_ISOLATED_SANDBOX_TYPE) ? + SandboxCommonDef::SANDBOX_ISOLATED_JSON_CONFIG : SandboxCommonDef::SANDBOX_APP_JSON_CONFIG; + + for (auto& config : SandboxCommon::GetCJsonConfig(type)) { + ret = SetPermissionAppSandboxProperty_(appProperty, config); + APPSPAWN_CHECK(ret == 0, return ret, "parse permission config failed"); + } + return ret; +} + +int32_t SandboxCore::SetSandboxProperty(AppSpawningCtx *appProperty, std::string &sandboxPackagePath) +{ + int32_t ret = 0; + const std::string bundleName = GetBundleName(appProperty); + ret = SetCommonAppSandboxProperty(appProperty, sandboxPackagePath); + APPSPAWN_CHECK(ret == 0, return ret, "SetCommonAppSandboxProperty failed, packagename is %{public}s", + bundleName.c_str()); + if (SandboxCommon::HasPrivateInBundleName(bundleName)) { + ret = SetPrivateAppSandboxProperty(appProperty); + APPSPAWN_CHECK(ret == 0, return ret, "SetPrivateAppSandboxProperty failed, packagename is %{public}s", + bundleName.c_str()); + } + ret = SetPermissionAppSandboxProperty(appProperty); + APPSPAWN_CHECK(ret == 0, return ret, "SetPermissionAppSandboxProperty failed, packagename is %{public}s", + bundleName.c_str()); + + ret = SetOverlayAppSandboxProperty(appProperty, sandboxPackagePath); + APPSPAWN_CHECK(ret == 0, return ret, "SetOverlayAppSandboxProperty failed, packagename is %{public}s", + bundleName.c_str()); + + ret = SetBundleResourceAppSandboxProperty(appProperty, sandboxPackagePath); + APPSPAWN_CHECK(ret == 0, return ret, "SetBundleResourceAppSandboxProperty failed, packagename is %{public}s", + bundleName.c_str()); + APPSPAWN_LOGV("Set appsandbox property success"); + return ret; +} + +int32_t SandboxCore::SetAppSandboxProperty(AppSpawningCtx *appProperty, uint32_t sandboxNsFlags) +{ + APPSPAWN_CHECK(appProperty != nullptr, return -1, "Invalid appspawn client"); + if (SandboxCommon::CheckBundleName(GetBundleName(appProperty)) != 0) { + return -1; + } + AppSpawnMsgDacInfo *dacInfo = reinterpret_cast(GetAppProperty(appProperty, TLV_DAC_INFO)); + if (dacInfo == nullptr) { + return -1; + } + + const std::string bundleName = GetBundleName(appProperty); + cJSON *tmpJson = nullptr; + std::string sandboxPackagePath = SandboxCommon::GetSandboxRootPath(appProperty, tmpJson); + SandboxCommon::CreateDirRecursiveWithClock(sandboxPackagePath.c_str(), SandboxCommonDef::FILE_MODE); + bool sandboxSharedStatus = SandboxCommon::IsPrivateSharedStatus(bundleName, appProperty) || + (CheckAppPermissionFlagSet(appProperty, static_cast(GetPermissionIndex(nullptr, + SandboxCommonDef::ACCESS_DLP_FILE_MODE.c_str()))) != 0); + + // add pid to a new mnt namespace + int rc = EnableSandboxNamespace(appProperty, sandboxNsFlags); + APPSPAWN_CHECK(rc == 0, return rc, "unshare failed, packagename is %{public}s", bundleName.c_str()); + if (UpdatePermissionFlags(appProperty) != 0) { + APPSPAWN_LOGW("Set app permission flag fail."); + return -1; + } + UpdateMsgFlagsWithPermission(appProperty); + // check app sandbox switch + if ((SandboxCommon::IsTotalSandboxEnabled(appProperty) == false) || + (SandboxCommon::IsAppSandboxEnabled(appProperty) == false)) { + rc = DoSandboxRootFolderCreateAdapt(sandboxPackagePath); + } else if (!sandboxSharedStatus) { + rc = DoSandboxRootFolderCreate(appProperty, sandboxPackagePath); + } + APPSPAWN_CHECK(rc == 0, return rc, "DoSandboxRootFolderCreate failed, %{public}s", bundleName.c_str()); + rc = SetSandboxProperty(appProperty, sandboxPackagePath); + APPSPAWN_CHECK(rc == 0, return rc, "SetSandboxProperty failed, %{public}s", bundleName.c_str()); + +#ifdef APPSPAWN_MOUNT_TMPSHM + MountDevShmPath(sandboxPackagePath); +#endif + +#ifndef APPSPAWN_TEST + rc = ChangeCurrentDir(sandboxPackagePath, bundleName, sandboxSharedStatus); + APPSPAWN_CHECK(rc == 0, return rc, "change current dir failed"); + APPSPAWN_LOGV("Change root dir success"); +#endif + SetDecWithDir(appProperty, dacInfo->uid / UID_BASE); + SetDecDenyWithDir(appProperty); + SetDecPolicy(); +#if defined(APPSPAWN_MOUNT_TMPSHM) && defined(WITH_SELINUX) + Restorecon(DEV_SHM_DIR); +#endif + return 0; +} + +int32_t SandboxCore::SetRenderSandboxPropertyNweb(const AppSpawningCtx *appProperty, std::string &sandboxPackagePath) +{ + char *processType = (char *)(GetAppSpawnMsgExtInfo(appProperty->message, MSG_EXT_NAME_PROCESS_TYPE, nullptr)); + APPSPAWN_CHECK(processType != nullptr, return -1, "Invalid processType data"); + SandboxCommonDef::SandboxConfigType type = CheckAppMsgFlagsSet(appProperty, APP_FLAGS_ISOLATED_SANDBOX_TYPE) ? + SandboxCommonDef::SANDBOX_ISOLATED_JSON_CONFIG : SandboxCommonDef::SANDBOX_APP_JSON_CONFIG; + + int ret = 0; + const char *bundleName = GetBundleName(appProperty); + for (auto& config : SandboxCommon::GetCJsonConfig(type)) { + cJSON *firstIndividual = GetFirstCommonConfig(config, SandboxCommonDef::g_privatePrefix); + if (!firstIndividual) { + continue; + } + if (strcmp(processType, "render") == 0) { + cJSON *renderInfo = GetFirstSubConfig(firstIndividual, SandboxCommonDef::g_ohosRender.c_str()); + if (!renderInfo) { + continue; + } + ret = DoAllMntPointsMount(appProperty, renderInfo, nullptr, SandboxCommonDef::g_ohosRender); + APPSPAWN_CHECK(ret == 0, return ret, "DoAllMntPointsMount failed, %{public}s", bundleName); + + ret = DoAllSymlinkPointslink(appProperty, renderInfo); + APPSPAWN_CHECK(ret == 0, return ret, "DoAllSymlinkPointslink failed, %{public}s", bundleName); + + ret = HandleFlagsPoint(appProperty, renderInfo); + APPSPAWN_CHECK_ONLY_LOG(ret == 0, "HandleFlagsPoint for render-sandbox failed, %{public}s", bundleName); + } else if (strcmp(processType, "gpu") == 0) { + cJSON *gpuInfo = GetFirstSubConfig(firstIndividual, SandboxCommonDef::g_ohosGpu.c_str()); + if (!gpuInfo) { + continue; + } + ret = DoAllMntPointsMount(appProperty, gpuInfo, nullptr, SandboxCommonDef::g_ohosGpu); + APPSPAWN_CHECK(ret == 0, return ret, "DoAllMntPointsMount failed, %{public}s", bundleName); + + ret = DoAllSymlinkPointslink(appProperty, gpuInfo); + APPSPAWN_CHECK(ret == 0, return ret, "DoAllSymlinkPointslink failed, %{public}s", bundleName); + + ret = HandleFlagsPoint(appProperty, gpuInfo); + APPSPAWN_CHECK_ONLY_LOG(ret == 0, "HandleFlagsPoint for gpu-sandbox failed, %{public}s", bundleName); + } + } + + return 0; +} + +int32_t SandboxCore::SetAppSandboxPropertyNweb(AppSpawningCtx *appProperty, uint32_t sandboxNsFlags) +{ + APPSPAWN_CHECK(appProperty != nullptr, return -1, "Invalid appspawn client"); + if (SandboxCommon::CheckBundleName(GetBundleName(appProperty)) != 0) { + return -1; + } + std::string sandboxPackagePath = SandboxCommonDef::g_sandBoxRootDirNweb; + const std::string bundleName = GetBundleName(appProperty); + bool sandboxSharedStatus = SandboxCommon::IsPrivateSharedStatus(bundleName, appProperty); + sandboxPackagePath += bundleName; + SandboxCommon::CreateDirRecursiveWithClock(sandboxPackagePath.c_str(), SandboxCommonDef::FILE_MODE); + + // add pid to a new mnt namespace + int rc = EnableSandboxNamespace(appProperty, sandboxNsFlags); + APPSPAWN_CHECK(rc == 0, return rc, "unshare failed, packagename is %{public}s", bundleName.c_str()); + + // check app sandbox switch + if ((SandboxCommon::IsTotalSandboxEnabled(appProperty) == false) || + (SandboxCommon::IsAppSandboxEnabled(appProperty) == false)) { + rc = DoSandboxRootFolderCreateAdapt(sandboxPackagePath); + } else if (!sandboxSharedStatus) { + rc = DoSandboxRootFolderCreate(appProperty, sandboxPackagePath); + } + APPSPAWN_CHECK(rc == 0, return rc, "DoSandboxRootFolderCreate failed, %{public}s", bundleName.c_str()); + // rendering process can be created by different apps, + // and the bundle names of these apps are different, + // so we can't use the method SetPrivateAppSandboxProperty + // which mount dirs by using bundle name. + rc = SetRenderSandboxPropertyNweb(appProperty, sandboxPackagePath); + APPSPAWN_CHECK(rc == 0, return rc, "SetRenderSandboxPropertyNweb for %{public}s failed", bundleName.c_str()); + + rc = SetOverlayAppSandboxProperty(appProperty, sandboxPackagePath); + APPSPAWN_CHECK(rc == 0, return rc, "SetOverlayAppSandboxProperty for %{public}s failed", bundleName.c_str()); + + rc = SetBundleResourceAppSandboxProperty(appProperty, sandboxPackagePath); + APPSPAWN_CHECK(rc == 0, return rc, "SetBundleResourceAppSandboxProperty for %{public}s failed", bundleName.c_str()); + +#ifndef APPSPAWN_TEST + rc = chdir(sandboxPackagePath.c_str()); + APPSPAWN_CHECK(rc == 0, return rc, "chdir %{public}s failed, err %{public}d", sandboxPackagePath.c_str(), errno); + + if (sandboxSharedStatus) { + rc = chroot(sandboxPackagePath.c_str()); + APPSPAWN_CHECK(rc == 0, return rc, "chroot %{public}s failed, err %{public}d", + sandboxPackagePath.c_str(), errno); + return 0; + } + + rc = syscall(SYS_pivot_root, sandboxPackagePath.c_str(), sandboxPackagePath.c_str()); + APPSPAWN_CHECK(rc == 0, return rc, "pivot %{public}s failed, err %{public}d", sandboxPackagePath.c_str(), errno); + + rc = umount2(".", MNT_DETACH); + APPSPAWN_CHECK(rc == 0, return rc, "MNT_DETACH failed, packagename is %{public}s", bundleName.c_str()); +#endif + return 0; +} + +int32_t SandboxCore::ChangeCurrentDir(std::string &sandboxPackagePath, const std::string &bundleName, + bool sandboxSharedStatus) +{ + int32_t ret = 0; + ret = chdir(sandboxPackagePath.c_str()); + APPSPAWN_CHECK(ret == 0, return ret, "chdir %{public}s failed, err %{public}d", sandboxPackagePath.c_str(), errno); + + if (sandboxSharedStatus) { + ret = chroot(sandboxPackagePath.c_str()); + APPSPAWN_CHECK(ret == 0, return ret, "chroot %{public}s failed, err %{public}d", + sandboxPackagePath.c_str(), errno); + return ret; + } + + ret = syscall(SYS_pivot_root, sandboxPackagePath.c_str(), sandboxPackagePath.c_str()); + APPSPAWN_CHECK(ret == 0, return ret, "pivot %{public}s failed, err %{public}d", sandboxPackagePath.c_str(), errno); + + ret = umount2(".", MNT_DETACH); + APPSPAWN_CHECK(ret == 0, return ret, "MNT_DETACH failed, packagename is %{public}s", bundleName.c_str()); + return ret; +} + + + +static const DecDenyPathTemplate DEC_DENY_PATH_MAP[] = { + {"ohos.permission.READ_WRITE_DOWNLOAD_DIRECTORY", "/storage/Users/currentUser/Download"}, + {"ohos.permission.READ_WRITE_DESKTOP_DIRECTORY", "/storage/Users/currentUser/Desktop"}, + {"ohos.permission.READ_WRITE_DOCUMENTS_DIRECTORY", "/storage/Users/currentUser/Documents"}, +}; + +int32_t SandboxCore::SetDecWithDir(const AppSpawningCtx *appProperty, uint32_t userId) +{ + AppSpawnMsgAccessToken *tokenInfo = + reinterpret_cast(GetAppProperty(appProperty, TLV_ACCESS_TOKEN_INFO)); + APPSPAWN_CHECK(tokenInfo != nullptr, return APPSPAWN_MSG_INVALID, "Get token id failed."); + + AppSpawnMsgBundleInfo *bundleInfo = + reinterpret_cast(GetAppProperty(appProperty, TLV_BUNDLE_INFO)); + APPSPAWN_CHECK(bundleInfo != nullptr, return APPSPAWN_MSG_INVALID, "No bundle info in msg %{public}s", + GetBundleName(appProperty)); + + uint32_t flags = CheckAppSpawnMsgFlag(appProperty->message, TLV_MSG_FLAGS, APP_FLAGS_ATOMIC_SERVICE) ? 0x4 : 0; + if (flags == 0) { + flags = (CheckAppSpawnMsgFlag(appProperty->message, TLV_MSG_FLAGS, APP_FLAGS_CLONE_ENABLE) && + bundleInfo->bundleIndex > 0) ? 0x1 : 0; + } + std::ostringstream clonePackageName; + if (flags == 1) { + clonePackageName << "+clone-" << bundleInfo->bundleIndex << "+" << bundleInfo->bundleName; + } else { + clonePackageName << bundleInfo->bundleName; + } + std::string dir = "/storage/Users/currentUser/Download/" + clonePackageName.str(); + DecPolicyInfo decPolicyInfo = {0}; + decPolicyInfo.pathNum = 1; + PathInfo pathInfo = {0}; + pathInfo.path = strdup(dir.c_str()); + if (pathInfo.path == nullptr) { + APPSPAWN_LOGE("strdup %{public}s failed, err %{public}d", dir.c_str(), errno); + return APPSPAWN_MSG_INVALID; + } + pathInfo.pathLen = static_cast(strlen(pathInfo.path)); + pathInfo.mode = SANDBOX_MODE_WRITE | SANDBOX_MODE_READ; + decPolicyInfo.path[0] = pathInfo; + decPolicyInfo.tokenId = tokenInfo->accessTokenIdEx; + decPolicyInfo.flag = true; + SetDecPolicyInfos(&decPolicyInfo); + + if (decPolicyInfo.path[0].path) { + free(decPolicyInfo.path[0].path); + decPolicyInfo.path[0].path = nullptr; + } + return 0; +} + +int32_t SandboxCore::SetDecPolicyWithPermission(const AppSpawningCtx *appProperty, SandboxMountConfig &mountConfig) +{ + if (mountConfig.decPaths.size() == 0) { + return 0; + } + AppSpawnMsgAccessToken *tokenInfo = + reinterpret_cast(GetAppProperty(appProperty, TLV_ACCESS_TOKEN_INFO)); + APPSPAWN_CHECK(tokenInfo != nullptr, return APPSPAWN_MSG_INVALID, "Get token id failed."); + + DecPolicyInfo decPolicyInfo = {0}; + decPolicyInfo.pathNum = mountConfig.decPaths.size(); + int ret = 0; + for (uint32_t i = 0; i < decPolicyInfo.pathNum; i++) { + PathInfo pathInfo = {0}; + pathInfo.path = strdup(mountConfig.decPaths[i].c_str()); + if (pathInfo.path == nullptr) { + APPSPAWN_LOGE("strdup %{public}s failed, err %{public}d", mountConfig.decPaths[i].c_str(), errno); + ret = APPSPAWN_ERROR_UTILS_MEM_FAIL; + goto EXIT; + } + pathInfo.pathLen = static_cast(strlen(pathInfo.path)); + pathInfo.mode = SANDBOX_MODE_WRITE | SANDBOX_MODE_READ; + decPolicyInfo.path[i] = pathInfo; + } + decPolicyInfo.tokenId = tokenInfo->accessTokenIdEx; + decPolicyInfo.flag = true; + SetDecPolicyInfos(&decPolicyInfo); +EXIT: + for (uint32_t i = 0; i < decPolicyInfo.pathNum; i++) { + if (decPolicyInfo.path[i].path) { + free(decPolicyInfo.path[i].path); + decPolicyInfo.path[i].path = nullptr; + } + } + return ret; +} + +void SandboxCore::SetDecDenyWithDir(const AppSpawningCtx *appProperty) +{ + int32_t userFileIndex = GetPermissionIndex(nullptr, SandboxCommonDef::READ_WRITE_USER_FILE_MODE.c_str()); + if (CheckAppPermissionFlagSet(appProperty, static_cast(userFileIndex)) == 0) { + APPSPAWN_LOGV("The app doesn't have %{public}s, no need to set deny rules", + SandboxCommonDef::READ_WRITE_USER_FILE_MODE.c_str()); + return; + } + + AppSpawnMsgAccessToken *tokenInfo = + reinterpret_cast(GetAppProperty(appProperty, TLV_ACCESS_TOKEN_INFO)); + APPSPAWN_CHECK(tokenInfo != nullptr, return, "Get token id failed"); + + DecPolicyInfo decPolicyInfo = {0}; + decPolicyInfo.pathNum = 0; + uint32_t count = ARRAY_LENGTH(DEC_DENY_PATH_MAP); + for (uint32_t i = 0, j = 0; i < count; i++) { + int32_t index = GetPermissionIndex(nullptr, DEC_DENY_PATH_MAP[i].permission); + if (CheckAppPermissionFlagSet(appProperty, static_cast(index))) { + continue; + } + PathInfo pathInfo = {0}; + pathInfo.path = const_cast(DEC_DENY_PATH_MAP[i].decPath); + pathInfo.pathLen = static_cast(strlen(pathInfo.path)); + pathInfo.mode = DEC_MODE_DENY_READ | DEC_MODE_DENY_WRITE; + decPolicyInfo.path[j++] = pathInfo; + decPolicyInfo.pathNum += 1; + } + decPolicyInfo.tokenId = tokenInfo->accessTokenIdEx; + decPolicyInfo.flag = true; + SetDecPolicyInfos(&decPolicyInfo); +} + +std::string SandboxCore::ConvertDebugRealPath(const AppSpawningCtx *appProperty, std::string path) +{ + AppSpawnMsgBundleInfo *info = + reinterpret_cast(GetAppProperty(appProperty, TLV_BUNDLE_INFO)); + AppSpawnMsgDacInfo *dacInfo = reinterpret_cast(GetAppProperty(appProperty, TLV_DAC_INFO)); + if (info == nullptr || dacInfo == nullptr) { + return ""; + } + if (CheckAppSpawnMsgFlag(appProperty->message, TLV_MSG_FLAGS, APP_FLAGS_ATOMIC_SERVICE)) { + path = SandboxCommon::ReplaceAllVariables(path, SandboxCommonDef::g_variablePackageName, info->bundleName); + } + return SandboxCommon::ConvertToRealPath(appProperty, path); +} + +void SandboxCore::DoUninstallDebugSandbox(std::vector &bundleList, cJSON *config) +{ + cJSON *mountPoints = cJSON_GetObjectItemCaseSensitive(config, SandboxCommonDef::g_mountPrefix); + if (mountPoints == nullptr || !cJSON_IsArray(mountPoints)) { + APPSPAWN_LOGI("Invalid mountPoints"); + return; + } + + auto processor = [&bundleList](cJSON *mntPoint) { + const char *srcPathChr = GetStringFromJsonObj(mntPoint, SandboxCommonDef::g_srcPath); + const char *sandboxPathChr = GetStringFromJsonObj(mntPoint, SandboxCommonDef::g_sandBoxPath); + if (srcPathChr == nullptr || sandboxPathChr == nullptr) { + return 0; + } + std::string tmpSandboxPath = sandboxPathChr; + for (const auto& currentBundle : bundleList) { + std::string sandboxPath = currentBundle + tmpSandboxPath; + APPSPAWN_LOGV("DoUninstallDebugSandbox with path %{public}s", sandboxPath.c_str()); + APPSPAWN_CHECK(access(sandboxPath.c_str(), F_OK) == 0, return 0, + "Invalid path %{public}s", sandboxPath.c_str()); + int ret = umount2(sandboxPath.c_str(), MNT_DETACH); + APPSPAWN_CHECK_ONLY_LOG(ret == 0, "umount failed %{public}d %{public}d", ret, errno); + ret = rmdir(sandboxPath.c_str()); + APPSPAWN_CHECK_ONLY_LOG(ret == 0, "rmdir failed %{public}d %{public}d", ret, errno); + } + return 0; + }; + + (void)SandboxCommon::HandleArrayForeach(mountPoints, processor); +} + +int32_t SandboxCore::GetPackageList(AppSpawningCtx *property, std::vector &bundleList, bool tmp) +{ + APPSPAWN_CHECK(property != nullptr, return APPSPAWN_ARG_INVALID, "Invalid property"); + AppDacInfo *info = reinterpret_cast(GetAppProperty(property, TLV_DAC_INFO)); + if (GetBundleName(property) == nullptr ||SandboxCommon::CheckBundleName(GetBundleName(property)) != 0 || + info == nullptr) { + std::string uid; + char *userId = (char *)GetAppSpawnMsgExtInfo(property->message, MSG_EXT_NAME_USERID, nullptr); + if (userId != nullptr) { + uid = std::string(userId); + } else { + APPSPAWN_CHECK(info != nullptr, return APPSPAWN_ARG_INVALID, "Invalid dacInfo"); + uid = std::to_string(info->uid / UID_BASE); + } + std::string defaultSandboxRoot = (tmp ? SandboxCommonDef::g_mntTmpRoot : SandboxCommonDef::g_mntShareRoot) + + uid + "/debug_hap"; + APPSPAWN_CHECK(access(defaultSandboxRoot.c_str(), F_OK) == 0, return APPSPAWN_ARG_INVALID, + "Failed to access %{public}s, err %{public}d", defaultSandboxRoot.c_str(), errno); + + DIR *dir = opendir(defaultSandboxRoot.c_str()); + if (dir == nullptr) { + APPSPAWN_LOGE("Failed to open %{public}s, err %{public}d", defaultSandboxRoot.c_str(), errno); + return APPSPAWN_SYSTEM_ERROR; + } + struct dirent *entry; + while ((entry = readdir(dir)) != nullptr) { + if (entry->d_name[0] == '.') { + continue; + } + std::string packagePath = defaultSandboxRoot + "/" + std::string(entry->d_name); + APPSPAWN_LOGV("GetPackageList %{public}s", packagePath.c_str()); + bundleList.push_back(packagePath); + } + closedir(dir); + } else { + bundleList.push_back(ConvertDebugRealPath(property, tmp ? SandboxCommonDef::g_mntTmpSandboxRoot : + SandboxCommonDef::g_mntShareSandboxRoot)); + } + return 0; +} + +int32_t SandboxCore::UninstallDebugSandbox(AppSpawnMgr *content, AppSpawningCtx *property) +{ + APPSPAWN_CHECK(property != nullptr && content != nullptr, return APPSPAWN_ARG_INVALID, "Invalid property"); + + std::vector bundleList; + int ret = GetPackageList(property, bundleList, true); + APPSPAWN_CHECK(ret == 0, return -1, "GetPackageList failed"); + SandboxCommonDef::SandboxConfigType type = CheckAppMsgFlagsSet(property, APP_FLAGS_ISOLATED_SANDBOX_TYPE) ? + SandboxCommonDef::SANDBOX_ISOLATED_JSON_CONFIG : SandboxCommonDef::SANDBOX_APP_JSON_CONFIG; + for (auto& wholeConfig : SandboxCommon::GetCJsonConfig(type)) { + cJSON *debugJson = GetFirstCommonConfig(wholeConfig, SandboxCommonDef::g_debughap); + if (!debugJson) { + continue; + } + cJSON *debugCommonConfig = GetFirstSubConfig(debugJson, SandboxCommonDef::g_commonPrefix); + if (!debugCommonConfig) { + continue; + } + DoUninstallDebugSandbox(bundleList, debugCommonConfig); + + cJSON *debugPermissionConfig = GetFirstSubConfig(debugJson, SandboxCommonDef::g_permissionPrefix); + if (!debugPermissionConfig) { + continue; + } + + cJSON *permissionChild = debugPermissionConfig->child; + while (permissionChild != nullptr) { + cJSON *permissionMountPaths = cJSON_GetArrayItem(permissionChild, 0); + if (!permissionMountPaths) { + permissionChild = permissionChild->next; + continue; + } + DoUninstallDebugSandbox(bundleList, permissionMountPaths); + permissionChild = permissionChild->next; + } + } + bundleList.clear(); + ret = GetPackageList(property, bundleList, false); + APPSPAWN_CHECK(ret == 0, return -1, "GetPackageList failed"); + for (const auto& currentBundle : bundleList) { + std::string sandboxPath = currentBundle; + APPSPAWN_LOGV("UninstallDebugSandbox with path %{public}s", sandboxPath.c_str()); + APPSPAWN_CHECK(access(sandboxPath.c_str(), F_OK) == 0, continue, + "Invalid path %{public}s", sandboxPath.c_str()); + ret = umount2(sandboxPath.c_str(), MNT_DETACH); + APPSPAWN_CHECK_ONLY_LOG(ret == 0, "umount failed %{public}d %{public}d", ret, errno); + ret = rmdir(sandboxPath.c_str()); + APPSPAWN_CHECK_ONLY_LOG(ret == 0, "rmdir failed %{public}d %{public}d", ret, errno); + } + + return 0; +} + +int32_t SandboxCore::DoMountDebugPoints(const AppSpawningCtx *appProperty, cJSON *appConfig) +{ + std::string bundleName = GetBundleName(appProperty); + cJSON *mountPoints = cJSON_GetObjectItemCaseSensitive(appConfig, SandboxCommonDef::g_mountPrefix); + if (mountPoints == nullptr || !cJSON_IsArray(mountPoints)) { + APPSPAWN_LOGI("mount config is not found, app name is %{public}s", bundleName.c_str()); + return 0; + } + + std::string sandboxRoot = ConvertDebugRealPath(appProperty, SandboxCommonDef::g_mntTmpSandboxRoot); + int atomicService = CheckAppSpawnMsgFlag(appProperty->message, TLV_MSG_FLAGS, APP_FLAGS_ATOMIC_SERVICE); + + auto processor = [&sandboxRoot, &atomicService, &appProperty](cJSON *mntPoint) { + const char *srcPathChr = GetStringFromJsonObj(mntPoint, SandboxCommonDef::g_srcPath); + const char *sandboxPathChr = GetStringFromJsonObj(mntPoint, SandboxCommonDef::g_sandBoxPath); + if (srcPathChr == nullptr || sandboxPathChr == nullptr) { + return 0; + } + std::string srcPath(srcPathChr); + std::string sandboxPath(sandboxPathChr); + srcPath = SandboxCommon::ConvertToRealPath(appProperty, srcPath); + sandboxPath = GetSandboxPath(appProperty, mntPoint, SandboxCommonDef::g_debughap, sandboxRoot); + if (access(sandboxPath.c_str(), F_OK) == 0) { + APPSPAWN_CHECK(atomicService, return 0, "sandbox path already exist"); + APPSPAWN_CHECK(umount2(sandboxPath.c_str(), MNT_DETACH) == 0, return 0, + "umount sandbox path failed, errno is %{public}d %{public}s", errno, sandboxPath.c_str()); + } + SandboxMountConfig mountConfig = {0}; + SandboxCommon::GetSandboxMountConfig(appProperty, SandboxCommonDef::g_debughap, mntPoint, mountConfig); + SharedMountArgs arg = { + .srcPath = srcPath.c_str(), + .destPath = sandboxPath.c_str(), + .fsType = mountConfig.fsType.c_str(), + .mountFlags = SandboxCommon::GetMountFlags(mntPoint), + .options = mountConfig.optionsPoint.c_str(), + .mountSharedFlag = + GetBoolValueFromJsonObj(mntPoint, SandboxCommonDef::g_mountSharedFlag, false) ? MS_SHARED : MS_SLAVE + }; + int ret = SandboxCommon::DoAppSandboxMountOnce(appProperty, &arg); + APPSPAWN_CHECK(ret == 0 || !SandboxCommon::IsMountSuccessful(mntPoint), return ret, + "DoMountDebugPoints %{public}s failed", arg.destPath); + return ret; + }; + + (void)SandboxCommon::HandleArrayForeach(mountPoints, processor); + return 0; +} + +int32_t SandboxCore::MountDebugSharefs(const AppSpawningCtx *property, const char *src, const char *target) +{ + char dataPath[SandboxCommonDef::OPTIONS_MAX_LEN] = {0}; + int ret = snprintf_s(dataPath, SandboxCommonDef::OPTIONS_MAX_LEN, SandboxCommonDef::OPTIONS_MAX_LEN - 1, + "%s/data", target); + if (ret >= 0 && access(dataPath, F_OK) == 0) { + return 0; + } + + ret = MakeDirRec(target, SandboxCommonDef::FILE_MODE, 1); + if (ret != 0) { + return APPSPAWN_SANDBOX_ERROR_MKDIR_FAIL; + } + + AppDacInfo *info = reinterpret_cast(GetAppProperty(property, TLV_DAC_INFO)); + if (info == nullptr) { + return APPSPAWN_ARG_INVALID; + } + char options[SandboxCommonDef::OPTIONS_MAX_LEN] = {0}; + ret = snprintf_s(options, SandboxCommonDef::OPTIONS_MAX_LEN, SandboxCommonDef::OPTIONS_MAX_LEN - 1, + "override_support_delete,user_id=%u", info->uid / UID_BASE); + if (ret <= 0) { + return APPSPAWN_ERROR_UTILS_MEM_FAIL; + } + + if (mount(src, target, "sharefs", MS_NODEV, options) != 0) { + APPSPAWN_LOGE("sharefs mount %{public}s to %{public}s failed, errno %{public}d", src, target, errno); + return APPSPAWN_SANDBOX_ERROR_MOUNT_FAIL; + } + if (mount(nullptr, target, nullptr, MS_SHARED, nullptr) != 0) { + APPSPAWN_LOGE("mount path %{public}s to shared failed, errno %{public}d", target, errno); + return APPSPAWN_SANDBOX_ERROR_MOUNT_FAIL; + } + + return 0; +} + +int32_t SandboxCore::InstallDebugSandbox(AppSpawnMgr *content, AppSpawningCtx *property) +{ + if (!IsDeveloperModeOn(property)) { + return 0; + } + + uint32_t len = 0; + char *provisionType = reinterpret_cast(GetAppPropertyExt(property, + MSG_EXT_NAME_PROVISION_TYPE, &len)); + if (provisionType == nullptr || len == 0 || strcmp(provisionType, "debug") != 0) { + return 0; + } + + SandboxCommonDef::SandboxConfigType type = CheckAppMsgFlagsSet(property, APP_FLAGS_ISOLATED_SANDBOX_TYPE) ? + SandboxCommonDef::SANDBOX_ISOLATED_JSON_CONFIG : SandboxCommonDef::SANDBOX_APP_JSON_CONFIG; + + for (auto& wholeConfig : SandboxCommon::GetCJsonConfig(type)) { + cJSON *debugJson = GetFirstCommonConfig(wholeConfig, SandboxCommonDef::g_debughap); + if (!debugJson) { + continue; + } + cJSON *debugCommonConfig = GetFirstSubConfig(debugJson, SandboxCommonDef::g_commonPrefix); + if (!debugCommonConfig) { + continue; + } + DoMountDebugPoints(property, debugCommonConfig); + + cJSON *debugPermissionConfig = GetFirstSubConfig(debugJson, SandboxCommonDef::g_permissionPrefix); + if (!debugPermissionConfig) { + continue; + } + + cJSON *permissionChild = debugPermissionConfig->child; + while (permissionChild != nullptr) { + int index = GetPermissionIndex(nullptr, permissionChild->string); + if (CheckAppPermissionFlagSet(property, static_cast(index)) == 0) { + permissionChild = permissionChild->next; + continue; + } + cJSON *permissionMountPaths = cJSON_GetArrayItem(permissionChild, 0); + if (!permissionMountPaths) { + permissionChild = permissionChild->next; + continue; + } + DoMountDebugPoints(property, permissionMountPaths); + + permissionChild = permissionChild->next; + } + } + + MountDebugSharefs(property, ConvertDebugRealPath(property, SandboxCommonDef::g_mntTmpSandboxRoot).c_str(), + ConvertDebugRealPath(property, SandboxCommonDef::g_mntShareSandboxRoot).c_str()); + return 0; +} +} // namespace AppSpawn +} // namespace OHOS diff --git a/modules/sandbox/sandbox_utils.h b/modules/sandbox/normal/sandbox_core.h old mode 100755 new mode 100644 similarity index 39% rename from modules/sandbox/sandbox_utils.h rename to modules/sandbox/normal/sandbox_core.h index a5d1b7e19494083d06524182b8adbcb521cde5bd..9f379b7206054b83d7d222d5c1aeee471b8d10b9 --- a/modules/sandbox/sandbox_utils.h +++ b/modules/sandbox/normal/sandbox_core.h @@ -1,5 +1,5 @@ /* - * Copyright (C) 2022-2023 Huawei Device Co., Ltd. + * Copyright (C) 2025 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -13,131 +13,116 @@ * limitations under the License. */ -#ifndef SANDBOX_UTILS_H -#define SANDBOX_UTILS_H +#ifndef SANDBOX_CORE_H +#define SANDBOX_CORE_H -#include #include -#include -#include #include - -#include "sandbox_shared_mount.h" +#include +#include "sandbox_def.h" +#include "appspawn_msg.h" #include "appspawn_server.h" #include "appspawn_manager.h" - -typedef enum { - SANBOX_APP_JSON_CONFIG, - SANBOX_ISOLATED_JSON_CONFIG -} SandboxConfigType; +#include "sandbox_shared_mount.h" +#include "sandbox_common.h" namespace OHOS { namespace AppSpawn { -class SandboxUtils { + +class SandboxCore { public: - static void StoreJsonConfig(nlohmann::json &appSandboxConfig, SandboxConfigType type); - static std::vector &GetJsonConfig(SandboxConfigType type); - static int32_t SetAppSandboxProperty(AppSpawningCtx *client, uint32_t sandboxNsFlags = CLONE_NEWNS); - static int32_t SetAppSandboxPropertyNweb(AppSpawningCtx *client, uint32_t sandboxNsFlags = CLONE_NEWNS); - static uint32_t GetSandboxNsFlags(bool isNweb); - static std::set GetMountPermissionNames(); - static std::string GetExtraInfoByType(const AppSpawningCtx *appProperty, const std::string &type); - typedef struct { - unsigned long mountFlags; - std::string optionsPoint; - std::string fsType; - std::string sandboxPath; - std::vector decPaths; - } SandboxMountConfig; - -#ifndef APPSPAWN_TEST -private: -#endif - static int32_t DoAppSandboxMountOnce(const AppSpawningCtx *appProperty, const SharedMountArgs *arg); - static int32_t DoSandboxFileCommonBind(const AppSpawningCtx *appProperty, nlohmann::json &wholeConfig); - static int32_t DoSandboxFileCommonSymlink(const AppSpawningCtx *appProperty, - nlohmann::json &wholeConfig); - static int32_t DoSandboxFilePrivateBind(const AppSpawningCtx *appProperty, nlohmann::json &wholeConfig); - static int32_t DoSandboxFilePrivateSymlink(const AppSpawningCtx *appProperty, - nlohmann::json &wholeConfig); - static int32_t DoSandboxFilePrivateFlagsPointHandle(const AppSpawningCtx *appProperty, - nlohmann::json &wholeConfig); - static int32_t DoSandboxFileCommonFlagsPointHandle(const AppSpawningCtx *appProperty, - nlohmann::json &wholeConfig); - static int32_t HandleFlagsPoint(const AppSpawningCtx *appProperty, - nlohmann::json &wholeConfig); - static int32_t SetPrivateAppSandboxProperty(const AppSpawningCtx *appProperty); - static int32_t SetCommonAppSandboxProperty(const AppSpawningCtx *appProperty, - std::string &sandboxPackagePath); - static int32_t MountAllHsp(const AppSpawningCtx *appProperty, std::string &sandboxPackagePath); - static int32_t MountAllGroup(const AppSpawningCtx *appProperty, std::string &sandboxPackagePath); + // 沙箱挂载公共处理 + static int32_t DoAllMntPointsMount(const AppSpawningCtx *appProperty, cJSON *appConfig, + const char *typeName, const std::string §ion = "app-base"); + static int32_t DoAddGid(AppSpawningCtx *appProperty, cJSON *appConfig, + const char* permissionName, const std::string §ion); + static int32_t DoAllSymlinkPointslink(const AppSpawningCtx *appProperty, cJSON *appConfig); + static int32_t DoSandboxRootFolderCreate(const AppSpawningCtx *appProperty, std::string &sandboxPackagePath); static int32_t DoSandboxRootFolderCreateAdapt(std::string &sandboxPackagePath); - static int32_t DoSandboxRootFolderCreate(const AppSpawningCtx *appProperty, - std::string &sandboxPackagePath); - static int32_t SetDecPolicyWithPermission(const AppSpawningCtx *appProperty, SandboxMountConfig &mountConfig); - static int32_t SetDecWithDir(const AppSpawningCtx *appProperty, uint32_t userId); - static void SetDecDenyWithDir(const AppSpawningCtx *appProperty); - static void DoSandboxChmod(nlohmann::json jsonConfig, std::string &sandboxRoot); - static int DoAllMntPointsMount(const AppSpawningCtx *appProperty, - nlohmann::json &appConfig, const char *typeName, const std::string §ion = "app-base"); - static int DoAllSymlinkPointslink(const AppSpawningCtx *appProperty, nlohmann::json &appConfig); - static std::string ConvertToRealPath(const AppSpawningCtx *appProperty, std::string path); - static std::string ConvertToRealPathWithPermission(const AppSpawningCtx *appProperty, std::string path); - static std::string GetSbxPathByConfig(const AppSpawningCtx *appProperty, nlohmann::json &config); - static bool CheckTotalSandboxSwitchStatus(const AppSpawningCtx *appProperty); - static bool CheckAppSandboxSwitchStatus(const AppSpawningCtx *appProperty); - static bool CheckBundleNameForPrivate(const std::string &bundleName); - static bool GetSbxSwitchStatusByConfig(nlohmann::json &config); - static unsigned long GetMountFlagsFromConfig(const std::vector &vec); - static int32_t SetCommonAppSandboxProperty_(const AppSpawningCtx *appProperty, - nlohmann::json &config); - static int32_t SetPrivateAppSandboxProperty_(const AppSpawningCtx *appProperty, - nlohmann::json &config); - static int32_t SetRenderSandboxProperty(const AppSpawningCtx *appProperty, - std::string &sandboxPackagePath); - static int32_t SetRenderSandboxPropertyNweb(const AppSpawningCtx *appProperty, - std::string &sandboxPackagePath); - static int32_t SetOverlayAppSandboxProperty(const AppSpawningCtx *appProperty, - std::string &sandboxPackagePath); + static int32_t HandleFlagsPoint(const AppSpawningCtx *appProperty, cJSON *appConfig); + static int32_t SetOverlayAppSandboxProperty(const AppSpawningCtx *appProperty, std::string &sandboxPackagePath); static int32_t SetBundleResourceAppSandboxProperty(const AppSpawningCtx *appProperty, std::string &sandboxPackagePath); - static int32_t DoSandboxFilePermissionBind(AppSpawningCtx *appProperty, - nlohmann::json &wholeConfig); - static int32_t SetPermissionAppSandboxProperty_(AppSpawningCtx *appProperty, - nlohmann::json &config); + static bool NeedNetworkIsolated(AppSpawningCtx *property); + + // 处理应用沙箱挂载 + static int32_t SetCommonAppSandboxProperty(const AppSpawningCtx *appProperty, std::string &sandboxPackagePath); + static int32_t SetPrivateAppSandboxProperty(const AppSpawningCtx *appProperty); static int32_t SetPermissionAppSandboxProperty(AppSpawningCtx *appProperty); - static int32_t DoAddGid(AppSpawningCtx *appProperty, nlohmann::json &appConfig, - const char* permissionName, const std::string §ion); - static int32_t CheckAppFullMountEnable(); - static void UpdateMsgFlagsWithPermission(AppSpawningCtx *appProperty); - static int32_t UpdatePermissionFlags(AppSpawningCtx *appProperty); static int32_t SetSandboxProperty(AppSpawningCtx *appProperty, std::string &sandboxPackagePath); + static int32_t SetAppSandboxProperty(AppSpawningCtx *appProperty, uint32_t sandboxNsFlags = CLONE_NEWNS); + + static int32_t SetRenderSandboxPropertyNweb(const AppSpawningCtx *appProperty, std::string &sandboxPackagePath); + static int32_t SetAppSandboxPropertyNweb(AppSpawningCtx *appProperty, uint32_t sandboxNsFlags = CLONE_NEWNS); + + // 沙箱目录切根 static int32_t ChangeCurrentDir(std::string &sandboxPackagePath, const std::string &bundleName, bool sandboxSharedStatus); - static int32_t GetMountPermissionFlags(const std::string permissionName); - static bool GetSandboxDacOverrideEnable(nlohmann::json &config); - static unsigned long GetSandboxMountFlags(nlohmann::json &config); - static std::string GetSandboxFsType(nlohmann::json &config); - static std::string GetSandboxOptions(const AppSpawningCtx *appProperty, nlohmann::json &config); - static std::vector GetSandboxDecPath(const AppSpawningCtx *appProperty, nlohmann::json &config); - static std::string GetSandboxPath(const AppSpawningCtx *appProperty, nlohmann::json &mntPoint, + + // 设置DEC规则 + static int32_t SetDecWithDir(const AppSpawningCtx *appProperty, uint32_t userId); + static int32_t SetDecPolicyWithPermission(const AppSpawningCtx *appProperty, SandboxMountConfig &mountConfig); + static void SetDecDenyWithDir(const AppSpawningCtx *appProperty); + + // debug hap + static int32_t UninstallDebugSandbox(AppSpawnMgr *content, AppSpawningCtx *property); + static int32_t InstallDebugSandbox(AppSpawnMgr *content, AppSpawningCtx *property); + +private: + // 获取应用信息 + static int EnableSandboxNamespace(AppSpawningCtx *appProperty, uint32_t sandboxNsFlags); + static uint32_t GetAppMsgFlags(const AppSpawningCtx *property); + static bool CheckMountFlag(const AppSpawningCtx *appProperty, const std::string bundleName, + cJSON *appConfig); + static void UpdateMsgFlagsWithPermission(AppSpawningCtx *appProperty); + static int32_t UpdatePermissionFlags(AppSpawningCtx *appProperty); + static std::string GetSandboxPath(const AppSpawningCtx *appProperty, cJSON *mntPoint, const std::string §ion, std::string sandboxRoot); - static void GetSandboxMountConfig(const AppSpawningCtx *appProperty, const std::string §ion, - nlohmann::json &mntPoint, SandboxMountConfig &mountConfig); -#ifdef APPSPAWN_MOUNT_TMPSHM - static void MountDevShmPath(std::string &sandboxPath); -#endif - static std::map> appSandboxConfig_; - static int32_t deviceTypeEnable_; -}; -class JsonUtils { -public: - static bool GetJsonObjFromJson(nlohmann::json &jsonObj, const std::string &jsonPath); - static bool GetStringFromJson(const nlohmann::json &json, const std::string &key, std::string &value); + + // 解析挂载信息公共函数 + static cJSON *GetFirstCommonConfig(cJSON *wholeConfig, const char *prefix); + static cJSON *GetFirstSubConfig(cJSON *parent, const char *key); + + // 处理dlpmanager挂载 + static int32_t DoDlpAppMountStrategy(const AppSpawningCtx *appProperty, const std::string &srcPath, + const std::string &sandboxPath, const std::string &fsType, unsigned long mountFlags); + static int32_t HandleSpecialAppMount(const AppSpawningCtx *appProperty, const std::string &srcPath, + const std::string &sandboxPath, const std::string &fsType, unsigned long mountFlags); + + // 处理应用私有挂载 + static cJSON *GetPrivateJsonInfo(const AppSpawningCtx *appProperty, cJSON *wholeConfig); + static int32_t DoSandboxFilePrivateBind(const AppSpawningCtx *appProperty, cJSON *wholeConfig); + static int32_t DoSandboxFilePrivateSymlink(const AppSpawningCtx *appProperty, cJSON *wholeConfig); + static int32_t DoSandboxFilePrivateFlagsPointHandle(const AppSpawningCtx *appProperty, cJSON *wholeConfig); + static int32_t SetPrivateAppSandboxProperty_(const AppSpawningCtx *appProperty, cJSON *config); + + // 处理应用基于权限挂载 + static int32_t DoSandboxFilePermissionBind(AppSpawningCtx *appProperty, cJSON *wholeConfig); + static int32_t SetPermissionAppSandboxProperty_(AppSpawningCtx *appProperty, cJSON *config); + + // 处理应用公共挂载 + static int32_t DoSandboxFileCommonBind(const AppSpawningCtx *appProperty, cJSON *wholeConfig); + static int32_t DoSandboxFileCommonSymlink(const AppSpawningCtx *appProperty, cJSON *wholeConfig); + static int32_t DoSandboxFileCommonFlagsPointHandle(const AppSpawningCtx *appProperty, cJSON *wholeConfig); + static int32_t SetCommonAppSandboxProperty_(const AppSpawningCtx *appProperty, cJSON *config); + + // 处理可变参数的挂载 + static int32_t MountAllHsp(const AppSpawningCtx *appProperty, std::string &sandboxPackagePath); + static int32_t MountAllGroup(const AppSpawningCtx *appProperty, std::string &sandboxPackagePath); + + // 沙箱回调函数 + static int32_t ProcessMountPoint(cJSON *mntPoint, MountPointProcessParams ¶ms); + + // debug hap + static std::string ConvertDebugRealPath(const AppSpawningCtx *appProperty, std::string path); + static void DoUninstallDebugSandbox(std::vector &bundleList, cJSON *mountPoints); + static int32_t GetPackageList(AppSpawningCtx *property, std::vector &bundleList, bool tmp); + + static int32_t DoMountDebugPoints(const AppSpawningCtx *appProperty, cJSON *appConfig); + static int32_t MountDebugSharefs(const AppSpawningCtx *property, const char *src, const char *target); }; + } // namespace AppSpawn } // namespace OHOS -int LoadAppSandboxConfig(AppSpawnMgr *content); - -#endif // SANDBOX_UTILS_H +#endif // SANDBOX_CORE_H diff --git a/modules/sandbox/normal/sandbox_def.h b/modules/sandbox/normal/sandbox_def.h new file mode 100644 index 0000000000000000000000000000000000000000..2762d14bb3f72f1b0264f512243470af576a9f0a --- /dev/null +++ b/modules/sandbox/normal/sandbox_def.h @@ -0,0 +1,161 @@ +/* + * Copyright (C) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SANDBOX_DEF_H +#define SANDBOX_DEF_H + +#include +#include +#include +#include + +namespace OHOS { +namespace AppSpawn { +namespace SandboxCommonDef { +// 全局常量定义 +constexpr int32_t OPTIONS_MAX_LEN = 256; +constexpr int32_t FILE_ACCESS_COMMON_DIR_STATUS = 0; +constexpr int32_t FILE_CROSS_APP_STATUS = 1; +constexpr static mode_t FILE_MODE = 0711; +constexpr static mode_t BASIC_MOUNT_FLAGS = MS_REC | MS_BIND; +constexpr int32_t MAX_MOUNT_TIME = 500; // 500us +constexpr int32_t LOCK_STATUS_SIZE = 16; + +// 沙盒配置文件 +const std::string APP_JSON_CONFIG = "/appdata-sandbox.json"; +const std::string APP_ISOLATED_JSON_CONFIG = "/appdata-sandbox-isolated.json"; + +/* 沙盒配置文件中关键字 */ +// 公共属性 +constexpr const char *g_sandboxRootPrefix = "sandbox-root"; +constexpr const char *g_sandBoxNsFlags = "sandbox-ns-flags"; +constexpr const char *g_topSandBoxSwitchPrefix = "top-sandbox-switch"; +constexpr const char *g_sandBoxSwitchPrefix = "sandbox-switch"; +const std::string g_ohosGpu = "__internal__.com.ohos.gpu"; +const std::string g_ohosRender = "__internal__.com.ohos.render"; +constexpr const char *g_commonPrefix = "common"; +constexpr const char *g_privatePrefix = "individual"; +constexpr const char *g_permissionPrefix = "permission"; +constexpr const char *g_appBase = "app-base"; +constexpr const char *g_appResources = "app-resources"; +constexpr const char *g_flagePoint = "flags-point"; +const std::string g_internal = "__internal__"; +const std::string g_mntTmpRoot = "/mnt/debugtmp/"; +const std::string g_mntShareRoot = "/mnt/debug/"; +const std::string g_sandboxRootPathTemplate = "/mnt/sandbox//"; +const std::string g_originSandboxPath = "/mnt/sandbox/"; + +// 挂载目录字段 +constexpr const char *g_mountPrefix = "mount-paths"; +constexpr const char *g_srcPath = "src-path"; +constexpr const char *g_sandBoxPath = "sandbox-path"; +constexpr const char *g_sandBoxFlags = "sandbox-flags"; +constexpr const char *g_fsType = "fs-type"; +constexpr const char *g_sandBoxOptions = "options"; +constexpr const char *g_actionStatuc = "check-action-status"; +constexpr const char *g_destMode = "dest-mode"; +constexpr const char *g_flags = "flags"; + +// 挂载可选属性 +constexpr const char *g_sandBoxShared = "sandbox-shared"; +constexpr const char *g_mountSharedFlag = "mount-shared-flag"; +constexpr const char *g_dacOverrideSensitive = "dac-override-sensitive"; +constexpr const char *g_sandBoxFlagsCustomized = "sandbox-flags-customized"; +constexpr const char *g_appAplName = "app-apl-name"; +constexpr const char *g_sandBoxDecPath = "dec-paths"; +constexpr const char *CREATE_SANDBOX_PATH = "create-sandbox-path"; + +// link目录字段 +constexpr const char *g_symlinkPrefix = "symbol-links"; +constexpr const char *g_targetName = "target-name"; +constexpr const char *g_linkName = "link-name"; + +constexpr const char *g_gidPrefix = "gids"; + +// 可变参数 +const std::string g_userId = ""; +const std::string g_permissionUser = ""; +const std::string g_packageName = ""; +const std::string g_packageNameIndex = ""; +const std::string g_variablePackageName = ""; +const std::string g_clonePackageName = ""; +const std::string g_arkWebPackageName = ""; +const std::string g_hostUserId = ""; + +/* HSP */ +const std::string HSPLIST_SOCKET_TYPE = "HspList"; +const std::string g_hspList_key_bundles = "bundles"; +const std::string g_hspList_key_modules = "modules"; +const std::string g_hspList_key_versions = "versions"; +const std::string g_sandboxHspInstallPath = "/data/storage/el1/bundle/"; + +/* DataGroup */ +const std::string DATA_GROUP_SOCKET_TYPE = "DataGroup"; +const std::string g_groupList_key_dataGroupId = "dataGroupId"; +const std::string g_groupList_key_gid = "gid"; +const std::string g_groupList_key_dir = "dir"; +const std::string g_groupList_key_uuid = "uuid"; + +/* Overlay */ +const std::string OVERLAY_SOCKET_TYPE = "Overlay"; +const std::string g_overlayPath = "/data/storage/overlay/"; + +/* system hap */ +const std::string APL_SYSTEM_CORE = "system_core"; +const std::string APL_SYSTEM_BASIC = "system_basic"; +const std::string g_physicalAppInstallPath = "/data/app/el1/bundle/public/"; +const std::string g_dataBundles = "/data/bundles/"; + +/* bundle resource with APP_FLAGS_BUNDLE_RESOURCES */ +const std::string g_bundleResourceSrcPath = "/data/service/el1/public/bms/bundle_resources/"; +const std::string g_bundleResourceDestPath = "/data/storage/bundle_resources/"; + +/* 配置文件中value校验值 */ +const std::string g_sandBoxRootDir = "/mnt/sandbox/"; +const std::string g_sandBoxRootDirNweb = "/mnt/sandbox/com.ohos.render/"; +const std::string DEV_SHM_DIR = "/dev/shm/"; +const std::string g_statusCheck = "true"; +const std::string g_sbxSwitchCheck = "ON"; +const std::string g_dlpBundleName = "com.ohos.dlpmanager"; + +/* debug hap */ +constexpr const char *g_mntTmpSandboxRoot = "/mnt/debugtmp//debug_hap/"; +constexpr const char *g_mntShareSandboxRoot = "/mnt/debug//debug_hap/"; +constexpr const char *g_debughap = "debug"; + +/* 分割符 */ +constexpr const char *g_fileSeparator = "/"; +constexpr const char *g_overlayDecollator = "|"; + +/* 权限名 */ +const std::string FILE_CROSS_APP_MODE = "ohos.permission.FILE_CROSS_APP"; +const std::string FILE_ACCESS_COMMON_DIR_MODE = "ohos.permission.FILE_ACCESS_COMMON_DIR"; +const std::string ACCESS_DLP_FILE_MODE = "ohos.permission.ACCESS_DLP_FILE"; +const std::string FILE_ACCESS_MANAGER_MODE = "ohos.permission.FILE_ACCESS_MANAGER"; +const std::string READ_WRITE_USER_FILE_MODE = "ohos.permission.READ_WRITE_USER_FILE"; +const std::string GET_ALL_PROCESSES_MODE = "ohos.permission.GET_ALL_PROCESSES"; +const std::string ARK_WEB_PERSIST_PACKAGE_NAME = "persist.arkwebcore.package_name"; + +// 枚举类型 +enum SandboxConfigType { + SANDBOX_APP_JSON_CONFIG, + SANDBOX_ISOLATED_JSON_CONFIG +}; + +} // namespace SandboxCommonDef +} // namespace AppSpawn +} // namespace OHOS + +#endif // SANDBOX_DEF_H \ No newline at end of file diff --git a/modules/sandbox/sandbox_shared_mount.cpp b/modules/sandbox/normal/sandbox_shared_mount.cpp similarity index 89% rename from modules/sandbox/sandbox_shared_mount.cpp rename to modules/sandbox/normal/sandbox_shared_mount.cpp index 528dca99020cbd9e80aa6f0296231ef98171d00f..fe9f145350f5deb8a46f4ff859a19e5fbc693beb 100644 --- a/modules/sandbox/sandbox_shared_mount.cpp +++ b/modules/sandbox/normal/sandbox_shared_mount.cpp @@ -86,13 +86,18 @@ const DataGroupSandboxPathTemplate *GetDataGroupArgTemplate(uint32_t category) return nullptr; } -bool IsValidDataGroupItem(nlohmann::json &item) +bool IsValidDataGroupItem(cJSON *item) { // Check if the item contains the specified key and if the value corresponding to the key is a string - if (item.contains(GROUPLIST_KEY_DATAGROUPID) && item[GROUPLIST_KEY_DATAGROUPID].is_string() && - item.contains(GROUPLIST_KEY_GID) && item[GROUPLIST_KEY_GID].is_string() && - item.contains(GROUPLIST_KEY_DIR) && item[GROUPLIST_KEY_DIR].is_string() && - item.contains(GROUPLIST_KEY_UUID) && item[GROUPLIST_KEY_UUID].is_string()) { + cJSON *datagroupId = cJSON_GetObjectItem(item, GROUPLIST_KEY_DATAGROUPID); + cJSON *gid = cJSON_GetObjectItem(item, GROUPLIST_KEY_GID); + cJSON *dir = cJSON_GetObjectItem(item, GROUPLIST_KEY_DIR); + cJSON *uuid = cJSON_GetObjectItem(item, GROUPLIST_KEY_UUID); + + if (datagroupId && cJSON_IsString(datagroupId) && + gid && cJSON_IsString(gid) && + dir && cJSON_IsString(dir) && + uuid && cJSON_IsString(uuid)) { return true; } return false; @@ -297,7 +302,16 @@ static int MountWithOther(const AppSpawningCtx *property, const AppDacInfo *info APPSPAWN_LOGE("snprintf options failed, errno %{public}d", errno); return APPSPAWN_ERROR_UTILS_MEM_FAIL; } - +#ifdef APPSPAWN_SUPPORT_NOSHAREFS + SharedMountArgs arg = { + .srcPath = sharefsDocsDir, + .destPath = storageUserPath, + .fsType = nullptr, + .mountFlags = MS_BIND | MS_REC, + .options = nullptr, + .mountSharedFlag = MS_SHARED + }; +#else SharedMountArgs arg = { .srcPath = sharefsDocsDir, .destPath = storageUserPath, @@ -306,6 +320,7 @@ static int MountWithOther(const AppSpawningCtx *property, const AppDacInfo *info .options = options, .mountSharedFlag = MS_SHARED }; +#endif ret = DoSharedMount(&arg); if (ret != 0) { APPSPAWN_LOGE("mount %{public}s shared failed, ret %{public}d", storageUserPath, ret); @@ -437,16 +452,6 @@ static int AddDataGroupItemToQueue(AppSpawnMgr *content, const std::string &srcP return 0; } -static std::string GetExtraInfoByType(const AppSpawningCtx *appPropery, const std::string &type) -{ - uint32_t len = 0; - char *info = reinterpret_cast(GetAppPropertyExt(appPropery, type.c_str(), &len)); - if (info == nullptr) { - return ""; - } - return std::string(info, len); -} - static void DumpDataGroupCtxQueue(const ListNode *front) { if (front == nullptr) { @@ -466,33 +471,51 @@ static void DumpDataGroupCtxQueue(const ListNode *front) } } +static inline cJSON *GetJsonObjFromExtInfo(const AppSpawningCtx *property, const char *name) +{ + uint32_t size = 0; + char *extInfo = (char *)(GetAppSpawnMsgExtInfo(property->message, name, &size)); + if (size == 0 || extInfo == nullptr) { + return nullptr; + } + APPSPAWN_LOGV("Get json name %{public}s value %{public}s", name, extInfo); + cJSON *extInfoJson = cJSON_Parse(extInfo); // need to free + APPSPAWN_CHECK(extInfoJson != nullptr, return nullptr, "Invalid ext info %{public}s for %{public}s", extInfo, name); + return extInfoJson; +} + static int ParseDataGroupList(AppSpawnMgr *content, const AppSpawningCtx *property, AppDacInfo *info, const char *varBundleName) { int ret = 0; - std::string dataGroupList = GetExtraInfoByType(property, DATA_GROUP_SOCKET_TYPE); - if (dataGroupList.length() == 0) { + cJSON *dataGroupList = GetJsonObjFromExtInfo(property, DATA_GROUP_SOCKET_TYPE); + if (dataGroupList == nullptr || !cJSON_IsArray(dataGroupList)) { APPSPAWN_LOGE("dataGroupList is empty"); return APPSPAWN_ARG_INVALID; } - nlohmann::json dataGroupJson = nlohmann::json::parse(dataGroupList.c_str(), nullptr, false); - if (dataGroupJson.is_discarded() && dataGroupJson.contains(GROUPLIST_KEY_DATAGROUPID) && - dataGroupJson.contains(GROUPLIST_KEY_GID) && dataGroupJson.contains(GROUPLIST_KEY_DIR) && - dataGroupJson.contains(GROUPLIST_KEY_UUID)) { - APPSPAWN_LOGE("dataGroupJson is discarded"); - return APPSPAWN_ARG_INVALID; - } - for (auto &item : dataGroupJson) { - APPSPAWN_CHECK(IsValidDataGroupItem(item), return -1, "Element is not a valid data group item"); - std::string srcPath = item[GROUPLIST_KEY_DIR]; - APPSPAWN_CHECK(!CheckPath(srcPath), return -1, "src path %{public}s is invalid", srcPath.c_str()); + // Iterate through the array (assuming groups is an array) + cJSON *item = nullptr; + cJSON_ArrayForEach(item, dataGroupList) { + // Check if the item is valid + APPSPAWN_CHECK((item != nullptr && IsValidDataGroupItem(item)), break, + "Element is not a valid data group item"); + + cJSON *dirItem = cJSON_GetObjectItemCaseSensitive(item, "dir"); + cJSON *uuidItem = cJSON_GetObjectItemCaseSensitive(item, "uuid"); + if (dirItem == nullptr || !cJSON_IsString(dirItem) || uuidItem == nullptr || !cJSON_IsString(uuidItem)) { + APPSPAWN_LOGE("Data group element is invalid"); + break; + } + + const char *srcPath = dirItem->valuestring; + APPSPAWN_CHECK(!CheckPath(srcPath), break, "src path %{public}s is invalid", srcPath); + + int elxValue = GetElxInfoFromDir(srcPath); + APPSPAWN_CHECK((elxValue >= EL2 && elxValue < ELX_MAX), break, "Get elx value failed"); - int elxValue = GetElxInfoFromDir(srcPath.c_str()); - APPSPAWN_CHECK((elxValue >= EL2 && elxValue < ELX_MAX), return -1, "Get elx value failed"); - const DataGroupSandboxPathTemplate *templateItem = GetDataGroupArgTemplate(elxValue); - APPSPAWN_CHECK(templateItem != nullptr, return -1, "Get data group arg template failed"); + APPSPAWN_CHECK(templateItem != nullptr, break, "Get data group arg template failed"); // If permission isn't null, need check permission flag if (templateItem->permission != nullptr) { @@ -502,18 +525,18 @@ static int ParseDataGroupList(AppSpawnMgr *content, const AppSpawningCtx *proper continue; } } - // sandboxPath: /mnt/sandbox///data/storage/el/group std::string sandboxPath = "/mnt/sandbox/" + std::to_string(info->uid / UID_BASE) + "/" + varBundleName + templateItem->sandboxPath; - ret = AddDataGroupItemToQueue(content, srcPath, sandboxPath, item[GROUPLIST_KEY_UUID]); + ret = AddDataGroupItemToQueue(content, srcPath, sandboxPath, uuidItem->valuestring); if (ret != 0) { APPSPAWN_LOGE("Add datagroup item to dataGroupCtxQueue failed, el%{public}d", elxValue); OH_ListRemoveAll(&content->dataGroupCtxQueue, nullptr); - return -1; + break; } } + cJSON_Delete(dataGroupList); DumpDataGroupCtxQueue(&content->dataGroupCtxQueue); return ret; @@ -552,7 +575,7 @@ int UpdateDataGroupDirs(AppSpawnMgr *content) } node = node->next; } - OH_ListRemoveAll(&content->dataGroupCtxQueue, NULL); + OH_ListRemoveAll(&content->dataGroupCtxQueue, nullptr); return 0; } @@ -581,7 +604,7 @@ static void MountDirToShared(AppSpawnMgr *content, const AppSpawningCtx *propert AppDacInfo *info = reinterpret_cast(GetAppProperty(property, TLV_DAC_INFO)); std::string varBundleName = ReplaceVarBundleName(property); - if (info == NULL || varBundleName == "") { + if (info == nullptr || varBundleName == "") { APPSPAWN_LOGE("Invalid app dac info or varBundleName"); return; } diff --git a/modules/sandbox/sandbox_shared_mount.h b/modules/sandbox/normal/sandbox_shared_mount.h similarity index 95% rename from modules/sandbox/sandbox_shared_mount.h rename to modules/sandbox/normal/sandbox_shared_mount.h index 1a24f2cce94ebc4c10277dc73ccc17985aee6874..c90efcdb5d00f215771bac7841c4a4c479403152 100644 --- a/modules/sandbox/sandbox_shared_mount.h +++ b/modules/sandbox/normal/sandbox_shared_mount.h @@ -16,13 +16,12 @@ #ifndef SANDBOX_SHARED_MOUNT_H #define SANDBOX_SHARED_MOUNT_H -#include "nlohmann/json.hpp" - #include "appspawn.h" #include "appspawn_hook.h" #include "appspawn_manager.h" #include "appspawn_utils.h" #include "list.h" +#include "json_utils.h" #ifdef __cplusplus extern "C" { @@ -57,7 +56,7 @@ struct SharedMountArgs { mode_t mountSharedFlag = MS_SLAVE; }; -bool IsValidDataGroupItem(nlohmann::json &item); +bool IsValidDataGroupItem(cJSON *item); int GetElxInfoFromDir(const char *path); const DataGroupSandboxPathTemplate *GetDataGroupArgTemplate(uint32_t category); void *GetEl1BundleMountCount(void); diff --git a/modules/sandbox/sandbox.gni b/modules/sandbox/sandbox.gni new file mode 100644 index 0000000000000000000000000000000000000000..bf26ed0c16e9f4da4428f64432bef8d6a0fb044f --- /dev/null +++ b/modules/sandbox/sandbox.gni @@ -0,0 +1,50 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +appspawn_sandbox_inc = [ + "//base/startup/appspawn/modules/sandbox" +] + +appspawn_sandbox_src = [ + "//base/startup/appspawn/modules/sandbox/sandbox_dec.c", + "//base/startup/appspawn/modules/sandbox/appspawn_permission.c", +] + +if (defined(appspawn_sandbox_new) && appspawn_sandbox_new) { + appspawn_sandbox_inc += [ + "//base/startup/appspawn/modules/sandbox/modern" + ] + + appspawn_sandbox_src += [ + "//base/startup/appspawn/modules/sandbox/modern/appspawn_mount_template.c", + "//base/startup/appspawn/modules/sandbox/modern/appspawn_sandbox.c", + "//base/startup/appspawn/modules/sandbox/modern/sandbox_adapter.cpp", + "//base/startup/appspawn/modules/sandbox/modern/sandbox_cfgvar.c", + "//base/startup/appspawn/modules/sandbox/modern/sandbox_debug_mode.c", + "//base/startup/appspawn/modules/sandbox/modern/sandbox_expand.c", + "//base/startup/appspawn/modules/sandbox/modern/sandbox_load.c", + "//base/startup/appspawn/modules/sandbox/modern/sandbox_manager.c", + "//base/startup/appspawn/modules/sandbox/modern/sandbox_shared.c", + ] +} else { + appspawn_sandbox_inc += [ + "//base/startup/appspawn/modules/sandbox/normal" + ] + + appspawn_sandbox_src += [ + "//base/startup/appspawn/modules/sandbox/normal/sandbox_shared_mount.cpp", + "//base/startup/appspawn/modules/sandbox/normal/appspawn_sandbox_manager.cpp", + "//base/startup/appspawn/modules/sandbox/normal/sandbox_common.cpp", + "//base/startup/appspawn/modules/sandbox/normal/sandbox_core.cpp" + ] +} \ No newline at end of file diff --git a/modules/sandbox/sandbox_utils.cpp b/modules/sandbox/sandbox_utils.cpp deleted file mode 100644 index 5fcefbc8e30347cbf0d69666592451d3ef052f0a..0000000000000000000000000000000000000000 --- a/modules/sandbox/sandbox_utils.cpp +++ /dev/null @@ -1,2284 +0,0 @@ -/* - * Copyright (C) 2024-2025 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "sandbox_utils.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "appspawn_hook.h" -#include "appspawn_mount_permission.h" -#include "appspawn_msg.h" -#include "appspawn_server.h" -#include "appspawn_service.h" -#include "appspawn_utils.h" -#include "config_policy_utils.h" -#ifdef WITH_DLP -#include "dlp_fuse_fd.h" -#endif -#include "init_param.h" -#include "init_utils.h" -#include "parameter.h" -#include "parameters.h" -#include "sandbox_dec.h" -#include "securec.h" -#ifdef APPSPAWN_HISYSEVENT -#include "hisysevent_adapter.h" -#endif - -#ifdef WITH_SELINUX -#include "hap_restorecon.h" -#ifdef APPSPAWN_MOUNT_TMPSHM -#include "policycoreutils.h" -#endif // APPSPAWN_MOUNT_TMPSHM -#endif // WITH_SELINUX - -#define MAX_MOUNT_TIME 500 // 500us -#define LOCK_STATUS_SIZE 16 -#define DEV_SHM_DIR "/dev/shm/" - -using namespace std; -using namespace OHOS; - -namespace OHOS { -namespace AppSpawn { -namespace { - constexpr int32_t OPTIONS_MAX_LEN = 256; - constexpr int32_t FILE_ACCESS_COMMON_DIR_STATUS = 0; - constexpr int32_t FILE_CROSS_APP_STATUS = 1; - constexpr static mode_t FILE_MODE = 0711; - constexpr static mode_t BASIC_MOUNT_FLAGS = MS_REC | MS_BIND; - constexpr std::string_view APL_SYSTEM_CORE("system_core"); - constexpr std::string_view APL_SYSTEM_BASIC("system_basic"); - const std::string APP_JSON_CONFIG("/appdata-sandbox.json"); - const std::string APP_ISOLATED_JSON_CONFIG("/appdata-sandbox-isolated.json"); - const std::string g_physicalAppInstallPath = "/data/app/el1/bundle/public/"; - const std::string g_sandboxGroupPath = "/data/storage/el2/group/"; - const std::string g_sandboxHspInstallPath = "/data/storage/el1/bundle/"; - const std::string g_sandBoxAppInstallPath = "/data/accounts/account_0/applications/"; - const std::string g_bundleResourceSrcPath = "/data/service/el1/public/bms/bundle_resources/"; - const std::string g_bundleResourceDestPath = "/data/storage/bundle_resources/"; - const std::string g_dataBundles = "/data/bundles/"; - const std::string g_userId = ""; - const std::string g_packageName = ""; - const std::string g_packageNameIndex = ""; - const std::string g_variablePackageName = ""; - const std::string g_clonePackageName = ""; - const std::string g_arkWebPackageName = ""; - const std::string g_hostUserId = ""; - const std::string g_sandBoxDir = "/mnt/sandbox/"; - const std::string g_statusCheck = "true"; - const std::string g_sbxSwitchCheck = "ON"; - const std::string g_dlpBundleName = "com.ohos.dlpmanager"; - const std::string g_internal = "__internal__"; - const std::string g_hspList_key_bundles = "bundles"; - const std::string g_hspList_key_modules = "modules"; - const std::string g_hspList_key_versions = "versions"; - const std::string g_overlayPath = "/data/storage/overlay/"; - const std::string g_groupList_key_dataGroupId = "dataGroupId"; - const std::string g_groupList_key_gid = "gid"; - const std::string g_groupList_key_dir = "dir"; - const std::string g_groupList_key_uuid = "uuid"; - const std::string HSPLIST_SOCKET_TYPE = "HspList"; - const std::string OVERLAY_SOCKET_TYPE = "Overlay"; - const std::string DATA_GROUP_SOCKET_TYPE = "DataGroup"; - const char *g_actionStatuc = "check-action-status"; - const char *g_appBase = "app-base"; - const char *g_appResources = "app-resources"; - const char *g_appAplName = "app-apl-name"; - const char *g_commonPrefix = "common"; - const char *g_destMode = "dest-mode"; - const char *g_fsType = "fs-type"; - const char *g_linkName = "link-name"; - const char *g_mountPrefix = "mount-paths"; - const char *g_gidPrefix = "gids"; - const char *g_privatePrefix = "individual"; - const char *g_permissionPrefix = "permission"; - const char *g_srcPath = "src-path"; - const char *g_sandBoxPath = "sandbox-path"; - const char *g_sandBoxFlags = "sandbox-flags"; - const char *g_sandBoxFlagsCustomized = "sandbox-flags-customized"; - const char *g_sandBoxOptions = "options"; - const char *g_dacOverrideSensitive = "dac-override-sensitive"; - const char *g_sandBoxShared = "sandbox-shared"; - const char *g_sandBoxSwitchPrefix = "sandbox-switch"; - const char *g_sandBoxDecPath = "dec-paths"; - const char *g_symlinkPrefix = "symbol-links"; - const char *g_sandboxRootPrefix = "sandbox-root"; - const char *g_topSandBoxSwitchPrefix = "top-sandbox-switch"; - const char *g_targetName = "target-name"; - const char *g_flagePoint = "flags-point"; - const char *g_mountSharedFlag = "mount-shared-flag"; - const char *g_flags = "flags"; - const char *g_sandBoxNsFlags = "sandbox-ns-flags"; - const char* g_fileSeparator = "/"; - const char* g_overlayDecollator = "|"; - const char *CREATE_SANDBOX_PATH = "create-sandbox-path"; - const std::string g_sandBoxRootDir = "/mnt/sandbox/"; - const std::string g_ohosGpu = "__internal__.com.ohos.gpu"; - const std::string g_ohosRender = "__internal__.com.ohos.render"; - const std::string g_sandBoxRootDirNweb = "/mnt/sandbox/com.ohos.render/"; - const std::string FILE_CROSS_APP_MODE = "ohos.permission.FILE_CROSS_APP"; - const std::string FILE_ACCESS_COMMON_DIR_MODE = "ohos.permission.FILE_ACCESS_COMMON_DIR"; - const std::string ACCESS_DLP_FILE_MODE = "ohos.permission.ACCESS_DLP_FILE"; - const std::string FILE_ACCESS_MANAGER_MODE = "ohos.permission.FILE_ACCESS_MANAGER"; - const std::string READ_WRITE_USER_FILE_MODE = "ohos.permission.READ_WRITE_USER_FILE"; - const std::string GET_ALL_PROCESSES_MODE = "ohos.permission.GET_ALL_PROCESSES"; - const std::string ARK_WEB_PERSIST_PACKAGE_NAME = "persist.arkwebcore.package_name"; - - const std::string& getArkWebPackageName() - { - static std::string arkWebPackageName; - if (arkWebPackageName.empty()) { - arkWebPackageName = system::GetParameter(ARK_WEB_PERSIST_PACKAGE_NAME, ""); - } - return arkWebPackageName; - } -} - -static uint32_t GetAppMsgFlags(const AppSpawningCtx *property) -{ - APPSPAWN_CHECK(property != nullptr && property->message != nullptr, - return 0, "Invalid property for name %{public}u", TLV_MSG_FLAGS); - AppSpawnMsgFlags *msgFlags = (AppSpawnMsgFlags *)GetAppSpawnMsgInfo(property->message, TLV_MSG_FLAGS); - APPSPAWN_CHECK(msgFlags != nullptr, - return 0, "No TLV_MSG_FLAGS in msg %{public}s", property->message->msgHeader.processName); - return msgFlags->flags[0]; -} - -bool JsonUtils::GetJsonObjFromJson(nlohmann::json &jsonObj, const std::string &jsonPath) -{ - APPSPAWN_CHECK(jsonPath.length() <= PATH_MAX, return false, "jsonPath is too long"); - std::ifstream jsonFileStream; - jsonFileStream.open(jsonPath.c_str(), std::ios::in); - APPSPAWN_CHECK_ONLY_EXPER(jsonFileStream.is_open(), return false); - std::ostringstream buf; - char ch; - while (buf && jsonFileStream.get(ch)) { - buf.put(ch); - } - jsonFileStream.close(); - jsonObj = nlohmann::json::parse(buf.str(), nullptr, false); - APPSPAWN_CHECK(!jsonObj.is_discarded() && jsonObj.is_structured(), return false, "Parse json file failed"); - return true; -} - -bool JsonUtils::GetStringFromJson(const nlohmann::json &json, const std::string &key, std::string &value) -{ - APPSPAWN_CHECK(json != nullptr && json.is_object(), return false, "json is not object."); - bool isRet = json.find(key) != json.end() && json.at(key).is_string(); - if (isRet) { - value = json.at(key).get(); - APPSPAWN_LOGV("Find key[%{public}s] : %{public}s successful.", key.c_str(), value.c_str()); - } - return isRet; -} - -std::map> SandboxUtils::appSandboxConfig_ = {}; -int32_t SandboxUtils::deviceTypeEnable_ = -1; - -void SandboxUtils::StoreJsonConfig(nlohmann::json &appSandboxConfig, SandboxConfigType type) -{ - SandboxUtils::appSandboxConfig_[type].push_back(appSandboxConfig); -} - -std::vector &SandboxUtils::GetJsonConfig(SandboxConfigType type) -{ - return SandboxUtils::appSandboxConfig_[type]; -} - -static void MakeDirRecursive(const std::string &path, mode_t mode) -{ - size_t size = path.size(); - if (size == 0) { - return; - } - - size_t index = 0; - do { - size_t pathIndex = path.find_first_of('/', index); - index = pathIndex == std::string::npos ? size : pathIndex + 1; - std::string dir = path.substr(0, index); -#ifndef APPSPAWN_TEST - APPSPAWN_CHECK(!(access(dir.c_str(), F_OK) < 0 && mkdir(dir.c_str(), mode) < 0), - return, "errno is %{public}d, mkdir %{public}s failed", errno, dir.c_str()); -#endif - } while (index < size); -} - -static void MakeDirRecursiveWithClock(const std::string &path, mode_t mode) -{ - size_t size = path.size(); - if (size == 0) { - return; - } -#ifdef APPSPAWN_HISYSEVENT - struct timespec startClock = {0}; - clock_gettime(CLOCK_MONOTONIC, &startClock); -#endif - size_t index = 0; - do { - size_t pathIndex = path.find_first_of('/', index); - index = pathIndex == std::string::npos ? size : pathIndex + 1; - std::string dir = path.substr(0, index); -#ifndef APPSPAWN_TEST - APPSPAWN_CHECK(!(access(dir.c_str(), F_OK) < 0 && mkdir(dir.c_str(), mode) < 0), - return, "errno is %{public}d, mkdir %{public}s failed", errno, dir.c_str()); -#endif - } while (index < size); - -#ifdef APPSPAWN_HISYSEVENT - struct timespec endClock = {0}; - clock_gettime(CLOCK_MONOTONIC, &endClock); - uint64_t diff = DiffTime(&startClock, &endClock); - - APPSPAWN_CHECK_ONLY_EXPER(diff < FUNC_REPORT_DURATION, - ReportAbnormalDuration("MakeDirRecursive", diff)); -#endif -} - -static bool CheckDirRecursive(const std::string &path) -{ - size_t size = path.size(); - if (size == 0) { - return false; - } - size_t index = 0; - do { - size_t pathIndex = path.find_first_of('/', index); - index = pathIndex == std::string::npos ? size : pathIndex + 1; - std::string dir = path.substr(0, index); -#ifndef APPSPAWN_TEST - APPSPAWN_CHECK(access(dir.c_str(), F_OK) == 0, - return false, "check dir %{public}s failed, strerror: %{public}s", dir.c_str(), strerror(errno)); -#endif - } while (index < size); - return true; -} - -static void CheckAndCreatFile(const char *file) -{ - if (access(file, F_OK) == 0) { - APPSPAWN_LOGI("file %{public}s already exist", file); - return; - } - std::string path = file; - auto pos = path.find_last_of('/'); - APPSPAWN_CHECK(pos != std::string::npos, return, "file %{public}s error", file); - std::string dir = path.substr(0, pos); - MakeDirRecursive(dir, FILE_MODE); - int fd = open(file, O_CREAT, FILE_MODE); - if (fd < 0) { - APPSPAWN_LOGW("failed create %{public}s, err=%{public}d", file, errno); - } else { - close(fd); - } - return; -} - -static void CheckMountStatus(const std::string &path) -{ - std::ifstream file("/proc/self/mountinfo"); - if (!file.is_open()) { - APPSPAWN_LOGE("Failed to open /proc/self/mountinfo errno %{public}d", errno); - return; - } - - bool flag = false; - std::string line; - while (std::getline(file, line)) { - if (line.find(path) != std::string::npos) { - flag = true; - APPSPAWN_LOGI("Current mountinfo %{public}s", line.c_str()); - } - } - file.close(); - APPSPAWN_CHECK_ONLY_LOG(flag, "Mountinfo not contains %{public}s", path.c_str()); -} - -static bool IsNeededCheckPathStatus(const AppSpawningCtx *appProperty, const char *path) -{ - if (strstr(path, "data/app/el1/") || strstr(path, "data/app/el2/")) { - return true; - } - if ((strstr(path, "data/app/el3/") || strstr(path, "data/app/el4/") || strstr(path, "data/app/el5/")) && - CheckAppMsgFlagsSet(appProperty, APP_FLAGS_UNLOCKED_STATUS)) { - return true; - } - return false; -} - -int32_t SandboxUtils::DoAppSandboxMountOnce(const AppSpawningCtx *appProperty, const SharedMountArgs *arg) -{ - if (!(arg && arg->srcPath && arg->destPath && arg->srcPath[0] != '\0' && arg->destPath[0] != '\0')) { - return 0; - } - if (strstr(arg->srcPath, "system/etc/hosts") != nullptr || strstr(arg->srcPath, "system/etc/profile") != nullptr) { - CheckAndCreatFile(arg->destPath); - } else { - MakeDirRecursive(arg->destPath, FILE_MODE); - } - - int ret = 0; - // to mount fs and bind mount files or directory - struct timespec mountStart = {0}; - clock_gettime(CLOCK_MONOTONIC_COARSE, &mountStart); - APPSPAWN_LOGV("Bind mount %{public}s to %{public}s '%{public}s' '%{public}lu' '%{public}s' '%{public}u'", - arg->srcPath, arg->destPath, arg->fsType, arg->mountFlags, arg->options, arg->mountSharedFlag); - ret = mount(arg->srcPath, arg->destPath, arg->fsType, arg->mountFlags, arg->options); - struct timespec mountEnd = {0}; - clock_gettime(CLOCK_MONOTONIC_COARSE, &mountEnd); - uint64_t diff = DiffTime(&mountStart, &mountEnd); - APPSPAWN_CHECK_ONLY_LOG(diff < MAX_MOUNT_TIME, "mount %{public}s time %{public}" PRId64 " us", arg->srcPath, diff); -#ifdef APPSPAWN_HISYSEVENT - APPSPAWN_CHECK_ONLY_EXPER(diff < FUNC_REPORT_DURATION, ReportAbnormalDuration("MOUNT", diff)); -#endif - if (ret != 0) { - APPSPAWN_LOGI("errno is: %{public}d, bind mount %{public}s to %{public}s", errno, arg->srcPath, arg->destPath); - if (errno == ENOENT && IsNeededCheckPathStatus(appProperty, arg->srcPath)) { - CheckDirRecursive(arg->srcPath); - } - return ret; - } - - ret = mount(nullptr, arg->destPath, nullptr, arg->mountSharedFlag, nullptr); - if (ret != 0) { - APPSPAWN_LOGI("errno is: %{public}d, private mount to %{public}s '%{public}u' failed", - errno, arg->destPath, arg->mountSharedFlag); - if (errno == EINVAL) { - CheckMountStatus(arg->destPath); - } - return ret; - } - return 0; -} - -static std::string& replace_all(std::string& str, const std::string& old_value, const std::string& new_value) -{ - while (true) { - std::string::size_type pos(0); - if ((pos = str.find(old_value)) != std::string::npos) { - str.replace(pos, old_value.length(), new_value); - } else { - break; - } - } - return str; -} - -static std::vector split(std::string &str, const std::string &pattern) -{ - std::string::size_type pos; - std::vector result; - str += pattern; - size_t size = str.size(); - - for (unsigned int i = 0; i < size; i++) { - pos = str.find(pattern, i); - if (pos < size) { - std::string s = str.substr(i, pos - i); - result.push_back(s); - i = pos + pattern.size() - 1; - } - } - - return result; -} - -void SandboxUtils::DoSandboxChmod(nlohmann::json jsonConfig, std::string &sandboxRoot) -{ - const std::map modeMap = {{"S_IRUSR", S_IRUSR}, {"S_IWUSR", S_IWUSR}, {"S_IXUSR", S_IXUSR}, - {"S_IRGRP", S_IRGRP}, {"S_IWGRP", S_IWGRP}, {"S_IXGRP", S_IXGRP}, - {"S_IROTH", S_IROTH}, {"S_IWOTH", S_IWOTH}, {"S_IXOTH", S_IXOTH}, - {"S_IRWXU", S_IRWXU}, {"S_IRWXG", S_IRWXG}, {"S_IRWXO", S_IRWXO}}; - std::string fileModeStr; - mode_t mode = 0; - - bool rc = JsonUtils::GetStringFromJson(jsonConfig, g_destMode, fileModeStr); - if (rc == false) { - return; - } - - std::vector modeVec = split(fileModeStr, "|"); - for (unsigned int i = 0; i < modeVec.size(); i++) { - if (modeMap.count(modeVec[i])) { - mode |= modeMap.at(modeVec[i]); - } - } - - chmod(sandboxRoot.c_str(), mode); -} - -unsigned long SandboxUtils::GetMountFlagsFromConfig(const std::vector &vec) -{ - const std::map MountFlagsMap = { {"rec", MS_REC}, {"MS_REC", MS_REC}, - {"bind", MS_BIND}, {"MS_BIND", MS_BIND}, - {"move", MS_MOVE}, {"MS_MOVE", MS_MOVE}, - {"slave", MS_SLAVE}, {"MS_SLAVE", MS_SLAVE}, - {"rdonly", MS_RDONLY}, {"MS_RDONLY", MS_RDONLY}, - {"shared", MS_SHARED}, {"MS_SHARED", MS_SHARED}, - {"unbindable", MS_UNBINDABLE}, - {"MS_UNBINDABLE", MS_UNBINDABLE}, - {"remount", MS_REMOUNT}, {"MS_REMOUNT", MS_REMOUNT}, - {"nosuid", MS_NOSUID}, {"MS_NOSUID", MS_NOSUID}, - {"nodev", MS_NODEV}, {"MS_NODEV", MS_NODEV}, - {"noexec", MS_NOEXEC}, {"MS_NOEXEC", MS_NOEXEC}, - {"noatime", MS_NOATIME}, {"MS_NOATIME", MS_NOATIME}, - {"lazytime", MS_LAZYTIME}, {"MS_LAZYTIME", MS_LAZYTIME}}; - unsigned long mountFlags = 0; - - for (unsigned int i = 0; i < vec.size(); i++) { - if (MountFlagsMap.count(vec[i])) { - mountFlags |= MountFlagsMap.at(vec[i]); - } - } - - return mountFlags; -} - -static void MakeAtomicServiceDir(const AppSpawningCtx *appProperty, std::string path, std::string variablePackageName) -{ - AppSpawnMsgDacInfo *dacInfo = reinterpret_cast(GetAppProperty(appProperty, TLV_DAC_INFO)); - APPSPAWN_CHECK(dacInfo != NULL, return, "No dac info in msg app property"); - if (path.find("/mnt/share") != std::string::npos) { - path = "/data/service/el2/" + std::to_string(dacInfo->uid / UID_BASE) + "/share/" + variablePackageName; - } - struct stat st = {}; - if (stat(path.c_str(), &st) == 0 && S_ISDIR(st.st_mode)) { - return; - } - - int ret = mkdir(path.c_str(), S_IRWXU); - APPSPAWN_CHECK(ret == 0, return, "mkdir %{public}s failed, errno %{public}d", path.c_str(), errno); - - if (path.find("/database") != std::string::npos || path.find("/data/service/el2") != std::string::npos) { - ret = chmod(path.c_str(), S_IRWXU | S_IRWXG | S_ISGID); - } else if (path.find("/log") != std::string::npos) { - ret = chmod(path.c_str(), S_IRWXU | S_IRWXG); - } - APPSPAWN_CHECK(ret == 0, return, "chmod %{public}s failed, errno %{public}d", path.c_str(), errno); - -#ifdef WITH_SELINUX - AppSpawnMsgDomainInfo *msgDomainInfo = - reinterpret_cast(GetAppProperty(appProperty, TLV_DOMAIN_INFO)); - APPSPAWN_CHECK(msgDomainInfo != NULL, return, "No domain info for %{public}s", GetProcessName(appProperty)); - HapContext hapContext; - HapFileInfo hapFileInfo; - hapFileInfo.pathNameOrig.push_back(path); - hapFileInfo.apl = msgDomainInfo->apl; - hapFileInfo.packageName = GetBundleName(appProperty); - hapFileInfo.hapFlags = msgDomainInfo->hapFlags; - if (CheckAppMsgFlagsSet(appProperty, APP_FLAGS_DEBUGGABLE)) { - hapFileInfo.hapFlags |= SELINUX_HAP_DEBUGGABLE; - } - if ((path.find("/base") != std::string::npos) || (path.find("/database") != std::string::npos)) { - ret = hapContext.HapFileRestorecon(hapFileInfo); - APPSPAWN_CHECK(ret == 0, return, "set dir %{public}s selinuxLabel failed, apl %{public}s, ret %{public}d", - path.c_str(), hapFileInfo.apl.c_str(), ret); - } -#endif - if (path.find("/base") != std::string::npos || path.find("/data/service/el2") != std::string::npos) { - ret = chown(path.c_str(), dacInfo->uid, dacInfo->gid); - } else if (path.find("/database") != std::string::npos) { - ret = chown(path.c_str(), dacInfo->uid, DecodeGid("ddms")); - } else if (path.find("/log") != std::string::npos) { - ret = chown(path.c_str(), dacInfo->uid, DecodeGid("log")); - } - APPSPAWN_CHECK(ret == 0, return, "chown %{public}s failed, errno %{public}d", path.c_str(), errno); - return; -} - -static std::string ReplaceVariablePackageName(const AppSpawningCtx *appProperty, const std::string &path) -{ - std::string tmpSandboxPath = path; - AppSpawnMsgBundleInfo *bundleInfo = - reinterpret_cast(GetAppProperty(appProperty, TLV_BUNDLE_INFO)); - APPSPAWN_CHECK(bundleInfo != NULL, return "", "No bundle info in msg %{public}s", GetBundleName(appProperty)); - - char *extension; - uint32_t flags = CheckAppSpawnMsgFlag(appProperty->message, TLV_MSG_FLAGS, APP_FLAGS_ATOMIC_SERVICE) ? 0x4 : 0; - if (flags == 0) { - flags = (CheckAppSpawnMsgFlag(appProperty->message, TLV_MSG_FLAGS, APP_FLAGS_CLONE_ENABLE) && - bundleInfo->bundleIndex > 0) ? 0x1 : 0; - flags |= CheckAppSpawnMsgFlag(appProperty->message, TLV_MSG_FLAGS, APP_FLAGS_EXTENSION_SANDBOX) ? 0x2 : 0; - extension = reinterpret_cast( - GetAppSpawnMsgExtInfo(appProperty->message, MSG_EXT_NAME_APP_EXTENSION, NULL)); - } - std::ostringstream variablePackageName; - switch (flags) { - case 0: // 0 default - variablePackageName << bundleInfo->bundleName; - break; - case 1: // 1 +clone-bundleIndex+packageName - variablePackageName << "+clone-" << bundleInfo->bundleIndex << "+" << bundleInfo->bundleName; - break; - case 2: { // 2 +extension-+packageName - APPSPAWN_CHECK(extension != NULL, return "", "Invalid extension data "); - variablePackageName << "+extension-" << extension << "+" << bundleInfo->bundleName; - break; - } - case 3: { // 3 +clone-bundleIndex+extension-+packageName - APPSPAWN_CHECK(extension != NULL, return "", "Invalid extension data "); - variablePackageName << "+clone-" << bundleInfo->bundleIndex << "+extension" << "-" << - extension << "+" << bundleInfo->bundleName; - break; - } - case 4: { // 4 +auid-+packageName - std::string accountId = SandboxUtils::GetExtraInfoByType(appProperty, MSG_EXT_NAME_ACCOUNT_ID); - variablePackageName << "+auid-" << accountId << "+" << bundleInfo->bundleName; - std::string atomicServicePath = path; - atomicServicePath = replace_all(atomicServicePath, g_variablePackageName, variablePackageName.str()); - MakeAtomicServiceDir(appProperty, atomicServicePath, variablePackageName.str()); - break; - } - default: - variablePackageName << bundleInfo->bundleName; - break; - } - tmpSandboxPath = replace_all(tmpSandboxPath, g_variablePackageName, variablePackageName.str()); - APPSPAWN_LOGV("tmpSandboxPath %{public}s", tmpSandboxPath.c_str()); - return tmpSandboxPath; -} - -static std::string ReplaceHostUserId(const AppSpawningCtx *appProperty, const std::string &path) -{ - std::string tmpSandboxPath = path; - int32_t uid = 0; - const char *userId = - (const char *)(GetAppSpawnMsgExtInfo(appProperty->message, MSG_EXT_NAME_PARENT_UID, NULL)); - if (userId != nullptr) { - uid = atoi(userId); - } - tmpSandboxPath = replace_all(tmpSandboxPath, g_hostUserId, std::to_string(uid / UID_BASE)); - APPSPAWN_LOGV("tmpSandboxPath %{public}s", tmpSandboxPath.c_str()); - return tmpSandboxPath; -} - -static std::string ReplaceClonePackageName(const AppSpawningCtx *appProperty, const std::string &path) -{ - std::string tmpSandboxPath = path; - AppSpawnMsgBundleInfo *bundleInfo = - reinterpret_cast(GetAppProperty(appProperty, TLV_BUNDLE_INFO)); - APPSPAWN_CHECK(bundleInfo != NULL, return "", "No bundle info in msg %{public}s", GetBundleName(appProperty)); - - std::string tmpBundlePath = bundleInfo->bundleName; - std::ostringstream variablePackageName; - if (CheckAppSpawnMsgFlag(appProperty->message, TLV_MSG_FLAGS, APP_FLAGS_CLONE_ENABLE)) { - variablePackageName << "+clone-" << bundleInfo->bundleIndex << "+" << bundleInfo->bundleName; - tmpBundlePath = variablePackageName.str(); - } - - tmpSandboxPath = replace_all(tmpSandboxPath, g_clonePackageName, tmpBundlePath); - APPSPAWN_LOGV("tmpSandboxPath %{public}s", tmpSandboxPath.c_str()); - return tmpSandboxPath; -} - -string SandboxUtils::ConvertToRealPath(const AppSpawningCtx *appProperty, std::string path) -{ - AppSpawnMsgBundleInfo *info = - reinterpret_cast(GetAppProperty(appProperty, TLV_BUNDLE_INFO)); - AppSpawnMsgDacInfo *dacInfo = reinterpret_cast(GetAppProperty(appProperty, TLV_DAC_INFO)); - if (info == nullptr || dacInfo == nullptr) { - return ""; - } - if (path.find(g_packageNameIndex) != std::string::npos) { - std::string bundleNameWithIndex = info->bundleName; - if (info->bundleIndex != 0) { - bundleNameWithIndex = std::to_string(info->bundleIndex) + "_" + bundleNameWithIndex; - } - path = replace_all(path, g_packageNameIndex, bundleNameWithIndex); - } - - if (path.find(g_packageName) != std::string::npos) { - path = replace_all(path, g_packageName, info->bundleName); - } - - if (path.find(g_userId) != std::string::npos) { - path = replace_all(path, g_userId, std::to_string(dacInfo->uid / UID_BASE)); - } - - if (path.find(g_hostUserId) != std::string::npos) { - path = ReplaceHostUserId(appProperty, path); - } - - if (path.find(g_variablePackageName) != std::string::npos) { - path = ReplaceVariablePackageName(appProperty, path); - } - - if (path.find(g_clonePackageName) != std::string::npos) { - path = ReplaceClonePackageName(appProperty, path); - } - - if (path.find(g_arkWebPackageName) != std::string::npos) { - path = replace_all(path, g_arkWebPackageName, getArkWebPackageName()); - APPSPAWN_LOGV( - "arkWeb sandbox, path %{public}s, package:%{public}s", - path.c_str(), getArkWebPackageName().c_str()); - } - - return path; -} - -std::string SandboxUtils::ConvertToRealPathWithPermission(const AppSpawningCtx *appProperty, - std::string path) -{ - AppSpawnMsgBundleInfo *info = - reinterpret_cast(GetAppProperty(appProperty, TLV_BUNDLE_INFO)); - if (info == nullptr) { - return ""; - } - if (path.find(g_packageNameIndex) != std::string::npos) { - std::string bundleNameWithIndex = info->bundleName; - if (info->bundleIndex != 0) { - bundleNameWithIndex = std::to_string(info->bundleIndex) + "_" + bundleNameWithIndex; - } - path = replace_all(path, g_packageNameIndex, bundleNameWithIndex); - } - - if (path.find(g_packageName) != std::string::npos) { - path = replace_all(path, g_packageName, info->bundleName); - } - - if (path.find(g_userId) != std::string::npos) { - if (deviceTypeEnable_ == FILE_CROSS_APP_STATUS) { - path = replace_all(path, g_userId, "currentUser"); - } else if (deviceTypeEnable_ == FILE_ACCESS_COMMON_DIR_STATUS) { - path = replace_all(path, g_userId, "currentUser"); - } else { - return ""; - } - } - return path; -} - -bool SandboxUtils::GetSandboxDacOverrideEnable(nlohmann::json &config) -{ - std::string dacOverrideSensitive = ""; - if (config.find(g_dacOverrideSensitive) == config.end()) { - return false; - } - dacOverrideSensitive = config[g_dacOverrideSensitive].get(); - if (dacOverrideSensitive.compare("true") == 0) { - return true; - } - return false; -} - -std::string SandboxUtils::GetSbxPathByConfig(const AppSpawningCtx *appProperty, nlohmann::json &config) -{ - AppSpawnMsgDacInfo *dacInfo = reinterpret_cast(GetAppProperty(appProperty, TLV_DAC_INFO)); - if (dacInfo == nullptr) { - return ""; - } - - std::string sandboxRoot = ""; - const std::string sandboxRootPathTemplate = "/mnt/sandbox//"; - const std::string originSandboxPath = "/mnt/sandbox/"; - std::string isolatedFlagText = CheckAppMsgFlagsSet(appProperty, APP_FLAGS_ISOLATED_SANDBOX_TYPE) ? "isolated/" : ""; - AppSpawnMsgBundleInfo *bundleInfo = - reinterpret_cast(GetAppProperty(appProperty, TLV_BUNDLE_INFO)); - if (bundleInfo == nullptr) { - return ""; - } - std::string tmpBundlePath = bundleInfo->bundleName; - std::ostringstream variablePackageName; - if (CheckAppSpawnMsgFlag(appProperty->message, TLV_MSG_FLAGS, APP_FLAGS_CLONE_ENABLE)) { - variablePackageName << "+clone-" << bundleInfo->bundleIndex << "+" << bundleInfo->bundleName; - tmpBundlePath = variablePackageName.str(); - } - const std::string variableSandboxRoot = g_sandBoxDir + to_string(dacInfo->uid / UID_BASE) + - "/" + isolatedFlagText.c_str() + tmpBundlePath; - if (config.find(g_sandboxRootPrefix) != config.end()) { - sandboxRoot = config[g_sandboxRootPrefix].get(); - if (sandboxRoot == originSandboxPath || sandboxRoot == sandboxRootPathTemplate) { - sandboxRoot = variableSandboxRoot; - } else { - sandboxRoot = ConvertToRealPath(appProperty, sandboxRoot); - APPSPAWN_LOGV("set sandbox-root name is %{public}s", sandboxRoot.c_str()); - } - } else { - sandboxRoot = variableSandboxRoot; - APPSPAWN_LOGV("set sandbox-root to default rootapp name is %{public}s", GetBundleName(appProperty)); - } - - return sandboxRoot; -} - -bool SandboxUtils::GetSbxSwitchStatusByConfig(nlohmann::json &config) -{ - if (config.find(g_sandBoxSwitchPrefix) != config.end()) { - std::string switchStatus = config[g_sandBoxSwitchPrefix].get(); - if (switchStatus == g_sbxSwitchCheck) { - return true; - } else { - return false; - } - } - - // if not find sandbox-switch node, default switch status is true - return true; -} - -static bool CheckMountConfig(nlohmann::json &mntPoint, const AppSpawningCtx *appProperty, - bool checkFlag) -{ - bool istrue = mntPoint.find(g_srcPath) == mntPoint.end() || (!mntPoint[g_srcPath].is_string()) || - mntPoint.find(g_sandBoxPath) == mntPoint.end() || (!mntPoint[g_sandBoxPath].is_string()) || - ((mntPoint.find(g_sandBoxFlags) == mntPoint.end()) && - (mntPoint.find(g_sandBoxFlagsCustomized) == mntPoint.end())); - APPSPAWN_CHECK(!istrue, return false, - "read mount config failed, app name is %{public}s", GetBundleName(appProperty)); - - AppSpawnMsgDomainInfo *info = - reinterpret_cast(GetAppProperty(appProperty, TLV_DOMAIN_INFO)); - APPSPAWN_CHECK(info != nullptr, return false, "Filed to get domain info %{public}s", GetBundleName(appProperty)); - - if (mntPoint[g_appAplName] != nullptr) { - std::string app_apl_name = mntPoint[g_appAplName].get(); - const char *p_app_apl = nullptr; - p_app_apl = app_apl_name.c_str(); - if (!strcmp(p_app_apl, info->apl)) { - return false; - } - } - - const std::string configSrcPath = mntPoint[g_srcPath].get(); - // special handle wps and don't use /data/app/xxx/ config - if (checkFlag && (configSrcPath.find("/data/app") != std::string::npos && - (configSrcPath.find("/base") != std::string::npos || - configSrcPath.find("/database") != std::string::npos - ) && configSrcPath.find(g_packageName) != std::string::npos)) { - return false; - } - - return true; -} - -static int32_t DoDlpAppMountStrategy(const AppSpawningCtx *appProperty, - const std::string &srcPath, const std::string &sandboxPath, - const std::string &fsType, unsigned long mountFlags) -{ - AppSpawnMsgDacInfo *dacInfo = reinterpret_cast(GetAppProperty(appProperty, TLV_DAC_INFO)); - if (dacInfo == nullptr) { - return -1; - } - - // umount fuse path, make sure that sandbox path is not a mount point - umount2(sandboxPath.c_str(), MNT_DETACH); - - int fd = open("/dev/fuse", O_RDWR); - APPSPAWN_CHECK(fd != -1, return -EINVAL, "open /dev/fuse failed, errno is %{public}d", errno); - - char options[OPTIONS_MAX_LEN]; - (void)sprintf_s(options, sizeof(options), "fd=%d," - "rootmode=40000,user_id=%u,group_id=%u,allow_other," - "context=\"u:object_r:dlp_fuse_file:s0\"," - "fscontext=u:object_r:dlp_fuse_file:s0", - fd, dacInfo->uid, dacInfo->gid); - - // To make sure destinationPath exist - MakeDirRecursive(sandboxPath, FILE_MODE); - - int ret = 0; -#ifndef APPSPAWN_TEST - APPSPAWN_LOGV("Bind mount %{public}s to %{public}s '%{public}s' '%{public}lu' '%{public}s'", - srcPath.c_str(), sandboxPath.c_str(), fsType.c_str(), mountFlags, options); - ret = mount(srcPath.c_str(), sandboxPath.c_str(), fsType.c_str(), mountFlags, options); - APPSPAWN_CHECK(ret == 0, close(fd); - return ret, "DoDlpAppMountStrategy failed, bind mount %{public}s to %{public}s failed %{public}d", - srcPath.c_str(), sandboxPath.c_str(), errno); - - ret = mount(nullptr, sandboxPath.c_str(), nullptr, MS_SHARED, nullptr); - APPSPAWN_CHECK(ret == 0, close(fd); - return ret, "errno is: %{public}d, private mount to %{public}s failed", errno, sandboxPath.c_str()); -#endif - /* set DLP_FUSE_FD */ -#ifdef WITH_DLP - SetDlpFuseFd(fd); -#endif - ret = fd; - return ret; -} - -static int32_t HandleSpecialAppMount(const AppSpawningCtx *appProperty, - const std::string &srcPath, const std::string &sandboxPath, const std::string &fsType, unsigned long mountFlags) -{ - std::string bundleName = GetBundleName(appProperty); - std::string processName = GetProcessName(appProperty); - /* dlp application mount strategy */ - /* dlp is an example, we should change to real bundle name later */ - if (bundleName.find(g_dlpBundleName) != std::string::npos && - processName.compare(g_dlpBundleName) == 0) { - if (!fsType.empty()) { - return DoDlpAppMountStrategy(appProperty, srcPath, sandboxPath, fsType, mountFlags); - } - } - return -1; -} - -static uint32_t ConvertFlagStr(const std::string &flagStr) -{ - const std::map flagsMap = {{"0", 0}, {"START_FLAGS_BACKUP", 1}, - {"DLP_MANAGER", 2}, - {"DEVELOPER_MODE", 17}, - {"PREINSTALLED_HAP", 29}, - {"CUSTOM_SANDBOX_HAP", 31}}; - - if (flagsMap.count(flagStr)) { - return 1 << flagsMap.at(flagStr); - } - - return 0; -} - -unsigned long SandboxUtils::GetSandboxMountFlags(nlohmann::json &config) -{ - unsigned long mountFlags = BASIC_MOUNT_FLAGS; - if (GetSandboxDacOverrideEnable(config) && (config.find(g_sandBoxFlagsCustomized) != config.end())) { - mountFlags = GetMountFlagsFromConfig(config[g_sandBoxFlagsCustomized].get>()); - } else if (config.find(g_sandBoxFlags) != config.end()) { - mountFlags = GetMountFlagsFromConfig(config[g_sandBoxFlags].get>()); - } - return mountFlags; -} - -std::string SandboxUtils::GetSandboxFsType(nlohmann::json &config) -{ - std::string fsType = ""; - if (GetSandboxDacOverrideEnable(config) && (config.find(g_fsType) != config.end())) { - fsType = config[g_fsType].get(); - } - return fsType; -} - -std::string SandboxUtils::GetSandboxOptions(const AppSpawningCtx *appProperty, nlohmann::json &config) -{ - AppSpawnMsgDacInfo *dacInfo = reinterpret_cast(GetAppProperty(appProperty, TLV_DAC_INFO)); - if (dacInfo == nullptr) { - return ""; - } - - std::string options = ""; - const int userIdBase = UID_BASE; - if (GetSandboxDacOverrideEnable(config) && (config.find(g_sandBoxOptions) != config.end())) { - options = config[g_sandBoxOptions].get() + ",user_id="; - options += std::to_string(dacInfo->uid / userIdBase); - } - return options; -} - -std::vector SandboxUtils::GetSandboxDecPath(const AppSpawningCtx *appProperty, nlohmann::json &config) -{ - AppSpawnMsgDacInfo *dacInfo = reinterpret_cast(GetAppProperty(appProperty, TLV_DAC_INFO)); - if (dacInfo == nullptr) { - return {}; - } - - std::vector decPaths = {}; - if (config.find(g_sandBoxDecPath) != config.end()) { - for (auto decPath : config[g_sandBoxDecPath].get>()) { - decPath = ConvertToRealPathWithPermission(appProperty, decPath); - decPaths.push_back(decPath); - } - } - return decPaths; -} - -void SandboxUtils::GetSandboxMountConfig(const AppSpawningCtx *appProperty, const std::string §ion, - nlohmann::json &mntPoint, SandboxMountConfig &mountConfig) -{ - if (section.compare(g_permissionPrefix) == 0) { - mountConfig.optionsPoint = GetSandboxOptions(appProperty, mntPoint); - mountConfig.fsType = GetSandboxFsType(mntPoint); - mountConfig.decPaths = GetSandboxDecPath(appProperty, mntPoint); - } else { - mountConfig.fsType = (mntPoint.find(g_fsType) != mntPoint.end()) ? mntPoint[g_fsType].get() : ""; - mountConfig.optionsPoint = ""; - mountConfig.decPaths = {}; - } - return; -} - -std::string SandboxUtils::GetSandboxPath(const AppSpawningCtx *appProperty, nlohmann::json &mntPoint, - const std::string §ion, std::string sandboxRoot) -{ - std::string sandboxPath = ""; - std::string tmpSandboxPath = mntPoint[g_sandBoxPath].get(); - if (section.compare(g_permissionPrefix) == 0) { - sandboxPath = sandboxRoot + ConvertToRealPathWithPermission(appProperty, tmpSandboxPath); - } else { - sandboxPath = sandboxRoot + ConvertToRealPath(appProperty, tmpSandboxPath); - } - return sandboxPath; -} - -static bool CheckMountFlag(const AppSpawningCtx *appProperty, const std::string bundleName, nlohmann::json &appConfig) -{ - if (appConfig.find(g_flags) != appConfig.end()) { - if (((ConvertFlagStr(appConfig[g_flags].get()) & GetAppMsgFlags(appProperty)) != 0) && - bundleName.find("wps") != std::string::npos) { - return true; - } - } - return false; -} - -int32_t SandboxUtils::SetDecWithDir(const AppSpawningCtx *appProperty, uint32_t userId) -{ - AppSpawnMsgAccessToken *tokenInfo = - reinterpret_cast(GetAppProperty(appProperty, TLV_ACCESS_TOKEN_INFO)); - APPSPAWN_CHECK(tokenInfo != NULL, return APPSPAWN_MSG_INVALID, "Get token id failed."); - - AppSpawnMsgBundleInfo *bundleInfo = - reinterpret_cast(GetAppProperty(appProperty, TLV_BUNDLE_INFO)); - APPSPAWN_CHECK(bundleInfo != NULL, return APPSPAWN_MSG_INVALID, "No bundle info in msg %{public}s", - GetBundleName(appProperty)); - - uint32_t flags = CheckAppSpawnMsgFlag(appProperty->message, TLV_MSG_FLAGS, APP_FLAGS_ATOMIC_SERVICE) ? 0x4 : 0; - if (flags == 0) { - flags = (CheckAppSpawnMsgFlag(appProperty->message, TLV_MSG_FLAGS, APP_FLAGS_CLONE_ENABLE) && - bundleInfo->bundleIndex > 0) ? 0x1 : 0; - } - std::ostringstream clonePackageName; - if (flags == 1) { - clonePackageName << "+clone-" << bundleInfo->bundleIndex << "+" << bundleInfo->bundleName; - } else { - clonePackageName << bundleInfo->bundleName; - } - std::string dir = "/storage/Users/currentUser/Download/" + clonePackageName.str(); - DecPolicyInfo decPolicyInfo = {0}; - decPolicyInfo.pathNum = 1; - PathInfo pathInfo = {0}; - pathInfo.path = strdup(dir.c_str()); - if (pathInfo.path == nullptr) { - APPSPAWN_LOGE("strdup %{public}s failed, err %{public}d", dir.c_str(), errno); - return APPSPAWN_MSG_INVALID; - } - pathInfo.pathLen = static_cast(strlen(pathInfo.path)); - pathInfo.mode = SANDBOX_MODE_WRITE | SANDBOX_MODE_READ; - decPolicyInfo.path[0] = pathInfo; - decPolicyInfo.tokenId = tokenInfo->accessTokenIdEx; - decPolicyInfo.flag = true; - SetDecPolicyInfos(&decPolicyInfo); - - if (decPolicyInfo.path[0].path) { - free(decPolicyInfo.path[0].path); - decPolicyInfo.path[0].path = nullptr; - } - return 0; -} - -int32_t SandboxUtils::SetDecPolicyWithPermission(const AppSpawningCtx *appProperty, SandboxMountConfig &mountConfig) -{ - if (mountConfig.decPaths.size() == 0) { - return 0; - } - AppSpawnMsgAccessToken *tokenInfo = - reinterpret_cast(GetAppProperty(appProperty, TLV_ACCESS_TOKEN_INFO)); - APPSPAWN_CHECK(tokenInfo != NULL, return APPSPAWN_MSG_INVALID, "Get token id failed."); - - DecPolicyInfo decPolicyInfo = {0}; - decPolicyInfo.pathNum = mountConfig.decPaths.size(); - int ret = 0; - for (uint32_t i = 0; i < decPolicyInfo.pathNum; i++) { - PathInfo pathInfo = {0}; - pathInfo.path = strdup(mountConfig.decPaths[i].c_str()); - if (pathInfo.path == nullptr) { - APPSPAWN_LOGE("strdup %{public}s failed, err %{public}d", mountConfig.decPaths[i].c_str(), errno); - ret = APPSPAWN_ERROR_UTILS_MEM_FAIL; - goto EXIT; - } - pathInfo.pathLen = static_cast(strlen(pathInfo.path)); - pathInfo.mode = SANDBOX_MODE_WRITE | SANDBOX_MODE_READ; - decPolicyInfo.path[i] = pathInfo; - } - decPolicyInfo.tokenId = tokenInfo->accessTokenIdEx; - decPolicyInfo.flag = true; - SetDecPolicyInfos(&decPolicyInfo); -EXIT: - for (uint32_t i = 0; i < decPolicyInfo.pathNum; i++) { - if (decPolicyInfo.path[i].path) { - free(decPolicyInfo.path[i].path); - decPolicyInfo.path[i].path = nullptr; - } - } - return ret; -} - -static const DecDenyPathTemplate DEC_DENY_PATH_MAP[] = { - {"ohos.permission.READ_WRITE_DOWNLOAD_DIRECTORY", "/storage/Users/currentUser/Download"}, - {"ohos.permission.READ_WRITE_DESKTOP_DIRECTORY", "/storage/Users/currentUser/Desktop"}, - {"ohos.permission.READ_WRITE_DOCUMENTS_DIRECTORY", "/storage/Users/currentUser/Documents"}, -}; -void SandboxUtils::SetDecDenyWithDir(const AppSpawningCtx *appProperty) -{ - int32_t userFileIndex = GetPermissionIndex(nullptr, READ_WRITE_USER_FILE_MODE.c_str()); - if (CheckAppPermissionFlagSet(appProperty, static_cast(userFileIndex)) == 0) { - APPSPAWN_LOGV("The app doesn't have %{public}s, no need to set deny rules", READ_WRITE_USER_FILE_MODE.c_str()); - return; - } - - AppSpawnMsgAccessToken *tokenInfo = - reinterpret_cast(GetAppProperty(appProperty, TLV_ACCESS_TOKEN_INFO)); - APPSPAWN_CHECK(tokenInfo != NULL, return, "Get token id failed"); - - DecPolicyInfo decPolicyInfo = {0}; - decPolicyInfo.pathNum = 0; - uint32_t count = ARRAY_LENGTH(DEC_DENY_PATH_MAP); - for (uint32_t i = 0, j = 0; i < count; i++) { - int32_t index = GetPermissionIndex(nullptr, DEC_DENY_PATH_MAP[i].permission); - if (CheckAppPermissionFlagSet(appProperty, static_cast(index))) { - continue; - } - PathInfo pathInfo = {0}; - pathInfo.path = const_cast(DEC_DENY_PATH_MAP[i].decPath); - pathInfo.pathLen = static_cast(strlen(pathInfo.path)); - pathInfo.mode = DEC_MODE_DENY_READ | DEC_MODE_DENY_WRITE; - decPolicyInfo.path[j++] = pathInfo; - decPolicyInfo.pathNum += 1; - } - decPolicyInfo.tokenId = tokenInfo->accessTokenIdEx; - decPolicyInfo.flag = true; - SetDecPolicyInfos(&decPolicyInfo); -} - -static bool GetCheckStatus(nlohmann::json &mntPoint) -{ - std::string value = g_statusCheck; - (void)JsonUtils::GetStringFromJson(mntPoint, g_actionStatuc, value); - if (value == g_statusCheck) { - return true; - } - return false; -} - -static bool GetCreateSandboxPath(nlohmann::json &json, std::string srcPath) -{ - APPSPAWN_CHECK(json != nullptr && json.is_object(), return true, "json is not object."); - bool isRet = json.find(CREATE_SANDBOX_PATH) != json.end() && json.at(CREATE_SANDBOX_PATH).is_string(); - if (isRet) { - std::string value = json.at(CREATE_SANDBOX_PATH).get(); - APPSPAWN_LOGV("Find create-sandbox-path: %{public}s successful.", value.c_str()); - if (value == "false" && access(srcPath.c_str(), F_OK) != 0) { - return false; - } - } - return true; -} - -int SandboxUtils::DoAllMntPointsMount(const AppSpawningCtx *appProperty, - nlohmann::json &appConfig, const char *typeName, const std::string §ion) -{ - std::string bundleName = GetBundleName(appProperty); - if (appConfig.find(g_mountPrefix) == appConfig.end()) { - APPSPAWN_LOGV("mount config is not found in %{public}s, app name is %{public}s", - section.c_str(), bundleName.c_str()); - return 0; - } - std::string sandboxRoot = GetSbxPathByConfig(appProperty, appConfig); - bool checkFlag = CheckMountFlag(appProperty, bundleName, appConfig); - nlohmann::json& mountPoints = appConfig[g_mountPrefix]; - unsigned int mountPointSize = mountPoints.size(); - for (unsigned int i = 0; i < mountPointSize; i++) { - nlohmann::json& mntPoint = mountPoints[i]; - APPSPAWN_CHECK_ONLY_EXPER(CheckMountConfig(mntPoint, appProperty, checkFlag), continue); - - std::string srcPath = ConvertToRealPath(appProperty, mntPoint[g_srcPath].get()); - APPSPAWN_CHECK_ONLY_EXPER(GetCreateSandboxPath(mntPoint, srcPath), continue); - std::string sandboxPath = GetSandboxPath(appProperty, mntPoint, section, sandboxRoot); - SandboxMountConfig mountConfig = {0}; - GetSandboxMountConfig(appProperty, section, mntPoint, mountConfig); - SharedMountArgs arg = { - .srcPath = srcPath.c_str(), - .destPath = sandboxPath.c_str(), - .fsType = mountConfig.fsType.c_str(), - .mountFlags = GetSandboxMountFlags(mntPoint), - .options = mountConfig.optionsPoint.c_str(), - .mountSharedFlag = (mntPoint.find(g_mountSharedFlag) != mntPoint.end()) ? MS_SHARED : MS_SLAVE - }; - - /* if app mount failed for special strategy, we need deal with common mount config */ - int ret = HandleSpecialAppMount(appProperty, arg.srcPath, arg.destPath, arg.fsType, arg.mountFlags); - if (ret < 0) { - ret = DoAppSandboxMountOnce(appProperty, &arg); - } - APPSPAWN_CHECK(ret == 0 || !GetCheckStatus(mntPoint), -#ifdef APPSPAWN_HISYSEVENT - ReportMountFail(bundleName.c_str(), arg.srcPath, arg.destPath, errno); - ret = APPSPAWN_SANDBOX_MOUNT_FAIL; -#endif - return ret, - "DoAppSandboxMountOnce section %{public}s failed, %{public}s", section.c_str(), arg.destPath); - SetDecPolicyWithPermission(appProperty, mountConfig); - DoSandboxChmod(mntPoint, sandboxRoot); - } - return 0; -} - -int32_t SandboxUtils::DoAddGid(AppSpawningCtx *appProperty, nlohmann::json &appConfig, - const char* permissionName, const std::string §ion) -{ - std::string bundleName = GetBundleName(appProperty); - if (appConfig.find(g_gidPrefix) == appConfig.end()) { - return 0; - } - AppSpawnMsgDacInfo *dacInfo = reinterpret_cast(GetAppProperty(appProperty, TLV_DAC_INFO)); - if (dacInfo == nullptr) { - return 0; - } - - nlohmann::json& gids = appConfig[g_gidPrefix]; - unsigned int gidSize = gids.size(); - for (unsigned int i = 0; i < gidSize; i++) { - if (dacInfo->gidCount < APP_MAX_GIDS) { - APPSPAWN_LOGI("add gid to gitTable in %{public}s, permission is %{public}s, gid:%{public}u", - bundleName.c_str(), permissionName, gids[i].get()); - dacInfo->gidTable[dacInfo->gidCount++] = gids[i].get(); - } - } - return 0; -} - -int SandboxUtils::DoAllSymlinkPointslink(const AppSpawningCtx *appProperty, nlohmann::json &appConfig) -{ - APPSPAWN_CHECK(appConfig.find(g_symlinkPrefix) != appConfig.end(), return 0, "symlink config is not found," - "maybe result sandbox launch failed app name is %{public}s", GetBundleName(appProperty)); - - nlohmann::json& symlinkPoints = appConfig[g_symlinkPrefix]; - std::string sandboxRoot = GetSbxPathByConfig(appProperty, appConfig); - unsigned int symlinkPointSize = symlinkPoints.size(); - - for (unsigned int i = 0; i < symlinkPointSize; i++) { - nlohmann::json& symPoint = symlinkPoints[i]; - - // Check the validity of the symlink configuration - if (symPoint.find(g_targetName) == symPoint.end() || (!symPoint[g_targetName].is_string()) || - symPoint.find(g_linkName) == symPoint.end() || (!symPoint[g_linkName].is_string())) { - APPSPAWN_LOGE("read symlink config failed, app name is %{public}s", GetBundleName(appProperty)); - continue; - } - - std::string targetName = ConvertToRealPath(appProperty, symPoint[g_targetName].get()); - std::string linkName = sandboxRoot + ConvertToRealPath(appProperty, symPoint[g_linkName].get()); - APPSPAWN_LOGV("symlink, from %{public}s to %{public}s", targetName.c_str(), linkName.c_str()); - - int ret = symlink(targetName.c_str(), linkName.c_str()); - if (ret && errno != EEXIST) { - APPSPAWN_LOGE("errno is %{public}d, symlink failed, %{public}s", errno, linkName.c_str()); - - std::string actionStatus = g_statusCheck; - (void)JsonUtils::GetStringFromJson(symPoint, g_actionStatuc, actionStatus); - if (actionStatus == g_statusCheck) { - return ret; - } - } - - DoSandboxChmod(symPoint, sandboxRoot); - } - - return 0; -} - -int32_t SandboxUtils::DoSandboxFilePrivateBind(const AppSpawningCtx *appProperty, - nlohmann::json &wholeConfig) -{ - const char *bundleName = GetBundleName(appProperty); - nlohmann::json& privateAppConfig = wholeConfig[g_privatePrefix][0]; - if (privateAppConfig.find(bundleName) != privateAppConfig.end()) { - APPSPAWN_LOGV("DoSandboxFilePrivateBind %{public}s", bundleName); - DoAddGid((AppSpawningCtx *)appProperty, privateAppConfig[bundleName][0], "", g_privatePrefix); - return DoAllMntPointsMount(appProperty, privateAppConfig[bundleName][0], nullptr, g_privatePrefix); - } - - return 0; -} - -int32_t SandboxUtils::DoSandboxFilePermissionBind(AppSpawningCtx *appProperty, - nlohmann::json &wholeConfig) -{ - if (wholeConfig.find(g_permissionPrefix) == wholeConfig.end()) { - APPSPAWN_LOGV("DoSandboxFilePermissionBind not found permission information in config file"); - return 0; - } - nlohmann::json& permissionAppConfig = wholeConfig[g_permissionPrefix][0]; - for (nlohmann::json::iterator it = permissionAppConfig.begin(); it != permissionAppConfig.end(); ++it) { - const std::string permission = it.key(); - int index = GetPermissionIndex(nullptr, permission.c_str()); - APPSPAWN_LOGV("DoSandboxFilePermissionBind mountPermissionFlags %{public}d", index); - if (CheckAppPermissionFlagSet(appProperty, static_cast(index))) { - DoAddGid(appProperty, permissionAppConfig[permission][0], permission.c_str(), g_permissionPrefix); - DoAllMntPointsMount(appProperty, permissionAppConfig[permission][0], permission.c_str(), - g_permissionPrefix); - } else { - APPSPAWN_LOGV("DoSandboxFilePermissionBind false %{public}s permission %{public}s", - GetBundleName(appProperty), permission.c_str()); - } - } - return 0; -} - -std::set SandboxUtils::GetMountPermissionNames() -{ - std::set permissionSet; - for (auto& config : SandboxUtils::GetJsonConfig(SANBOX_APP_JSON_CONFIG)) { - if (config.find(g_permissionPrefix) == config.end()) { - continue; - } - nlohmann::json& permissionAppConfig = config[g_permissionPrefix][0]; - for (auto it = permissionAppConfig.begin(); it != permissionAppConfig.end(); it++) { - permissionSet.insert(it.key()); - } - } - APPSPAWN_LOGI("GetMountPermissionNames size: %{public}lu", static_cast(permissionSet.size())); - return permissionSet; -} - -int32_t SandboxUtils::DoSandboxFilePrivateSymlink(const AppSpawningCtx *appProperty, - nlohmann::json &wholeConfig) -{ - const char *bundleName = GetBundleName(appProperty); - nlohmann::json& privateAppConfig = wholeConfig[g_privatePrefix][0]; - if (privateAppConfig.find(bundleName) != privateAppConfig.end()) { - return DoAllSymlinkPointslink(appProperty, privateAppConfig[bundleName][0]); - } - - return 0; -} - -int32_t SandboxUtils::HandleFlagsPoint(const AppSpawningCtx *appProperty, - nlohmann::json &appConfig) -{ - if (appConfig.find(g_flagePoint) == appConfig.end()) { - return 0; - } - - nlohmann::json& flagsPoints = appConfig[g_flagePoint]; - unsigned int flagsPointSize = flagsPoints.size(); - - for (unsigned int i = 0; i < flagsPointSize; i++) { - nlohmann::json& flagPoint = flagsPoints[i]; - - if (flagPoint.find(g_flags) != flagPoint.end() && flagPoint[g_flags].is_string()) { - std::string flagsStr = flagPoint[g_flags].get(); - uint32_t flag = ConvertFlagStr(flagsStr); - if ((GetAppMsgFlags(appProperty) & flag) == 0) { - continue; - } - int ret = DoAllMntPointsMount(appProperty, flagPoint, nullptr, g_flagePoint); - if (ret != 0) { - APPSPAWN_LOGE("DoAllMntPointsMount failed ret: %{public}d", ret); - } - } else { - APPSPAWN_LOGE("read flags config failed, app name is %{public}s", GetBundleName(appProperty)); - } - } - - return 0; -} - -int32_t SandboxUtils::DoSandboxFilePrivateFlagsPointHandle(const AppSpawningCtx *appProperty, - nlohmann::json &wholeConfig) -{ - const char *bundleName = GetBundleName(appProperty); - nlohmann::json& privateAppConfig = wholeConfig[g_privatePrefix][0]; - if (privateAppConfig.find(bundleName) != privateAppConfig.end()) { - return HandleFlagsPoint(appProperty, privateAppConfig[bundleName][0]); - } - - return 0; -} - -int32_t SandboxUtils::DoSandboxFileCommonFlagsPointHandle(const AppSpawningCtx *appProperty, - nlohmann::json &wholeConfig) -{ - nlohmann::json& commonConfig = wholeConfig[g_commonPrefix][0]; - if (commonConfig.find(g_appResources) != commonConfig.end()) { - return HandleFlagsPoint(appProperty, commonConfig[g_appResources][0]); - } - - return 0; -} - -int32_t SandboxUtils::DoSandboxFileCommonBind(const AppSpawningCtx *appProperty, nlohmann::json &wholeConfig) -{ - nlohmann::json& commonConfig = wholeConfig[g_commonPrefix][0]; - int ret = 0; - - if (commonConfig.find(g_appBase) != commonConfig.end()) { - ret = DoAllMntPointsMount(appProperty, commonConfig[g_appBase][0], nullptr, g_appBase); - if (ret) { - return ret; - } - } - - if (commonConfig.find(g_appResources) != commonConfig.end()) { - ret = DoAllMntPointsMount(appProperty, commonConfig[g_appResources][0], nullptr, g_appResources); - } - - return ret; -} - -int32_t SandboxUtils::DoSandboxFileCommonSymlink(const AppSpawningCtx *appProperty, - nlohmann::json &wholeConfig) -{ - nlohmann::json& commonConfig = wholeConfig[g_commonPrefix][0]; - int ret = 0; - - if (commonConfig.find(g_appBase) != commonConfig.end()) { - ret = DoAllSymlinkPointslink(appProperty, commonConfig[g_appBase][0]); - if (ret) { - return ret; - } - } - - if (commonConfig.find(g_appResources) != commonConfig.end()) { - ret = DoAllSymlinkPointslink(appProperty, commonConfig[g_appResources][0]); - } - - return ret; -} - -int32_t SandboxUtils::SetPrivateAppSandboxProperty_(const AppSpawningCtx *appProperty, - nlohmann::json &config) -{ - int ret = DoSandboxFilePrivateBind(appProperty, config); - APPSPAWN_CHECK(ret == 0, return ret, "DoSandboxFilePrivateBind failed"); - - ret = DoSandboxFilePrivateSymlink(appProperty, config); - APPSPAWN_CHECK_ONLY_LOG(ret == 0, "DoSandboxFilePrivateSymlink failed"); - - ret = DoSandboxFilePrivateFlagsPointHandle(appProperty, config); - APPSPAWN_CHECK_ONLY_LOG(ret == 0, "DoSandboxFilePrivateFlagsPointHandle failed"); - - return ret; -} - -int32_t SandboxUtils::SetPermissionAppSandboxProperty_(AppSpawningCtx *appProperty, - nlohmann::json &config) -{ - int ret = DoSandboxFilePermissionBind(appProperty, config); - APPSPAWN_CHECK(ret == 0, return ret, "DoSandboxFilePermissionBind failed"); - return ret; -} - - -int32_t SandboxUtils::SetRenderSandboxProperty(const AppSpawningCtx *appProperty, - std::string &sandboxPackagePath) -{ - return 0; -} - -int32_t SandboxUtils::SetRenderSandboxPropertyNweb(const AppSpawningCtx *appProperty, - std::string &sandboxPackagePath) -{ - SandboxConfigType type = CheckAppMsgFlagsSet(appProperty, APP_FLAGS_ISOLATED_SANDBOX_TYPE) ? - SANBOX_ISOLATED_JSON_CONFIG : SANBOX_APP_JSON_CONFIG; - - for (auto& config : SandboxUtils::GetJsonConfig(type)) { - nlohmann::json& privateAppConfig = config[g_privatePrefix][0]; - char *processType = (char *)(GetAppSpawnMsgExtInfo(appProperty->message, MSG_EXT_NAME_PROCESS_TYPE, NULL)); - APPSPAWN_CHECK(processType != NULL, return -1, "Invalid processType data"); - - if (strcmp(processType, "render") == 0 && privateAppConfig.find(g_ohosRender) != privateAppConfig.end()) { - int ret = DoAllMntPointsMount(appProperty, privateAppConfig[g_ohosRender][0], nullptr, g_ohosRender); - APPSPAWN_CHECK(ret == 0, return ret, "DoAllMntPointsMount failed, %{public}s", - GetBundleName(appProperty)); - ret = DoAllSymlinkPointslink(appProperty, privateAppConfig[g_ohosRender][0]); - APPSPAWN_CHECK(ret == 0, return ret, "DoAllSymlinkPointslink failed, %{public}s", - GetBundleName(appProperty)); - ret = HandleFlagsPoint(appProperty, privateAppConfig[g_ohosRender][0]); - APPSPAWN_CHECK_ONLY_LOG(ret == 0, "HandleFlagsPoint for render-sandbox failed, %{public}s", - GetBundleName(appProperty)); - } else if (strcmp(processType, "gpu") == 0 && privateAppConfig.find(g_ohosGpu) != privateAppConfig.end()) { - int ret = DoAllMntPointsMount(appProperty, privateAppConfig[g_ohosGpu][0], nullptr, g_ohosGpu); - APPSPAWN_CHECK(ret == 0, return ret, "DoAllMntPointsMount failed, %{public}s", - GetBundleName(appProperty)); - ret = DoAllSymlinkPointslink(appProperty, privateAppConfig[g_ohosGpu][0]); - APPSPAWN_CHECK(ret == 0, return ret, "DoAllSymlinkPointslink failed, %{public}s", - GetBundleName(appProperty)); - ret = HandleFlagsPoint(appProperty, privateAppConfig[g_ohosGpu][0]); - APPSPAWN_CHECK_ONLY_LOG(ret == 0, "HandleFlagsPoint for render-sandbox failed, %{public}s", - GetBundleName(appProperty)); - } - } - return 0; -} - -int32_t SandboxUtils::SetPrivateAppSandboxProperty(const AppSpawningCtx *appProperty) -{ - int ret = 0; - SandboxConfigType type = CheckAppMsgFlagsSet(appProperty, APP_FLAGS_ISOLATED_SANDBOX_TYPE) ? - SANBOX_ISOLATED_JSON_CONFIG : SANBOX_APP_JSON_CONFIG; - - for (auto& config : SandboxUtils::GetJsonConfig(type)) { - ret = SetPrivateAppSandboxProperty_(appProperty, config); - APPSPAWN_CHECK(ret == 0, return ret, "parse adddata-sandbox config failed"); - } - return ret; -} - -static bool GetSandboxPrivateSharedStatus(const string &bundleName, AppSpawningCtx *appProperty) -{ - bool result = false; - SandboxConfigType type = CheckAppMsgFlagsSet(appProperty, APP_FLAGS_ISOLATED_SANDBOX_TYPE) ? - SANBOX_ISOLATED_JSON_CONFIG : SANBOX_APP_JSON_CONFIG; - - for (auto& config : SandboxUtils::GetJsonConfig(type)) { - nlohmann::json& privateAppConfig = config[g_privatePrefix][0]; - if (privateAppConfig.find(bundleName) != privateAppConfig.end() && - privateAppConfig[bundleName][0].find(g_sandBoxShared) != - privateAppConfig[bundleName][0].end()) { - string sandboxSharedStatus = - privateAppConfig[bundleName][0][g_sandBoxShared].get(); - if (sandboxSharedStatus == g_statusCheck) { - result = true; - } - } - } - return result; -} - -int32_t SandboxUtils::SetPermissionAppSandboxProperty(AppSpawningCtx *appProperty) -{ - int ret = 0; - SandboxConfigType type = CheckAppMsgFlagsSet(appProperty, APP_FLAGS_ISOLATED_SANDBOX_TYPE) ? - SANBOX_ISOLATED_JSON_CONFIG : SANBOX_APP_JSON_CONFIG; - - for (auto& config : SandboxUtils::GetJsonConfig(type)) { - ret = SetPermissionAppSandboxProperty_(appProperty, config); - APPSPAWN_CHECK(ret == 0, return ret, "parse adddata-sandbox config failed"); - } - return ret; -} - - -int32_t SandboxUtils::SetCommonAppSandboxProperty_(const AppSpawningCtx *appProperty, - nlohmann::json &config) -{ - int rc = 0; - - rc = DoSandboxFileCommonBind(appProperty, config); - APPSPAWN_CHECK(rc == 0, return rc, "DoSandboxFileCommonBind failed, %{public}s", GetBundleName(appProperty)); - - // if sandbox switch is off, don't do symlink work again - if (CheckAppSandboxSwitchStatus(appProperty) == true && (CheckTotalSandboxSwitchStatus(appProperty) == true)) { - rc = DoSandboxFileCommonSymlink(appProperty, config); - APPSPAWN_CHECK(rc == 0, return rc, "DoSandboxFileCommonSymlink failed, %{public}s", GetBundleName(appProperty)); - } - - rc = DoSandboxFileCommonFlagsPointHandle(appProperty, config); - APPSPAWN_CHECK_ONLY_LOG(rc == 0, "DoSandboxFilePrivateFlagsPointHandle failed"); - - return rc; -} - -int32_t SandboxUtils::SetCommonAppSandboxProperty(const AppSpawningCtx *appProperty, - std::string &sandboxPackagePath) -{ - int ret = 0; - SandboxConfigType type = CheckAppMsgFlagsSet(appProperty, APP_FLAGS_ISOLATED_SANDBOX_TYPE) ? - SANBOX_ISOLATED_JSON_CONFIG : SANBOX_APP_JSON_CONFIG; - - for (auto& jsonConfig : SandboxUtils::GetJsonConfig(type)) { - ret = SetCommonAppSandboxProperty_(appProperty, jsonConfig); - APPSPAWN_CHECK(ret == 0, return ret, - "parse appdata config for common failed, %{public}s", sandboxPackagePath.c_str()); - } - - ret = MountAllHsp(appProperty, sandboxPackagePath); - APPSPAWN_CHECK(ret == 0, return ret, "mount extraInfo failed, %{public}s", sandboxPackagePath.c_str()); - - ret = MountAllGroup(appProperty, sandboxPackagePath); - APPSPAWN_CHECK(ret == 0, return ret, "mount groupList failed, %{public}s", sandboxPackagePath.c_str()); - - AppSpawnMsgDomainInfo *info = - reinterpret_cast(GetAppProperty(appProperty, TLV_DOMAIN_INFO)); - APPSPAWN_CHECK(info != nullptr, return -1, "No domain info %{public}s", sandboxPackagePath.c_str()); - if (strcmp(info->apl, APL_SYSTEM_BASIC.data()) == 0 || strcmp(info->apl, APL_SYSTEM_CORE.data()) == 0 || - CheckAppMsgFlagsSet(appProperty, APP_FLAGS_ACCESS_BUNDLE_DIR)) { - // need permission check for system app here - std::string destbundlesPath = sandboxPackagePath + g_dataBundles; - SharedMountArgs arg = { - .srcPath = g_physicalAppInstallPath.c_str(), - .destPath = destbundlesPath.c_str() - }; - DoAppSandboxMountOnce(appProperty, &arg); - } - - return 0; -} - -static inline bool CheckPath(const std::string& name) -{ - return !name.empty() && name != "." && name != ".." && name.find("/") == std::string::npos; -} - -std::string SandboxUtils::GetExtraInfoByType(const AppSpawningCtx *appProperty, const std::string &type) -{ - uint32_t len = 0; - char *info = reinterpret_cast(GetAppPropertyExt(appProperty, type.c_str(), &len)); - if (info == nullptr) { - return ""; - } - return std::string(info, len); -} - -int32_t SandboxUtils::MountAllHsp(const AppSpawningCtx *appProperty, std::string &sandboxPackagePath) -{ - int ret = 0; - string hspListInfo = GetExtraInfoByType(appProperty, HSPLIST_SOCKET_TYPE); - if (hspListInfo.length() == 0) { - return ret; - } - - nlohmann::json hsps = nlohmann::json::parse(hspListInfo.c_str(), nullptr, false); - APPSPAWN_CHECK(!hsps.is_discarded() && hsps.contains(g_hspList_key_bundles) && hsps.contains(g_hspList_key_modules) - && hsps.contains(g_hspList_key_versions), return -1, "MountAllHsp: json parse failed"); - - nlohmann::json& bundles = hsps[g_hspList_key_bundles]; - nlohmann::json& modules = hsps[g_hspList_key_modules]; - nlohmann::json& versions = hsps[g_hspList_key_versions]; - APPSPAWN_CHECK(bundles.is_array() && modules.is_array() && versions.is_array() && bundles.size() == modules.size() - && bundles.size() == versions.size(), return -1, "MountAllHsp: value is not arrary or sizes are not same"); - - APPSPAWN_LOGV("MountAllHsp: app = %{public}s, cnt = %{public}lu", - GetBundleName(appProperty), static_cast(bundles.size())); - for (uint32_t i = 0; i < bundles.size(); i++) { - // elements in json arrary can be different type - APPSPAWN_CHECK(bundles[i].is_string() && modules[i].is_string() && versions[i].is_string(), - return -1, "MountAllHsp: element type error"); - - std::string libBundleName = bundles[i]; - std::string libModuleName = modules[i]; - std::string libVersion = versions[i]; - APPSPAWN_CHECK(CheckPath(libBundleName) && CheckPath(libModuleName) && CheckPath(libVersion), - return -1, "MountAllHsp: path error"); - - std::string libPhysicalPath = g_physicalAppInstallPath + libBundleName + "/" + libVersion + "/" + libModuleName; - std::string mntPath = sandboxPackagePath + g_sandboxHspInstallPath + libBundleName + "/" + libModuleName; - SharedMountArgs arg = { - .srcPath = libPhysicalPath.c_str(), - .destPath = mntPath.c_str() - }; - ret = DoAppSandboxMountOnce(appProperty, &arg); - APPSPAWN_CHECK(ret == 0, return ret, "mount library failed %{public}d", ret); - } - return ret; -} - -int32_t SandboxUtils::DoSandboxRootFolderCreateAdapt(std::string &sandboxPackagePath) -{ -#ifndef APPSPAWN_TEST - int rc = mount(nullptr, "/", nullptr, MS_REC | MS_SLAVE, nullptr); - APPSPAWN_CHECK(rc == 0, return rc, "set propagation slave failed"); -#endif - MakeDirRecursive(sandboxPackagePath, FILE_MODE); - - // bind mount "/" to /mnt/sandbox// path - // rootfs: to do more resources bind mount here to get more strict resources constraints -#ifndef APPSPAWN_TEST - rc = mount("/", sandboxPackagePath.c_str(), nullptr, BASIC_MOUNT_FLAGS, nullptr); - APPSPAWN_CHECK(rc == 0, return rc, "mount bind / failed, %{public}d", errno); -#endif - return 0; -} - -int32_t SandboxUtils::MountAllGroup(const AppSpawningCtx *appProperty, std::string &sandboxPackagePath) -{ - int ret = 0; - string dataGroupInfo = GetExtraInfoByType(appProperty, DATA_GROUP_SOCKET_TYPE); - if (dataGroupInfo.length() == 0) { - return ret; - } - - nlohmann::json groups = nlohmann::json::parse(dataGroupInfo.c_str(), nullptr, false); - if (groups.is_discarded() && groups.contains(g_groupList_key_dataGroupId) && groups.contains(g_groupList_key_dir) && - groups.contains(g_groupList_key_gid) && groups.contains(g_groupList_key_uuid)) { - APPSPAWN_LOGE("dataGroupJson is discarded"); - return APPSPAWN_ARG_INVALID; - } - - for (auto& item : groups) { - // elements in json arrary can be different type - APPSPAWN_CHECK(IsValidDataGroupItem(item), return -1, "MountAllGroup: data group item error"); - std::string srcPath = item[g_groupList_key_dir]; - APPSPAWN_CHECK(!CheckPath(srcPath), return -1, "MountAllGroup: path error"); - - int elxValue = GetElxInfoFromDir(srcPath.c_str()); - APPSPAWN_CHECK((elxValue >= EL2 && elxValue < ELX_MAX), return -1, "Get elx value failed"); - - const DataGroupSandboxPathTemplate *templateItem = GetDataGroupArgTemplate(elxValue); - APPSPAWN_CHECK(templateItem != nullptr, return -1, "Get data group arg template failed"); - - // If permission isn't null, need check permission flag - if (templateItem->permission != nullptr) { - int index = GetPermissionIndex(nullptr, templateItem->permission); - APPSPAWN_LOGV("mount dir no lock mount permission flag %{public}d", index); - if (CheckAppPermissionFlagSet(appProperty, static_cast(index)) == 0) { - continue; - } - } - - std::string dataGroupUuid = item[g_groupList_key_uuid]; - std::string mntPath = sandboxPackagePath + templateItem->sandboxPath + dataGroupUuid; - mode_t mountSharedFlag = MS_SLAVE; - if (CheckAppMsgFlagsSet(appProperty, APP_FLAGS_ISOLATED_SANDBOX)) { - mountSharedFlag |= MS_REMOUNT | MS_NODEV | MS_RDONLY | MS_BIND; - } - SharedMountArgs arg = { - .srcPath = srcPath.c_str(), - .destPath = mntPath.c_str(), - .mountSharedFlag = mountSharedFlag - }; - ret = DoAppSandboxMountOnce(appProperty, &arg); - if (ret != 0) { - APPSPAWN_LOGE("mount el%{public}d datagroup failed", elxValue); - } - } - return 0; -} - -int32_t SandboxUtils::DoSandboxRootFolderCreate(const AppSpawningCtx *appProperty, - std::string &sandboxPackagePath) -{ -#ifndef APPSPAWN_TEST - int rc = mount(nullptr, "/", nullptr, MS_REC | MS_SLAVE, nullptr); - if (rc) { - return rc; - } -#endif - SharedMountArgs arg = { - .srcPath = sandboxPackagePath.c_str(), - .destPath = sandboxPackagePath.c_str() - }; - DoAppSandboxMountOnce(appProperty, &arg); - - return 0; -} - -uint32_t SandboxUtils::GetSandboxNsFlags(bool isNweb) -{ - uint32_t nsFlags = 0; - nlohmann::json appConfig; - const std::map NamespaceFlagsMap = { {"pid", CLONE_NEWPID}, - {"net", CLONE_NEWNET} }; - - if (!CheckTotalSandboxSwitchStatus(nullptr)) { - return nsFlags; - } - - for (auto& config : SandboxUtils::GetJsonConfig(SANBOX_APP_JSON_CONFIG)) { - if (isNweb) { - nlohmann::json& privateAppConfig = config[g_privatePrefix][0]; - if (privateAppConfig.find(g_ohosRender) == privateAppConfig.end()) { - continue; - } - appConfig = privateAppConfig[g_ohosRender][0]; - } else { - nlohmann::json& baseConfig = config[g_commonPrefix][0]; - if (baseConfig.find(g_appBase) == baseConfig.end()) { - continue; - } - appConfig = baseConfig[g_appBase][0]; - } - if (appConfig.find(g_sandBoxNsFlags) == appConfig.end()) { - continue; - } - const auto vec = appConfig[g_sandBoxNsFlags].get>(); - for (unsigned int j = 0; j < vec.size(); j++) { - if (NamespaceFlagsMap.count(vec[j])) { - nsFlags |= NamespaceFlagsMap.at(vec[j]); - } - } - } - - if (!nsFlags) { - APPSPAWN_LOGE("config is not found %{public}s ns config", isNweb ? "Nweb" : "App"); - } - return nsFlags; -} - -bool SandboxUtils::CheckBundleNameForPrivate(const std::string &bundleName) -{ - if (bundleName.find(g_internal) != std::string::npos) { - return false; - } - return true; -} - -bool SandboxUtils::CheckTotalSandboxSwitchStatus(const AppSpawningCtx *appProperty) -{ - SandboxConfigType type = CheckAppMsgFlagsSet(appProperty, APP_FLAGS_ISOLATED_SANDBOX_TYPE) ? - SANBOX_ISOLATED_JSON_CONFIG : SANBOX_APP_JSON_CONFIG; - - for (auto& wholeConfig : SandboxUtils::GetJsonConfig(type)) { - if (wholeConfig.find(g_commonPrefix) == wholeConfig.end()) { - continue; - } - nlohmann::json& commonAppConfig = wholeConfig[g_commonPrefix][0]; - if (commonAppConfig.find(g_topSandBoxSwitchPrefix) != commonAppConfig.end()) { - std::string switchStatus = commonAppConfig[g_topSandBoxSwitchPrefix].get(); - return switchStatus == g_sbxSwitchCheck; - } - } - // default sandbox switch is on - return true; -} - -bool SandboxUtils::CheckAppSandboxSwitchStatus(const AppSpawningCtx *appProperty) -{ - bool rc = true; - SandboxConfigType type = CheckAppMsgFlagsSet(appProperty, APP_FLAGS_ISOLATED_SANDBOX_TYPE) ? - SANBOX_ISOLATED_JSON_CONFIG : SANBOX_APP_JSON_CONFIG; - - for (auto& wholeConfig : SandboxUtils::GetJsonConfig(type)) { - if (wholeConfig.find(g_privatePrefix) == wholeConfig.end()) { - continue; - } - nlohmann::json& privateAppConfig = wholeConfig[g_privatePrefix][0]; - if (privateAppConfig.find(GetBundleName(appProperty)) != privateAppConfig.end()) { - nlohmann::json& appConfig = privateAppConfig[GetBundleName(appProperty)][0]; - rc = GetSbxSwitchStatusByConfig(appConfig); - if (rc) { - break; - } - } - } - // default sandbox switch is on - return rc; -} - -static int CheckBundleName(const std::string &bundleName) -{ - if (bundleName.empty() || bundleName.size() > APP_LEN_BUNDLE_NAME) { - return -1; - } - if (bundleName.find('\\') != std::string::npos || bundleName.find('/') != std::string::npos) { - return -1; - } - return 0; -} - -int32_t SandboxUtils::SetOverlayAppSandboxProperty(const AppSpawningCtx *appProperty, - string &sandboxPackagePath) -{ - int ret = 0; - if (!CheckAppMsgFlagsSet(appProperty, APP_FLAGS_OVERLAY)) { - return ret; - } - - string overlayInfo = GetExtraInfoByType(appProperty, OVERLAY_SOCKET_TYPE); - set mountedSrcSet; - vector splits = split(overlayInfo, g_overlayDecollator); - string sandboxOverlayPath = sandboxPackagePath + g_overlayPath; - for (auto hapPath : splits) { - size_t pathIndex = hapPath.find_last_of(g_fileSeparator); - if (pathIndex == string::npos) { - continue; - } - std::string srcPath = hapPath.substr(0, pathIndex); - if (mountedSrcSet.find(srcPath) != mountedSrcSet.end()) { - APPSPAWN_LOGV("%{public}s have mounted before, no need to mount twice.", srcPath.c_str()); - continue; - } - - auto bundleNameIndex = srcPath.find_last_of(g_fileSeparator); - string destPath = sandboxOverlayPath + srcPath.substr(bundleNameIndex + 1, srcPath.length()); - SharedMountArgs arg = { - .srcPath = srcPath.c_str(), - .destPath = destPath.c_str() - }; - int32_t retMount = DoAppSandboxMountOnce(appProperty, &arg); - if (retMount != 0) { - APPSPAWN_LOGE("fail to mount overlay path, src is %{public}s.", hapPath.c_str()); - ret = retMount; - } - - mountedSrcSet.emplace(srcPath); - } - return ret; -} - -int32_t SandboxUtils::SetBundleResourceAppSandboxProperty(const AppSpawningCtx *appProperty, - string &sandboxPackagePath) -{ - if (!CheckAppMsgFlagsSet(appProperty, APP_FLAGS_BUNDLE_RESOURCES)) { - return 0; - } - - string destPath = sandboxPackagePath + g_bundleResourceDestPath; - SharedMountArgs arg = { - .srcPath = g_bundleResourceSrcPath.c_str(), - .destPath = destPath.c_str() - }; - return DoAppSandboxMountOnce(appProperty, &arg); -} - -int32_t SandboxUtils::CheckAppFullMountEnable() -{ - if (deviceTypeEnable_ != -1) { - return deviceTypeEnable_; - } - - char value[] = "false"; - int32_t ret = GetParameter("const.filemanager.full_mount.enable", "false", value, sizeof(value)); - if (ret > 0 && (strcmp(value, "true")) == 0) { - deviceTypeEnable_ = FILE_CROSS_APP_STATUS; - } else if (ret > 0 && (strcmp(value, "false")) == 0) { - deviceTypeEnable_ = FILE_ACCESS_COMMON_DIR_STATUS; - } else { - deviceTypeEnable_ = -1; - } - - return deviceTypeEnable_; -} - -int32_t SandboxUtils::SetSandboxProperty(AppSpawningCtx *appProperty, std::string &sandboxPackagePath) -{ - int32_t ret = 0; - const std::string bundleName = GetBundleName(appProperty); - ret = SetCommonAppSandboxProperty(appProperty, sandboxPackagePath); - APPSPAWN_CHECK(ret == 0, return ret, "SetCommonAppSandboxProperty failed, packagename is %{public}s", - bundleName.c_str()); - if (CheckBundleNameForPrivate(bundleName)) { - ret = SetPrivateAppSandboxProperty(appProperty); - APPSPAWN_CHECK(ret == 0, return ret, "SetPrivateAppSandboxProperty failed, packagename is %{public}s", - bundleName.c_str()); - } - ret = SetPermissionAppSandboxProperty(appProperty); - APPSPAWN_CHECK(ret == 0, return ret, "SetPermissionAppSandboxProperty failed, packagename is %{public}s", - bundleName.c_str()); - - ret = SetOverlayAppSandboxProperty(appProperty, sandboxPackagePath); - APPSPAWN_CHECK(ret == 0, return ret, "SetOverlayAppSandboxProperty failed, packagename is %{public}s", - bundleName.c_str()); - - ret = SetBundleResourceAppSandboxProperty(appProperty, sandboxPackagePath); - APPSPAWN_CHECK(ret == 0, return ret, "SetBundleResourceAppSandboxProperty failed, packagename is %{public}s", - bundleName.c_str()); - APPSPAWN_LOGV("Set appsandbox property success"); - return ret; -} - -int32_t SandboxUtils::ChangeCurrentDir(std::string &sandboxPackagePath, const std::string &bundleName, - bool sandboxSharedStatus) -{ - int32_t ret = 0; - ret = chdir(sandboxPackagePath.c_str()); - APPSPAWN_CHECK(ret == 0, return ret, "chdir failed, packagename is %{public}s, path is %{public}s", - bundleName.c_str(), sandboxPackagePath.c_str()); - - if (sandboxSharedStatus) { - ret = chroot(sandboxPackagePath.c_str()); - APPSPAWN_CHECK(ret == 0, return ret, "chroot failed, path is %{public}s errno is %{public}d", - sandboxPackagePath.c_str(), errno); - return ret; - } - - ret = syscall(SYS_pivot_root, sandboxPackagePath.c_str(), sandboxPackagePath.c_str()); - APPSPAWN_CHECK(ret == 0, return ret, "errno is %{public}d, pivot root failed, packagename is %{public}s", - errno, bundleName.c_str()); - - ret = umount2(".", MNT_DETACH); - APPSPAWN_CHECK(ret == 0, return ret, "MNT_DETACH failed, packagename is %{public}s", bundleName.c_str()); - return ret; -} - -static int EnableSandboxNamespace(AppSpawningCtx *appProperty, uint32_t sandboxNsFlags) -{ -#ifdef APPSPAWN_HISYSEVENT - struct timespec startClock = {0}; - clock_gettime(CLOCK_MONOTONIC, &startClock); -#endif - int rc = unshare(sandboxNsFlags); -#ifdef APPSPAWN_HISYSEVENT - struct timespec endClock = {0}; - clock_gettime(CLOCK_MONOTONIC, &endClock); - uint64_t diff = DiffTime(&startClock, &endClock); - APPSPAWN_CHECK_ONLY_EXPER(diff < FUNC_REPORT_DURATION, ReportAbnormalDuration("unshare", diff)); -#endif - APPSPAWN_CHECK(rc == 0, return rc, "unshare failed, packagename is %{public}s", GetBundleName(appProperty)); - - if ((sandboxNsFlags & CLONE_NEWNET) == CLONE_NEWNET) { - rc = EnableNewNetNamespace(); - APPSPAWN_CHECK(rc == 0, return rc, "Set new netnamespace failed %{public}s", GetBundleName(appProperty)); - } - return 0; -} - -void SandboxUtils::UpdateMsgFlagsWithPermission(AppSpawningCtx *appProperty) -{ - int32_t processIndex = GetPermissionIndex(nullptr, GET_ALL_PROCESSES_MODE.c_str()); - if ((CheckAppPermissionFlagSet(appProperty, static_cast(processIndex)) == 0)) { - APPSPAWN_LOGV("Don't need set GET_ALL_PROCESSES_MODE flag"); - return; - } - - int ret = SetAppSpawnMsgFlag(appProperty->message, TLV_MSG_FLAGS, APP_FLAGS_GET_ALL_PROCESSES); - if (ret != 0) { - APPSPAWN_LOGV("Set GET_ALL_PROCESSES_MODE flag failed"); - } -} - -int32_t SandboxUtils::UpdatePermissionFlags(AppSpawningCtx *appProperty) -{ - int32_t index = 0; - int32_t appFullMountStatus = CheckAppFullMountEnable(); - if (appFullMountStatus == FILE_CROSS_APP_STATUS) { - index = GetPermissionIndex(nullptr, FILE_CROSS_APP_MODE.c_str()); - } else if (appFullMountStatus == FILE_ACCESS_COMMON_DIR_STATUS) { - index = GetPermissionIndex(nullptr, FILE_ACCESS_COMMON_DIR_MODE.c_str()); - } - int32_t userFileIndex = GetPermissionIndex(nullptr, READ_WRITE_USER_FILE_MODE.c_str()); - int32_t fileMgrIndex = GetPermissionIndex(nullptr, FILE_ACCESS_MANAGER_MODE.c_str()); - if ((CheckAppPermissionFlagSet(appProperty, static_cast(userFileIndex)) != 0) && - (CheckAppPermissionFlagSet(appProperty, static_cast(fileMgrIndex)) != 0)) { - APPSPAWN_LOGE("invalid msg request."); - return -1; - } - if (index > 0 && (fileMgrIndex > 0 && userFileIndex > 0) && - (CheckAppPermissionFlagSet(appProperty, static_cast(userFileIndex)) == 0) && - (CheckAppPermissionFlagSet(appProperty, static_cast(fileMgrIndex)) == 0)) { - return SetAppPermissionFlags(appProperty, index); - } - return 0; -} - -#ifdef APPSPAWN_MOUNT_TMPSHM -void SandboxUtils::MountDevShmPath(std::string &sandboxPath) -{ - std::string sandboxDevShmPath = sandboxPath + DEV_SHM_DIR; - int result = mount("tmpfs", sandboxDevShmPath.c_str(), "tmpfs", MS_NOSUID | MS_NOEXEC | MS_NODEV, "size=32M"); - if (result != 0) { - APPSPAWN_LOGW("Error mounting %{public}s to tmpfs, errno %{public}d", sandboxDevShmPath.c_str(), errno); - } -} -#endif - -int32_t SandboxUtils::SetAppSandboxProperty(AppSpawningCtx *appProperty, uint32_t sandboxNsFlags) -{ - APPSPAWN_CHECK(appProperty != nullptr, return -1, "Invalid appspwn client"); - if (CheckBundleName(GetBundleName(appProperty)) != 0) { - return -1; - } - AppSpawnMsgDacInfo *dacInfo = reinterpret_cast(GetAppProperty(appProperty, TLV_DAC_INFO)); - if (dacInfo == nullptr) { - return -1; - } - - const std::string bundleName = GetBundleName(appProperty); - nlohmann::json tmpJson = {}; - std::string sandboxPackagePath = GetSbxPathByConfig(appProperty, tmpJson); - MakeDirRecursiveWithClock(sandboxPackagePath.c_str(), FILE_MODE); - bool sandboxSharedStatus = GetSandboxPrivateSharedStatus(bundleName, appProperty) || - (CheckAppPermissionFlagSet(appProperty, static_cast(GetPermissionIndex(nullptr, - ACCESS_DLP_FILE_MODE.c_str()))) != 0); - - // add pid to a new mnt namespace - int rc = EnableSandboxNamespace(appProperty, sandboxNsFlags); - APPSPAWN_CHECK(rc == 0, return rc, "unshare failed, packagename is %{public}s", bundleName.c_str()); - if (UpdatePermissionFlags(appProperty) != 0) { - APPSPAWN_LOGW("Set app permission flag fail."); - return -1; - } - UpdateMsgFlagsWithPermission(appProperty); - // check app sandbox switch - if ((CheckTotalSandboxSwitchStatus(appProperty) == false) || - (CheckAppSandboxSwitchStatus(appProperty) == false)) { - rc = DoSandboxRootFolderCreateAdapt(sandboxPackagePath); - } else if (!sandboxSharedStatus) { - rc = DoSandboxRootFolderCreate(appProperty, sandboxPackagePath); - } - APPSPAWN_CHECK(rc == 0, return rc, "DoSandboxRootFolderCreate failed, %{public}s", bundleName.c_str()); - rc = SetSandboxProperty(appProperty, sandboxPackagePath); - APPSPAWN_CHECK(rc == 0, return rc, "SetSandboxProperty failed, %{public}s", bundleName.c_str()); - -#ifdef APPSPAWN_MOUNT_TMPSHM - MountDevShmPath(sandboxPackagePath); -#endif - -#ifndef APPSPAWN_TEST - rc = ChangeCurrentDir(sandboxPackagePath, bundleName, sandboxSharedStatus); - APPSPAWN_CHECK(rc == 0, return rc, "change current dir failed"); - APPSPAWN_LOGV("Change root dir success"); -#endif - SetDecWithDir(appProperty, dacInfo->uid / UID_BASE); - SetDecDenyWithDir(appProperty); - SetDecPolicy(); -#if defined(APPSPAWN_MOUNT_TMPSHM) && defined(WITH_SELINUX) - Restorecon(DEV_SHM_DIR); -#endif - return 0; -} - -int32_t SandboxUtils::SetAppSandboxPropertyNweb(AppSpawningCtx *appProperty, uint32_t sandboxNsFlags) -{ - APPSPAWN_CHECK(appProperty != nullptr, return -1, "Invalid appspwn client"); - if (CheckBundleName(GetBundleName(appProperty)) != 0) { - return -1; - } - std::string sandboxPackagePath = g_sandBoxRootDirNweb; - const std::string bundleName = GetBundleName(appProperty); - bool sandboxSharedStatus = GetSandboxPrivateSharedStatus(bundleName, appProperty); - sandboxPackagePath += bundleName; - MakeDirRecursiveWithClock(sandboxPackagePath.c_str(), FILE_MODE); - - // add pid to a new mnt namespace - int rc = EnableSandboxNamespace(appProperty, sandboxNsFlags); - APPSPAWN_CHECK(rc == 0, return rc, "unshare failed, packagename is %{public}s", bundleName.c_str()); - - // check app sandbox switch - if ((CheckTotalSandboxSwitchStatus(appProperty) == false) || - (CheckAppSandboxSwitchStatus(appProperty) == false)) { - rc = DoSandboxRootFolderCreateAdapt(sandboxPackagePath); - } else if (!sandboxSharedStatus) { - rc = DoSandboxRootFolderCreate(appProperty, sandboxPackagePath); - } - APPSPAWN_CHECK(rc == 0, return rc, "DoSandboxRootFolderCreate failed, %{public}s", bundleName.c_str()); - // rendering process can be created by different apps, - // and the bundle names of these apps are different, - // so we can't use the method SetPrivateAppSandboxProperty - // which mount dirs by using bundle name. - rc = SetRenderSandboxPropertyNweb(appProperty, sandboxPackagePath); - APPSPAWN_CHECK(rc == 0, return rc, "SetRenderSandboxPropertyNweb failed, packagename is %{public}s", - sandboxPackagePath.c_str()); - - rc = SetOverlayAppSandboxProperty(appProperty, sandboxPackagePath); - APPSPAWN_CHECK(rc == 0, return rc, "SetOverlayAppSandboxProperty failed, packagename is %{public}s", - bundleName.c_str()); - - rc = SetBundleResourceAppSandboxProperty(appProperty, sandboxPackagePath); - APPSPAWN_CHECK(rc == 0, return rc, "SetBundleResourceAppSandboxProperty failed, packagename is %{public}s", - bundleName.c_str()); - -#ifndef APPSPAWN_TEST - rc = chdir(sandboxPackagePath.c_str()); - APPSPAWN_CHECK(rc == 0, return rc, "chdir failed, packagename is %{public}s, path is %{public}s", - bundleName.c_str(), sandboxPackagePath.c_str()); - - if (sandboxSharedStatus) { - rc = chroot(sandboxPackagePath.c_str()); - APPSPAWN_CHECK(rc == 0, return rc, "chroot failed, path is %{public}s errno is %{public}d", - sandboxPackagePath.c_str(), errno); - return 0; - } - - rc = syscall(SYS_pivot_root, sandboxPackagePath.c_str(), sandboxPackagePath.c_str()); - APPSPAWN_CHECK(rc == 0, return rc, "errno is %{public}d, pivot root failed, packagename is %{public}s", - errno, bundleName.c_str()); - - rc = umount2(".", MNT_DETACH); - APPSPAWN_CHECK(rc == 0, return rc, "MNT_DETACH failed, packagename is %{public}s", bundleName.c_str()); -#endif - return 0; -} -} // namespace AppSpawn -} // namespace OHOS - -static bool AppSandboxPidNsIsSupport(void) -{ - char buffer[10] = {0}; - uint32_t buffSize = sizeof(buffer); - - if (SystemGetParameter("const.sandbox.pidns.support", buffer, &buffSize) != 0) { - return true; - } - if (!strcmp(buffer, "false")) { - return false; - } - return true; -} - -int LoadAppSandboxConfig(AppSpawnMgr *content) -{ - bool rc = true; - // load sandbox config - nlohmann::json appSandboxConfig; - CfgFiles *files = GetCfgFiles("etc/sandbox"); - for (int i = 0; (files != nullptr) && (i < MAX_CFG_POLICY_DIRS_CNT); ++i) { - if (files->paths[i] == nullptr) { - continue; - } - std::string path = files->paths[i]; - std::string appPath = path + OHOS::AppSpawn::APP_JSON_CONFIG; - APPSPAWN_LOGI("LoadAppSandboxConfig %{public}s", appPath.c_str()); - rc = OHOS::AppSpawn::JsonUtils::GetJsonObjFromJson(appSandboxConfig, appPath); - APPSPAWN_CHECK(rc, continue, "Failed to load app data sandbox config %{public}s", appPath.c_str()); - OHOS::AppSpawn::SandboxUtils::StoreJsonConfig(appSandboxConfig, SANBOX_APP_JSON_CONFIG); - - std::string isolatedPath = path + OHOS::AppSpawn::APP_ISOLATED_JSON_CONFIG; - APPSPAWN_LOGI("LoadAppSandboxConfig %{public}s", isolatedPath.c_str()); - rc = OHOS::AppSpawn::JsonUtils::GetJsonObjFromJson(appSandboxConfig, isolatedPath); - APPSPAWN_CHECK(rc, continue, "Failed to load app data sandbox config %{public}s", isolatedPath.c_str()); - OHOS::AppSpawn::SandboxUtils::StoreJsonConfig(appSandboxConfig, SANBOX_ISOLATED_JSON_CONFIG); - } - FreeCfgFiles(files); - bool isNweb = IsNWebSpawnMode(content); - if (!isNweb && !AppSandboxPidNsIsSupport()) { - return 0; - } - content->content.sandboxNsFlags = OHOS::AppSpawn::SandboxUtils::GetSandboxNsFlags(isNweb); - return 0; -} - -static bool NeedNetworkIsolated(AppSpawningCtx *property) -{ - int developerMode = IsDeveloperModeOpen(); - if (CheckAppMsgFlagsSet(property, APP_FLAGS_ISOLATED_SANDBOX) && !developerMode) { - return true; - } - - if (CheckAppMsgFlagsSet(property, APP_FLAGS_ISOLATED_NETWORK)) { - std::string extensionType = - OHOS::AppSpawn::SandboxUtils::GetExtraInfoByType(property, MSG_EXT_NAME_EXTENSION_TYPE); - if (extensionType.length() == 0 || !developerMode) { - return true; - } - } - - return false; -} - -int32_t SetAppSandboxProperty(AppSpawnMgr *content, AppSpawningCtx *property) -{ - APPSPAWN_CHECK(property != nullptr, return -1, "Invalid appspwn client"); - APPSPAWN_CHECK(content != nullptr, return -1, "Invalid appspwn content"); - // clear g_mountInfo in the child process - std::map* mapPtr = static_cast*>(GetEl1BundleMountCount()); - if (mapPtr == nullptr) { - APPSPAWN_LOGE("Get el1 bundle mount count failed"); - return APPSPAWN_ARG_INVALID; - } - mapPtr->clear(); - int ret = 0; - // no sandbox - if (CheckAppMsgFlagsSet(property, APP_FLAGS_NO_SANDBOX)) { - return 0; - } - if ((content->content.sandboxNsFlags & CLONE_NEWPID) == CLONE_NEWPID) { - ret = getprocpid(); - if (ret < 0) { - return ret; - } - } - uint32_t sandboxNsFlags = CLONE_NEWNS; - - if (NeedNetworkIsolated(property)) { - sandboxNsFlags |= content->content.sandboxNsFlags & CLONE_NEWNET ? CLONE_NEWNET : 0; - } - - APPSPAWN_LOGV("SetAppSandboxProperty sandboxNsFlags 0x%{public}x", sandboxNsFlags); - - if (IsNWebSpawnMode(content)) { - ret = OHOS::AppSpawn::SandboxUtils::SetAppSandboxPropertyNweb(property, sandboxNsFlags); - } else { - ret = OHOS::AppSpawn::SandboxUtils::SetAppSandboxProperty(property, sandboxNsFlags); - } - // for module test do not create sandbox, use APP_FLAGS_IGNORE_SANDBOX to ignore sandbox result - if (CheckAppMsgFlagsSet(property, APP_FLAGS_IGNORE_SANDBOX)) { - APPSPAWN_LOGW("Do not care sandbox result %{public}d", ret); - return 0; - } - return ret; -} - -#define USER_ID_SIZE 16 -#define DIR_MODE 0711 - -static int SpawnMountDirToShared(AppSpawnMgr *content, AppSpawningCtx *property) -{ -#ifndef APPSPAWN_SANDBOX_NEW - if (!IsNWebSpawnMode(content)) { - // mount dynamic directory - MountToShared(content, property); - } -#endif - return 0; -} - -static void UmountDir(const char *rootPath, const char *targetPath, const AppSpawnedProcessInfo *appInfo) -{ - size_t allPathSize = strlen(rootPath) + USER_ID_SIZE + strlen(appInfo->name) + strlen(targetPath) + 2; - char *path = reinterpret_cast(malloc(sizeof(char) * (allPathSize))); - APPSPAWN_CHECK(path != NULL, return, "Failed to malloc path"); - - int ret = sprintf_s(path, allPathSize, "%s%u/%s%s", rootPath, appInfo->uid / UID_BASE, - appInfo->name, targetPath); - APPSPAWN_CHECK(ret > 0 && ((size_t)ret < allPathSize), free(path); - return, "Failed to get sandbox path errno %{public}d", errno); - - ret = umount2(path, MNT_DETACH); - if (ret == 0) { - APPSPAWN_LOGI("Umount2 sandbox path %{public}s success", path); - } else { - APPSPAWN_LOGW("Failed to umount2 sandbox path %{public}s errno %{public}d", path, errno); - } - free(path); -} - -static int UmountSandboxPath(const AppSpawnMgr *content, const AppSpawnedProcessInfo *appInfo) -{ - APPSPAWN_CHECK(content != NULL && appInfo != NULL && appInfo->name != NULL, - return -1, "Invalid content or appInfo"); - if (!IsAppSpawnMode(content)) { - return 0; - } - APPSPAWN_LOGV("UmountSandboxPath name %{public}s pid %{public}d", appInfo->name, appInfo->pid); - const char rootPath[] = "/mnt/sandbox/"; - const char el1Path[] = "/data/storage/el1/bundle"; - - std::string varBundleName = std::string(appInfo->name); - if (appInfo->appIndex > 0) { - varBundleName = "+clone-" + std::to_string(appInfo->appIndex) + "+" + varBundleName; - } - - uint32_t userId = appInfo->uid / UID_BASE; - std::string key = std::to_string(userId) + "-" + varBundleName; - map *el1BundleCountMap = static_cast*>(GetEl1BundleMountCount()); - if (el1BundleCountMap == nullptr || el1BundleCountMap->find(key) == el1BundleCountMap->end()) { - return 0; - } - (*el1BundleCountMap)[key]--; - if ((*el1BundleCountMap)[key] == 0) { - APPSPAWN_LOGV("no app %{public}s use it in userId %{public}u, need umount", appInfo->name, userId); - UmountDir(rootPath, el1Path, appInfo); - el1BundleCountMap->erase(key); - } else { - APPSPAWN_LOGV("app %{public}s use it mount times %{public}d in userId %{public}u, not need umount", - appInfo->name, (*el1BundleCountMap)[key], userId); - } - return 0; -} - -#ifndef APPSPAWN_SANDBOX_NEW -MODULE_CONSTRUCTOR(void) -{ - APPSPAWN_LOGV("Load sandbox module ..."); - (void)AddServerStageHook(STAGE_SERVER_PRELOAD, HOOK_PRIO_SANDBOX, LoadAppSandboxConfig); - (void)AddAppSpawnHook(STAGE_PARENT_PRE_FORK, HOOK_PRIO_COMMON, SpawnMountDirToShared); - (void)AddAppSpawnHook(STAGE_CHILD_EXECUTE, HOOK_PRIO_SANDBOX, SetAppSandboxProperty); - (void)AddProcessMgrHook(STAGE_SERVER_APP_UMOUNT, HOOK_PRIO_SANDBOX, UmountSandboxPath); -} -#endif diff --git a/service/hnp/base/hnp_base.h b/service/hnp/base/hnp_base.h index 5129a0de0d9793e3c2b49818a23d972d41947b03..f296384ba5e88dda58cd4f1b5bbd0b63213856f8 100644 --- a/service/hnp/base/hnp_base.h +++ b/service/hnp/base/hnp_base.h @@ -327,6 +327,21 @@ char *HnpCurrentVersionGet(const char *name); HILOG_ERROR(LOG_CORE, "[%{public}s:%{public}d]" args, (__FILE_NAME__), (__LINE__), ##__VA_ARGS__); \ HnpLogPrintf(HNP_LOG_ERROR, "HNP", "[%{public}s:%{public}d]" args, (__FILE_NAME__), (__LINE__), ##__VA_ARGS__) #endif +#define HNP_ERROR_CHECK(ret, statement, format, ...) \ + do { \ + if (!(ret)) { \ + HNP_LOGE(format, ##__VA_ARGS__); \ + statement; \ + } \ + } while (0) + +#define HNP_INFO_CHECK(ret, statement, format, ...) \ + do { \ + if (!(ret)) { \ + HNP_LOGI(format, ##__VA_ARGS__); \ + statement; \ + } \ + } while (0) #ifdef __cplusplus } diff --git a/service/hnp/installer/src/hnp_installer.c b/service/hnp/installer/src/hnp_installer.c index c8bee46446842598bde023d918cd4f82c7f2b428..c9658e8aae680d445b27531447aa7d53a919e335 100644 --- a/service/hnp/installer/src/hnp_installer.c +++ b/service/hnp/installer/src/hnp_installer.c @@ -197,6 +197,55 @@ static int HnpInstall(const char *hnpFile, HnpInstallInfo *hnpInfo, HnpCfgInfo * return HnpGenerateSoftLink(hnpInfo->hnpVersionPath, hnpInfo->hnpBasePath, hnpCfg); } +/** + * 删除 ../hnppublic/bin目录下所有失效的hnp + */ +APPSPAWN_STATIC void ClearSoftLink(int uid) +{ + char path[MAX_FILE_PATH_LEN] = {0}; + ssize_t bytes = snprintf_s(path, MAX_FILE_PATH_LEN, MAX_FILE_PATH_LEN - 1, + HNP_DEFAULT_INSTALL_ROOT_PATH"/%d/hnppublic/bin", uid); + HNP_ERROR_CHECK(bytes > 0, return, + "Build bin path failed %{public}d %{public}zd", uid, bytes); + + DIR *dir = opendir(path); + HNP_ERROR_CHECK(dir != NULL, return, + "open bin path failed %{public}s %{public}d", path, errno); + + struct dirent *entry; + int count = 0; + while ((entry = readdir(dir)) != NULL) { + if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { + continue; + } + count++; + HNP_INFO_CHECK(entry->d_type == DT_LNK, continue, + "not lnk file %s skip to next", entry->d_name); + + char sourcePath[MAX_FILE_PATH_LEN] = {0}; + bytes = snprintf_s(sourcePath, MAX_FILE_PATH_LEN, MAX_FILE_PATH_LEN - 1, + "%s/%s", path, entry->d_name); + HNP_ERROR_CHECK(bytes > 0, continue, + "build soft link path failed %{public}s", entry->d_name); + + char targetPath[MAX_FILE_PATH_LEN] = {0}; + bytes = readlink(sourcePath, targetPath, MAX_FILE_PATH_LEN); + HNP_ERROR_CHECK(bytes > 0, continue, "readlink failed %{public}s", sourcePath); + + char linkPath[MAX_FILE_PATH_LEN] = {0}; + bytes = snprintf_s(linkPath, MAX_FILE_PATH_LEN, MAX_FILE_PATH_LEN - 1, + "%s/%s", path, targetPath); + HNP_ERROR_CHECK(bytes > 0, continue, "build link file source path failed %{public}s", targetPath); + + if (access(linkPath, F_OK) != 0) { + int ret = unlink(sourcePath); + HNP_LOGI("unlink file %{public}s %{public}d", sourcePath, ret); + } + } + HNP_LOGI("file count is %d", count); + closedir(dir); +} + /** * 卸载公共hnp. * @@ -249,6 +298,7 @@ static int HnpUnInstallPublicHnp(const char* packageName, const char *name, cons } if (HnpPathFileCount(hnpNamePath) == 0) { + ClearSoftLink(uid); return HnpDeleteFolder(hnpNamePath); } diff --git a/standard/BUILD.gn b/standard/BUILD.gn index 779676dc5a73a6876ea528c2268bc181d750252c..f04763ddff415df47065d4578ef38d6d9afd488a 100644 --- a/standard/BUILD.gn +++ b/standard/BUILD.gn @@ -49,7 +49,6 @@ ohos_executable("appspawn") { "${appspawn_path}/standard/appspawn_main.c", "${appspawn_path}/standard/appspawn_msgmgr.c", "${appspawn_path}/standard/appspawn_service.c", - "${appspawn_path}/standard/nwebspawn_launcher.c", ] defines = [] @@ -169,7 +168,6 @@ ohos_executable("cjappspawn") { "${appspawn_path}/standard/appspawn_main.c", "${appspawn_path}/standard/appspawn_msgmgr.c", "${appspawn_path}/standard/appspawn_service.c", - "${appspawn_path}/standard/nwebspawn_launcher.c", ] defines = [ "CJAPP_SPAWN" ] @@ -237,7 +235,6 @@ ohos_executable("nativespawn") { "${appspawn_path}/standard/appspawn_main.c", "${appspawn_path}/standard/appspawn_msgmgr.c", "${appspawn_path}/standard/appspawn_service.c", - "${appspawn_path}/standard/nwebspawn_launcher.c", ] defines = [ "NATIVE_SPAWN" ] @@ -320,7 +317,6 @@ ohos_executable("nwebspawn") { "${appspawn_path}/standard/appspawn_main.c", "${appspawn_path}/standard/appspawn_msgmgr.c", "${appspawn_path}/standard/appspawn_service.c", - "${appspawn_path}/standard/nwebspawn_launcher.c", ] defines = ["NWEB_SPAWN"] diff --git a/standard/appspawn_service.c b/standard/appspawn_service.c index fa68507df51868d5858f6e9c5c17e6384f2f833a..ee46ffc7be98d1ea3cfcdc8cefdf67bdfb3f6a26 100644 --- a/standard/appspawn_service.c +++ b/standard/appspawn_service.c @@ -438,10 +438,8 @@ APPSPAWN_STATIC bool MsgDevicedebugCheck(TaskHandle stream, AppSpawnMsgNode *mes } AppSpawnMsg *msg = &message->msgHeader; - if (msg->msgType != MSG_DEVICE_DEBUG) { - APPSPAWN_LOGE("appspawn devicedebug msg type is not devicedebug [%{public}d]", msg->msgType); - return false; - } + APPSPAWN_CHECK(msg->msgType == MSG_DEVICE_DEBUG, return false, + "appspawn devicedebug msg type is not devicedebug [%{public}d]", msg->msgType); return true; } @@ -745,10 +743,8 @@ static int WritePreforkMsg(AppSpawningCtx *property, uint32_t memSize) static int GetAppSpawnMsg(AppSpawningCtx *property, uint32_t memSize) { uint8_t *buffer = (uint8_t *)GetMapMem(property->client.id, "prefork", memSize, true, false); - if (buffer == NULL) { - APPSPAWN_LOGE("prefork buffer is null can not write propery"); - return -1; - } + APPSPAWN_CHECK(buffer != NULL, return -1, "prefork buffer is null can not write propery"); + uint32_t msgRecvLen = 0; uint32_t remainLen = 0; property->forkCtx.childMsg = (char *)buffer; @@ -1606,21 +1602,13 @@ APPSPAWN_STATIC void ProcessUninstallDebugHap(AppSpawnConnection *connection, Ap APPSPAWN_STATIC int AppspawpnDevicedebugKill(int pid, cJSON *args) { cJSON *signal = cJSON_GetObjectItem(args, "signal"); - if (!cJSON_IsNumber(signal)) { - APPSPAWN_LOGE("appspawn devicedebug json get signal fail"); - return -1; - } + APPSPAWN_CHECK(cJSON_IsNumber(signal), return -1, "appspawn devicedebug json get signal fail"); AppSpawnedProcess *appInfo = GetSpawnedProcess(pid); - if (appInfo == NULL) { - APPSPAWN_LOGE("appspawn devicedebug get app info unsuccess, pid=%{public}d", pid); - return APPSPAWN_DEVICEDEBUG_ERROR_APP_NOT_EXIST; - } - - if (!appInfo->isDebuggable) { - APPSPAWN_LOGE("appspawn devicedebug process is not debuggable, pid=%{public}d", pid); - return APPSPAWN_DEVICEDEBUG_ERROR_APP_NOT_DEBUGGABLE; - } + APPSPAWN_CHECK(appInfo != NULL, return APPSPAWN_DEVICEDEBUG_ERROR_APP_NOT_EXIST, + "appspawn devicedebug get app info unsuccess, pid=%{public}d", pid); + APPSPAWN_CHECK(appInfo->isDebuggable, return APPSPAWN_DEVICEDEBUG_ERROR_APP_NOT_DEBUGGABLE, + "appspawn devicedebug process is not debuggable, pid=%{public}d", pid); APPSPAWN_LOGI("appspawn devicedebug debugable=%{public}d, pid=%{public}d, signal=%{public}d", appInfo->isDebuggable, pid, (int)signal->valueint); @@ -1655,31 +1643,19 @@ APPSPAWN_STATIC int ProcessAppSpawnDeviceDebugMsg(AppSpawnMsgNode *message) } cJSON *json = cJSON_Parse(jsonString); - if (json == NULL) { - APPSPAWN_LOGE("appspawn devicedebug json parse fail"); - return -1; - } + APPSPAWN_CHECK(json != NULL, return -1, "appspawn devicedebug json parse fail"); cJSON *app = cJSON_GetObjectItem(json, "app"); - if (!cJSON_IsNumber(app)) { - APPSPAWN_LOGE("appspawn devicedebug json get app fail"); - cJSON_Delete(json); - return -1; - } + APPSPAWN_CHECK(cJSON_IsNumber(app), cJSON_Delete(json); + return -1, "appspawn devicedebug json get app fail"); cJSON *op = cJSON_GetObjectItem(json, "op"); - if (!cJSON_IsString(op) || op->valuestring == NULL) { - APPSPAWN_LOGE("appspawn devicedebug json get op fail"); - cJSON_Delete(json); - return -1; - } + APPSPAWN_CHECK(cJSON_IsString(op) && op->valuestring != NULL, cJSON_Delete(json); + return -1, "appspawn devicedebug json get op fail"); cJSON *args = cJSON_GetObjectItem(json, "args"); - if (!cJSON_IsObject(args)) { - APPSPAWN_LOGE("appspawn devicedebug json get args fail"); - cJSON_Delete(json); - return -1; - } + APPSPAWN_CHECK(cJSON_IsObject(args), cJSON_Delete(json); + return -1, "appspawn devicedebug json get args fail"); int result = AppspawnDevicedebugDeal(op->valuestring, app->valueint, args); cJSON_Delete(json); diff --git a/standard/appspawn_service.h b/standard/appspawn_service.h index 5bc324e7a47db1309a6ba19c4a5fcfe59b8b9af6..92dbbe135e3ede4ab01996d32d785eb6bb56e201 100644 --- a/standard/appspawn_service.h +++ b/standard/appspawn_service.h @@ -75,8 +75,6 @@ typedef struct { AppSpawnStartArg arg; } AppSpawnStartArgTemplate; -pid_t NWebSpawnLaunch(void); -void NWebSpawnInit(void); AppSpawnContent *StartSpawnService(const AppSpawnStartArg *arg, uint32_t argvSize, int argc, char *const argv[]); void AppSpawnDestroyContent(AppSpawnContent *content); diff --git a/standard/nwebspawn_launcher.c b/standard/nwebspawn_launcher.c deleted file mode 100644 index 58c337c88098f2cb92c4513cac33952b94c92ad1..0000000000000000000000000000000000000000 --- a/standard/nwebspawn_launcher.c +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (c) 2024 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include -#include -#include -#include -#include - -#include -#include -#include - -#include "appspawn.h" -#include "appspawn_modulemgr.h" -#include "appspawn_msg.h" -#include "appspawn_server.h" -#include "appspawn_service.h" -#include "appspawn_utils.h" -#include "parameter.h" -#include "securec.h" - -#ifdef CODE_SIGNATURE_ENABLE -#include "code_sign_attr_utils.h" -#endif -#ifdef WITH_SELINUX -#include "selinux/selinux.h" -#endif - -#define NWEB_UID 3081 -#define NWEB_GID 3081 -#define NWEB_NAME "nwebspawn" -#define NATIVE_NAME "nativespawn" -#define CAP_NUM 2 -#define BITLEN32 32 - -void NWebSpawnInit(void) -{ - APPSPAWN_LOGI("NWebSpawnInit"); -#ifdef CODE_SIGNATURE_ENABLE - // ownerId must been set before setcon & setuid - (void)SetXpmOwnerId(PROCESS_OWNERID_NWEB, NULL); -#endif -#ifdef WITH_SELINUX - setcon("u:r:nwebspawn:s0"); -#endif - pid_t pid = getpid(); - setpriority(PRIO_PROCESS, pid, 0); - struct __user_cap_header_struct capHeader; - capHeader.version = _LINUX_CAPABILITY_VERSION_3; - capHeader.pid = 0; - // old CAP_SYS_ADMIN | CAP_SETGID | CAP_SETUID - const uint64_t inheriTable = CAP_TO_MASK(CAP_SYS_ADMIN) | CAP_TO_MASK(CAP_SETGID) | - CAP_TO_MASK(CAP_SETUID) | CAP_TO_MASK(CAP_KILL); - const uint64_t permitted = inheriTable; - const uint64_t effective = inheriTable; - struct __user_cap_data_struct capData[CAP_NUM] = {}; - for (int j = 0; j < CAP_NUM; ++j) { - capData[0].inheritable = (__u32)(inheriTable); - capData[1].inheritable = (__u32)(inheriTable >> BITLEN32); - capData[0].permitted = (__u32)(permitted); - capData[1].permitted = (__u32)(permitted >> BITLEN32); - capData[0].effective = (__u32)(effective); - capData[1].effective = (__u32)(effective >> BITLEN32); - } - capset(&capHeader, capData); - for (int i = 0; i <= CAP_LAST_CAP; ++i) { - prctl(PR_CAP_AMBIENT, PR_CAP_AMBIENT_RAISE, i, 0, 0); - } -#ifndef APPSPAWN_TEST - (void)prctl(PR_SET_NAME, NWEB_NAME); -#endif - setuid(NWEB_UID); - setgid(NWEB_GID); -} - -pid_t NWebSpawnLaunch(void) -{ - enum fdsan_error_level errorLevel = fdsan_get_error_level(); - pid_t ret = fork(); - if (ret == 0) { - // Inherit the error level of the original process - (void)fdsan_set_error_level(errorLevel); - NWebSpawnInit(); - } - APPSPAWN_LOGI("nwebspawn fork success pid: %{public}d", ret); - return ret; -} \ No newline at end of file diff --git a/test/BUILD.gn b/test/BUILD.gn index faf729d9c56f1840fdcbd2fe15711d336a872169..bfb189b8a27475925fed3ede238ccca8be707db1 100644 --- a/test/BUILD.gn +++ b/test/BUILD.gn @@ -31,7 +31,9 @@ group("unittest") { deps += [ "unittest/app_spawn_standard_test:AppSpawn_coldrun_ut" ] } deps += [ "unittest/hnp_test:HnpTest" ] + deps += [ "unittest/single_test/hnp_installer:hnp_installer_test" ] deps += [ "unittest/devicedebug_test:DevicedebugTest" ] + deps += [ "unittest/app_spawn_hisysevent_test:AppSpawn_HisysEvent_ut" ] } else { testonly = true deps = [ "unittest/app_spawn_lite_test:unittest" ] diff --git a/test/mock/app_spawn_stub.cpp b/test/mock/app_spawn_stub.cpp index 5de78bf44ed9a0c48bbe465625b96bb6b2fe8494..420375c03f976fc1cdd7796a3266b596ba592684 100644 --- a/test/mock/app_spawn_stub.cpp +++ b/test/mock/app_spawn_stub.cpp @@ -49,6 +49,18 @@ #include #endif +static uint32_t g_preloadParamResult = 0; +static uint32_t g_preloadEtsParamResult = 0; +void SetBoolParamResult(const char *key, bool flag) +{ + if (strcmp(key, "persist.appspawn.preload") == 0) { + flag ? (g_preloadParamResult = true) : (g_preloadParamResult = false); + } + if (strcmp(key, "persist.appspawn.preloadets") == 0) { + flag ? (g_preloadEtsParamResult = true) : (g_preloadEtsParamResult = false); + } +} + namespace OHOS { namespace system { bool GetIntParameter(const std::string &key, bool def, bool arg1 = false, bool arg2 = false) @@ -58,6 +70,12 @@ namespace system { bool GetBoolParameter(const std::string &key, bool def) { + if (strcmp(key.c_str(), "persist.appspawn.preload") == 0) { + return g_preloadParamResult ? true : false; + } + if (strcmp(key.c_str(), "persist.appspawn.preloadets") == 0) { + return g_preloadEtsParamResult ? true : false; + } return def; } } // namespace system @@ -148,6 +166,10 @@ int GetParameter(const char *key, const char *def, char *value, uint32_t len) if (strcmp(key, "persist.arkwebcore.package_name") == 0) { return strcpy_s(value, len, "com.ohos.arkwebcore") == 0 ? strlen("com.ohos.arkwebcore") : -1; } + if (strcmp(key, "persist.arkwebcore.install_path") == 0) { + return strcpy_s(value, len, "/data/app/el1/bundle/public/com.ohos.nweb/ArkWWebCore.hap") == 0 ? + strlen("/data/app/el1/bundle/public/com.ohos.nweb/ArkWWebCore.hap") : -1; + } return -1; } diff --git a/test/mock/app_spawn_stub.h b/test/mock/app_spawn_stub.h index 1e70b90f29d36121d38476ba751fcc8e5e53c4c4..d451750eabff564ed08e0f85cb9fef7ab8b87df5 100644 --- a/test/mock/app_spawn_stub.h +++ b/test/mock/app_spawn_stub.h @@ -26,11 +26,24 @@ #include "cJSON.h" #include "appspawn_client.h" #include "appspawn_hook.h" +#include "appspawn_encaps.h" + +void SetBoolParamResult(const char *key, bool flag); +int SetSelinuxConNweb(const AppSpawnMgr *content, const AppSpawningCtx *property); #ifdef __cplusplus extern "C" { #endif +typedef struct TagMountTestArg { + const char *originPath; + const char *destinationPath; + const char *fsType; + unsigned long mountFlags; + const char *options; + mode_t mountSharedFlag; +} MountTestArg; + typedef struct AppSpawnContent AppSpawnContent; typedef struct AppSpawnClient AppSpawnClient; typedef struct TagAppSpawnReqMsgNode AppSpawnReqMsgNode; @@ -46,13 +59,20 @@ typedef struct TagAppSpawnForkArg AppSpawnForkArg; typedef struct TagAppSpawnMsgNode AppSpawnMsgNode; typedef struct TagAppSpawnMgr AppSpawnMgr; typedef struct TagPathMountNode PathMountNode; -typedef struct TagMountArg MountArg; +typedef struct TagMountTestArg MountTestArg; typedef struct TagVarExtraData VarExtraData; typedef struct TagSandboxSection SandboxSection; -typedef struct TagAppSpawnNamespace AppSpawnNamespace; +typedef struct TagAppSpawnNamespace { + AppSpawnExtData extData; + int nsSelfPidFd; + int nsInitPidFd; +} AppSpawnNamespace; typedef struct TagAppSpawnedProcess AppSpawnedProcessInfo; +int AppSpawnExtDataCompareDataId(ListNode *node, void *data); AppSpawnNamespace *GetAppSpawnNamespace(const AppSpawnMgr *content); +int SetPidNamespace(int nsPidFd, int nsType); +AppSpawnNamespace *CreateAppSpawnNamespace(void); void DeleteAppSpawnNamespace(AppSpawnNamespace *ns); void FreeAppSpawnNamespace(struct TagAppSpawnExtData *data); int PreForkSetPidNamespace(AppSpawnMgr *content, AppSpawningCtx *property); @@ -91,7 +111,7 @@ int ParseAppSandboxConfig(const cJSON *appSandboxConfig, AppSpawnSandboxCfg *san AppSpawnSandboxCfg *CreateAppSpawnSandbox(ExtDataType type); void AddDefaultVariable(void); bool CheckDirRecursive(const char *path); -void CreateDemandSrc(const SandboxContext *context, const PathMountNode *sandboxNode, const MountArg *args); +void CreateDemandSrc(const SandboxContext *context, const PathMountNode *sandboxNode, const MountTestArg *args); int CheckSandboxMountNode(const SandboxContext *context, const SandboxSection *section, const PathMountNode *sandboxNode, uint32_t operation); int AppSpawnClearEnv(AppSpawnMgr *content, AppSpawningCtx *property); @@ -104,6 +124,7 @@ int LoadPermission(AppSpawnClientType type); void DeletePermission(AppSpawnClientType type); int SetProcessName(const AppSpawnMgr *content, const AppSpawningCtx *property); int SetIsolateDir(const AppSpawningCtx *property); +int SetCapabilities(const AppSpawnMgr *content, const AppSpawningCtx *property); int SetFdEnv(AppSpawnMgr *content, AppSpawningCtx *property); int PreLoadEnablePidNs(AppSpawnMgr *content); int NsInitFunc(); @@ -115,7 +136,16 @@ void SetSystemEnv(void); void RunAppSandbox(const char *ptyName); HOOK_MGR *GetAppSpawnHookMgr(void); int SpawnKickDogStart(AppSpawnMgr *mgrContent); -int AddPermissionToEncaps(cJSON *extInfoJson, cJSON *encaps, uint32_t *permissionCount); +int AddMembersToEncapsInfo(cJSON *extInfoJson, UserEncaps *encapsInfo); +int SpawnSetPermissions(AppSpawningCtx *property, UserEncaps *encapsInfo); +int AddPermissionItemToEncapsInfo(UserEncap *encap, cJSON *permissionItem); +void FreeEncapsInfo(UserEncaps *encapsInfo); +int SpawnSetEncapsPermissions(AppSpawnMgr *content, AppSpawningCtx *property); +int WriteEncapsInfo(int fd, AppSpawnEncapsBaseType encapsType, const void *encapsInfo, uint32_t flag); +int AddPermissionIntArrayToValue(cJSON *arrayItem, UserEncap *encap, int arraySize); +int AddPermissionBoolArrayToValue(cJSON *arrayItem, UserEncap *encap, int arraySize); +int AddPermissionStrArrayToValue(cJSON *arrayItem, UserEncap *encap); +int AddPermissionArrayToValue(cJSON *permissionItemArr, UserEncap *encap); #ifdef APPSPAWN_HITRACE_OPTION int FilterAppSpawnTrace(AppSpawnMgr *content, AppSpawningCtx *property); @@ -139,6 +169,5 @@ StubNode *GetStubNode(int type); #ifdef __cplusplus } #endif -int SetSelinuxConNweb(const AppSpawnMgr *content, const AppSpawningCtx *property); -void InitAppCommonEnv(const AppSpawningCtx *property); + #endif // APPSPAWN_TEST_STUB_H diff --git a/test/mock/app_system_stub.c b/test/mock/app_system_stub.c index d9eb03aec2967d9366b7849a2e714ee314b932db..6a204c92a348c71693d06a311de62c6a07e8655b 100644 --- a/test/mock/app_system_stub.c +++ b/test/mock/app_system_stub.c @@ -36,7 +36,6 @@ #include "appspawn_hook.h" #include "appspawn_server.h" -#include "appspawn_sandbox.h" #include "hilog/log.h" #include "securec.h" @@ -172,7 +171,7 @@ int MountStub(const char *originPath, const char *destinationPath, if (node == NULL || node->arg == NULL || (node->flags & STUB_NEED_CHECK) != STUB_NEED_CHECK) { return 0; } - MountArg *args = (MountArg *)node->arg; + MountTestArg *args = (MountTestArg *)node->arg; printf("args->originPath %s == %s \n", args->originPath, originPath); printf("args->destinationPath %s == %s \n", args->destinationPath, destinationPath); @@ -237,6 +236,9 @@ int AccessStub(const char *pathName, int mode) if (strstr(pathName, "/mnt/sandbox/50/com.example.myapplication/data/storage/el2") != NULL) { return -1; } + if (strstr(pathName, "/mnt/sandbox/100/debug_hap/com.example.myapplication/data/storage/el2") != NULL) { + return -1; + } if (strstr(pathName, "/data/app/el5/100/base/com.example.myapplication") != NULL) { return -1; } diff --git a/test/mock/js_runtime.h b/test/mock/js_runtime.h index 3870ea6ffed124ec70f4a9efbfcbc2129da70a10..4e05753fdc702c4c35825411f845965c820aa41d 100644 --- a/test/mock/js_runtime.h +++ b/test/mock/js_runtime.h @@ -27,6 +27,7 @@ namespace AbilityRuntime { public: enum class Language { JS = 0, + ETS = 1, }; struct Options { diff --git a/test/moduletest/BUILD.gn b/test/moduletest/BUILD.gn index 79f39b125306497896879413f722f22c8de4f575..2eb10a4a3bcc84b03a9b0e19487c1c30fbb1e90e 100644 --- a/test/moduletest/BUILD.gn +++ b/test/moduletest/BUILD.gn @@ -61,7 +61,7 @@ ohos_moduletest("AppSpawnModuleTest") { sources = [ "${appspawn_path}/test/moduletest/appspawn_client_test.cpp", - "${appspawn_path}/test/moduletest/appspawn_module_test.cpp", + #"${appspawn_path}/test/moduletest/appspawn_module_test.cpp", "${appspawn_path}/test/moduletest/appspawn_test_cmder.cpp", ] diff --git a/test/unittest/app_spawn_client_test/BUILD.gn b/test/unittest/app_spawn_client_test/BUILD.gn index 136553b5883c70d9cc27338ebb161da15993308e..3b3932f688b2acc1fb7fafbd7855e20e43a59580 100644 --- a/test/unittest/app_spawn_client_test/BUILD.gn +++ b/test/unittest/app_spawn_client_test/BUILD.gn @@ -39,6 +39,8 @@ ohos_unittest("AppSpawn_client_ut") { "${appspawn_path}/modules/ace_adapter", "${appspawn_path}/modules/common", "${appspawn_path}/modules/sandbox", + "${appspawn_path}/modules/sandbox/normal", + "${appspawn_path}/modules/sandbox/modern", "${appspawn_path}/modules/module_engine/include", "${appspawn_path}/modules/sysevent", "${appspawn_innerkits_path}/client", @@ -66,7 +68,6 @@ ohos_unittest("AppSpawn_client_ut") { "${appspawn_path}/standard/appspawn_appmgr.c", "${appspawn_path}/standard/appspawn_msgmgr.c", "${appspawn_path}/standard/appspawn_service.c", - "${appspawn_path}/standard/nwebspawn_launcher.c", "${appspawn_path}/util/src/appspawn_utils.c", ] diff --git a/test/unittest/app_spawn_client_test/app_spawn_interface_test.cpp b/test/unittest/app_spawn_client_test/app_spawn_interface_test.cpp index 60386f6b8cb7f8c2f7657dfb2ee375431d333c25..005db33db56ffdc94d118f2a1dfc404c3891373d 100644 --- a/test/unittest/app_spawn_client_test/app_spawn_interface_test.cpp +++ b/test/unittest/app_spawn_client_test/app_spawn_interface_test.cpp @@ -603,12 +603,6 @@ HWTEST_F(AppSpawnInterfaceTest, App_Spawn_Interface_GetSpawnTimeout_001, TestSiz EXPECT_EQ(timeout >= 2, 1); // 2 test } -HWTEST_F(AppSpawnInterfaceTest, App_Spawn_Interface_NWeb, TestSize.Level0) -{ - pid_t pid = NWebSpawnLaunch(); - EXPECT_GE(pid, 0); -} - /** * @brief 测试接口:SpawnListenFdSet * diff --git a/test/unittest/app_spawn_hisysevent_test/BUILD.gn b/test/unittest/app_spawn_hisysevent_test/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..e3ef281fd1f16da8d6159e0399cedd0daa238b59 --- /dev/null +++ b/test/unittest/app_spawn_hisysevent_test/BUILD.gn @@ -0,0 +1,47 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/startup/appspawn/appspawn.gni") +import("//build/test.gni") + +ohos_unittest("AppSpawn_HisysEvent_ut") { + module_out_path = "appspawn/appspawn" + deps = [] + if (appspawn_unittest_coverage) { + cflags = [ "--coverage" ] + ldflags = [ "--coverage" ] + cflags_cc = [ "--coverage" ] + } + defines = [ + "APPSPAWN_TEST", + ] + + include_dirs = [ + "${appspawn_path}/modules/sysevent", + "${appspawn_path}/util/include", + "${appspawn_path}/test/unittest/app_spawn_hisysevent_test", + ] + + sources = [ + "${appspawn_path}/modules/sysevent/hisysevent_adapter.cpp", + "${appspawn_path}/test/unittest/app_spawn_hisysevent_test/app_spawn_hisysevent_test.cpp", + "${appspawn_path}/test/unittest/app_spawn_hisysevent_test/app_spawn_hisysevent_stub.c", + ] + + external_deps = [ + "hisysevent:libhisysevent", + "hilog:libhilog", + "init:libbegetutil", + "c_utils:utils", + ] +} \ No newline at end of file diff --git a/test/unittest/app_spawn_hisysevent_test/app_spawn_hisysevent_stub.c b/test/unittest/app_spawn_hisysevent_test/app_spawn_hisysevent_stub.c new file mode 100644 index 0000000000000000000000000000000000000000..f3716f0ee0a167bcbce129d6cb7a93625b554c1c --- /dev/null +++ b/test/unittest/app_spawn_hisysevent_test/app_spawn_hisysevent_stub.c @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "app_spawn_hisysevent_stub.h" +#include "appspawn_utils.h" + +#ifdef __cplusplus +extern "C" { +#endif + +bool g_CreateTimerStatus = true; + +void SetCreateTimerStatus(bool status) +{ + if (status) { + g_CreateTimerStatus = true; + } else { + g_CreateTimerStatus = false; + } +} + +int CreateHisysTimerLoop(AppSpawnHisyseventInfo *hisyseventInfo) +{ + return 0; +} + +#ifdef __cplusplus +} +#endif \ No newline at end of file diff --git a/test/unittest/app_spawn_hisysevent_test/app_spawn_hisysevent_stub.h b/test/unittest/app_spawn_hisysevent_test/app_spawn_hisysevent_stub.h new file mode 100644 index 0000000000000000000000000000000000000000..b0c2606bc72484160586dd036ef73509d9137767 --- /dev/null +++ b/test/unittest/app_spawn_hisysevent_test/app_spawn_hisysevent_stub.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef APP_SPAWN_HISYSEVENT_STUB_H +#define APP_SPAWN_HISYSEVENT_STUB_H + +#include "hisysevent_adapter.h" +#include "hisysevent.h" + +#ifdef __cplusplus +extern "C" { +#endif + +void SetCreateTimerStatus(bool status); +int CreateHisysTimerLoop(AppSpawnHisyseventInfo *hisyseventInfo); + +#ifdef __cplusplus +} +#endif +#endif \ No newline at end of file diff --git a/test/unittest/app_spawn_hisysevent_test/app_spawn_hisysevent_test.cpp b/test/unittest/app_spawn_hisysevent_test/app_spawn_hisysevent_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..abba0b6a4b804246a7cb34459efb640a5743ba93 --- /dev/null +++ b/test/unittest/app_spawn_hisysevent_test/app_spawn_hisysevent_test.cpp @@ -0,0 +1,156 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include "app_spawn_hisysevent_stub.h" + +using namespace testing; +using namespace testing::ext; + +namespace OHOS { +class AppSpawnHisysEventTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void AppSpawnHisysEventTest::SetUpTestCase() +{ + GTEST_LOG_(INFO) << "AppSpawn_HisysEvent_TEST SetUpTestCase"; +} + +void AppSpawnHisysEventTest::TearDownTestCase() +{ + GTEST_LOG_(INFO) << "AppSpawn_HisysEvent_TEST TearDownTestCase"; +} + +void AppSpawnHisysEventTest::SetUp() +{ + GTEST_LOG_(INFO) << "AppSpawn_HisysEvent_TEST SetUp"; +} + +void AppSpawnHisysEventTest::TearDown() +{ + GTEST_LOG_(INFO) << "AppSpawn_HisysEvent_TEST TearDown"; +} + +/** +* @tc.name: AppSpawnHisysEvent_001 +* @tc.desc: Verify InitHisyseventTimer success. +* @tc.type: FUNC +*/ +HWTEST_F(AppSpawnHisysEventTest, AppSpawnHisysEvent_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "AppSpawnHisysEvent_001 test...."; + SetCreateTimerStatus(true); + AppSpawnHisyseventInfo * hisyseventInfo = InitHisyseventTimer(); + EXPECT_NE(hisyseventInfo, NULL); + DeleteHisyseventInfo(hisyseventInfo); + hisyseventInfo = NULL; +} + +/** +* @tc.name: AppSpawnHisysEvent_002 +* @tc.desc: Verify InitHisyseventTimer fail. +* @tc.type: FUNC +*/ +HWTEST_F(AppSpawnHisysEventTest, AppSpawnHisysEvent_002, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "AppSpawnHisysEvent_002 test...."; + SetCreateTimerStatus(false); + AppSpawnHisyseventInfo * hisyseventInfo = InitHisyseventTimer(); + EXPECT_NE(hisyseventInfo, NULL); + DeleteHisyseventInfo(hisyseventInfo); + hisyseventInfo = NULL; +} + +/** +* @tc.name: AppSpawnHisysEvent_003 +* @tc.desc: Verify Add bootevent count success. +* @tc.type: FUNC +*/ +HWTEST_F(AppSpawnHisysEventTest, AppSpawnHisysEvent_003, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "AppSpawnHisysEvent_003 test...."; + SetCreateTimerStatus(true); + AppSpawnHisyseventInfo * hisyseventInfo = InitHisyseventTimer(); + EXPECT_NE(hisyseventInfo, NULL); + AddStatisticEventInfo(hisyseventInfo, 20, true); + int count = hisyseventInfo->bootEvent.eventCount; + EXPECT_EQ(count, 1); + DeleteHisyseventInfo(hisyseventInfo); + hisyseventInfo = NULL; +} + +/** +* @tc.name: AppSpawnHisysEvent_004 +* @tc.desc: Verify Add bootevent duration success. +* @tc.type: FUNC +*/ +HWTEST_F(AppSpawnHisysEventTest, AppSpawnHisysEvent_004, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "AppSpawnHisysEvent_004 test...."; + SetCreateTimerStatus(true); + AppSpawnHisyseventInfo * hisyseventInfo = InitHisyseventTimer(); + EXPECT_NE(hisyseventInfo, NULL); + AddStatisticEventInfo(hisyseventInfo, 20, true); + int duration = hisyseventInfo->bootEvent.totalDuration; + EXPECT_EQ(duration, 20); + DeleteHisyseventInfo(hisyseventInfo); + hisyseventInfo = NULL; +} + +/** +* @tc.name: AppSpawnHisysEvent_005 +* @tc.desc: Verify Add manualevent duration success. +* @tc.type: FUNC +*/ +HWTEST_F(AppSpawnHisysEventTest, AppSpawnHisysEvent_005, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "AppSpawnHisysEvent_005 test...."; + SetCreateTimerStatus(true); + AppSpawnHisyseventInfo * hisyseventInfo = InitHisyseventTimer(); + EXPECT_NE(hisyseventInfo, NULL); + AddStatisticEventInfo(hisyseventInfo, 20, false); + int duration = hisyseventInfo->manualEvent.totalDuration; + EXPECT_EQ(duration, 20); + DeleteHisyseventInfo(hisyseventInfo); + hisyseventInfo = NULL; +} + +/** +* @tc.name: AppSpawnHisysEvent_006 +* @tc.desc: Verify manualevent maxduration and minduration success. +* @tc.type: FUNC +*/ +HWTEST_F(AppSpawnHisysEventTest, AppSpawnHisysEvent_006, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "AppSpawnHisysEvent_006 test...."; + SetCreateTimerStatus(true); + AppSpawnHisyseventInfo * hisyseventInfo = InitHisyseventTimer(); + EXPECT_NE(hisyseventInfo, NULL); + AddStatisticEventInfo(hisyseventInfo, 10, true); + AddStatisticEventInfo(hisyseventInfo, 20, true); + AddStatisticEventInfo(hisyseventInfo, 30, true); + int maxduration = hisyseventInfo->bootEvent.maxDuration; + int minduration = hisyseventInfo->bootEvent.minDuration; + EXPECT_EQ(maxduration, 30); + EXPECT_EQ(minduration, 10); + DeleteHisyseventInfo(hisyseventInfo); + hisyseventInfo = NULL; +} +} // namespace OHOS diff --git a/test/unittest/app_spawn_standard_test/BUILD.gn b/test/unittest/app_spawn_standard_test/BUILD.gn index 15a882f557c5fe69357c92810960bc5c6f254180..af8665d238578e540ae427c7df224733d07080f8 100644 --- a/test/unittest/app_spawn_standard_test/BUILD.gn +++ b/test/unittest/app_spawn_standard_test/BUILD.gn @@ -12,12 +12,14 @@ # limitations under the License. import("//base/startup/appspawn/appspawn.gni") +import("//base/startup/appspawn/modules/sandbox/sandbox.gni") import("//build/test.gni") ohos_unittest("AppSpawn_ut") { module_out_path = "appspawn/appspawn" + cflags = [ "-Dprivate=public" ] if (appspawn_unittest_coverage) { - cflags = [ "--coverage" ] + cflags += [ "--coverage" ] ldflags = [ "--coverage" ] cflags_cc = [ "--coverage" ] } @@ -26,6 +28,7 @@ ohos_unittest("AppSpawn_ut") { "APPSPAWN_BASE_DIR=\"/data/appspawn_ut\"", "APPSPAWN_LABEL=\"APPSPAWN_UT\"", "APPSPAWN_TEST", + "APPSPAWN_CLIENT", "APPSPAWN_DEBUG", "DEBUG_BEGETCTL_BOOT", "USER_TIMER_TO_CHECK", @@ -63,7 +66,6 @@ ohos_unittest("AppSpawn_ut") { "${appspawn_path}/modules/modulemgr", "${appspawn_path}/modules/ace_adapter", "${appspawn_path}/modules/common", - "${appspawn_path}/modules/sandbox", "${appspawn_path}/modules/sysevent", "${appspawn_innerkits_path}/client", "${appspawn_innerkits_path}/include", @@ -73,6 +75,7 @@ ohos_unittest("AppSpawn_ut") { "${appspawn_path}/test/unittest", "${appspawn_path}/util/include", ] + include_dirs += appspawn_sandbox_inc sources = [ "${appspawn_path}/common/appspawn_server.c", "${appspawn_path}/common/appspawn_trace.cpp", @@ -81,7 +84,6 @@ ohos_unittest("AppSpawn_ut") { "${appspawn_path}/standard/appspawn_kickdog.c", "${appspawn_path}/standard/appspawn_msgmgr.c", "${appspawn_path}/standard/appspawn_service.c", - "${appspawn_path}/standard/nwebspawn_launcher.c", "${appspawn_path}/util/src/appspawn_utils.c", ] @@ -104,16 +106,8 @@ ohos_unittest("AppSpawn_ut") { "${appspawn_path}/modules/common/appspawn_namespace.c", "${appspawn_path}/modules/common/appspawn_silk.c", "${appspawn_path}/modules/nweb_adapter/nwebspawn_adapter.cpp", - "${appspawn_path}/modules/sandbox/appspawn_mount_template.c", - "${appspawn_path}/modules/sandbox/appspawn_permission.c", - "${appspawn_path}/modules/sandbox/appspawn_sandbox.c", - "${appspawn_path}/modules/sandbox/sandbox_adapter.cpp", - "${appspawn_path}/modules/sandbox/sandbox_cfgvar.c", - "${appspawn_path}/modules/sandbox/sandbox_dec.c", - "${appspawn_path}/modules/sandbox/sandbox_expand.c", - "${appspawn_path}/modules/sandbox/sandbox_load.c", - "${appspawn_path}/modules/sandbox/sandbox_manager.c", ] + sources += appspawn_sandbox_src # add stub include_dirs += [ "${appspawn_path}/test/mock" ] @@ -132,7 +126,6 @@ ohos_unittest("AppSpawn_ut") { "${appspawn_path}/test/unittest/app_spawn_standard_test/app_spawn_command_lexer_test.cpp", "${appspawn_path}/test/unittest/app_spawn_standard_test/app_spawn_kickdog_test.cpp", "${appspawn_path}/test/unittest/app_spawn_standard_test/app_spawn_module_interface_test.cpp", - "${appspawn_path}/test/unittest/app_spawn_standard_test/app_spawn_sandboxmgr_test.cpp", "${appspawn_path}/test/unittest/app_spawn_standard_test/app_spawn_service_test.cpp", "${appspawn_path}/test/unittest/app_spawn_standard_test/app_spawn_silk_test.cpp", "${appspawn_path}/test/unittest/app_spawn_standard_test/nweb_spawn_service_test.cpp", @@ -141,15 +134,13 @@ ohos_unittest("AppSpawn_ut") { if (defined(appspawn_sandbox_new) && appspawn_sandbox_new) { sources += [ - "${appspawn_path}/modules/sandbox/sandbox_shared.c", "${appspawn_path}/test/unittest/app_spawn_standard_test/app_spawn_sandbox_new_mount_test.cpp", "${appspawn_path}/test/unittest/app_spawn_standard_test/app_spawn_sandbox_new_test.cpp", + "${appspawn_path}/test/unittest/app_spawn_standard_test/app_spawn_sandboxmgr_test.cpp", ] defines += [ "APPSPAWN_SANDBOX_NEW" ] } else { sources += [ - "${appspawn_path}/modules/sandbox/sandbox_shared_mount.cpp", - "${appspawn_path}/modules/sandbox/sandbox_utils.cpp", "${appspawn_path}/test/unittest/app_spawn_standard_test/app_spawn_sandbox_test.cpp", ] } @@ -224,8 +215,9 @@ ohos_unittest("AppSpawn_ut") { ohos_unittest("AppSpawn_coldrun_ut") { module_out_path = "appspawn/appspawn" + cflags = [ "-Dprivate=public" ] if (appspawn_unittest_coverage) { - cflags = [ "--coverage" ] + cflags += [ "--coverage" ] ldflags = [ "--coverage" ] cflags_cc = [ "--coverage" ] } @@ -235,6 +227,7 @@ ohos_unittest("AppSpawn_coldrun_ut") { "APPSPAWN_LABEL=\"APPSPAWN_UT\"", "APPSPAWN_TEST", "APPSPAWN_DEBUG", + "APPSPAWN_CLIENT", "DEBUG_BEGETCTL_BOOT", "USER_TIMER_TO_CHECK", "OHOS_DEBUG", @@ -271,7 +264,6 @@ ohos_unittest("AppSpawn_coldrun_ut") { "${appspawn_path}/modules/modulemgr", "${appspawn_path}/modules/ace_adapter", "${appspawn_path}/modules/common", - "${appspawn_path}/modules/sandbox", "${appspawn_path}/modules/sysevent", "${appspawn_innerkits_path}/client", "${appspawn_innerkits_path}/include", @@ -281,6 +273,7 @@ ohos_unittest("AppSpawn_coldrun_ut") { "${appspawn_path}/test/unittest", "${appspawn_path}/util/include", ] + include_dirs += appspawn_sandbox_inc sources = [ "${appspawn_path}/common/appspawn_server.c", "${appspawn_path}/common/appspawn_trace.cpp", @@ -289,7 +282,6 @@ ohos_unittest("AppSpawn_coldrun_ut") { "${appspawn_path}/standard/appspawn_kickdog.c", "${appspawn_path}/standard/appspawn_msgmgr.c", "${appspawn_path}/standard/appspawn_service.c", - "${appspawn_path}/standard/nwebspawn_launcher.c", "${appspawn_path}/util/src/appspawn_utils.c", ] @@ -312,16 +304,8 @@ ohos_unittest("AppSpawn_coldrun_ut") { "${appspawn_path}/modules/common/appspawn_namespace.c", "${appspawn_path}/modules/common/appspawn_silk.c", "${appspawn_path}/modules/nweb_adapter/nwebspawn_adapter.cpp", - "${appspawn_path}/modules/sandbox/appspawn_mount_template.c", - "${appspawn_path}/modules/sandbox/appspawn_permission.c", - "${appspawn_path}/modules/sandbox/appspawn_sandbox.c", - "${appspawn_path}/modules/sandbox/sandbox_adapter.cpp", - "${appspawn_path}/modules/sandbox/sandbox_cfgvar.c", - "${appspawn_path}/modules/sandbox/sandbox_dec.c", - "${appspawn_path}/modules/sandbox/sandbox_expand.c", - "${appspawn_path}/modules/sandbox/sandbox_load.c", - "${appspawn_path}/modules/sandbox/sandbox_manager.c", ] + sources += appspawn_sandbox_src if (appspawn_use_encaps == true) { sources += [ "${appspawn_path}/modules/common/appspawn_encaps.c" ] @@ -343,12 +327,6 @@ ohos_unittest("AppSpawn_coldrun_ut") { if (defined(appspawn_sandbox_new) && appspawn_sandbox_new) { defines += [ "APPSPAWN_SANDBOX_NEW" ] - sources += [ "${appspawn_path}/modules/sandbox/sandbox_shared.c" ] - } else { - sources += [ - "${appspawn_path}/modules/sandbox/sandbox_shared_mount.cpp", - "${appspawn_path}/modules/sandbox/sandbox_utils.cpp", - ] } configs = [ "${appspawn_path}:appspawn_config" ] @@ -415,8 +393,9 @@ ohos_unittest("AppSpawn_coldrun_ut") { ohos_unittest("AppSpawn_common_ut") { module_out_path = "appspawn/appspawn" + cflags = [ "-Dprivate=public" ] if (appspawn_unittest_coverage) { - cflags = [ "--coverage" ] + cflags += [ "--coverage" ] ldflags = [ "--coverage" ] cflags_cc = [ "--coverage" ] } @@ -426,6 +405,7 @@ ohos_unittest("AppSpawn_common_ut") { "APPSPAWN_LABEL=\"APPSPAWN_UT\"", "APPSPAWN_TEST", "APPSPAWN_DEBUG", + "APPSPAWN_CLIENT", "DEBUG_BEGETCTL_BOOT", "USER_TIMER_TO_CHECK", "OHOS_DEBUG", @@ -462,7 +442,6 @@ ohos_unittest("AppSpawn_common_ut") { "${appspawn_path}/modules/modulemgr", "${appspawn_path}/modules/ace_adapter", "${appspawn_path}/modules/common", - "${appspawn_path}/modules/sandbox", "${appspawn_path}/modules/sysevent", "${appspawn_innerkits_path}/client", "${appspawn_innerkits_path}/include", @@ -472,6 +451,7 @@ ohos_unittest("AppSpawn_common_ut") { "${appspawn_path}/test/unittest", "${appspawn_path}/util/include", ] + include_dirs += appspawn_sandbox_inc sources = [ "${appspawn_path}/common/appspawn_server.c", "${appspawn_path}/common/appspawn_trace.cpp", @@ -480,7 +460,6 @@ ohos_unittest("AppSpawn_common_ut") { "${appspawn_path}/standard/appspawn_kickdog.c", "${appspawn_path}/standard/appspawn_msgmgr.c", "${appspawn_path}/standard/appspawn_service.c", - "${appspawn_path}/standard/nwebspawn_launcher.c", "${appspawn_path}/util/src/appspawn_utils.c", ] @@ -504,16 +483,8 @@ ohos_unittest("AppSpawn_common_ut") { "${appspawn_path}/modules/common/appspawn_namespace.c", "${appspawn_path}/modules/common/appspawn_silk.c", "${appspawn_path}/modules/nweb_adapter/nwebspawn_adapter.cpp", - "${appspawn_path}/modules/sandbox/appspawn_mount_template.c", - "${appspawn_path}/modules/sandbox/appspawn_permission.c", - "${appspawn_path}/modules/sandbox/appspawn_sandbox.c", - "${appspawn_path}/modules/sandbox/sandbox_adapter.cpp", - "${appspawn_path}/modules/sandbox/sandbox_cfgvar.c", - "${appspawn_path}/modules/sandbox/sandbox_dec.c", - "${appspawn_path}/modules/sandbox/sandbox_expand.c", - "${appspawn_path}/modules/sandbox/sandbox_load.c", - "${appspawn_path}/modules/sandbox/sandbox_manager.c", ] + sources += appspawn_sandbox_src # add stub include_dirs += [ "${appspawn_path}/test/mock" ] @@ -525,18 +496,13 @@ ohos_unittest("AppSpawn_common_ut") { # add test include_dirs += [ "${appspawn_path}/test/unittest" ] sources += [ + "${appspawn_path}/test/unittest/app_spawn_standard_test/app_spawn_ace_test.cpp", "${appspawn_path}/test/unittest/app_spawn_standard_test/app_spawn_common_test.cpp", "${appspawn_path}/test/unittest/app_spawn_test_helper.cpp", ] if (defined(appspawn_sandbox_new) && appspawn_sandbox_new) { defines += [ "APPSPAWN_SANDBOX_NEW" ] - sources += [ "${appspawn_path}/modules/sandbox/sandbox_shared.c" ] - } else { - sources += [ - "${appspawn_path}/modules/sandbox/sandbox_shared_mount.cpp", - "${appspawn_path}/modules/sandbox/sandbox_utils.cpp", - ] } configs = [ "${appspawn_path}:appspawn_config" ] diff --git a/test/unittest/app_spawn_standard_test/app_spawn_ace_test.cpp b/test/unittest/app_spawn_standard_test/app_spawn_ace_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3516d98a634071b6bc08266666aa1af728ac7bdb --- /dev/null +++ b/test/unittest/app_spawn_standard_test/app_spawn_ace_test.cpp @@ -0,0 +1,206 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +#include "appspawn.h" +#include "appspawn_hook.h" +#include "appspawn_manager.h" +#include "app_spawn_stub.h" +#include "app_spawn_test_helper.h" + +using namespace testing; +using namespace testing::ext; +using namespace OHOS; + +APPSPAWN_STATIC int RunChildThread(const AppSpawnMgr *content, const AppSpawningCtx *property); +APPSPAWN_STATIC int RunChildByRenderCmd(const AppSpawnMgr *content, const AppSpawningCtx *property); +APPSPAWN_STATIC int PreLoadAppSpawn(AppSpawnMgr *content); +APPSPAWN_STATIC int DlopenAppSpawn(AppSpawnMgr *content); + +namespace OHOS { +static AppSpawnTestHelper g_testHelper; +class AppSpawnAceTest : public testing::Test { +public: + static void SetUpTestCase() {} + static void TearDownTestCase() {} + void SetUp() {} + void TearDown() {} +}; + +/** + * @brief nwebspawn进行预加载 + * @note 预期结果: nwebspawn不支持预加载,直接返回 + * + */ +HWTEST_F(AppSpawnAceTest, App_Spawn_Ace_Preload_001, TestSize.Level0) +{ + AppSpawnMgr *mgr = CreateAppSpawnMgr(MODE_FOR_NWEB_SPAWN); + ASSERT_NE(mgr, nullptr); + mgr->content.longProcName = const_cast(NWEBSPAWN_SERVER_NAME); + mgr->content.longProcNameLen = APP_LEN_PROC_NAME; + + int ret = PreLoadAppSpawn(mgr); + DeleteAppSpawnMgr(mgr); + EXPECT_EQ(ret, 0); +} + +/** + * @brief cjappspawn进行预加载 + * @note 预期结果: cjappspawn通过processName校验,执行LoadExtendCJLib预加载 + * + */ +HWTEST_F(AppSpawnAceTest, App_Spawn_Ace_Preload_002, TestSize.Level0) +{ + AppSpawnMgr *mgr = CreateAppSpawnMgr(MODE_FOR_CJAPP_SPAWN); + ASSERT_NE(mgr, nullptr); + mgr->content.longProcName = const_cast(CJAPPSPAWN_SERVER_NAME); + mgr->content.longProcNameLen = APP_LEN_PROC_NAME; + + int ret = PreLoadAppSpawn(mgr); + DeleteAppSpawnMgr(mgr); + EXPECT_EQ(ret, 0); +} + +/** + * @brief 未设置preload参数时(使用参数默认值),appspawn进行预加载 + * @note 预期结果: appspawn根据参数默认值判断是否执行preload预加载 + * + */ +HWTEST_F(AppSpawnAceTest, App_Spawn_Ace_Preload_003, TestSize.Level0) +{ + AppSpawnMgr *mgr = CreateAppSpawnMgr(MODE_FOR_APP_SPAWN); + ASSERT_NE(mgr, nullptr); + mgr->content.longProcName = const_cast(APPSPAWN_SERVER_NAME); + mgr->content.longProcNameLen = APP_LEN_PROC_NAME; + + int ret = PreLoadAppSpawn(mgr); + DeleteAppSpawnMgr(mgr); + EXPECT_EQ(ret, 0); +} + +/** + * @brief preload参数设置为true时,测试appspawn进行预加载 + * @note 预期结果: appspawn执行preload预加载 + * + */ +HWTEST_F(AppSpawnAceTest, App_Spawn_Ace_Preload_004, TestSize.Level0) +{ + AppSpawnMgr *mgr = CreateAppSpawnMgr(MODE_FOR_APP_SPAWN); + ASSERT_NE(mgr, nullptr); + mgr->content.longProcName = const_cast(APPSPAWN_SERVER_NAME); + mgr->content.longProcNameLen = APP_LEN_PROC_NAME; + + SetBoolParamResult("persist.appspawn.preload", true); + int ret = PreLoadAppSpawn(mgr); + SetBoolParamResult("persist.appspawn.preload", false); + DeleteAppSpawnMgr(mgr); + EXPECT_EQ(ret, 0); +} + +/** + * @brief preload参数和preloadets参数均设置为true时,测试appspawn进行预加载 + * @note 预期结果: appspawn执行preload和preloadets预加载 + * + */ +HWTEST_F(AppSpawnAceTest, App_Spawn_Ace_Preload_005, TestSize.Level0) +{ + AppSpawnMgr *mgr = CreateAppSpawnMgr(MODE_FOR_APP_SPAWN); + ASSERT_NE(mgr, nullptr); + mgr->content.longProcName = const_cast(APPSPAWN_SERVER_NAME); + mgr->content.longProcNameLen = APP_LEN_PROC_NAME; + + SetBoolParamResult("persist.appspawn.preload", true); + SetBoolParamResult("persist.appspawn.preloadets", true); + int ret = PreLoadAppSpawn(mgr); + SetBoolParamResult("persist.appspawn.preload", false); + SetBoolParamResult("persist.appspawn.preloadets", false); + DeleteAppSpawnMgr(mgr); + EXPECT_EQ(ret, 0); +} + +/** + * @brief nwebspawn进行加载system libs + * @note 预期结果: nwebspawn不支持加载system libs,直接返回 + * + */ +HWTEST_F(AppSpawnAceTest, App_Spawn_Ace_Dlopen_001, TestSize.Level0) +{ + AppSpawnMgr *mgr = CreateAppSpawnMgr(MODE_FOR_NWEB_SPAWN); + ASSERT_NE(mgr, nullptr); + + int ret = DlopenAppSpawn(mgr); + DeleteAppSpawnMgr(mgr); + EXPECT_EQ(ret, 0); +} + +/** + * @brief appspawn进行加载system libs + * @note 预期结果: appspawn加载system libs正常 + * + */ +HWTEST_F(AppSpawnAceTest, App_Spawn_Ace_Dlopen_002, TestSize.Level0) +{ + AppSpawnMgr *mgr = CreateAppSpawnMgr(MODE_FOR_APP_SPAWN); + ASSERT_NE(mgr, nullptr); + + int ret = DlopenAppSpawn(mgr); + DeleteAppSpawnMgr(mgr); + EXPECT_EQ(ret, 0); +} + +/** + * @brief appspawn执行RunChildThread + * @note 预期结果: 执行正常,分支覆盖 + * + */ +HWTEST_F(AppSpawnAceTest, App_Spawn_Ace_RunChild_001, TestSize.Level0) +{ + AppSpawnMgr *mgr = CreateAppSpawnMgr(MODE_FOR_APP_SPAWN); + ASSERT_NE(mgr, nullptr); + AppSpawningCtx *property = CreateAppSpawningCtx(); + ASSERT_NE(property, nullptr); + property->message = CreateAppSpawnMsg(); + ASSERT_NE(property->message, nullptr); + + int ret = RunChildThread(mgr, property); + DeleteAppSpawningCtx(property); + DeleteAppSpawnMgr(mgr); + EXPECT_EQ(ret, 0); +} + +/** + * @brief appspawn执行RunChildByRenderCmd + * @note 预期结果: 执行正常,分支覆盖 + * + */ +HWTEST_F(AppSpawnAceTest, App_Spawn_Ace_RunChild_002, TestSize.Level0) +{ + AppSpawnMgr *mgr = CreateAppSpawnMgr(MODE_FOR_APP_SPAWN); + ASSERT_NE(mgr, nullptr); + AppSpawningCtx *property = CreateAppSpawningCtx(); + ASSERT_NE(property, nullptr); + property->message = CreateAppSpawnMsg(); + ASSERT_NE(property->message, nullptr); + + int ret = RunChildByRenderCmd(mgr, property); + DeleteAppSpawningCtx(property); + DeleteAppSpawnMgr(mgr); + EXPECT_EQ(ret, -1); +} +} // namespace OHOS diff --git a/test/unittest/app_spawn_standard_test/app_spawn_appmgr_test.cpp b/test/unittest/app_spawn_standard_test/app_spawn_appmgr_test.cpp index c4099de46d3f3c93007ab0fc1466912c3395c7ed..fa70b18659e8b559304d511413df94d0d33c1546 100644 --- a/test/unittest/app_spawn_standard_test/app_spawn_appmgr_test.cpp +++ b/test/unittest/app_spawn_standard_test/app_spawn_appmgr_test.cpp @@ -25,7 +25,6 @@ #include "appspawn_manager.h" #include "appspawn_modulemgr.h" #include "appspawn_permission.h" -#include "appspawn_sandbox.h" #include "appspawn_utils.h" #include "securec.h" diff --git a/test/unittest/app_spawn_standard_test/app_spawn_beget_test.cpp b/test/unittest/app_spawn_standard_test/app_spawn_beget_test.cpp index 7d257e194df85c5cef09d345c0713ddd819b57c9..0f0b45d0984a7511c0a19a4227a3a7743e203b5a 100644 --- a/test/unittest/app_spawn_standard_test/app_spawn_beget_test.cpp +++ b/test/unittest/app_spawn_standard_test/app_spawn_beget_test.cpp @@ -163,9 +163,6 @@ HWTEST_F(AppSpawnBegetCtlTest, App_Spawn_BetgetCtl_004, TestSize.Level0) AppSpawningCtx *property = nullptr; int ret = -1; do { - // add default - AddDefaultVariable(); - // create msg ret = AppSpawnClientInit(APPSPAWN_SERVER_NAME, &clientHandle); APPSPAWN_CHECK(ret == 0, break, "Failed to create reqMgr %{public}s", APPSPAWN_SERVER_NAME); diff --git a/test/unittest/app_spawn_standard_test/app_spawn_common_test.cpp b/test/unittest/app_spawn_standard_test/app_spawn_common_test.cpp index c0e73013a74a2a7b3112df468e14a5bc828555fe..52e09332600c2225ce63e2c166bdb5dfe8382253 100644 --- a/test/unittest/app_spawn_standard_test/app_spawn_common_test.cpp +++ b/test/unittest/app_spawn_standard_test/app_spawn_common_test.cpp @@ -28,6 +28,7 @@ #include "appspawn_server.h" #include "appspawn_manager.h" #include "appspawn_adapter.h" +#include "appspawn_encaps.h" #include "appspawn.h" #include "appspawn_hook.h" #include "appspawn_permission.h" @@ -40,11 +41,6 @@ using namespace testing; using namespace testing::ext; using namespace OHOS; -APPSPAWN_STATIC int BuildFdInfoMap(const AppSpawnMsgNode *message, std::map &fdMap, int isColdRun); -APPSPAWN_STATIC void LoadExtendCJLib(void); -APPSPAWN_STATIC int PreLoadAppSpawn(AppSpawnMgr *content); -APPSPAWN_STATIC int RunChildByRenderCmd(const AppSpawnMgr *content, const AppSpawningCtx *property); - namespace OHOS { static AppSpawnTestHelper g_testHelper; class AppSpawnCommonTest : public testing::Test { @@ -390,60 +386,6 @@ HWTEST_F(AppSpawnCommonTest, App_Spawn_Common_016, TestSize.Level0) AppSpawnHiSysEventWrite(); } -HWTEST_F(AppSpawnCommonTest, App_Spawn_Common_017, TestSize.Level0) -{ - AppSpawnMgr *content = CreateAppSpawnMgr(MODE_FOR_NWEB_SPAWN); - EXPECT_EQ(content != nullptr, 1); - int ret = -1; - do { - LoadExtendCJLib(); - } while (0); - DeleteAppSpawnMgr(content); - ASSERT_EQ(ret, -1); -} - -HWTEST_F(AppSpawnCommonTest, App_Spawn_Common_018, TestSize.Level0) -{ - AppSpawnMgr *content = CreateAppSpawnMgr(MODE_FOR_NWEB_SPAWN); - EXPECT_EQ(content != nullptr, 1); - int ret = -1; - do { - // spawn - ret = PreLoadAppSpawn(content); - } while (0); - DeleteAppSpawnMgr(content); - ASSERT_EQ(ret, 0); -} - -HWTEST_F(AppSpawnCommonTest, App_Spawn_Common_019, TestSize.Level0) -{ - AppSpawnMgr *content = CreateAppSpawnMgr(MODE_FOR_NWEB_SPAWN); - EXPECT_EQ(content != nullptr, 1); - int ret = -1; - do { - RunChildByRenderCmd(nullptr, nullptr); - } while (0); - DeleteAppSpawnMgr(content); - ASSERT_EQ(ret, -1); -} - -HWTEST_F(AppSpawnCommonTest, App_Spawn_Common_020, TestSize.Level0) -{ - AppSpawnMgr *content = CreateAppSpawnMgr(MODE_FOR_NWEB_SPAWN); - EXPECT_EQ(content != nullptr, 1); - int ret = -1; - do { - // spawn - AppSpawnMsgNode *msgNode = CreateAppSpawnMsg(); - EXPECT_EQ(msgNode != nullptr, 1); - std::map fdMap; - ret = BuildFdInfoMap(msgNode, fdMap, 0); - } while (0); - DeleteAppSpawnMgr(content); - ASSERT_EQ(ret, -1); -} - - HWTEST_F(AppSpawnCommonTest, App_Spawn_Common_021, TestSize.Level0) { int ret = SetInternetPermission(nullptr); @@ -658,97 +600,709 @@ HWTEST_F(AppSpawnCommonTest, App_Spawn_Common_031, TestSize.Level0) AppSpawnClientInit(nullptr, nullptr); } +HWTEST_F(AppSpawnCommonTest, App_Spawn_Common_GetAppSpawnNamespace, TestSize.Level0) +{ + int ret = -1; + AppSpawnMgr *mgr = nullptr; + AppSpawnNamespace *appSpawnNamespace = nullptr; + mgr = CreateAppSpawnMgr(MODE_FOR_APP_SPAWN); + EXPECT_EQ(mgr != nullptr, 1); + appSpawnNamespace = CreateAppSpawnNamespace(); + appSpawnNamespace->nsSelfPidFd = GetNsPidFd(getpid()); + OH_ListInit(&appSpawnNamespace->extData.node); + OH_ListAddTail(&mgr->extData, &appSpawnNamespace->extData.node); + AppSpawnNamespace *appSpawnNamespace1 = nullptr; + appSpawnNamespace1 = GetAppSpawnNamespace(mgr); + EXPECT_EQ(appSpawnNamespace1 != nullptr, 1); + uint32_t dataId = EXT_DATA_NAMESPACE; + AppSpawnExtDataCompareDataId(&mgr->extData, (void *)&dataId); + DeleteAppSpawnNamespace(appSpawnNamespace); + DeleteAppSpawnMgr(mgr); +} + +HWTEST_F(AppSpawnCommonTest, App_Spawn_Common_GetPidByName, TestSize.Level0) +{ + int ret = -1; + AppSpawnMgr *mgr = nullptr; + AppSpawnNamespace *appSpawnNamespace = nullptr; + mgr = CreateAppSpawnMgr(MODE_FOR_APP_SPAWN); + EXPECT_EQ(mgr != nullptr, 1); + appSpawnNamespace = CreateAppSpawnNamespace(); + OH_ListInit(&appSpawnNamespace->extData.node); + OH_ListAddTail(&mgr->extData, &appSpawnNamespace->extData.node); + appSpawnNamespace->nsInitPidFd = GetNsPidFd(getpid()); + pid_t pid = GetPidByName("appspawn"); + EXPECT_EQ(pid > 0, 1); + DeleteAppSpawnNamespace(appSpawnNamespace); + DeleteAppSpawnMgr(mgr); +} + +HWTEST_F(AppSpawnCommonTest, App_Spawn_Common_PreLoadEnablePidNs, TestSize.Level0) +{ + int ret = -1; + AppSpawnMgr *mgr = nullptr; + AppSpawnNamespace *appSpawnNamespace = nullptr; + mgr = CreateAppSpawnMgr(MODE_FOR_APP_SPAWN); + EXPECT_EQ(mgr != nullptr, 1); + mgr->content.sandboxNsFlags = CLONE_NEWPID; + ret = PreLoadEnablePidNs(mgr); + EXPECT_EQ(ret, 0); + AppSpawnNamespace *appSpawnNamespace1 = nullptr; + appSpawnNamespace1 = GetAppSpawnNamespace(mgr); + EXPECT_EQ(appSpawnNamespace1 != nullptr, 1); + DeleteAppSpawnNamespace(appSpawnNamespace); + DeleteAppSpawnMgr(mgr); + SetPidNamespace(0, 0); +} + +HWTEST_F(AppSpawnCommonTest, App_Spawn_Common_PreForkSetPidNamespace, TestSize.Level0) +{ + int ret = -1; + AppSpawnMgr *mgr = nullptr; + AppSpawnNamespace *appSpawnNamespace = nullptr; + mgr = CreateAppSpawnMgr(MODE_FOR_APP_SPAWN); + EXPECT_EQ(mgr != nullptr, 1); + mgr->content.sandboxNsFlags = CLONE_NEWPID; + ret = PreLoadEnablePidNs(mgr); + EXPECT_EQ(ret, 0); + PreForkSetPidNamespace(mgr, nullptr); + PostForkSetPidNamespace(mgr, nullptr); + mgr->content.sandboxNsFlags = 0; + PreForkSetPidNamespace(mgr, nullptr); + PostForkSetPidNamespace(mgr, nullptr); + DeleteAppSpawnNamespace(appSpawnNamespace); + DeleteAppSpawnMgr(mgr); + SetPidNamespace(0, 0); +} + HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_001, TestSize.Level0) { - const char encapsJsonStr[] = "{\"name\":\"Permissions\",\"ohos.encaps.count\":0,\"permissions\":" - "[{\"ohos.permission.bool\":true},{\"ohos.permission.int\":3225},{\"ohos.permission.string\":\"test\"}," - "{\"ohos.permission.array\":[1,2,3,4,5]}]}"; + AppSpawnClientHandle clientHandle = nullptr; + AppSpawnReqMsgHandle reqHandle = 0; + AppSpawningCtx *property = nullptr; + AppSpawnMgr *mgr = nullptr; + int ret = -1; + do { + mgr = CreateAppSpawnMgr(MODE_FOR_APP_SPAWN); + EXPECT_EQ(mgr != nullptr, 1); + // create msg + ret = AppSpawnClientInit(APPSPAWN_SERVER_NAME, &clientHandle); + APPSPAWN_CHECK(ret == 0, break, "Failed to create reqMgr %{public}s", APPSPAWN_SERVER_NAME); + reqHandle = g_testHelper.CreateMsg(clientHandle, MSG_APP_SPAWN, 0); + APPSPAWN_CHECK(reqHandle != INVALID_REQ_HANDLE, break, "Failed to create req %{public}s", APPSPAWN_SERVER_NAME); + const char *permissions = "{\"name\":\"Permissions\",\"ohos.encaps.count\":6,\"permissions\":" + "[{\"ohos.permission.bool\":true},{\"ohos.permission.int\":3225},{\"ohos.permission.string\":\"nihaoma\"}," + "{\"ohos.permission.strarray\":[\"abc\",\"def\"]},{\"ohos.permission.intarray\":[1,2,3,4,5]}," + "{\"ohos.permission.boolarray\":[true,false,true]}]}"; + ret = AppSpawnReqMsgAddExtInfo(reqHandle, MSG_EXT_NAME_JIT_PERMISSIONS, + reinterpret_cast(const_cast(permissions)), strlen(permissions) + 1); + APPSPAWN_CHECK(ret == 0, break, "Failed to add permissions"); + const char *maxChildProcess = "512"; + ret = AppSpawnReqMsgAddExtInfo(reqHandle, MSG_EXT_NAME_MAX_CHILD_PROCCESS_MAX, + reinterpret_cast(const_cast(maxChildProcess)), strlen(maxChildProcess) + 1); + APPSPAWN_CHECK(ret == 0, break, "Failed to add maxChildProcess"); + property = g_testHelper.GetAppProperty(clientHandle, reqHandle); + APPSPAWN_CHECK_ONLY_EXPER(property != nullptr, break); - cJSON *encapsJson = cJSON_Parse(encapsJsonStr); - uint32_t permissionCount = 0; - int ret = AddPermissionToEncaps(encapsJson, NULL, &permissionCount); - EXPECT_EQ(ret, APPSPAWN_ARG_INVALID); + ret = SpawnSetEncapsPermissions(NULL, property); + EXPECT_EQ(ret, APPSPAWN_ARG_INVALID); - cJSON_Delete(encapsJson); + ret = SpawnSetEncapsPermissions(mgr, NULL); + EXPECT_EQ(ret, APPSPAWN_ARG_INVALID); + + ret = SpawnSetEncapsPermissions(mgr, property); + } while (0); + + EXPECT_EQ(ret, 0); + DeleteAppSpawningCtx(property); + AppSpawnClientDestroy(clientHandle); + DeleteAppSpawnMgr(mgr); } HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_002, TestSize.Level0) { - const char encapsJsonStr[] = "{\"name\":\"Permissions\",\"ohos.encaps.count\":4,\"permissions\":" + AppSpawnClientHandle clientHandle = nullptr; + AppSpawnReqMsgHandle reqHandle = 0; + AppSpawningCtx *property = nullptr; + AppSpawnMgr *mgr = nullptr; + int ret = -1; + do { + mgr = CreateAppSpawnMgr(MODE_FOR_APP_SPAWN); + EXPECT_EQ(mgr != nullptr, 1); + // create msg + ret = AppSpawnClientInit(APPSPAWN_SERVER_NAME, &clientHandle); + APPSPAWN_CHECK(ret == 0, break, "Failed to create reqMgr %{public}s", APPSPAWN_SERVER_NAME); + reqHandle = g_testHelper.CreateMsg(clientHandle, MSG_APP_SPAWN, 0); + APPSPAWN_CHECK(reqHandle != INVALID_REQ_HANDLE, break, + "Failed to create req %{public}s", APPSPAWN_SERVER_NAME); + property = g_testHelper.GetAppProperty(clientHandle, reqHandle); + APPSPAWN_CHECK_ONLY_EXPER(property != nullptr, break); + ret = SpawnSetEncapsPermissions(mgr, property); + } while (0); + + EXPECT_EQ(ret, 0); + DeleteAppSpawningCtx(property); + AppSpawnClientDestroy(clientHandle); + DeleteAppSpawnMgr(mgr); +} + +HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_003, TestSize.Level0) +{ + AppSpawnClientHandle clientHandle = nullptr; + AppSpawnReqMsgHandle reqHandle = 0; + AppSpawningCtx *property = nullptr; + UserEncaps encapsInfo = {0}; + int ret = -1; + do { + // create msg + ret = AppSpawnClientInit(APPSPAWN_SERVER_NAME, &clientHandle); + APPSPAWN_CHECK(ret == 0, break, "Failed to create reqMgr %{public}s", APPSPAWN_SERVER_NAME); + reqHandle = g_testHelper.CreateMsg(clientHandle, MSG_APP_SPAWN, 0); + APPSPAWN_CHECK(reqHandle != INVALID_REQ_HANDLE, break, + "Failed to create req %{public}s", APPSPAWN_SERVER_NAME); + const char *permissions = "{\"name\":\"Permissions\",\"ohos.encaps.count\":0,\"permissions\":" "[{\"ohos.permission.bool\":true},{\"ohos.permission.int\":3225},{\"ohos.permission.string\":\"test\"}," "{\"ohos.permission.array\":[1,2,3,4,5]}]}"; + ret = AppSpawnReqMsgAddExtInfo(reqHandle, MSG_EXT_NAME_JIT_PERMISSIONS, + reinterpret_cast(const_cast(permissions)), strlen(permissions) + 1); + APPSPAWN_CHECK(ret == 0, break, "Failed to add permissions"); + const char *maxChildProcess = "512"; + ret = AppSpawnReqMsgAddExtInfo(reqHandle, MSG_EXT_NAME_MAX_CHILD_PROCCESS_MAX, + reinterpret_cast(const_cast(maxChildProcess)), strlen(maxChildProcess) + 1); + APPSPAWN_CHECK(ret == 0, break, "Failed to add maxChildProcess"); + property = g_testHelper.GetAppProperty(clientHandle, reqHandle); + APPSPAWN_CHECK_ONLY_EXPER(property != nullptr, break); + ret = SpawnSetPermissions(property, &encapsInfo); + } while (0); - cJSON *encapsJson = cJSON_Parse(encapsJsonStr); - uint32_t permissionCount = 0; - int ret = AddPermissionToEncaps(encapsJson, NULL, &permissionCount); - EXPECT_EQ(ret, APPSPAWN_ERROR_UTILS_ADD_JSON_FAIL); + EXPECT_EQ(ret, APPSPAWN_ARG_INVALID); + DeleteAppSpawningCtx(property); + AppSpawnClientDestroy(clientHandle); + FreeEncapsInfo(&encapsInfo); +} - cJSON_Delete(encapsJson); +HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_004, TestSize.Level0) +{ + AppSpawnClientHandle clientHandle = nullptr; + AppSpawnReqMsgHandle reqHandle = 0; + AppSpawningCtx *property = nullptr; + UserEncaps encapsInfo = {0}; + int ret = -1; + do { + // create msg + ret = AppSpawnClientInit(APPSPAWN_SERVER_NAME, &clientHandle); + APPSPAWN_CHECK(ret == 0, break, "Failed to create reqMgr %{public}s", APPSPAWN_SERVER_NAME); + reqHandle = g_testHelper.CreateMsg(clientHandle, MSG_APP_SPAWN, 0); + APPSPAWN_CHECK(reqHandle != INVALID_REQ_HANDLE, break, + "Failed to create req %{public}s", APPSPAWN_SERVER_NAME); + const char *permissions = "{\"name\":\"Permissions\",\"ohos.encaps.count\":2,\"permissions\":" + "[{\"ohos.permission.bool\":true},{\"ohos.permission.int\":3225}]}"; + ret = AppSpawnReqMsgAddExtInfo(reqHandle, MSG_EXT_NAME_JIT_PERMISSIONS, + reinterpret_cast(const_cast(permissions)), strlen(permissions) + 1); + APPSPAWN_CHECK(ret == 0, break, "Failed to add permissions"); + property = g_testHelper.GetAppProperty(clientHandle, reqHandle); + APPSPAWN_CHECK_ONLY_EXPER(property != nullptr, break); + ret = SpawnSetPermissions(property, &encapsInfo); + } while (0); + + EXPECT_EQ(ret, 0); + EXPECT_EQ(encapsInfo.encapsCount, 2); + DeleteAppSpawningCtx(property); + AppSpawnClientDestroy(clientHandle); + FreeEncapsInfo(&encapsInfo); } -HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_003, TestSize.Level0) +HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_005, TestSize.Level0) +{ + UserEncaps encapsInfo = {0}; + int ret = AddMembersToEncapsInfo(NULL, &encapsInfo); + EXPECT_EQ(ret, APPSPAWN_ARG_INVALID); +} + +HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_006, TestSize.Level0) { const char encapsJsonStr[] = "{\"name\":\"Permissions\",\"ohos.encaps.count\":5,\"permissions\":" "[{\"ohos.permission.bool\":true},{\"ohos.permission.int\":3225},{\"ohos.permission.string\":\"test\"}," "{\"ohos.permission.array\":[1,2,3,4,5]}]}"; - cJSON *encapsOut = cJSON_CreateObject(); - EXPECT_NE(encapsOut, nullptr); cJSON *encapsJson = cJSON_Parse(encapsJsonStr); - uint32_t permissionCount = 0; - + EXPECT_NE(encapsJson, nullptr); cJSON *permissions = cJSON_GetObjectItemCaseSensitive(encapsJson, "permissions"); EXPECT_NE(permissions, nullptr); cJSON *emptyItem = cJSON_CreateObject(); - cJSON_AddItemToArray(permissions, emptyItem); - - int ret = AddPermissionToEncaps(encapsJson, encapsOut, &permissionCount); + EXPECT_TRUE(cJSON_AddItemToArray(permissions, emptyItem)); + UserEncaps encapsInfo = {0}; + int ret = AddMembersToEncapsInfo(encapsJson, &encapsInfo); EXPECT_EQ(ret, APPSPAWN_ERROR_UTILS_DECODE_JSON_FAIL); cJSON_Delete(encapsJson); - cJSON_Delete(encapsOut); + FreeEncapsInfo(&encapsInfo); } -HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_004, TestSize.Level0) +HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_007, TestSize.Level0) { const char encapsJsonStr[] = "{\"name\":\"Permissions\",\"ohos.encaps.count\":4,\"permissions\":" "[{\"ohos.permission.bool\":true},{\"ohos.permission.int\":3225},{\"ohos.permission.string\":\"test\"}," - "{\"ohos.permission.array\":[1,2,3,4,5]}]}"; + "{\"ohos.permission.array\":[1,\"abc\",3,4,5]}]}"; - cJSON *encapsOut = cJSON_CreateObject(); - EXPECT_NE(encapsOut, nullptr); cJSON *encapsJson = cJSON_Parse(encapsJsonStr); - uint32_t permissionCount = 0; + EXPECT_NE(encapsJson, nullptr); + UserEncaps encapsInfo = {0}; + int ret = AddMembersToEncapsInfo(encapsJson, &encapsInfo); + EXPECT_EQ(ret, APPSPAWN_ERROR_UTILS_ADD_JSON_FAIL); - cJSON *permissions = cJSON_GetObjectItemCaseSensitive(encapsJson, "permissions"); - EXPECT_NE(permissions, nullptr); - cJSON *permission = cJSON_GetArrayItem(permissions, 0); - EXPECT_NE(permission, nullptr); - permission->child = nullptr; - int ret = AddPermissionToEncaps(encapsJson, encapsOut, &permissionCount); - EXPECT_EQ(ret, APPSPAWN_ERROR_UTILS_DECODE_JSON_FAIL); + cJSON_Delete(encapsJson); + FreeEncapsInfo(&encapsInfo); +} + +HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_008, TestSize.Level0) +{ + const char permissionItemStr[] = "{\"ohos.permission.bool\":true}"; + + cJSON *permissionItem = cJSON_Parse(permissionItemStr); + EXPECT_NE(permissionItem, nullptr); + UserEncap encap; + (void)memset_s(&encap, sizeof(encap), 0, sizeof(encap)); + // permissionItem->string is NULL + int ret = AddPermissionItemToEncapsInfo(&encap, permissionItem); + EXPECT_EQ(ret, APPSPAWN_SYSTEM_ERROR); + + cJSON_Delete(permissionItem); +} + +HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_009, TestSize.Level0) +{ + // len = 512 + "\0" + const char permissionItemStr[] = "{\"ohos.permission.string\":\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"}"; + + cJSON *permissionItem = cJSON_Parse(permissionItemStr); + EXPECT_NE(permissionItem, nullptr); + cJSON *permissionChild = permissionItem->child; + EXPECT_NE(permissionChild, nullptr); + UserEncap encap; + (void)memset_s(&encap, sizeof(encap), 0, sizeof(encap)); + int ret = AddPermissionItemToEncapsInfo(&encap, permissionChild); + EXPECT_EQ(ret, APPSPAWN_ARG_INVALID); + + cJSON_Delete(permissionItem); +} + +HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_010, TestSize.Level0) +{ + const char permissionItemStr[] = "{\"ohos.permission.strarray\":[\"abc\",\"def\",1]}"; + + cJSON *permissionItem = cJSON_Parse(permissionItemStr); + EXPECT_NE(permissionItem, nullptr); + cJSON *permissionChild = permissionItem->child; + EXPECT_NE(permissionChild, nullptr); + UserEncap encap; + (void)memset_s(&encap, sizeof(encap), 0, sizeof(encap)); + int ret = AddPermissionItemToEncapsInfo(&encap, permissionChild); + EXPECT_EQ(ret, APPSPAWN_ARG_INVALID); + + cJSON_Delete(permissionItem); +} + +HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_011, TestSize.Level0) +{ + const char permissionItemStr[] = "{\"ohos.permission.boolarray\":[true,false,\"abc\"]}"; + + cJSON *permissionItem = cJSON_Parse(permissionItemStr); + EXPECT_NE(permissionItem, nullptr); + cJSON *permissionChild = permissionItem->child; + EXPECT_NE(permissionChild, nullptr); + UserEncap encap; + (void)memset_s(&encap, sizeof(encap), 0, sizeof(encap)); + int ret = AddPermissionItemToEncapsInfo(&encap, permissionChild); + EXPECT_EQ(ret, APPSPAWN_ARG_INVALID); + + cJSON_Delete(permissionItem); +} + +HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_012, TestSize.Level0) +{ + const char permissionItemStr[] = "{\"ohos.permission.intarray\":[1,2,3,4,false]}"; + + cJSON *permissionItem = cJSON_Parse(permissionItemStr); + EXPECT_NE(permissionItem, nullptr); + cJSON *permissionChild = permissionItem->child; + EXPECT_NE(permissionChild, nullptr); + UserEncap encap; + (void)memset_s(&encap, sizeof(encap), 0, sizeof(encap)); + int ret = AddPermissionItemToEncapsInfo(&encap, permissionChild); + EXPECT_EQ(ret, APPSPAWN_ARG_INVALID); + + cJSON_Delete(permissionItem); +} + +HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_013, TestSize.Level0) +{ + // array len = 510 + "\0" * 3 + const char permissionItemStr[] = "{\"ohos.permission.strarray\":[\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "\",\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAA\",\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"]}"; + + cJSON *permissionItem = cJSON_Parse(permissionItemStr); + EXPECT_NE(permissionItem, nullptr); + cJSON *permissionChild = permissionItem->child; + EXPECT_NE(permissionChild, nullptr); + UserEncap encap; + (void)memset_s(&encap, sizeof(encap), 0, sizeof(encap)); + int ret = AddPermissionItemToEncapsInfo(&encap, permissionChild); + EXPECT_EQ(ret, APPSPAWN_ARG_INVALID); + + cJSON_Delete(permissionItem); +} + +HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_014, TestSize.Level0) +{ + // array len = 509 + "\0" * 3 + const char permissionItemStr[] = "{\"ohos.permission.strarray\":[\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "\",\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAA\",\"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\"]}"; + + cJSON *permissionItem = cJSON_Parse(permissionItemStr); + EXPECT_NE(permissionItem, nullptr); + cJSON *permissionChild = permissionItem->child; + EXPECT_NE(permissionChild, nullptr); + UserEncap encap; + (void)memset_s(&encap, sizeof(encap), 0, sizeof(encap)); + int ret = AddPermissionItemToEncapsInfo(&encap, permissionChild); + EXPECT_EQ(ret, 0); + EXPECT_EQ(encap.valueLen, 512); + EXPECT_EQ(encap.type, ENCAPS_CHAR_ARRAY); + + cJSON_Delete(permissionItem); +} + +HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_015, TestSize.Level0) +{ + // key len = 64 + "\0" + const char permissionItemStr[] = "{\"ohos.permission.strarrayabcdefghijklmnopqrstuvwxyzaaaaaaaaaaaaaa\":\"abc\"}"; + + cJSON *permissionItem = cJSON_Parse(permissionItemStr); + EXPECT_NE(permissionItem, nullptr); + cJSON *permissionChild = permissionItem->child; + EXPECT_NE(permissionChild, nullptr); + UserEncap encap; + (void)memset_s(&encap, sizeof(encap), 0, sizeof(encap)); + int ret = AddPermissionItemToEncapsInfo(&encap, permissionChild); + EXPECT_EQ(ret, APPSPAWN_SYSTEM_ERROR); + + cJSON_Delete(permissionItem); +} + +HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_016, TestSize.Level0) +{ + // key len = 63 + "\0" + const char permissionItemStr[] = "{\"ohos.permission.strarrayabcdefghijklmnopqrstuvwxyzaaaaaaaaaaaaa\":\"abc\"}"; + + cJSON *permissionItem = cJSON_Parse(permissionItemStr); + EXPECT_NE(permissionItem, nullptr); + cJSON *permissionChild = permissionItem->child; + EXPECT_NE(permissionChild, nullptr); + UserEncap encap; + (void)memset_s(&encap, sizeof(encap), 0, sizeof(encap)); + int ret = AddPermissionItemToEncapsInfo(&encap, permissionChild); + EXPECT_EQ(ret, 0); + + cJSON_Delete(permissionItem); +} + +HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_017, TestSize.Level0) +{ + const char permissionItemStr[] = "{\"ohos.permission.int\":128}"; + + cJSON *permissionItem = cJSON_Parse(permissionItemStr); + EXPECT_NE(permissionItem, nullptr); + cJSON *permissionChild = permissionItem->child; + EXPECT_NE(permissionChild, nullptr); + UserEncap encap; + (void)memset_s(&encap, sizeof(encap), 0, sizeof(encap)); + int ret = AddPermissionItemToEncapsInfo(&encap, permissionChild); + EXPECT_EQ(ret, 0); + EXPECT_EQ(encap.type, ENCAPS_INT); + EXPECT_EQ(encap.value.intValue, 128); + + cJSON_Delete(permissionItem); +} + +HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_018, TestSize.Level0) +{ + const char permissionItemStr[] = "{\"ohos.permission.bool\":true}"; + + cJSON *permissionItem = cJSON_Parse(permissionItemStr); + EXPECT_NE(permissionItem, nullptr); + cJSON *permissionChild = permissionItem->child; + EXPECT_NE(permissionChild, nullptr); + UserEncap encap; + (void)memset_s(&encap, sizeof(encap), 0, sizeof(encap)); + int ret = AddPermissionItemToEncapsInfo(&encap, permissionChild); + EXPECT_EQ(ret, 0); + EXPECT_EQ(encap.type, ENCAPS_BOOL); + EXPECT_EQ(encap.value.intValue, 1); + + cJSON_Delete(permissionItem); +} + +HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_019, TestSize.Level0) +{ + const char encapsJsonStr[] = "{\"name\":\"Permissions\",\"ohos.encaps.count\":6,\"permissions\":100}"; + + cJSON *encapsJson = cJSON_Parse(encapsJsonStr); + EXPECT_NE(encapsJson, nullptr); + UserEncaps encapsInfo = {0}; + int ret = AddMembersToEncapsInfo(encapsJson, &encapsInfo); + EXPECT_EQ(ret, APPSPAWN_ARG_INVALID); cJSON_Delete(encapsJson); - cJSON_Delete(encapsOut); + FreeEncapsInfo(&encapsInfo); } -HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_005, TestSize.Level0) +HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_020, TestSize.Level0) { - const char encapsJsonStr[] = "{\"name\":\"Permissions\",\"ohos.encaps.count\":4,\"permissions\":" - "[{\"ohos.permission.bool\":true},{\"ohos.permission.int\":3225},{\"ohos.permission.string\":\"test\"}," - "{\"ohos.permission.array\":[1,2,3,4,5]}]}"; + const char encapsJsonStr[] = "{\"name\":\"Permissions\",\"ohos.encaps.count\":\"6\",\"permissions\":" + "[{\"ohos.permission.bool\":true},{\"ohos.permission.int\":3225},{\"ohos.permission.string\":\"nihaoma\"}," + "{\"ohos.permission.strarray\":[\"abc\",\"def\"]},{\"ohos.permission.intarray\":[1,2,3,4,5]}," + "{\"ohos.permission.boolarray\":[true,false,true]}]}"; - cJSON *encapsOut = cJSON_CreateObject(); - EXPECT_NE(encapsOut, nullptr); cJSON *encapsJson = cJSON_Parse(encapsJsonStr); - uint32_t permissionCount = 0; + EXPECT_NE(encapsJson, nullptr); + UserEncaps encapsInfo = {0}; + int ret = AddMembersToEncapsInfo(encapsJson, &encapsInfo); + EXPECT_EQ(ret, APPSPAWN_ARG_INVALID); - int ret = AddPermissionToEncaps(encapsJson, encapsOut, &permissionCount); - EXPECT_EQ(ret, 0); - EXPECT_EQ(permissionCount, 4); + cJSON_Delete(encapsJson); + FreeEncapsInfo(&encapsInfo); +} + +HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_021, TestSize.Level0) +{ + const char permissionItemStr[] = "{\"ohos.permission.intarray\":[]}"; + + cJSON *permissionItem = cJSON_Parse(permissionItemStr); + EXPECT_NE(permissionItem, nullptr); + cJSON *permissionChild = permissionItem->child; + EXPECT_NE(permissionChild, nullptr); + UserEncap encap; + (void)memset_s(&encap, sizeof(encap), 0, sizeof(encap)); + int ret = AddPermissionItemToEncapsInfo(&encap, permissionChild); + EXPECT_EQ(ret, APPSPAWN_ARG_INVALID); + + cJSON_Delete(permissionItem); +} + +HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_022, TestSize.Level0) +{ + const char permissionItemStr[] = "{\"ohos.permission.strarray\":[\"abc\",\"\",\"def\"]}"; + + cJSON *permissionItem = cJSON_Parse(permissionItemStr); + EXPECT_NE(permissionItem, nullptr); + cJSON *permissionChild = permissionItem->child; + EXPECT_NE(permissionChild, nullptr); + UserEncap encap; + (void)memset_s(&encap, sizeof(encap), 0, sizeof(encap)); + int ret = AddPermissionItemToEncapsInfo(&encap, permissionChild); + EXPECT_EQ(ret, APPSPAWN_ARG_INVALID); + + cJSON_Delete(permissionItem); +} + +HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_023, TestSize.Level0) +{ + const char permissionItemStr[] = "{\"ohos.permission.str\":\"\"}"; + + cJSON *permissionItem = cJSON_Parse(permissionItemStr); + EXPECT_NE(permissionItem, nullptr); + cJSON *permissionChild = permissionItem->child; + EXPECT_NE(permissionChild, nullptr); + UserEncap encap; + (void)memset_s(&encap, sizeof(encap), 0, sizeof(encap)); + int ret = AddPermissionItemToEncapsInfo(&encap, permissionChild); + EXPECT_EQ(ret, APPSPAWN_ARG_INVALID); + + cJSON_Delete(permissionItem); +} + +HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_024, TestSize.Level0) +{ + const char permissionItemStr[] = "[1,2,3,4,5]"; + + cJSON *permissionItem = cJSON_Parse(permissionItemStr); + EXPECT_NE(permissionItem, nullptr); + cJSON *permissionChild = permissionItem->child; + EXPECT_NE(permissionChild, nullptr); + UserEncap encap; + (void)memset_s(&encap, sizeof(encap), 0, sizeof(encap)); + int ret = AddPermissionIntArrayToValue(permissionChild, &encap, 6); + EXPECT_EQ(ret, APPSPAWN_ARG_INVALID); + + cJSON_Delete(permissionItem); +} + +HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_025, TestSize.Level0) +{ + const char permissionItemStr[] = "[true,false,true]"; + + cJSON *permissionItem = cJSON_Parse(permissionItemStr); + EXPECT_NE(permissionItem, nullptr); + cJSON *permissionChild = permissionItem->child; + EXPECT_NE(permissionChild, nullptr); + UserEncap encap; + (void)memset_s(&encap, sizeof(encap), 0, sizeof(encap)); + int ret = AddPermissionBoolArrayToValue(permissionChild, &encap, 4); + EXPECT_EQ(ret, APPSPAWN_ARG_INVALID); + + cJSON_Delete(permissionItem); +} + +HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_026, TestSize.Level0) +{ + const char permissionItemStr[] = "[\"abc\",\"def\"]"; + + cJSON *permissionItem = cJSON_Parse(permissionItemStr); + EXPECT_NE(permissionItem, nullptr); + cJSON *item = cJSON_CreateString(""); + EXPECT_NE(item, nullptr); + free(item->valuestring); + item->valuestring = nullptr; + EXPECT_EQ(cJSON_AddItemToArray(permissionItem, item), 1); + cJSON *permissionChild = permissionItem->child; + EXPECT_NE(permissionChild, nullptr); + UserEncap encap; + (void)memset_s(&encap, sizeof(encap), 0, sizeof(encap)); + int ret = AddPermissionStrArrayToValue(permissionChild, &encap); + EXPECT_EQ(ret, APPSPAWN_ARG_INVALID); + + cJSON_Delete(permissionItem); +} + +HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_027, TestSize.Level0) +{ + const char permissionItemStr[] = "{\"ohos.permission.intarray\":[{\"ohos.permission.bool\":true},2,3,4,5]}"; + + cJSON *permissionItem = cJSON_Parse(permissionItemStr); + EXPECT_NE(permissionItem, nullptr); + cJSON *permissionChild = permissionItem->child; + UserEncap encap; + (void)memset_s(&encap, sizeof(encap), 0, sizeof(encap)); + int ret = AddPermissionArrayToValue(permissionChild, &encap); + EXPECT_EQ(ret, APPSPAWN_ARG_INVALID); + + cJSON_Delete(permissionItem); +} + +HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_028, TestSize.Level0) +{ + const char permissionItemStr[] = "{\"permissions\":{\"ohos.permission.bool\":true}}"; + + cJSON *permissionItem = cJSON_Parse(permissionItemStr); + EXPECT_NE(permissionItem, nullptr); + cJSON *permissionChild = permissionItem->child; + EXPECT_NE(permissionChild, nullptr); + UserEncap encap; + (void)memset_s(&encap, sizeof(encap), 0, sizeof(encap)); + int ret = AddPermissionItemToEncapsInfo(&encap, permissionChild); + EXPECT_EQ(ret, APPSPAWN_ARG_INVALID); + + cJSON_Delete(permissionItem); +} + +HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_029, TestSize.Level0) +{ + const char encapsJsonStr[] = "{\"name\":\"Permissions\",\"ohos.encaps.count\":6,\"permissions\":[]}"; + + cJSON *encapsJson = cJSON_Parse(encapsJsonStr); + EXPECT_NE(encapsJson, nullptr); + UserEncaps encapsInfo = {0}; + int ret = AddMembersToEncapsInfo(encapsJson, &encapsInfo); + EXPECT_EQ(ret, APPSPAWN_ARG_INVALID); cJSON_Delete(encapsJson); - cJSON_Delete(encapsOut); + FreeEncapsInfo(&encapsInfo); +} + +HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_030, TestSize.Level0) +{ + AppSpawnClientHandle clientHandle = nullptr; + AppSpawnReqMsgHandle reqHandle = 0; + AppSpawningCtx *property = nullptr; + UserEncaps encapsInfo = {0}; + int ret = -1; + do { + // create msg + ret = AppSpawnClientInit(APPSPAWN_SERVER_NAME, &clientHandle); + APPSPAWN_CHECK(ret == 0, break, "Failed to create reqMgr %{public}s", APPSPAWN_SERVER_NAME); + reqHandle = g_testHelper.CreateMsg(clientHandle, MSG_SPAWN_NATIVE_PROCESS, 0); + APPSPAWN_CHECK(reqHandle != INVALID_REQ_HANDLE, break, + "Failed to create req %{public}s", APPSPAWN_SERVER_NAME); + const char *permissions = "{\"name\":\"Permissions\",\"ohos.encaps.count\":4,\"permissions\":" + "[{\"ohos.permission.bool\":true},{\"ohos.permission.int\":3225},{\"ohos.permission.string\":\"test\"}," + "{\"ohos.permission.array\":[1,2,3,4,5]}]}"; + ret = AppSpawnReqMsgAddExtInfo(reqHandle, MSG_EXT_NAME_JIT_PERMISSIONS, + reinterpret_cast(const_cast(permissions)), strlen(permissions) + 1); + APPSPAWN_CHECK(ret == 0, break, "Failed to add permissions"); + const char *maxChildProcess = "512"; + ret = AppSpawnReqMsgAddExtInfo(reqHandle, MSG_EXT_NAME_MAX_CHILD_PROCCESS_MAX, + reinterpret_cast(const_cast(maxChildProcess)), strlen(maxChildProcess) + 1); + APPSPAWN_CHECK(ret == 0, break, "Failed to add maxChildProcess"); + property = g_testHelper.GetAppProperty(clientHandle, reqHandle); + APPSPAWN_CHECK_ONLY_EXPER(property != nullptr, break); + ret = SpawnSetPermissions(property, &encapsInfo); + } while (0); + + EXPECT_EQ(ret, 0); + EXPECT_EQ(encapsInfo.encapsCount, 4); + DeleteAppSpawningCtx(property); + AppSpawnClientDestroy(clientHandle); + FreeEncapsInfo(&encapsInfo); +} + +HWTEST_F(AppSpawnCommonTest, App_Spawn_Encaps_031, TestSize.Level0) +{ + AppSpawnClientHandle clientHandle = nullptr; + AppSpawnReqMsgHandle reqHandle = 0; + AppSpawningCtx *property = nullptr; + UserEncaps encapsInfo = {0}; + int ret = -1; + do { + // create msg + ret = AppSpawnClientInit(APPSPAWN_SERVER_NAME, &clientHandle); + APPSPAWN_CHECK(ret == 0, break, "Failed to create reqMgr %{public}s", APPSPAWN_SERVER_NAME); + reqHandle = g_testHelper.CreateMsg(clientHandle, MSG_APP_SPAWN, 0); + APPSPAWN_CHECK(reqHandle != INVALID_REQ_HANDLE, break, + "Failed to create req %{public}s", APPSPAWN_SERVER_NAME); + const char *permissions = "{\"name\":\"Permissions\",\"ohos.encaps.count\":4,\"permissions\":" + "[{\"ohos.permission.bool\":true},{\"ohos.permission.int\":3225},{\"ohos.permission.string\":\"test\"}," + "{\"ohos.permission.array\":[1,2,3,4,5]}]}"; + ret = AppSpawnReqMsgAddExtInfo(reqHandle, MSG_EXT_NAME_JIT_PERMISSIONS, + reinterpret_cast(const_cast(permissions)), strlen(permissions) + 1); + APPSPAWN_CHECK(ret == 0, break, "Failed to add permissions"); + const char *maxChildProcess = "0"; + ret = AppSpawnReqMsgAddExtInfo(reqHandle, MSG_EXT_NAME_MAX_CHILD_PROCCESS_MAX, + reinterpret_cast(const_cast(maxChildProcess)), strlen(maxChildProcess) + 1); + APPSPAWN_CHECK(ret == 0, break, "Failed to add maxChildProcess"); + property = g_testHelper.GetAppProperty(clientHandle, reqHandle); + APPSPAWN_CHECK_ONLY_EXPER(property != nullptr, break); + ret = SpawnSetPermissions(property, &encapsInfo); + } while (0); + + EXPECT_EQ(ret, 0); + EXPECT_EQ(encapsInfo.encapsCount, 4); + DeleteAppSpawningCtx(property); + AppSpawnClientDestroy(clientHandle); + FreeEncapsInfo(&encapsInfo); } HWTEST_F(AppSpawnCommonTest, App_Spawn_SetFdEnv, TestSize.Level0) @@ -838,4 +1392,30 @@ HWTEST_F(AppSpawnCommonTest, App_Spawn_FilterAppSpawnTrace, TestSize.Level0) } #endif +HWTEST_F(AppSpawnCommonTest, App_Spawn_SetCapabilities, TestSize.Level0) +{ + AppSpawnClientHandle clientHandle = nullptr; + AppSpawnReqMsgHandle reqHandle = 0; + AppSpawningCtx *property = nullptr; + AppSpawnMgr *mgr = nullptr; + int ret = -1; + do { + mgr = CreateAppSpawnMgr(MODE_FOR_NWEB_SPAWN); + EXPECT_EQ(mgr != nullptr, 1); + // create msg + ret = AppSpawnClientInit(NWEBSPAWN_SERVER_NAME, &clientHandle); + APPSPAWN_CHECK(ret == 0, break, "Failed to create reqMgr %{public}s", NWEBSPAWN_SERVER_NAME); + reqHandle = g_testHelper.CreateMsg(clientHandle, MSG_APP_SPAWN, 0); + APPSPAWN_CHECK(reqHandle != INVALID_REQ_HANDLE, break, + "Failed to create req %{public}s", NWEBSPAWN_SERVER_NAME); + property = g_testHelper.GetAppProperty(clientHandle, reqHandle); + APPSPAWN_CHECK_ONLY_EXPER(property != nullptr, break); + ret = SetCapabilities(mgr, property); + } while (0); + DeleteAppSpawningCtx(property); + AppSpawnClientDestroy(clientHandle); + DeleteAppSpawnMgr(mgr); + ASSERT_EQ(ret, 0); +} + } // namespace OHOS diff --git a/test/unittest/app_spawn_standard_test/app_spawn_module_interface_test.cpp b/test/unittest/app_spawn_standard_test/app_spawn_module_interface_test.cpp index 640399f30d33ff6a986adece5970cb27f547d7c0..a8821f6086dfd925b086d38c58ba107917851d24 100644 --- a/test/unittest/app_spawn_standard_test/app_spawn_module_interface_test.cpp +++ b/test/unittest/app_spawn_standard_test/app_spawn_module_interface_test.cpp @@ -25,7 +25,6 @@ #include "appspawn_manager.h" #include "appspawn_modulemgr.h" #include "appspawn_permission.h" -#include "appspawn_sandbox.h" #include "appspawn_utils.h" #include "cJSON.h" #include "json_utils.h" diff --git a/test/unittest/app_spawn_standard_test/app_spawn_sandbox_test.cpp b/test/unittest/app_spawn_standard_test/app_spawn_sandbox_test.cpp index a8d6bb9f6dc5228689758fc55cd3e255976804e7..d0e46d925edb1482273e2b9ccf83a7a2bca2316b 100644 --- a/test/unittest/app_spawn_standard_test/app_spawn_sandbox_test.cpp +++ b/test/unittest/app_spawn_standard_test/app_spawn_sandbox_test.cpp @@ -23,7 +23,9 @@ #include "appspawn_service.h" #include "json_utils.h" #include "parameter.h" -#include "sandbox_utils.h" +#include "sandbox_def.h" +#include "sandbox_core.h" +#include "sandbox_common.h" #include "securec.h" #include "app_spawn_stub.h" @@ -34,7 +36,6 @@ using namespace testing; using namespace testing::ext; using namespace OHOS::AppSpawn; -using nlohmann::json; namespace OHOS { AppSpawnTestHelper g_testHelper; @@ -51,9 +52,33 @@ void AppSpawnSandboxTest::SetUpTestCase() {} void AppSpawnSandboxTest::TearDownTestCase() {} -void AppSpawnSandboxTest::SetUp() {} +void AppSpawnSandboxTest::SetUp() { + const TestInfo *info = UnitTest::GetInstance()->current_test_info(); + GTEST_LOG_(INFO) << info->test_suite_name() << "." << info->name() << " start"; + APPSPAWN_LOGI("%{public}s.%{public}s start", info->test_suite_name(), info->name()); -void AppSpawnSandboxTest::TearDown() {} + std::vector &appVec = + AppSpawn::SandboxCommon::GetCJsonConfig(SandboxCommonDef::SANDBOX_APP_JSON_CONFIG); + appVec.erase(appVec.begin(), appVec.end()); + + std::vector &isolatedVec = + AppSpawn::SandboxCommon::GetCJsonConfig(SandboxCommonDef::SANDBOX_ISOLATED_JSON_CONFIG); + isolatedVec.erase(isolatedVec.begin(), isolatedVec.end()); +} + +void AppSpawnSandboxTest::TearDown() { + std::vector &appVec = + AppSpawn::SandboxCommon::GetCJsonConfig(SandboxCommonDef::SANDBOX_APP_JSON_CONFIG); + appVec.erase(appVec.begin(), appVec.end()); + + std::vector &isolatedVec = + AppSpawn::SandboxCommon::GetCJsonConfig(SandboxCommonDef::SANDBOX_ISOLATED_JSON_CONFIG); + isolatedVec.erase(isolatedVec.begin(), isolatedVec.end()); + + const TestInfo *info = UnitTest::GetInstance()->current_test_info(); + GTEST_LOG_(INFO) << info->test_suite_name() << "." << info->name() << " end"; + APPSPAWN_LOGI("%{public}s.%{public}s end", info->test_suite_name(), info->name()); +} static AppSpawningCtx *GetTestAppProperty() { @@ -85,14 +110,14 @@ static AppSpawningCtx *GetTestAppPropertyWithExtInfo(const char *name, const cha */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_08, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_08 start"; g_testHelper.SetTestUid(1000); // 1000 test g_testHelper.SetTestGid(1000); // 1000 test g_testHelper.SetProcessName("ohos.samples.ecg"); AppSpawningCtx *appProperty = GetTestAppProperty(); - OHOS::AppSpawn::SandboxUtils::SetAppSandboxProperty(appProperty); + int32_t ret = AppSpawn::SandboxCore::SetAppSandboxProperty(appProperty, CLONE_NEWPID); + EXPECT_EQ(ret, 0); + DeleteAppSpawningCtx(appProperty); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_08 end"; } /** @@ -104,70 +129,62 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_08, TestSize.Level0) */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_09, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_09 start"; g_testHelper.SetProcessName("com.ohos.dlpmanager"); g_testHelper.SetTestApl("normal"); AppSpawningCtx *appProperty = GetTestAppProperty(); - OHOS::AppSpawn::SandboxUtils::SetAppSandboxProperty(appProperty); + int32_t ret = AppSpawn::SandboxCore::SetAppSandboxProperty(appProperty, CLONE_NEWPID); + EXPECT_EQ(ret, 0); + DeleteAppSpawningCtx(appProperty); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_09 end"; } HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_09_1, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_09_1 start"; g_testHelper.SetTestUid(1000); // 1000 test g_testHelper.SetTestGid(1000); // 1000 test g_testHelper.SetProcessName("com.ohos.dlpmanager"); g_testHelper.SetTestApl("normal"); - AppSpawningCtx *appProperty = GetTestAppProperty(); - int ret = OHOS::AppSpawn::SandboxUtils::SetAppSandboxProperty(nullptr); + int32_t ret = AppSpawn::SandboxCore::SetAppSandboxProperty(nullptr, CLONE_NEWPID); EXPECT_NE(ret, 0); - DeleteAppSpawningCtx(appProperty); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_09_1 end"; } HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_09_2, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_09_1 start"; g_testHelper.SetTestUid(1000); // 1000 test g_testHelper.SetTestGid(1000); // 1000 test g_testHelper.SetProcessName(""); g_testHelper.SetTestApl("normal"); AppSpawningCtx *appProperty = GetTestAppProperty(); - - int ret = OHOS::AppSpawn::SandboxUtils::SetAppSandboxProperty(appProperty); + int32_t ret = AppSpawn::SandboxCore::SetAppSandboxProperty(appProperty, CLONE_NEWPID); EXPECT_NE(ret, 0); + DeleteAppSpawningCtx(appProperty); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_09_1 end"; } HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_09_3, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_09_1 start"; g_testHelper.SetTestUid(1000); // 1000 test g_testHelper.SetTestGid(1000); // 1000 test g_testHelper.SetProcessName("com.\\ohos.dlpmanager"); g_testHelper.SetTestApl("normal"); AppSpawningCtx *appProperty = GetTestAppProperty(); - int ret = OHOS::AppSpawn::SandboxUtils::SetAppSandboxProperty(appProperty); + int32_t ret = AppSpawn::SandboxCore::SetAppSandboxProperty(appProperty, CLONE_NEWPID); EXPECT_NE(ret, 0); + DeleteAppSpawningCtx(appProperty); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_09_1 end"; } HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_09_4, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_09_1 start"; g_testHelper.SetTestUid(1000); // 1000 test g_testHelper.SetTestGid(1000); // 1000 test g_testHelper.SetProcessName("com./ohos.dlpmanager"); g_testHelper.SetTestApl("normal"); AppSpawningCtx *appProperty = GetTestAppProperty(); - int ret = OHOS::AppSpawn::SandboxUtils::SetAppSandboxProperty(appProperty); + int32_t ret = AppSpawn::SandboxCore::SetAppSandboxProperty(appProperty, CLONE_NEWPID); EXPECT_NE(ret, 0); + DeleteAppSpawningCtx(appProperty); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_09_1 end"; } /** @@ -179,7 +196,6 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_09_4, TestSize.Level0) */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_10, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_10 start"; std::string mJsconfig = "{ \ \"common\":[{ \ \"top-sandbox-switch\": \"ON\", \ @@ -197,19 +213,20 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_10, TestSize.Level0) }], \ \"individual\": [] \ }"; - nlohmann::json j_config = nlohmann::json::parse(mJsconfig.c_str()); + cJSON *j_config = cJSON_Parse(mJsconfig.c_str()); + ASSERT_NE(j_config, nullptr); + AppSpawn::SandboxCommon::StoreCJsonConfig(j_config, SandboxCommonDef::SANDBOX_APP_JSON_CONFIG); - OHOS::AppSpawn::SandboxUtils::StoreJsonConfig(j_config, SANBOX_APP_JSON_CONFIG); - GTEST_LOG_(INFO) << "SetAppSandboxProperty start" << std::endl; g_testHelper.SetTestUid(1000); // 1000 test g_testHelper.SetTestGid(1000); // 1000 test g_testHelper.SetProcessName("test.appspawn"); g_testHelper.SetTestApl("normal"); AppSpawningCtx *appProperty = GetTestAppProperty(); - GTEST_LOG_(INFO) << "SetAppSandboxProperty section 2" << std::endl; - OHOS::AppSpawn::SandboxUtils::SetAppSandboxProperty(appProperty); + int32_t ret = AppSpawn::SandboxCore::SetAppSandboxProperty(appProperty, CLONE_NEWPID); + EXPECT_EQ(ret, 0); + + cJSON_Delete(j_config); DeleteAppSpawningCtx(appProperty); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_10 end"; } /** @@ -221,7 +238,6 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_10, TestSize.Level0) */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_13, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_13 start"; std::string mJsconfig = "{ \ \"common\":[{ \ \"app-base\":[{ \ @@ -238,19 +254,20 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_13, TestSize.Level0) }], \ \"individual\": [] \ }"; - nlohmann::json j_config = nlohmann::json::parse(mJsconfig.c_str()); - - OHOS::AppSpawn::SandboxUtils::StoreJsonConfig(j_config, SANBOX_APP_JSON_CONFIG); + cJSON *j_config = cJSON_Parse(mJsconfig.c_str()); + ASSERT_NE(j_config, nullptr); + AppSpawn::SandboxCommon::StoreCJsonConfig(j_config, SandboxCommonDef::SANDBOX_APP_JSON_CONFIG); - GTEST_LOG_(INFO) << "SetAppSandboxProperty start" << std::endl; g_testHelper.SetTestUid(1000); // 1000 test g_testHelper.SetTestGid(1000); // 1000 test g_testHelper.SetProcessName("test.appspawn"); g_testHelper.SetTestApl("normal"); AppSpawningCtx *appProperty = GetTestAppProperty(); - OHOS::AppSpawn::SandboxUtils::SetAppSandboxProperty(appProperty); + int32_t ret = AppSpawn::SandboxCore::SetAppSandboxProperty(appProperty, CLONE_NEWPID); + EXPECT_EQ(ret, 0); + + cJSON_Delete(j_config); DeleteAppSpawningCtx(appProperty); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_13 end"; } /** @@ -262,7 +279,6 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_13, TestSize.Level0) */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_14, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_14 start"; std::string mJsconfig = "{ \ \"common\":[{ \ \"app-base\":[{ \ @@ -278,22 +294,20 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_14, TestSize.Level0) }], \ \"individual\": [] \ }"; - nlohmann::json j_config = nlohmann::json::parse(mJsconfig.c_str()); - - OHOS::AppSpawn::SandboxUtils::StoreJsonConfig(j_config, SANBOX_APP_JSON_CONFIG); - - GTEST_LOG_(INFO) << "SetAppSandboxProperty start" << std::endl; + cJSON *j_config = cJSON_Parse(mJsconfig.c_str()); + ASSERT_NE(j_config, nullptr); + AppSpawn::SandboxCommon::StoreCJsonConfig(j_config, SandboxCommonDef::SANDBOX_APP_JSON_CONFIG); g_testHelper.SetTestUid(1000); // 1000 test g_testHelper.SetTestGid(1000); // 1000 test g_testHelper.SetProcessName("test.appspawn"); g_testHelper.SetTestApl("normal"); AppSpawningCtx *appProperty = GetTestAppProperty(); + int32_t ret = AppSpawn::SandboxCore::SetAppSandboxProperty(appProperty, CLONE_NEWPID); + EXPECT_EQ(ret, 0); - GTEST_LOG_(INFO) << "SetAppSandboxProperty section 2" << std::endl; - OHOS::AppSpawn::SandboxUtils::SetAppSandboxProperty(appProperty); + cJSON_Delete(j_config); DeleteAppSpawningCtx(appProperty); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_14 end"; } /** @@ -305,7 +319,6 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_14, TestSize.Level0) */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_15, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_15 start"; std::string mJsconfig = "{ \ \"common\":[{ \ \"app-base\":[{ \ @@ -322,20 +335,20 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_15, TestSize.Level0) }], \ \"individual\": [] \ }"; - nlohmann::json j_config = nlohmann::json::parse(mJsconfig.c_str()); + cJSON *j_config = cJSON_Parse(mJsconfig.c_str()); + ASSERT_NE(j_config, nullptr); + AppSpawn::SandboxCommon::StoreCJsonConfig(j_config, SandboxCommonDef::SANDBOX_APP_JSON_CONFIG); - OHOS::AppSpawn::SandboxUtils::StoreJsonConfig(j_config, SANBOX_APP_JSON_CONFIG); - - GTEST_LOG_(INFO) << "SetAppSandboxProperty start" << std::endl; g_testHelper.SetTestUid(1000); // 1000 test g_testHelper.SetTestGid(1000); // 1000 test g_testHelper.SetProcessName("test.appspawn"); g_testHelper.SetTestApl("normal"); AppSpawningCtx *appProperty = GetTestAppProperty(); - GTEST_LOG_(INFO) << "SetAppSandboxProperty section 2" << std::endl; - OHOS::AppSpawn::SandboxUtils::SetAppSandboxProperty(appProperty); + int32_t ret = AppSpawn::SandboxCore::SetAppSandboxProperty(appProperty, CLONE_NEWPID); + EXPECT_EQ(ret, 0); + + cJSON_Delete(j_config); DeleteAppSpawningCtx(appProperty); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_15 end"; } /** @@ -347,7 +360,6 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_15, TestSize.Level0) */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_16, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_16 start"; std::string mJsconfig = "{ \ \"common\":[{ \ \"app-base\":[{ \ @@ -357,30 +369,30 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_16, TestSize.Level0) }], \ \"individual\": [] \ }"; - nlohmann::json j_config = nlohmann::json::parse(mJsconfig.c_str()); + cJSON *j_config = cJSON_Parse(mJsconfig.c_str()); + ASSERT_NE(j_config, nullptr); + AppSpawn::SandboxCommon::StoreCJsonConfig(j_config, SandboxCommonDef::SANDBOX_APP_JSON_CONFIG); - OHOS::AppSpawn::SandboxUtils::StoreJsonConfig(j_config, SANBOX_APP_JSON_CONFIG); - - GTEST_LOG_(INFO) << "SetAppSandboxProperty start" << std::endl; g_testHelper.SetTestUid(1000); // 1000 test g_testHelper.SetTestGid(1000); // 1000 test g_testHelper.SetProcessName("test.appspawn"); g_testHelper.SetTestApl("normal"); AppSpawningCtx *appProperty = GetTestAppProperty(); - OHOS::AppSpawn::SandboxUtils::SetAppSandboxProperty(appProperty); + int32_t ret = AppSpawn::SandboxCore::SetAppSandboxProperty(appProperty, CLONE_NEWPID); + EXPECT_EQ(ret, 0); + + cJSON_Delete(j_config); DeleteAppSpawningCtx(appProperty); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_16 end"; } HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_17, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_09 start"; - nlohmann::json appSandboxConfig; - bool rc = JsonUtils::GetJsonObjFromJson(appSandboxConfig, ""); - EXPECT_FALSE(rc); + cJSON *appSandboxConfig = GetJsonObjFromFile(""); + EXPECT_EQ(appSandboxConfig, nullptr); + std::string path(256, 'w'); // 256 test - rc = JsonUtils::GetJsonObjFromJson(appSandboxConfig, path); - EXPECT_FALSE(rc); + appSandboxConfig = GetJsonObjFromFile(path.c_str()); + EXPECT_EQ(appSandboxConfig, nullptr); std::string mJsconfig = "{ \ \"common\":[{ \ @@ -391,45 +403,51 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_17, TestSize.Level0) }], \ \"individual\": [] \ }"; - nlohmann::json j_config = nlohmann::json::parse(mJsconfig.c_str()); - OHOS::AppSpawn::SandboxUtils::StoreJsonConfig(j_config, SANBOX_APP_JSON_CONFIG); + cJSON *j_config = cJSON_Parse(mJsconfig.c_str()); + ASSERT_NE(j_config, nullptr); + AppSpawn::SandboxCommon::StoreCJsonConfig(j_config, SandboxCommonDef::SANDBOX_APP_JSON_CONFIG); + + const char *value = GetStringFromJsonObj(j_config, "common"); + EXPECT_EQ(value, nullptr); - std::string value; - rc = JsonUtils::GetStringFromJson(j_config, "common", value); - EXPECT_FALSE(rc); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_09 end"; + cJSON_Delete(j_config); } HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_18, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_18 start"; std::string mJsconfig1 = "{ \ \"sandbox-switch\": \"ON\", \ \"sandbox-root\" : \"/mnt/sandbox//\" \ }"; - nlohmann::json j_config1 = nlohmann::json::parse(mJsconfig1.c_str()); - bool ret = OHOS::AppSpawn::SandboxUtils::GetSbxSwitchStatusByConfig(j_config1); + cJSON *j_config1 = cJSON_Parse(mJsconfig1.c_str()); + ASSERT_NE(j_config1, nullptr); + bool ret = AppSpawn::SandboxCommon::GetSwitchStatus(j_config1); EXPECT_TRUE(ret); std::string mJsconfig2 = "{ \ \"sandbox-switch\": \"OFF\", \ \"sandbox-root\" : \"/mnt/sandbox//\" \ }"; - nlohmann::json j_config2 = nlohmann::json::parse(mJsconfig2.c_str()); - ret = OHOS::AppSpawn::SandboxUtils::GetSbxSwitchStatusByConfig(j_config2); + cJSON *j_config2 = cJSON_Parse(mJsconfig2.c_str()); + ASSERT_NE(j_config2, nullptr); + ret = AppSpawn::SandboxCommon::GetSwitchStatus(j_config2); EXPECT_FALSE(ret); std::string mJsconfig3 = "{ \ \"sandbox-root\" : \"/mnt/sandbox//\" \ }"; - nlohmann::json j_config3 = nlohmann::json::parse(mJsconfig3.c_str()); - ret = OHOS::AppSpawn::SandboxUtils::GetSbxSwitchStatusByConfig(j_config3); + cJSON *j_config3 = cJSON_Parse(mJsconfig3.c_str()); + ASSERT_NE(j_config3, nullptr); + ret = AppSpawn::SandboxCommon::GetSwitchStatus(j_config3); EXPECT_TRUE(ret); + + cJSON_Delete(j_config1); + cJSON_Delete(j_config2); + cJSON_Delete(j_config3); } HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_20, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_20 start"; std::string mJsconfig = "{ \ \"common\":[{ \ \"top-sandbox-switch\": \"OFF\", \ @@ -440,16 +458,17 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_20, TestSize.Level0) }], \ \"individual\": [] \ }"; - nlohmann::json j_config = nlohmann::json::parse(mJsconfig.c_str()); - OHOS::AppSpawn::SandboxUtils::StoreJsonConfig(j_config, SANBOX_APP_JSON_CONFIG); + cJSON *j_config = cJSON_Parse(mJsconfig.c_str()); + ASSERT_NE(j_config, nullptr); + AppSpawn::SandboxCommon::StoreCJsonConfig(j_config, SandboxCommonDef::SANDBOX_APP_JSON_CONFIG); g_testHelper.SetTestUid(1000); // 1000 test g_testHelper.SetTestGid(1000); // 1000 test g_testHelper.SetProcessName("test.appspawn"); g_testHelper.SetTestApl("normal"); AppSpawningCtx *appProperty = GetTestAppProperty(); - - OHOS::AppSpawn::SandboxUtils::SetAppSandboxProperty(appProperty); + int32_t ret = AppSpawn::SandboxCore::SetAppSandboxProperty(appProperty, CLONE_NEWPID); + EXPECT_EQ(ret, 0); std::string mJsconfig1 = "{ \ \"common\":[{ \ @@ -465,29 +484,33 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_20, TestSize.Level0) }] \ }] \ }"; - nlohmann::json j_config1 = nlohmann::json::parse(mJsconfig1.c_str()); - OHOS::AppSpawn::SandboxUtils::StoreJsonConfig(j_config1, SANBOX_APP_JSON_CONFIG); - OHOS::AppSpawn::SandboxUtils::SetAppSandboxProperty(appProperty); + cJSON *j_config1 = cJSON_Parse(mJsconfig1.c_str()); + ASSERT_NE(j_config1, nullptr); + + AppSpawn::SandboxCommon::StoreCJsonConfig(j_config1, SandboxCommonDef::SANDBOX_APP_JSON_CONFIG); + ret = AppSpawn::SandboxCore::SetAppSandboxProperty(appProperty, CLONE_NEWPID); + EXPECT_EQ(ret, 0); + + cJSON_Delete(j_config); + cJSON_Delete(j_config1); DeleteAppSpawningCtx(appProperty); } HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_21, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_21 start"; - - bool ret = OHOS::AppSpawn::SandboxUtils::CheckBundleNameForPrivate(std::string("__internal__")); + bool ret = AppSpawn::SandboxCommon::HasPrivateInBundleName(std::string("__internal__")); EXPECT_FALSE(ret); } HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_22, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_22 start"; std::string mJsconfig1 = "{ \ \"common\":[], \ \"individual\": [] \ }"; - nlohmann::json j_config1 = nlohmann::json::parse(mJsconfig1.c_str()); - OHOS::AppSpawn::SandboxUtils::StoreJsonConfig(j_config1, SANBOX_APP_JSON_CONFIG); + cJSON *j_config = cJSON_Parse(mJsconfig1.c_str()); + ASSERT_NE(j_config, nullptr); + AppSpawn::SandboxCommon::StoreCJsonConfig(j_config, SandboxCommonDef::SANDBOX_APP_JSON_CONFIG); g_testHelper.SetTestUid(1000); // 1000 test g_testHelper.SetTestGid(1000); // 1000 test @@ -497,24 +520,15 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_22, TestSize.Level0) const char *strl1 = "/mnt/sandbox/100/test.bundle1"; std::string testBundle = strl1; - int ret = OHOS::AppSpawn::SandboxUtils::SetCommonAppSandboxProperty(appProperty, testBundle); - DeleteAppSpawningCtx(appProperty); + int32_t ret = AppSpawn::SandboxCore::SetCommonAppSandboxProperty(appProperty, testBundle); EXPECT_EQ(ret, 0); -} -HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_23, TestSize.Level0) -{ - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_23 start"; - const char *strl1 = "/mnt/sandbox/100/test.bundle1"; - std::string testBundle = strl1; - int ret = OHOS::AppSpawn::SandboxUtils::SetRenderSandboxProperty(nullptr, testBundle); - EXPECT_EQ(ret, 0); + cJSON_Delete(j_config); + DeleteAppSpawningCtx(appProperty); } HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_24, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_24 start"; - g_testHelper.SetTestUid(1000); // 1000 test g_testHelper.SetTestGid(1000); // 1000 test g_testHelper.SetProcessName("test.bundle.name1"); @@ -542,8 +556,9 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_24, TestSize.Level0) }] \ }] \ }"; - nlohmann::json j_config1 = nlohmann::json::parse(mJsconfig1.c_str()); - int ret = OHOS::AppSpawn::SandboxUtils::DoSandboxFileCommonSymlink(appProperty, j_config1); + cJSON *j_config1 = cJSON_Parse(mJsconfig1.c_str()); + ASSERT_NE(j_config1, nullptr); + int32_t ret = AppSpawn::SandboxCore::DoSandboxFileCommonSymlink(appProperty, j_config1); EXPECT_EQ(ret, 0); std::string mJsconfig2 = "{ \ @@ -558,15 +573,18 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_24, TestSize.Level0) }] \ }] \ }"; - nlohmann::json j_config2 = nlohmann::json::parse(mJsconfig2.c_str()); - ret = OHOS::AppSpawn::SandboxUtils::DoSandboxFileCommonSymlink(appProperty, j_config2); - DeleteAppSpawningCtx(appProperty); + cJSON *j_config2 = cJSON_Parse(mJsconfig2.c_str()); + ASSERT_NE(j_config2, nullptr); + ret = AppSpawn::SandboxCore::DoSandboxFileCommonSymlink(appProperty, j_config2); EXPECT_EQ(ret, 0); + + cJSON_Delete(j_config1); + cJSON_Delete(j_config2); + DeleteAppSpawningCtx(appProperty); } HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_25, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_25 start"; g_testHelper.SetTestUid(1000); // 1000 test g_testHelper.SetTestGid(1000); // 1000 test g_testHelper.SetProcessName("test.bundle.wps"); @@ -596,23 +614,26 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_25, TestSize.Level0) }] \ }] \ }"; - nlohmann::json j_config1 = nlohmann::json::parse(mJsconfig1.c_str()); - int ret = OHOS::AppSpawn::SandboxUtils::DoSandboxFileCommonBind(appProperty, j_config1); + cJSON *j_config1 = cJSON_Parse(mJsconfig1.c_str()); + ASSERT_NE(j_config1, nullptr); + int32_t ret = AppSpawn::SandboxCore::DoSandboxFileCommonBind(appProperty, j_config1); EXPECT_EQ(ret, 0); - ret = OHOS::AppSpawn::SandboxUtils::DoSandboxFileCommonFlagsPointHandle(appProperty, j_config1); - DeleteAppSpawningCtx(appProperty); + ret = AppSpawn::SandboxCore::DoSandboxFileCommonFlagsPointHandle(appProperty, j_config1); EXPECT_EQ(ret, 0); + + cJSON_Delete(j_config1); + DeleteAppSpawningCtx(appProperty); } HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_26, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_26 start"; g_testHelper.SetTestUid(1000); // 1000 test g_testHelper.SetTestGid(1000); // 1000 test g_testHelper.SetProcessName("com.ohos.dlpmanager"); g_testHelper.SetTestApl("system_basic"); AppSpawningCtx *appProperty = GetTestAppProperty(); + std::string mJsconfig2 = "{ \ \"common\":[{ \ \"app-base\" : [{ \ @@ -627,15 +648,17 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_26, TestSize.Level0) }] \ }] \ }"; - nlohmann::json j_config2 = nlohmann::json::parse(mJsconfig2.c_str()); - int ret = OHOS::AppSpawn::SandboxUtils::DoSandboxFileCommonBind(appProperty, j_config2); - DeleteAppSpawningCtx(appProperty); + cJSON *j_config2 = cJSON_Parse(mJsconfig2.c_str()); + ASSERT_NE(j_config2, nullptr); + int32_t ret = AppSpawn::SandboxCore::DoSandboxFileCommonBind(appProperty, j_config2); EXPECT_NE(ret, 0); + + cJSON_Delete(j_config2); + DeleteAppSpawningCtx(appProperty); } HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_27, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_27 start"; g_testHelper.SetTestUid(1000); // 1000 test g_testHelper.SetTestGid(1000); // 1000 test g_testHelper.SetProcessName("test.bundle.name"); @@ -650,8 +673,9 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_27, TestSize.Level0) }] \ }] \ }"; - nlohmann::json j_config1 = nlohmann::json::parse(mJsconfig1.c_str()); - int ret = OHOS::AppSpawn::SandboxUtils::DoSandboxFilePrivateFlagsPointHandle(appProperty, j_config1); + cJSON *j_config1 = cJSON_Parse(mJsconfig1.c_str()); + ASSERT_NE(j_config1, nullptr); + int32_t ret = AppSpawn::SandboxCore::DoSandboxFilePrivateFlagsPointHandle(appProperty, j_config1); EXPECT_EQ(ret, 0); std::string mJsconfig2 = "{ \ @@ -671,15 +695,18 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_27, TestSize.Level0) }] \ }] \ }"; - nlohmann::json j_config2 = nlohmann::json::parse(mJsconfig2.c_str()); - ret = OHOS::AppSpawn::SandboxUtils::DoSandboxFilePrivateFlagsPointHandle(appProperty, j_config2); - DeleteAppSpawningCtx(appProperty); + cJSON *j_config2 = cJSON_Parse(mJsconfig2.c_str()); + ASSERT_NE(j_config2, nullptr); + ret = AppSpawn::SandboxCore::DoSandboxFilePrivateFlagsPointHandle(appProperty, j_config2); EXPECT_EQ(ret, 0); + + cJSON_Delete(j_config1); + cJSON_Delete(j_config2); + DeleteAppSpawningCtx(appProperty); } HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_28, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_28 start"; g_testHelper.SetTestUid(1000); // 1000 test g_testHelper.SetTestGid(1000); // 1000 test g_testHelper.SetProcessName("test.bundle.name"); @@ -705,15 +732,17 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_28, TestSize.Level0) }] \ }] \ }"; - nlohmann::json j_config3 = nlohmann::json::parse(mJsconfig3.c_str()); - int ret = OHOS::AppSpawn::SandboxUtils::DoSandboxFilePrivateFlagsPointHandle(appProperty, j_config3); - DeleteAppSpawningCtx(appProperty); + cJSON *j_config3 = cJSON_Parse(mJsconfig3.c_str()); + ASSERT_NE(j_config3, nullptr); + int ret = AppSpawn::SandboxCore::DoSandboxFilePrivateFlagsPointHandle(appProperty, j_config3); EXPECT_EQ(ret, 0); + + cJSON_Delete(j_config3); + DeleteAppSpawningCtx(appProperty); } HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_29, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_29 start"; g_testHelper.SetTestUid(1000); // 1000 test g_testHelper.SetTestGid(1000); // 1000 test g_testHelper.SetProcessName("test.bundle.name"); @@ -739,15 +768,17 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_29, TestSize.Level0) }] \ }] \ }"; - nlohmann::json j_config3 = nlohmann::json::parse(mJsconfig3.c_str()); - int ret = OHOS::AppSpawn::SandboxUtils::DoSandboxFilePrivateFlagsPointHandle(appProperty, j_config3); - DeleteAppSpawningCtx(appProperty); + cJSON *j_config3 = cJSON_Parse(mJsconfig3.c_str()); + ASSERT_NE(j_config3, nullptr); + int ret = AppSpawn::SandboxCore::DoSandboxFilePrivateFlagsPointHandle(appProperty, j_config3); EXPECT_EQ(ret, 0); + + cJSON_Delete(j_config3); + DeleteAppSpawningCtx(appProperty); } HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_30, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_30 start"; g_testHelper.SetTestUid(1000); // 1000 test g_testHelper.SetTestGid(1000); // 1000 test g_testHelper.SetProcessName("com.ohos.wps"); @@ -765,8 +796,9 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_30, TestSize.Level0) \"check-action-status\": \"false\" \ }] \ }"; - nlohmann::json j_config3 = nlohmann::json::parse(mJsconfig3.c_str()); - int ret = OHOS::AppSpawn::SandboxUtils::DoAllMntPointsMount(appProperty, j_config3, nullptr); + cJSON *j_config3 = cJSON_Parse(mJsconfig3.c_str()); + ASSERT_NE(j_config3, nullptr); + int32_t ret = AppSpawn::SandboxCore::DoAllMntPointsMount(appProperty, j_config3, nullptr); EXPECT_EQ(ret, 0); std::string mJsconfig4 = "{ \ @@ -779,15 +811,18 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_30, TestSize.Level0) \"check-action-status\": \"false\" \ }] \ }"; - nlohmann::json j_config4 = nlohmann::json::parse(mJsconfig4.c_str()); - ret = OHOS::AppSpawn::SandboxUtils::DoAllMntPointsMount(appProperty, j_config4, nullptr); - DeleteAppSpawningCtx(appProperty); + cJSON *j_config4 = cJSON_Parse(mJsconfig4.c_str()); + ASSERT_NE(j_config4, nullptr); + ret = AppSpawn::SandboxCore::DoAllMntPointsMount(appProperty, j_config4, nullptr); EXPECT_EQ(ret, 0); + + cJSON_Delete(j_config3); + cJSON_Delete(j_config4); + DeleteAppSpawningCtx(appProperty); } HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_31, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_31 start"; g_testHelper.SetTestUid(1000); // 1000 test g_testHelper.SetTestGid(1000); // 1000 test g_testHelper.SetProcessName("com.ohos.dlpmanager"); @@ -804,8 +839,9 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_31, TestSize.Level0) \"check-action-status\": \"false\" \ }] \ }"; - nlohmann::json j_config1 = nlohmann::json::parse(mJsconfig1.c_str()); - int ret = OHOS::AppSpawn::SandboxUtils::DoAllMntPointsMount(appProperty, j_config1, nullptr); + cJSON *j_config1 = cJSON_Parse(mJsconfig1.c_str()); + ASSERT_NE(j_config1, nullptr); + int32_t ret = AppSpawn::SandboxCore::DoAllMntPointsMount(appProperty, j_config1, nullptr); EXPECT_EQ(ret, 0); std::string mJsconfig2 = "{ \ @@ -826,32 +862,36 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_31, TestSize.Level0) \"check-action-status\": \"true\" \ }] \ }"; + cJSON *j_config2 = cJSON_Parse(mJsconfig2.c_str()); + ASSERT_NE(j_config2, nullptr); + ret = AppSpawn::SandboxCore::DoAllMntPointsMount(appProperty, j_config2, nullptr); + EXPECT_NE(ret, 0); - nlohmann::json j_config2 = nlohmann::json::parse(mJsconfig2.c_str()); - ret = OHOS::AppSpawn::SandboxUtils::DoAllMntPointsMount(appProperty, j_config2, nullptr); + cJSON_Delete(j_config1); + cJSON_Delete(j_config2); DeleteAppSpawningCtx(appProperty); - EXPECT_TRUE(ret != 0); } HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_32, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_32 start"; - int ret = OHOS::AppSpawn::SandboxUtils::DoAppSandboxMountOnce(nullptr, nullptr); + int32_t ret = AppSpawn::SandboxCommon::DoAppSandboxMountOnce(nullptr, nullptr); EXPECT_EQ(ret, 0); std::string mJsconfig1 = "{ \ \"dest-mode\" : \"S_IRUSR|S_IWUSR|S_IXUSR\" \ }"; - nlohmann::json j_config1 = nlohmann::json::parse(mJsconfig1.c_str()); + cJSON *j_config1 = cJSON_Parse(mJsconfig1.c_str()); + ASSERT_NE(j_config1, nullptr); std::string sandboxRoot; const char *str = "/data/test11122"; sandboxRoot = str; - OHOS::AppSpawn::SandboxUtils::DoSandboxChmod(j_config1, sandboxRoot); + AppSpawn::SandboxCommon::SetSandboxPathChmod(j_config1, sandboxRoot); + + cJSON_Delete(j_config1); } HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_34, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_34 start"; g_testHelper.SetTestUid(1000); // 1000 test g_testHelper.SetTestGid(1000); // 1000 test g_testHelper.SetProcessName("com.ohos.dlpmanager"); @@ -865,19 +905,19 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_34, TestSize.Level0) \"versions\":[\"v10001\", \"v10002\"] \ }"; AppSpawningCtx *appProperty = GetTestAppPropertyWithExtInfo("HspList", hspListStr); - int ret = OHOS::AppSpawn::SandboxUtils::MountAllHsp(appProperty, testBundle); + int32_t ret = AppSpawn::SandboxCore::MountAllHsp(appProperty, testBundle); + EXPECT_EQ(ret, 0); + DeleteAppSpawningCtx(appProperty); - EXPECT_EQ(0, ret); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_34 end"; } static void InvalidJsonTest(std::string &testBundle) { char hspListStr[] = "{"; AppSpawningCtx *appProperty = GetTestAppPropertyWithExtInfo("HspList", hspListStr); - int ret = OHOS::AppSpawn::SandboxUtils::MountAllHsp(appProperty, testBundle); + int32_t ret = AppSpawn::SandboxCore::MountAllHsp(appProperty, testBundle); DeleteAppSpawningCtx(appProperty); - EXPECT_NE(0, ret); + EXPECT_EQ(ret, 0); } static void NoBundleTest(std::string &testBundle) @@ -887,9 +927,9 @@ static void NoBundleTest(std::string &testBundle) \"versions\":[\"v10001\", \"v10002\"] \ }"; AppSpawningCtx *appProperty = GetTestAppPropertyWithExtInfo("HspList", hspListStr); - int ret = OHOS::AppSpawn::SandboxUtils::MountAllHsp(appProperty, testBundle); + int32_t ret = AppSpawn::SandboxCore::MountAllHsp(appProperty, testBundle); DeleteAppSpawningCtx(appProperty); - EXPECT_NE(0, ret); + EXPECT_NE(ret, 0); } static void NoModulesTest(std::string &testBundle) @@ -900,9 +940,9 @@ static void NoModulesTest(std::string &testBundle) }"; AppSpawningCtx *appProperty = GetTestAppPropertyWithExtInfo("HspList", hspListStr); - int ret = OHOS::AppSpawn::SandboxUtils::MountAllHsp(appProperty, testBundle); + int32_t ret = AppSpawn::SandboxCore::MountAllHsp(appProperty, testBundle); DeleteAppSpawningCtx(appProperty); - EXPECT_NE(0, ret); + EXPECT_NE(ret, 0); } static void NoVersionsTest(std::string &testBundle) @@ -912,9 +952,9 @@ static void NoVersionsTest(std::string &testBundle) \"modules\":[\"module1\", \"module2\"] \ }"; AppSpawningCtx *appProperty = GetTestAppPropertyWithExtInfo("HspList", hspListStr); - int ret = OHOS::AppSpawn::SandboxUtils::MountAllHsp(appProperty, testBundle); + int32_t ret = AppSpawn::SandboxCore::MountAllHsp(appProperty, testBundle); DeleteAppSpawningCtx(appProperty); - EXPECT_NE(0, ret); + EXPECT_NE(ret, 0); } static void ListSizeNotSameTest(std::string &testBundle) @@ -925,9 +965,9 @@ static void ListSizeNotSameTest(std::string &testBundle) \"versions\":[\"v10001\", \"v10002\"] \ }"; AppSpawningCtx *appProperty = GetTestAppPropertyWithExtInfo("HspList", hspListStr); - int ret = OHOS::AppSpawn::SandboxUtils::MountAllHsp(appProperty, testBundle); + int32_t ret = AppSpawn::SandboxCore::MountAllHsp(appProperty, testBundle); DeleteAppSpawningCtx(appProperty); - EXPECT_NE(0, ret); + EXPECT_NE(ret, 0); } static void ValueTypeIsNotArraryTest(std::string &testBundle) @@ -938,9 +978,9 @@ static void ValueTypeIsNotArraryTest(std::string &testBundle) \"versions\": 1001 \ }"; AppSpawningCtx *appProperty = GetTestAppPropertyWithExtInfo("HspList", hspListStr); - int ret = OHOS::AppSpawn::SandboxUtils::MountAllHsp(appProperty, testBundle); + int32_t ret = AppSpawn::SandboxCore::MountAllHsp(appProperty, testBundle); DeleteAppSpawningCtx(appProperty); - EXPECT_NE(0, ret); + EXPECT_NE(ret, 0); } static void ElementTypeIsNotStringTest(std::string &testBundle) @@ -951,9 +991,9 @@ static void ElementTypeIsNotStringTest(std::string &testBundle) \"versions\": [1001, 1002] \ }"; AppSpawningCtx *appProperty = GetTestAppPropertyWithExtInfo("HspList", hspListStr); - int ret = OHOS::AppSpawn::SandboxUtils::MountAllHsp(appProperty, testBundle); + int32_t ret = AppSpawn::SandboxCore::MountAllHsp(appProperty, testBundle); DeleteAppSpawningCtx(appProperty); - EXPECT_NE(0, ret); + EXPECT_NE(ret, 0); } static void ElementTypeIsNotSameTestSN(std::string &testBundle) @@ -965,9 +1005,9 @@ static void ElementTypeIsNotSameTestSN(std::string &testBundle) \"versions\": [\"v10001\", 1002] \ }"; AppSpawningCtx *appProperty = GetTestAppPropertyWithExtInfo("HspList", hspListStr); - int ret = OHOS::AppSpawn::SandboxUtils::MountAllHsp(appProperty, testBundle); + int32_t ret = AppSpawn::SandboxCore::MountAllHsp(appProperty, testBundle); DeleteAppSpawningCtx(appProperty); - EXPECT_NE(0, ret); + EXPECT_NE(ret, 0); } static void ElementTypeIsNotSameTestNS(std::string &testBundle) @@ -979,14 +1019,13 @@ static void ElementTypeIsNotSameTestNS(std::string &testBundle) \"versions\": [1001, \"v10002\"] \ }"; AppSpawningCtx *appProperty = GetTestAppPropertyWithExtInfo("HspList", hspListStr); - int ret = OHOS::AppSpawn::SandboxUtils::MountAllHsp(appProperty, testBundle); + int32_t ret = AppSpawn::SandboxCore::MountAllHsp(appProperty, testBundle); DeleteAppSpawningCtx(appProperty); - EXPECT_NE(0, ret); + EXPECT_NE(ret, 0); } HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_35, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_35 start"; const char *strl1 = "/mnt/sandbox/100/test.bundle1"; std::string testBundle = strl1; InvalidJsonTest(testBundle); @@ -998,12 +1037,10 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_35, TestSize.Level0) ElementTypeIsNotStringTest(testBundle); ElementTypeIsNotSameTestSN(testBundle); ElementTypeIsNotSameTestNS(testBundle); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_35 end"; } HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_36, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_36 start"; const char *strl1 = "/mnt/sandbox/100/test.bundle1"; std::string testBundle = strl1; @@ -1014,9 +1051,9 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_36, TestSize.Level0) \"versions\":[\"v10001\", \"v10002\"] \ }"; AppSpawningCtx *appProperty = GetTestAppPropertyWithExtInfo("HspList", hspListStr); - int ret = OHOS::AppSpawn::SandboxUtils::MountAllHsp(appProperty, testBundle); + int32_t ret = AppSpawn::SandboxCore::MountAllHsp(appProperty, testBundle); DeleteAppSpawningCtx(appProperty); - EXPECT_NE(0, ret); + EXPECT_NE(ret, 0); } { // name is . char hspListStr[] = "{ \ @@ -1025,9 +1062,9 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_36, TestSize.Level0) \"versions\":[\"v10001\", \"v10002\"] \ }"; AppSpawningCtx *appProperty = GetTestAppPropertyWithExtInfo("HspList", hspListStr); - int ret = OHOS::AppSpawn::SandboxUtils::MountAllHsp(appProperty, testBundle); + int32_t ret = AppSpawn::SandboxCore::MountAllHsp(appProperty, testBundle); DeleteAppSpawningCtx(appProperty); - EXPECT_NE(0, ret); + EXPECT_NE(ret, 0); } { // name is .. char hspListStr[] = "{ \ @@ -1036,9 +1073,9 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_36, TestSize.Level0) \"versions\":[\"v10001\", \"v10002\"] \ }"; AppSpawningCtx *appProperty = GetTestAppPropertyWithExtInfo("HspList", hspListStr); - int ret = OHOS::AppSpawn::SandboxUtils::MountAllHsp(appProperty, testBundle); + int32_t ret = AppSpawn::SandboxCore::MountAllHsp(appProperty, testBundle); DeleteAppSpawningCtx(appProperty); - EXPECT_NE(0, ret); + EXPECT_NE(ret, 0); } { // name contains / char hspListStr[] = "{ \ @@ -1047,16 +1084,14 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_36, TestSize.Level0) \"versions\":[\"v10001\", \"v10002\"] \ }"; AppSpawningCtx *appProperty = GetTestAppPropertyWithExtInfo("HspList", hspListStr); - int ret = OHOS::AppSpawn::SandboxUtils::MountAllHsp(appProperty, testBundle); + int32_t ret = AppSpawn::SandboxCore::MountAllHsp(appProperty, testBundle); DeleteAppSpawningCtx(appProperty); - EXPECT_NE(0, ret); + EXPECT_NE(ret, 0); } - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_36 end"; } HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_37, TestSize.Level0) { - APPSPAWN_LOGI("App_Spawn_Sandbox_37 start"); g_testHelper.SetTestUid(1000); // 1000 test g_testHelper.SetTestGid(1000); // 1000 test g_testHelper.SetProcessName("ohos.samples.xxx"); @@ -1064,22 +1099,21 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_37, TestSize.Level0) AppSpawningCtx *appProperty = GetTestAppProperty(); AppSpawnMgr content; - LoadAppSandboxConfig(&content); + AppSpawn::SandboxCommon::LoadAppSandboxConfigCJson(&content); std::string sandboxPackagePath = "/mnt/sandbox/100/"; const std::string bundleName = GetBundleName(appProperty); sandboxPackagePath += bundleName; - int ret = SandboxUtils::SetPrivateAppSandboxProperty(appProperty); - EXPECT_EQ(0, ret); - ret = SandboxUtils::SetCommonAppSandboxProperty(appProperty, sandboxPackagePath); + int32_t ret = AppSpawn::SandboxCore::SetPrivateAppSandboxProperty(appProperty); + EXPECT_EQ(ret, 0); + ret = AppSpawn::SandboxCore::SetCommonAppSandboxProperty(appProperty, sandboxPackagePath); + EXPECT_EQ(ret, 0); + DeleteAppSpawningCtx(appProperty); - EXPECT_EQ(0, ret); - APPSPAWN_LOGI("App_Spawn_Sandbox_37 end"); } HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_38, TestSize.Level0) { - APPSPAWN_LOGI("App_Spawn_Sandbox_38 start"); g_testHelper.SetTestUid(1000); // 1000 test g_testHelper.SetTestGid(1000); // 1000 test g_testHelper.SetProcessName("com.example.deviceinfo"); @@ -1108,19 +1142,20 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_38, TestSize.Level0) }] \ }] \ }"; - - nlohmann::json p_config1 = nlohmann::json::parse(pJsconfig1.c_str()); - OHOS::AppSpawn::SandboxUtils::StoreJsonConfig(p_config1, SANBOX_APP_JSON_CONFIG); + cJSON *j_config = cJSON_Parse(pJsconfig1.c_str()); + ASSERT_NE(j_config, nullptr); + AppSpawn::SandboxCommon::StoreCJsonConfig(j_config, SandboxCommonDef::SANDBOX_APP_JSON_CONFIG); std::string sandboxPackagePath = "/mnt/sandbox/100/"; const std::string bundleName = GetBundleName(appProperty); sandboxPackagePath += bundleName; - int ret = SandboxUtils::SetPrivateAppSandboxProperty(appProperty); - EXPECT_EQ(0, ret); - ret = SandboxUtils::SetCommonAppSandboxProperty(appProperty, sandboxPackagePath); + int32_t ret = AppSpawn::SandboxCore::SetPrivateAppSandboxProperty(appProperty); + EXPECT_EQ(ret, 0); + ret = AppSpawn::SandboxCore::SetCommonAppSandboxProperty(appProperty, sandboxPackagePath); + EXPECT_EQ(ret, 0); + + cJSON_Delete(j_config); DeleteAppSpawningCtx(appProperty); - EXPECT_EQ(0, ret); - APPSPAWN_LOGI("App_Spawn_Sandbox_38 end"); } /** @@ -1132,7 +1167,6 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_38, TestSize.Level0) */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_39, TestSize.Level0) { - APPSPAWN_LOGI("App_Spawn_Sandbox_39 start"); g_testHelper.SetTestUid(1000); // 1000 test g_testHelper.SetTestGid(1000); // 1000 test g_testHelper.SetProcessName("com.ohos.demo"); @@ -1143,11 +1177,12 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_39, TestSize.Level0) overlayInfo += "/data/app/el1/bundle/public/com.ohos.demo/feature.hsp|"; AppSpawningCtx *appProperty = GetTestAppPropertyWithExtInfo("Overlay", overlayInfo.c_str()); std::string sandBoxRootDir = "/mnt/sandbox/100/com.ohos.demo"; - int32_t ret = OHOS::AppSpawn::SandboxUtils::SetOverlayAppSandboxProperty(appProperty, sandBoxRootDir); + int32_t ret = AppSpawn::SandboxCore::SetOverlayAppSandboxProperty(appProperty, sandBoxRootDir); + EXPECT_EQ(ret, 0); + DeleteAppSpawningCtx(appProperty); - EXPECT_EQ(0, ret); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_39 end"; } + /** * @tc.name: App_Spawn_Sandbox_40 * @tc.desc: load group info config SetAppSandboxProperty @@ -1157,7 +1192,6 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_39, TestSize.Level0) */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_40, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_40 start"; g_testHelper.SetTestUid(1000); // 1000 test g_testHelper.SetTestGid(1000); // 1000 test g_testHelper.SetProcessName("com.ohos.demo"); @@ -1179,22 +1213,21 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_40, TestSize.Level0) } ])"; AppSpawningCtx *appProperty = GetTestAppPropertyWithExtInfo("DataGroup", dataGroupInfoListStr); - int ret = OHOS::AppSpawn::SandboxUtils::MountAllGroup(appProperty, sandboxPrefix); + int32_t ret = AppSpawn::SandboxCore::MountAllGroup(appProperty, sandboxPrefix); + EXPECT_EQ(ret, 0); + DeleteAppSpawningCtx(appProperty); - EXPECT_EQ(0, ret); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_40 end"; } /** * @tc.name: App_Spawn_Sandbox_41 - * @tc.desc: parse namespace config. + * @tc.desc: parse namespace config * @tc.type: FUNC * @tc.require:issueI8B63M * @tc.author: */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_41, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_41 start"; std::string mJsconfig = "{ \ \"common\":[{ \ \"top-sandbox-switch\": \"ON\", \ @@ -1214,29 +1247,28 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_41, TestSize.Level0) }] \ }] \ }"; - nlohmann::json j_config = nlohmann::json::parse(mJsconfig.c_str()); - - OHOS::AppSpawn::SandboxUtils::StoreJsonConfig(j_config, SANBOX_APP_JSON_CONFIG); + cJSON *j_config = cJSON_Parse(mJsconfig.c_str()); + ASSERT_NE(j_config, nullptr); + AppSpawn::SandboxCommon::StoreCJsonConfig(j_config, SandboxCommonDef::SANDBOX_APP_JSON_CONFIG); - uint32_t cloneFlags = OHOS::AppSpawn::SandboxUtils::GetSandboxNsFlags(false); + uint32_t cloneFlags = AppSpawn::SandboxCommon::GetSandboxNsFlags(false); EXPECT_EQ(!!(cloneFlags & CLONE_NEWPID), true); - cloneFlags = OHOS::AppSpawn::SandboxUtils::GetSandboxNsFlags(true); + cloneFlags = AppSpawn::SandboxCommon::GetSandboxNsFlags(true); EXPECT_EQ(!!(cloneFlags & (CLONE_NEWPID | CLONE_NEWNET)), true); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_41 end"; + cJSON_Delete(j_config); } /** * @tc.name: App_Spawn_Sandbox_42 - * @tc.desc: parse config file for fstype . + * @tc.desc: parse config file for fstype * @tc.type: FUNC * @tc.require: https://gitee.com/openharmony/startup_appspawn/issues/I8OF9K * @tc.author: */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_42, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_42 start"; std::string mJsconfig = "{ \ \"mount-paths\": [{ \ \"src-path\": \"/data/app/el1//base\", \ @@ -1247,16 +1279,26 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_42, TestSize.Level0) \"options\": \"support_overwrite=1\" \ }] \ }"; - nlohmann::json j_config = nlohmann::json::parse(mJsconfig.c_str()); - const char *mountPath = "mount-paths"; - nlohmann::json j_secondConfig = j_config[mountPath][0]; - OHOS::AppSpawn::SandboxUtils::StoreJsonConfig(j_config, SANBOX_APP_JSON_CONFIG); - - std::string fsType = OHOS::AppSpawn::SandboxUtils::GetSandboxFsType(j_secondConfig); - int ret = strcmp(fsType.c_str(), "sharefs"); - EXPECT_EQ(ret, 0); + cJSON *j_config = cJSON_Parse(mJsconfig.c_str()); + ASSERT_NE(j_config, nullptr); + AppSpawn::SandboxCommon::StoreCJsonConfig(j_config, SandboxCommonDef::SANDBOX_APP_JSON_CONFIG); + + int ret = 0; + do { + cJSON *mountPoints = cJSON_GetObjectItemCaseSensitive(j_config, "mount-paths"); + APPSPAWN_CHECK(mountPoints != nullptr || cJSON_IsArray(mountPoints), ret = -1; + break, "Invalid mountPaths config"); + + for (int i = 0; i < cJSON_GetArraySize(mountPoints); ++i) { + cJSON *mntPoint = cJSON_GetArrayItem(mountPoints, i); + APPSPAWN_CHECK(mntPoint != nullptr, ret = -2; break, "Invalid mountPoint config"); + std::string fsType = AppSpawn::SandboxCommon::GetFsType(mntPoint); + ret = strcmp(fsType.c_str(), "sharefs"); + } + EXPECT_EQ(ret, 0); + } while (0); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_42 end"; + cJSON_Delete(j_config); } /** @@ -1268,7 +1310,6 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_42, TestSize.Level0) */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_43, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_43 start"; std::string mJsconfig = "{ \ \"mount-paths\": [{ \ \"src-path\": \"/data/app/el1//base\", \ @@ -1279,18 +1320,29 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_43, TestSize.Level0) \"options\": \"support_overwrite=1\" \ }] \ }"; - nlohmann::json j_config = nlohmann::json::parse(mJsconfig.c_str()); - const char *mountPath = "mount-paths"; - nlohmann::json j_secondConfig = j_config[mountPath][0]; + cJSON *j_config = cJSON_Parse(mJsconfig.c_str()); + ASSERT_NE(j_config, nullptr); + AppSpawn::SandboxCommon::StoreCJsonConfig(j_config, SandboxCommonDef::SANDBOX_APP_JSON_CONFIG); - OHOS::AppSpawn::SandboxUtils::StoreJsonConfig(j_config, SANBOX_APP_JSON_CONFIG); - OHOS::AppSpawn::SandboxUtils::SandboxMountConfig mountConfig; - std::string section = "common"; + int ret = 0; AppSpawningCtx *appProperty = GetTestAppProperty(); - OHOS::AppSpawn::SandboxUtils::GetSandboxMountConfig(appProperty, section, j_secondConfig, mountConfig); - int ret = strcmp(mountConfig.fsType.c_str(), "sharefs"); - EXPECT_EQ(ret, 0); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_43 end"; + do { + cJSON *mountPoints = cJSON_GetObjectItemCaseSensitive(j_config, "mount-paths"); + APPSPAWN_CHECK(mountPoints != nullptr || cJSON_IsArray(mountPoints), ret = -1; + break, "Invalid mountPaths config"); + + for (int i = 0; i < cJSON_GetArraySize(mountPoints); ++i) { + cJSON *mntPoint = cJSON_GetArrayItem(mountPoints, i); + APPSPAWN_CHECK(mntPoint != nullptr, ret = -2; break, "Invalid mntPoint config"); + SandboxMountConfig mountConfig = {0}; + AppSpawn::SandboxCommon::GetSandboxMountConfig(appProperty, "common", mntPoint, mountConfig); + ret = strcmp(mountConfig.fsType.c_str(), "sharefs"); + } + EXPECT_EQ(ret, 0); + } while (0); + + cJSON_Delete(j_config); + DeleteAppSpawningCtx(appProperty); } /** @@ -1302,7 +1354,6 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_43, TestSize.Level0) */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_44, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_44 start"; std::string mJsconfig = "{ \ \"mount-paths\": [{ \ \"src-path\": \"/data/app/el1//base\", \ @@ -1313,18 +1364,29 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_44, TestSize.Level0) \"options\": \"support_overwrite=1\" \ }] \ }"; - nlohmann::json j_config = nlohmann::json::parse(mJsconfig.c_str()); - const char *mountPath = "mount-paths"; - nlohmann::json j_secondConfig = j_config[mountPath][0]; + cJSON *j_config = cJSON_Parse(mJsconfig.c_str()); + ASSERT_NE(j_config, nullptr); + AppSpawn::SandboxCommon::StoreCJsonConfig(j_config, SandboxCommonDef::SANDBOX_APP_JSON_CONFIG); - OHOS::AppSpawn::SandboxUtils::StoreJsonConfig(j_config, SANBOX_APP_JSON_CONFIG); - OHOS::AppSpawn::SandboxUtils::SandboxMountConfig mountConfig; - std::string section = "permission"; + int ret = 0; AppSpawningCtx *appProperty = GetTestAppProperty(); - OHOS::AppSpawn::SandboxUtils::GetSandboxMountConfig(appProperty, section, j_secondConfig, mountConfig); - int ret = strcmp(mountConfig.fsType.c_str(), "sharefs"); - EXPECT_EQ(ret, 0); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_44 end"; + do { + cJSON *mountPoints = cJSON_GetObjectItemCaseSensitive(j_config, "mount-paths"); + APPSPAWN_CHECK(mountPoints != nullptr || cJSON_IsArray(mountPoints), ret = -1; + break, "Invalid mountPaths config"); + + for (int i = 0; i < cJSON_GetArraySize(mountPoints); ++i) { + cJSON *mntPoint = cJSON_GetArrayItem(mountPoints, i); + APPSPAWN_CHECK(mntPoint != nullptr, ret = -2; break, "Invalid mntPoint config"); + SandboxMountConfig mountConfig = {0}; + AppSpawn::SandboxCommon::GetSandboxMountConfig(appProperty, "permission", mntPoint, mountConfig); + ret = strcmp(mountConfig.fsType.c_str(), "sharefs"); + } + EXPECT_EQ(ret, 0); + } while (0); + + cJSON_Delete(j_config); + DeleteAppSpawningCtx(appProperty); } /** @@ -1336,7 +1398,6 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_44, TestSize.Level0) */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_45, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_45 start"; std::string mJsconfig = "{ \ \"mount-paths\": [{ \ \"src-path\": \"/data/app/el1//base\", \ @@ -1347,21 +1408,32 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_45, TestSize.Level0) \"options\": \"support_overwrite=1\" \ }] \ }"; - nlohmann::json j_config = nlohmann::json::parse(mJsconfig.c_str()); - const char *mountPath = "mount-paths"; - nlohmann::json j_secondConfig = j_config[mountPath][0]; + cJSON *j_config = cJSON_Parse(mJsconfig.c_str()); + ASSERT_NE(j_config, nullptr); + AppSpawn::SandboxCommon::StoreCJsonConfig(j_config, SandboxCommonDef::SANDBOX_APP_JSON_CONFIG); - OHOS::AppSpawn::SandboxUtils::StoreJsonConfig(j_config, SANBOX_APP_JSON_CONFIG); + int ret = 0; AppSpawningCtx *appProperty = GetTestAppProperty(); - std::string options = OHOS::AppSpawn::SandboxUtils::GetSandboxOptions(appProperty, j_secondConfig); - int ret = strcmp(options.c_str(), "support_overwrite=1,user_id=100"); - EXPECT_EQ(ret, 0); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_45 end"; + do { + cJSON *mountPoints = cJSON_GetObjectItemCaseSensitive(j_config, "mount-paths"); + APPSPAWN_CHECK(mountPoints != nullptr || cJSON_IsArray(mountPoints), ret = -1; + break, "Invalid mountPaths config"); + + for (int i = 0; i < cJSON_GetArraySize(mountPoints); ++i) { + cJSON *mntPoint = cJSON_GetArrayItem(mountPoints, i); + APPSPAWN_CHECK(mntPoint != nullptr, ret = -2; break, "Invalid mountPoint config"); + std::string options = AppSpawn::SandboxCommon::GetOptions(appProperty, mntPoint); + ret = strcmp(options.c_str(), "support_overwrite=1,user_id=100"); + } + EXPECT_EQ(ret, 0); + } while (0); + + cJSON_Delete(j_config); + DeleteAppSpawningCtx(appProperty); } HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_46, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_46 start"; g_testHelper.SetTestUid(1000); // 1000 test g_testHelper.SetTestGid(1000); // 1000 test g_testHelper.SetProcessName("com.example.myapplication"); @@ -1378,8 +1450,9 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_46, TestSize.Level0) \"check-action-status\": \"false\" \ }] \ }"; - nlohmann::json j_config1 = nlohmann::json::parse(mJsconfig1.c_str()); - int ret = OHOS::AppSpawn::SandboxUtils::DoAllMntPointsMount(appProperty, j_config1, nullptr); + cJSON *j_config1 = cJSON_Parse(mJsconfig1.c_str()); + ASSERT_NE(j_config1, nullptr); + int32_t ret = AppSpawn::SandboxCore::DoAllMntPointsMount(appProperty, j_config1, nullptr); EXPECT_EQ(ret, 0); std::string mJsconfig2 = "{ \ @@ -1392,15 +1465,18 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_46, TestSize.Level0) \"create-sandbox-path\": \"true\" \ }] \ }"; - nlohmann::json j_config2 = nlohmann::json::parse(mJsconfig2.c_str()); - ret = OHOS::AppSpawn::SandboxUtils::DoAllMntPointsMount(appProperty, j_config2, nullptr); - DeleteAppSpawningCtx(appProperty); + cJSON *j_config2 = cJSON_Parse(mJsconfig2.c_str()); + ASSERT_NE(j_config2, nullptr); + ret = AppSpawn::SandboxCore::DoAllMntPointsMount(appProperty, j_config2, nullptr); EXPECT_EQ(ret, 0); + + cJSON_Delete(j_config1); + cJSON_Delete(j_config2); + DeleteAppSpawningCtx(appProperty); } HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_47, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_47 start"; g_testHelper.SetTestUid(1000); // 1000 test g_testHelper.SetTestGid(1000); // 1000 test g_testHelper.SetProcessName("com.example.myapplication"); @@ -1417,8 +1493,9 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_47, TestSize.Level0) \"check-action-status\": \"false\" \ }] \ }"; - nlohmann::json j_config1 = nlohmann::json::parse(mJsconfig1.c_str()); - int ret = OHOS::AppSpawn::SandboxUtils::DoAllMntPointsMount(appProperty, j_config1, nullptr); + cJSON *j_config1 = cJSON_Parse(mJsconfig1.c_str()); + ASSERT_NE(j_config1, nullptr); + int32_t ret = AppSpawn::SandboxCore::DoAllMntPointsMount(appProperty, j_config1, nullptr); EXPECT_EQ(ret, 0); std::string mJsconfig2 = "{ \ @@ -1431,10 +1508,14 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_47, TestSize.Level0) \"create-sandbox-path\": \"false\" \ }] \ }"; - nlohmann::json j_config2 = nlohmann::json::parse(mJsconfig2.c_str()); - ret = OHOS::AppSpawn::SandboxUtils::DoAllMntPointsMount(appProperty, j_config2, nullptr); - DeleteAppSpawningCtx(appProperty); + cJSON *j_config2 = cJSON_Parse(mJsconfig2.c_str()); + ASSERT_NE(j_config2, nullptr); + ret = AppSpawn::SandboxCore::DoAllMntPointsMount(appProperty, j_config2, nullptr); EXPECT_EQ(ret, 0); + + cJSON_Delete(j_config1); + cJSON_Delete(j_config2); + DeleteAppSpawningCtx(appProperty); } /** * @brief 测试app extension @@ -1443,10 +1524,9 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_47, TestSize.Level0) HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_AppExtension_004, TestSize.Level0) { AppSpawningCtx *spawningCtx = GetTestAppProperty(); - std::string path = SandboxUtils::ConvertToRealPath(spawningCtx, "/system//module"); - APPSPAWN_LOGV("path %{public}s", path.c_str()); - ASSERT_EQ(path.c_str() != nullptr, 1); - ASSERT_EQ(strcmp(path.c_str(), "/system/com.example.myapplication/module") == 0, 1); + std::string path = AppSpawn::SandboxCommon::ConvertToRealPath(spawningCtx, "/system//module"); + ASSERT_NE(path.c_str(), nullptr); + ASSERT_EQ(strcmp(path.c_str(), "/system/com.example.myapplication/module"), 0); DeleteAppSpawningCtx(spawningCtx); } @@ -1457,10 +1537,9 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_AppExtension_005, TestSize.Level int ret = SetAppSpawnMsgFlag(spawningCtx->message, TLV_MSG_FLAGS, APP_FLAGS_CLONE_ENABLE); ASSERT_EQ(ret, 0); - std::string path = SandboxUtils::ConvertToRealPath(spawningCtx, "/system//module"); - APPSPAWN_LOGV("path %{public}s", path.c_str()); - ASSERT_EQ(path.c_str() != nullptr, 1); // +clone-bundleIndex+packageName - ASSERT_EQ(strcmp(path.c_str(), "/system/+clone-100+com.example.myapplication/module") == 0, 1); + std::string path = AppSpawn::SandboxCommon::ConvertToRealPath(spawningCtx, "/system//module"); + ASSERT_NE(path.c_str(), nullptr); // +clone-bundleIndex+packageName + ASSERT_EQ(strcmp(path.c_str(), "/system/+clone-100+com.example.myapplication/module"), 0); DeleteAppSpawningCtx(spawningCtx); } @@ -1478,10 +1557,10 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_AppExtension_006, TestSize.Level AppSpawningCtx *spawningCtx = g_testHelper.GetAppProperty(clientHandle, reqHandle); ASSERT_EQ(spawningCtx != nullptr, 1); - std::string path = SandboxUtils::ConvertToRealPath(spawningCtx, "/system//module"); - APPSPAWN_LOGV("path %{public}s", path.c_str()); - ASSERT_EQ(path.c_str() != nullptr, 1); // +extension-+packageName - ASSERT_EQ(strcmp(path.c_str(), "/system/+extension-test001+com.example.myapplication/module") == 0, 1); + std::string path = AppSpawn::SandboxCommon::ConvertToRealPath(spawningCtx, "/system//module"); + ASSERT_NE(path.c_str(), nullptr); // +extension-+packageName + ASSERT_EQ(strcmp(path.c_str(), "/system/+extension-test001+com.example.myapplication/module"), 0); + DeleteAppSpawningCtx(spawningCtx); AppSpawnClientDestroy(clientHandle); } @@ -1502,11 +1581,10 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_AppExtension_007, TestSize.Level AppSpawningCtx *spawningCtx = g_testHelper.GetAppProperty(clientHandle, reqHandle); ASSERT_EQ(spawningCtx != nullptr, 1); - std::string path = SandboxUtils::ConvertToRealPath(spawningCtx, "/system//module"); - APPSPAWN_LOGV("path %{public}s", path.c_str()); - ASSERT_EQ(path.c_str() != nullptr, 1); // +clone-bundleIndex+extension-+packageName + std::string path = AppSpawn::SandboxCommon::ConvertToRealPath(spawningCtx, "/system//module"); + ASSERT_NE(path.c_str(), nullptr); // +clone-bundleIndex+extension-+packageName + ASSERT_EQ(strcmp(path.c_str(), "/system/+clone-100+extension-test001+com.example.myapplication/module"), 0); - ASSERT_EQ(strcmp(path.c_str(), "/system/+clone-100+extension-test001+com.example.myapplication/module") == 0, 1); DeleteAppSpawningCtx(spawningCtx); AppSpawnClientDestroy(clientHandle); } @@ -1525,8 +1603,7 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_AppExtension_008, TestSize.Level AppSpawningCtx *spawningCtx = g_testHelper.GetAppProperty(clientHandle, reqHandle); ASSERT_EQ(spawningCtx != nullptr, 1); - std::string path = SandboxUtils::ConvertToRealPath(spawningCtx, "/system//module"); - APPSPAWN_LOGV("path %{public}s", path.c_str()); + std::string path = AppSpawn::SandboxCommon::ConvertToRealPath(spawningCtx, "/system//module"); ASSERT_STREQ(path.c_str(), ""); DeleteAppSpawningCtx(spawningCtx); @@ -1545,8 +1622,7 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_AppExtension_009, TestSize.Level AppSpawningCtx *spawningCtx = g_testHelper.GetAppProperty(clientHandle, reqHandle); ASSERT_EQ(spawningCtx != nullptr, 1); - std::string path = SandboxUtils::ConvertToRealPath(spawningCtx, "/system//module"); - APPSPAWN_LOGV("path %{public}s", path.c_str()); + std::string path = AppSpawn::SandboxCommon::ConvertToRealPath(spawningCtx, "/system//module"); ASSERT_STREQ(path.c_str(), ""); DeleteAppSpawningCtx(spawningCtx); @@ -1562,7 +1638,6 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_AppExtension_009, TestSize.Level #define DEC_PATH_SIZE 3 HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_dec_01, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_dec_01 start"; std::string mJsconfig = "{ \ \"mount-paths\": [{ \ \"src-path\": \"\", \ @@ -1571,23 +1646,34 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_dec_01, TestSize.Level0) \"dec-paths\": [ \"/storage/Users\", \"/storage/External\", \"/storage/test\" ] \ }] \ }"; - nlohmann::json j_config = nlohmann::json::parse(mJsconfig.c_str()); - const char *mountPath = "mount-paths"; - nlohmann::json j_secondConfig = j_config[mountPath][0]; - std::string section = "permission"; - OHOS::AppSpawn::SandboxUtils::StoreJsonConfig(j_config, SANBOX_APP_JSON_CONFIG); - OHOS::AppSpawn::SandboxUtils::SandboxMountConfig mountConfig; + cJSON *j_config = cJSON_Parse(mJsconfig.c_str()); + ASSERT_NE(j_config, nullptr); + AppSpawn::SandboxCommon::StoreCJsonConfig(j_config, SandboxCommonDef::SANDBOX_APP_JSON_CONFIG); + + int ret = 0; AppSpawningCtx *appProperty = GetTestAppProperty(); - OHOS::AppSpawn::SandboxUtils::GetSandboxMountConfig(appProperty, section, j_secondConfig, mountConfig); - int decPathSize = mountConfig.decPaths.size(); - EXPECT_EQ(decPathSize, DEC_PATH_SIZE); - int ret = strcmp(mountConfig.decPaths[0].c_str(), "/storage/Users"); - EXPECT_EQ(ret, 0); - ret = strcmp(mountConfig.decPaths[1].c_str(), "/storage/External"); - EXPECT_EQ(ret, 0); - ret = strcmp(mountConfig.decPaths[2].c_str(), "/storage/test"); - EXPECT_EQ(ret, 0); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_dec_01 end"; + do { + cJSON *mountPoints = cJSON_GetObjectItemCaseSensitive(j_config, "mount-paths"); + APPSPAWN_CHECK(mountPoints != nullptr || cJSON_IsArray(mountPoints), ret = -1; + break, "Invalid mountPaths config"); + + for (int i = 0; i < cJSON_GetArraySize(mountPoints); ++i) { + cJSON *mntPoint = cJSON_GetArrayItem(mountPoints, i); + APPSPAWN_CHECK(mntPoint != nullptr, ret = -2; break, "Invalid mntPoint config"); + SandboxMountConfig mountConfig = {0}; + AppSpawn::SandboxCommon::GetSandboxMountConfig(appProperty, "permission", mntPoint, mountConfig); + + int decPathSize = mountConfig.decPaths.size(); + ASSERT_EQ(decPathSize, DEC_PATH_SIZE); + ret = strcmp(mountConfig.decPaths[0].c_str(), "/storage/Users") || + strcmp(mountConfig.decPaths[1].c_str(), "/storage/External") || + strcmp(mountConfig.decPaths[2].c_str(), "/storage/test"); + } + EXPECT_EQ(ret, 0); + } while (0); + + cJSON_Delete(j_config); + DeleteAppSpawningCtx(appProperty); } /** @@ -1598,7 +1684,6 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_dec_01, TestSize.Level0) */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_dec_02, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_dec_02 start"; std::string mJsconfig = "{ \ \"mount-paths\": [{ \ \"src-path\": \"\", \ @@ -1607,18 +1692,31 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_dec_02, TestSize.Level0) \"dec-paths\": [ ] \ }] \ }"; - nlohmann::json j_config = nlohmann::json::parse(mJsconfig.c_str()); - const char *mountPath = "mount-paths"; - nlohmann::json j_secondConfig = j_config[mountPath][0]; - std::string section = "permission"; - OHOS::AppSpawn::SandboxUtils::StoreJsonConfig(j_config, SANBOX_APP_JSON_CONFIG); - OHOS::AppSpawn::SandboxUtils::SandboxMountConfig mountConfig; + cJSON *j_config = cJSON_Parse(mJsconfig.c_str()); + ASSERT_NE(j_config, nullptr); + AppSpawn::SandboxCommon::StoreCJsonConfig(j_config, SandboxCommonDef::SANDBOX_APP_JSON_CONFIG); + + int ret = 0; AppSpawningCtx *appProperty = GetTestAppProperty(); - OHOS::AppSpawn::SandboxUtils::GetSandboxMountConfig(appProperty, section, j_secondConfig, mountConfig); - int decPathSize = mountConfig.decPaths.size(); - EXPECT_EQ(decPathSize, 0); + do { + cJSON *mountPoints = cJSON_GetObjectItemCaseSensitive(j_config, "mount-paths"); + APPSPAWN_CHECK(mountPoints != nullptr || cJSON_IsArray(mountPoints), ret = -1; + break, "Invalid mountPaths config"); + + for (int i = 0; i < cJSON_GetArraySize(mountPoints); ++i) { + cJSON *mntPoint = cJSON_GetArrayItem(mountPoints, i); + APPSPAWN_CHECK(mntPoint != nullptr, ret = -2; break, "Invalid mntPoint config"); + SandboxMountConfig mountConfig = {0}; + AppSpawn::SandboxCommon::GetSandboxMountConfig(appProperty, "permission", mntPoint, mountConfig); + + int decPathSize = mountConfig.decPaths.size(); + EXPECT_EQ(decPathSize, 0); + } + EXPECT_EQ(ret, 0); + } while (0); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_dec_02 end"; + cJSON_Delete(j_config); + DeleteAppSpawningCtx(appProperty); } /** @@ -1629,7 +1727,6 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_dec_02, TestSize.Level0) */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_dec_03, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_dec_03 start"; std::string mJsconfig = "{ \ \"mount-paths\": [{ \ \"src-path\": \"\", \ @@ -1638,18 +1735,32 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_dec_03, TestSize.Level0) \"dec-paths\": [ \"/storage/Users\", \"/storage/External\", \"/storage/test\" ] \ }] \ }"; - nlohmann::json j_config = nlohmann::json::parse(mJsconfig.c_str()); - const char *mountPath = "mount-paths"; - nlohmann::json j_secondConfig = j_config[mountPath][0]; - std::string section = "permission"; - OHOS::AppSpawn::SandboxUtils::StoreJsonConfig(j_config, SANBOX_APP_JSON_CONFIG); - OHOS::AppSpawn::SandboxUtils::SandboxMountConfig mountConfig; + cJSON *j_config = cJSON_Parse(mJsconfig.c_str()); + ASSERT_NE(j_config, nullptr); + AppSpawn::SandboxCommon::StoreCJsonConfig(j_config, SandboxCommonDef::SANDBOX_APP_JSON_CONFIG); + + int ret = 0; AppSpawningCtx *appProperty = GetTestAppProperty(); - OHOS::AppSpawn::SandboxUtils::GetSandboxMountConfig(appProperty, section, j_secondConfig, mountConfig); - int decPathSize = mountConfig.decPaths.size(); - EXPECT_EQ(decPathSize, DEC_PATH_SIZE); - OHOS::AppSpawn::SandboxUtils::SetDecPolicyWithPermission(appProperty, mountConfig); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_dec_03 end"; + do { + cJSON *mountPoints = cJSON_GetObjectItemCaseSensitive(j_config, "mount-paths"); + APPSPAWN_CHECK(mountPoints != nullptr || cJSON_IsArray(mountPoints), ret = -1; + break, "Invalid mountPaths config"); + + for (int i = 0; i < cJSON_GetArraySize(mountPoints); ++i) { + cJSON *mntPoint = cJSON_GetArrayItem(mountPoints, i); + APPSPAWN_CHECK(mntPoint != nullptr, ret = -2; break, "Invalid mntPoint config"); + SandboxMountConfig mountConfig = {0}; + AppSpawn::SandboxCommon::GetSandboxMountConfig(appProperty, "permission", mntPoint, mountConfig); + + int decPathSize = mountConfig.decPaths.size(); + EXPECT_EQ(decPathSize, DEC_PATH_SIZE); + ret = AppSpawn::SandboxCore::SetDecPolicyWithPermission(appProperty, mountConfig); + } + EXPECT_EQ(ret, 0); + } while (0); + + cJSON_Delete(j_config); + DeleteAppSpawningCtx(appProperty); } /** @@ -1660,7 +1771,6 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_dec_03, TestSize.Level0) */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_dec_04, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_dec_04 start"; std::string mJsconfig = "{ \ \"mount-paths\": [{ \ \"src-path\": \"\", \ @@ -1669,21 +1779,33 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_dec_04, TestSize.Level0) \"dec-paths\": [ \"/storage/Users\", \"/storage/External\", \"/storage/test\" ] \ }] \ }"; - nlohmann::json j_config = nlohmann::json::parse(mJsconfig.c_str()); - const char *mountPath = "mount-paths"; - nlohmann::json j_secondConfig = j_config[mountPath][0]; - std::string section = "permission"; - OHOS::AppSpawn::SandboxUtils::StoreJsonConfig(j_config, SANBOX_APP_JSON_CONFIG); - OHOS::AppSpawn::SandboxUtils::SandboxMountConfig mountConfig; - AppSpawningCtx *appProperty = GetTestAppProperty(); - OHOS::AppSpawn::SandboxUtils::GetSandboxMountConfig(appProperty, section, j_secondConfig, mountConfig); - int decPathSize = mountConfig.decPaths.size(); - EXPECT_EQ(decPathSize, DEC_PATH_SIZE); + cJSON *j_config = cJSON_Parse(mJsconfig.c_str()); + ASSERT_NE(j_config, nullptr); + AppSpawn::SandboxCommon::StoreCJsonConfig(j_config, SandboxCommonDef::SANDBOX_APP_JSON_CONFIG); - int ret = OHOS::AppSpawn::SandboxUtils::DoAllMntPointsMount(appProperty, j_config, nullptr, "permission"); + int ret = 0; + AppSpawningCtx *appProperty = GetTestAppProperty(); + do { + cJSON *mountPoints = cJSON_GetObjectItemCaseSensitive(j_config, "mount-paths"); + APPSPAWN_CHECK(mountPoints != nullptr || cJSON_IsArray(mountPoints), ret = -1; + break, "Invalid mountPaths config"); + + for (int i = 0; i < cJSON_GetArraySize(mountPoints); ++i) { + cJSON *mntPoint = cJSON_GetArrayItem(mountPoints, i); + APPSPAWN_CHECK(mntPoint != nullptr, ret = -2; break, "Invalid mntPoint config"); + SandboxMountConfig mountConfig = {0}; + AppSpawn::SandboxCommon::GetSandboxMountConfig(appProperty, "permission", mntPoint, mountConfig); + + int decPathSize = mountConfig.decPaths.size(); + EXPECT_EQ(decPathSize, DEC_PATH_SIZE); + } + EXPECT_EQ(ret, 0); + } while (0); + ret = AppSpawn::SandboxCore::DoAllMntPointsMount(appProperty, j_config, nullptr, "permission"); EXPECT_EQ(ret, 0); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_dec_04 end"; + cJSON_Delete(j_config); + DeleteAppSpawningCtx(appProperty); } /** @@ -1694,7 +1816,6 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_dec_04, TestSize.Level0) */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_dec_05, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_dec_05 start"; std::string mJsconfig = "{ \ \"mount-paths\": [{ \ \"src-path\": \"\", \ @@ -1703,21 +1824,33 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_dec_05, TestSize.Level0) \"dec-paths\": [ \"/storage/Users//Download\" ] \ }] \ }"; - nlohmann::json j_config = nlohmann::json::parse(mJsconfig.c_str()); - const char *mountPath = "mount-paths"; - nlohmann::json j_secondConfig = j_config[mountPath][0]; - std::string section = "permission"; - OHOS::AppSpawn::SandboxUtils::StoreJsonConfig(j_config, SANBOX_APP_JSON_CONFIG); - OHOS::AppSpawn::SandboxUtils::SandboxMountConfig mountConfig; - AppSpawningCtx *appProperty = GetTestAppProperty(); - OHOS::AppSpawn::SandboxUtils::GetSandboxMountConfig(appProperty, section, j_secondConfig, mountConfig); - int decPathSize = mountConfig.decPaths.size(); - EXPECT_EQ(decPathSize, 1); + cJSON *j_config = cJSON_Parse(mJsconfig.c_str()); + ASSERT_NE(j_config, nullptr); + AppSpawn::SandboxCommon::StoreCJsonConfig(j_config, SandboxCommonDef::SANDBOX_APP_JSON_CONFIG); - int ret = OHOS::AppSpawn::SandboxUtils::DoAllMntPointsMount(appProperty, j_config, nullptr, "permission"); + int ret = 0; + AppSpawningCtx *appProperty = GetTestAppProperty(); + do { + cJSON *mountPoints = cJSON_GetObjectItemCaseSensitive(j_config, "mount-paths"); + APPSPAWN_CHECK(mountPoints != nullptr || cJSON_IsArray(mountPoints), ret = -1; + break, "Invalid mountPaths config"); + + for (int i = 0; i < cJSON_GetArraySize(mountPoints); ++i) { + cJSON *mntPoint = cJSON_GetArrayItem(mountPoints, i); + APPSPAWN_CHECK(mntPoint != nullptr, ret = -2; break, "Invalid mntPoint config"); + SandboxMountConfig mountConfig = {0}; + AppSpawn::SandboxCommon::GetSandboxMountConfig(appProperty, "permission", mntPoint, mountConfig); + + int decPathSize = mountConfig.decPaths.size(); + EXPECT_EQ(decPathSize, 1); + } + EXPECT_EQ(ret, 0); + } while (0); + ret = AppSpawn::SandboxCore::DoAllMntPointsMount(appProperty, j_config, nullptr, "permission"); EXPECT_EQ(ret, 0); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_dec_05 end"; + cJSON_Delete(j_config); + DeleteAppSpawningCtx(appProperty); } /** @@ -1728,24 +1861,22 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_dec_05, TestSize.Level0) */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_dec_06, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_dec_06 start"; AppSpawningCtx *appProperty = GetTestAppProperty(); - OHOS::AppSpawn::SandboxUtils::SetDecDenyWithDir(appProperty); + AppSpawn::SandboxCore::SetDecDenyWithDir(appProperty); int32_t userFileIndex = GetPermissionIndex(nullptr, "ohos.permission.READ_WRITE_USER_FILE"); ASSERT_NE(userFileIndex, 0); int ret = SetAppPermissionFlags(appProperty, userFileIndex); ASSERT_EQ(ret, 0); - OHOS::AppSpawn::SandboxUtils::SetDecDenyWithDir(appProperty); + AppSpawn::SandboxCore::SetDecDenyWithDir(appProperty); int32_t downloadIndex = GetPermissionIndex(nullptr, "ohos.permission.READ_WRITE_DOWNLOAD_DIRECTORY"); ASSERT_NE(downloadIndex, 0); ret = SetAppPermissionFlags(appProperty, downloadIndex); ASSERT_EQ(ret, 0); - OHOS::AppSpawn::SandboxUtils::SetDecDenyWithDir(appProperty); + AppSpawn::SandboxCore::SetDecDenyWithDir(appProperty); DeleteAppSpawningCtx(appProperty); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_dec_06 end"; } /** @@ -1756,7 +1887,6 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_dec_06, TestSize.Level0) */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_01, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_01 start"; char dataGroupInfoListStr[] = R"( { "gid": "1002", @@ -1765,10 +1895,12 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_01, TestSize.Level0 "uuid": "49c016e6-065a-abd1-5867-b1f91114f840" } )"; - nlohmann::json j_config = nlohmann::json::parse(dataGroupInfoListStr); + cJSON *j_config = cJSON_Parse(dataGroupInfoListStr); + ASSERT_NE(j_config, nullptr); bool ret = IsValidDataGroupItem(j_config); EXPECT_TRUE(ret); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_01 end"; + + cJSON_Delete(j_config); } /** @@ -1779,7 +1911,6 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_01, TestSize.Level0 */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_02, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_02 start"; char dataGroupInfoListStr[] = R"([ { "gid": "1002", @@ -1794,16 +1925,19 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_02, TestSize.Level0 "uuid": "49c016e6-065a-abd1-5867-b1f91114f840" } ])"; - nlohmann::json j_config = nlohmann::json::parse(dataGroupInfoListStr); + cJSON *j_config = cJSON_Parse(dataGroupInfoListStr); + ASSERT_NE(j_config, nullptr); bool ret = false; - for (auto& item : j_config) { - ret = IsValidDataGroupItem(item); - if (ret != true) { + cJSON *child = nullptr; + cJSON_ArrayForEach(child, j_config) { + ret = IsValidDataGroupItem(child); + if (!ret) { break; } } EXPECT_TRUE(ret); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_02 end"; + + cJSON_Delete(j_config); } /** @@ -1814,7 +1948,6 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_02, TestSize.Level0 */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_03, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_03 start"; char dataGroupInfoListStr[] = R"( { "gid": "1002", @@ -1823,10 +1956,12 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_03, TestSize.Level0 "uuid": "49c016e6-065a-abd1-5867-b1f91114f840" } )"; - nlohmann::json j_config = nlohmann::json::parse(dataGroupInfoListStr); + cJSON *j_config = cJSON_Parse(dataGroupInfoListStr); + ASSERT_NE(j_config, nullptr); bool ret = IsValidDataGroupItem(j_config); EXPECT_FALSE(ret); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_03 end"; + + cJSON_Delete(j_config); } /** @@ -1837,7 +1972,6 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_03, TestSize.Level0 */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_04, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_04 start"; char dataGroupInfoListStr[] = R"( { "gid": 1002, @@ -1846,10 +1980,12 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_04, TestSize.Level0 "uuid": "49c016e6-065a-abd1-5867-b1f91114f840" } )"; - nlohmann::json j_config = nlohmann::json::parse(dataGroupInfoListStr); + cJSON *j_config = cJSON_Parse(dataGroupInfoListStr); + ASSERT_NE(j_config, nullptr); bool ret = IsValidDataGroupItem(j_config); EXPECT_FALSE(ret); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_04 end"; + + cJSON_Delete(j_config); } /** @@ -1860,7 +1996,6 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_04, TestSize.Level0 */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_05, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_05 start"; char dataGroupInfoListStr[] = R"( { "gid": "1002", @@ -1869,10 +2004,12 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_05, TestSize.Level0 "uuid": "49c016e6-065a-abd1-5867-b1f91114f840" } )"; - nlohmann::json j_config = nlohmann::json::parse(dataGroupInfoListStr); + cJSON *j_config = cJSON_Parse(dataGroupInfoListStr); + ASSERT_NE(j_config, nullptr); bool ret = IsValidDataGroupItem(j_config); EXPECT_FALSE(ret); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_05 end"; + + cJSON_Delete(j_config); } /** @@ -1883,7 +2020,6 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_05, TestSize.Level0 */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_06, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_06 start"; char dataGroupInfoListStr[] = R"( { "gid": "1002", @@ -1892,10 +2028,12 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_06, TestSize.Level0 "uuid": 124 } )"; - nlohmann::json j_config = nlohmann::json::parse(dataGroupInfoListStr); + cJSON *j_config = cJSON_Parse(dataGroupInfoListStr); + ASSERT_NE(j_config, nullptr); bool ret = IsValidDataGroupItem(j_config); EXPECT_FALSE(ret); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_06 end"; + + cJSON_Delete(j_config); } /** @@ -1906,7 +2044,6 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_06, TestSize.Level0 */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_07, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_07 start"; char dataGroupInfoListStr[] = R"( { "gid": 1002, @@ -1915,10 +2052,12 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_07, TestSize.Level0 "uuid": "49c016e6-065a-abd1-5867-b1f91114f840" } )"; - nlohmann::json j_config = nlohmann::json::parse(dataGroupInfoListStr); + cJSON *j_config = cJSON_Parse(dataGroupInfoListStr); + ASSERT_NE(j_config, nullptr); bool ret = IsValidDataGroupItem(j_config); EXPECT_FALSE(ret); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_07 end"; + + cJSON_Delete(j_config); } /** @@ -1929,7 +2068,6 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_07, TestSize.Level0 */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_08, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_08 start"; char dataGroupInfoListStr[] = R"( { "gid": "1002", @@ -1938,10 +2076,12 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_08, TestSize.Level0 "uuid": "49c016e6-065a-abd1-5867-b1f91114f840" } )"; - nlohmann::json j_config = nlohmann::json::parse(dataGroupInfoListStr); + cJSON *j_config = cJSON_Parse(dataGroupInfoListStr); + ASSERT_NE(j_config, nullptr); bool ret = IsValidDataGroupItem(j_config); EXPECT_FALSE(ret); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_08 end"; + + cJSON_Delete(j_config); } /** @@ -1952,7 +2092,6 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_08, TestSize.Level0 */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_09, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_09 start"; char dataGroupInfoListStr[] = R"( { "gid": "1002", @@ -1961,10 +2100,12 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_09, TestSize.Level0 "uuid": 124 } )"; - nlohmann::json j_config = nlohmann::json::parse(dataGroupInfoListStr); + cJSON *j_config = cJSON_Parse(dataGroupInfoListStr); + ASSERT_NE(j_config, nullptr); bool ret = IsValidDataGroupItem(j_config); EXPECT_FALSE(ret); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_09 end"; + + cJSON_Delete(j_config); } /** @@ -1975,7 +2116,6 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_09, TestSize.Level0 */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_10, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_10 start"; char dataGroupInfoListStr[] = R"( { "gid": 1002, @@ -1984,10 +2124,12 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_10, TestSize.Level0 "uuid": "49c016e6-065a-abd1-5867-b1f91114f840" } )"; - nlohmann::json j_config = nlohmann::json::parse(dataGroupInfoListStr); + cJSON *j_config = cJSON_Parse(dataGroupInfoListStr); + ASSERT_NE(j_config, nullptr); bool ret = IsValidDataGroupItem(j_config); EXPECT_FALSE(ret); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_10 end"; + + cJSON_Delete(j_config); } /** @@ -1998,7 +2140,6 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_10, TestSize.Level0 */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_11, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_11 start"; char dataGroupInfoListStr[] = R"( { "gid": 1002, @@ -2007,10 +2148,12 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_11, TestSize.Level0 "uuid": 124 } )"; - nlohmann::json j_config = nlohmann::json::parse(dataGroupInfoListStr); + cJSON *j_config = cJSON_Parse(dataGroupInfoListStr); + ASSERT_NE(j_config, nullptr); bool ret = IsValidDataGroupItem(j_config); EXPECT_FALSE(ret); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_11 end"; + + cJSON_Delete(j_config); } /** @@ -2021,7 +2164,6 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_11, TestSize.Level0 */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_12, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_12 start"; char dataGroupInfoListStr[] = R"( { "gid": "1002", @@ -2030,10 +2172,12 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_12, TestSize.Level0 "uuid": 124 } )"; - nlohmann::json j_config = nlohmann::json::parse(dataGroupInfoListStr); + cJSON *j_config = cJSON_Parse(dataGroupInfoListStr); + ASSERT_NE(j_config, nullptr); bool ret = IsValidDataGroupItem(j_config); EXPECT_FALSE(ret); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_12 end"; + + cJSON_Delete(j_config); } /** @@ -2044,11 +2188,9 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_12, TestSize.Level0 */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_13, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_13 start"; std::string str = "/data/storage/el2/group/"; int res = GetElxInfoFromDir(str.c_str()); EXPECT_EQ(res, EL2); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_13 end"; } /** @@ -2059,11 +2201,9 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_13, TestSize.Level0 */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_14, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_14 start"; std::string str = "/data/storage/el3/group/"; int res = GetElxInfoFromDir(str.c_str()); EXPECT_EQ(res, EL3); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_14 end"; } /** @@ -2074,11 +2214,9 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_14, TestSize.Level0 */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_15, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_15 start"; std::string str = "/data/storage/el4/group/"; int res = GetElxInfoFromDir(str.c_str()); EXPECT_EQ(res, EL4); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_15 end"; } /** @@ -2089,11 +2227,9 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_15, TestSize.Level0 */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_16, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_16 start"; std::string str = "/data/storage/el5/group/"; int res = GetElxInfoFromDir(str.c_str()); EXPECT_EQ(res, EL5); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_16 end"; } /** @@ -2104,11 +2240,9 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_16, TestSize.Level0 */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_17, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_17 start"; std::string str = "/data/storage/el0/group/"; int res = GetElxInfoFromDir(str.c_str()); EXPECT_EQ(res, ELX_MAX); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_17 end"; } /** @@ -2119,11 +2253,9 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_17, TestSize.Level0 */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_18, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_18 start"; std::string str = "/data/storage/el6/group/"; int res = GetElxInfoFromDir(str.c_str()); EXPECT_EQ(res, ELX_MAX); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_18 end"; } /** @@ -2134,10 +2266,8 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_18, TestSize.Level0 */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_19, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_19 start"; int res = GetElxInfoFromDir(nullptr); EXPECT_EQ(res, ELX_MAX); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_19 end"; } /** @@ -2148,12 +2278,10 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_19, TestSize.Level0 */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_20, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_20 start"; const DataGroupSandboxPathTemplate *templateItem = GetDataGroupArgTemplate(EL2); ASSERT_EQ(templateItem != nullptr, 1); int res = strcmp(templateItem->elxName, "el2"); EXPECT_EQ(res, 0); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_20 end"; } /** @@ -2164,12 +2292,10 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_20, TestSize.Level0 */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_21, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_21 start"; const DataGroupSandboxPathTemplate *templateItem = GetDataGroupArgTemplate(EL3); ASSERT_EQ(templateItem != nullptr, 1); int res = strcmp(templateItem->elxName, "el3"); EXPECT_EQ(res, 0); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_21 end"; } /** @@ -2180,12 +2306,10 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_21, TestSize.Level0 */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_22, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_22 start"; const DataGroupSandboxPathTemplate *templateItem = GetDataGroupArgTemplate(EL4); ASSERT_EQ(templateItem != nullptr, 1); int res = strcmp(templateItem->elxName, "el4"); EXPECT_EQ(res, 0); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_22 end"; } /** @@ -2196,12 +2320,10 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_22, TestSize.Level0 */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_23, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_23 start"; const DataGroupSandboxPathTemplate *templateItem = GetDataGroupArgTemplate(EL5); ASSERT_EQ(templateItem != nullptr, 1); int res = strcmp(templateItem->elxName, "el5"); EXPECT_EQ(res, 0); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_23 end"; } /** @@ -2212,13 +2334,11 @@ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_23, TestSize.Level0 */ HWTEST_F(AppSpawnSandboxTest, App_Spawn_Sandbox_Shared_Mount_24, TestSize.Level0) { - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_24 start"; const DataGroupSandboxPathTemplate *templateItem = GetDataGroupArgTemplate(6); int res = -1; if (templateItem == nullptr) { res = 0; } EXPECT_EQ(res, 0); - GTEST_LOG_(INFO) << "App_Spawn_Sandbox_Shared_Mount_24 end"; } } // namespace OHOS diff --git a/test/unittest/app_spawn_standard_test/app_spawn_service_test.cpp b/test/unittest/app_spawn_standard_test/app_spawn_service_test.cpp index 9f5dfe1b4be5c241c1718657f4fbfa54588742f3..6a920439b95c77717a9215bbb45be3601ef1ea85 100644 --- a/test/unittest/app_spawn_standard_test/app_spawn_service_test.cpp +++ b/test/unittest/app_spawn_standard_test/app_spawn_service_test.cpp @@ -63,34 +63,27 @@ public: }; /** - * @brief 正常消息发送和接收,完整应用孵化过程 + * @brief 向appspawn发送MSG_APP_SPAWN类型的消息 + * @note 预期结果:appspawn接收到请求消息,孵化应用进程 * */ -HWTEST_F(AppSpawnServiceTest, App_Spawn_001, TestSize.Level0) +HWTEST_F(AppSpawnServiceTest, App_Spawn_MSG_APP_SPAWN_001, TestSize.Level0) { int ret = 0; AppSpawnClientHandle clientHandle = nullptr; do { - APPSPAWN_LOGV("App_Spawn_001 start"); ret = AppSpawnClientInit(APPSPAWN_SERVER_NAME, &clientHandle); APPSPAWN_CHECK(ret == 0, break, "Failed to create client %{public}s", APPSPAWN_SERVER_NAME); AppSpawnReqMsgHandle reqHandle = testServer->CreateMsg(clientHandle, MSG_APP_SPAWN, 0); - AppSpawnReqMsgSetAppFlag(reqHandle, APP_FLAGS_NO_SANDBOX); - AppSpawnReqMsgSetAppFlag(reqHandle, APP_FLAGS_DEBUGGABLE); - AppSpawnReqMsgSetAppFlag(reqHandle, APP_FLAGS_NATIVEDEBUG); - AppSpawnReqMsgSetAppFlag(reqHandle, APP_FLAGS_BUNDLE_RESOURCES); - AppSpawnReqMsgSetAppFlag(reqHandle, APP_FLAGS_ACCESS_BUNDLE_DIR); - AppSpawnResult result = {}; ret = AppSpawnClientSendMsg(clientHandle, reqHandle, &result); - APPSPAWN_LOGV("App_Spawn_001 recv result %{public}d %{public}d", result.result, result.pid); - APPSPAWN_CHECK(ret == 0, break, "Failed to send msg %{public}d", ret); - if (ret == 0 && result.pid > 0) { - APPSPAWN_LOGV("App_Spawn_001 Kill pid %{public}d ", result.pid); - DumpSpawnStack(result.pid); - kill(result.pid, SIGKILL); - } + APPSPAWN_CHECK(ret == 0 && result.pid > 0, ret = -1; + break, "Failed to send MSG_APP_SPAWN, ret %{public}d pid %{public}d", ret, result.pid); + + DumpSpawnStack(result.pid); + ret = kill(result.pid, SIGKILL); + APPSPAWN_CHECK(ret == 0, break, "unable to kill pid %{public}d, err %{public}d", result.pid, errno); } while (0); AppSpawnClientDestroy(clientHandle); @@ -98,33 +91,100 @@ HWTEST_F(AppSpawnServiceTest, App_Spawn_001, TestSize.Level0) } /** - * @brief 模拟测试,孵化进程退出后,MSG_GET_RENDER_TERMINATION_STATUS + * @brief 通过多线程模拟多个客户端向appspawn发送MSG_APP_SPAWN类型的消息 + * @note 预期结果:appspawn接收到请求消息,逐个孵化应用进程 * */ -HWTEST_F(AppSpawnServiceTest, App_Spawn_002, TestSize.Level0) +HWTEST_F(AppSpawnServiceTest, App_Spawn_MSG_APP_SPAWN_002, TestSize.Level0) +{ + int ret = 0; + AppSpawnClientHandle clientHandle = nullptr; + do { + ret = AppSpawnClientInit(APPSPAWN_SERVER_NAME, &clientHandle); + APPSPAWN_CHECK(ret == 0, break, "Failed to create client %{public}s", APPSPAWN_SERVER_NAME); + + auto sendMsg = [this, &ret](AppSpawnClientHandle clientHandle) { + AppSpawnReqMsgHandle reqHandle = testServer->CreateMsg(clientHandle, MSG_APP_SPAWN, 0); + + AppSpawnResult result = {}; + ret = AppSpawnClientSendMsg(clientHandle, reqHandle, &result); + APPSPAWN_CHECK(ret == 0 && result.pid > 0, ret = -1; + return, "Failed to send MSG_APP_SPAWN, ret %{public}d pid %{public}d", ret, result.pid); + + ret = kill(result.pid, SIGKILL); + APPSPAWN_CHECK(ret == 0, return, "unable to kill pid %{public}d, err %{public}d", result.pid, errno); + }; + std::thread thread1(sendMsg, clientHandle); + std::thread thread2(sendMsg, clientHandle); + std::thread thread3(sendMsg, clientHandle); + std::thread thread4(sendMsg, clientHandle); + std::thread thread5(sendMsg, clientHandle); + thread1.join(); + thread2.join(); + thread3.join(); + thread4.join(); + thread5.join(); + } while (0); + + AppSpawnClientDestroy(clientHandle); + ASSERT_EQ(ret, 0); +} + +/** + * @brief appspawn孵化的应用进程退出后,向appspawn发送MSG_GET_RENDER_TERMINATION_STATUS类型的消息 + * @note 预期结果:appspawn不支持处理该类型消息,不会根据消息中传入的pid去查询进程的退出状态 + * + */ +HWTEST_F(AppSpawnServiceTest, App_Spawn_MSG_GET_RENDER_TERMINATION_STATUS_001, TestSize.Level0) { int ret = 0; AppSpawnClientHandle clientHandle = nullptr; do { - APPSPAWN_LOGV("App_Spawn_002 start"); ret = AppSpawnClientInit(APPSPAWN_SERVER_NAME, &clientHandle); APPSPAWN_CHECK(ret == 0, break, "Failed to create client %{public}s", APPSPAWN_SERVER_NAME); AppSpawnReqMsgHandle reqHandle = testServer->CreateMsg(clientHandle, MSG_APP_SPAWN, 0); + AppSpawnResult result = {}; ret = AppSpawnClientSendMsg(clientHandle, reqHandle, &result); - APPSPAWN_LOGV("App_Spawn_002 recv result %{public}d %{public}d", result.result, result.pid); - if (ret != 0 || result.pid == 0) { - ret = -1; - break; - } - // stop child and termination - APPSPAWN_LOGI("App_Spawn_002 Kill pid %{public}d ", result.pid); - kill(result.pid, SIGKILL); - // MSG_GET_RENDER_TERMINATION_STATUS - ret = AppSpawnTerminateMsgCreate(result.pid, &reqHandle); + APPSPAWN_CHECK(ret == 0 && result.pid > 0, ret = -1; + break, "Failed to send MSG_APP_SPAWN, ret %{public}d pid %{public}d", ret, result.pid); + + ret = kill(result.pid, SIGKILL); + APPSPAWN_CHECK(ret == 0, break, "unable to kill pid %{public}d, err %{public}d", result.pid, errno); + + ret = AppSpawnTerminateMsgCreate(result.pid, &reqHandle); // MSG_GET_RENDER_TERMINATION_STATUS APPSPAWN_CHECK(ret == 0, break, "Failed to create termination msg %{public}s", APPSPAWN_SERVER_NAME); + + ret = AppSpawnClientSendMsg(clientHandle, reqHandle, &result); + APPSPAWN_CHECK(ret == 0 && result.result == APPSPAWN_MSG_INVALID, ret = -1; + break, "Failed to send MSG_GET_RENDER_TERMINATION_STATUS, ret %{public}d", ret); + } while (0); + + AppSpawnClientDestroy(clientHandle); + ASSERT_EQ(ret, 0); +} + +/** + * @brief 向appspawn发送MSG_SPAWN_NATIVE_PROCESS类型的消息 + * @note 预期结果:appspawn接收到请求消息,孵化native进程 + * + */ +HWTEST_F(AppSpawnServiceTest, App_Spawn_MSG_SPAWN_NATIVE_PROCESS_001, TestSize.Level0) +{ + int ret = 0; + AppSpawnClientHandle clientHandle = nullptr; + do { + ret = AppSpawnClientInit(APPSPAWN_SERVER_NAME, &clientHandle); + APPSPAWN_CHECK(ret == 0, break, "Failed to create client %{public}s", APPSPAWN_SERVER_NAME); + AppSpawnReqMsgHandle reqHandle = testServer->CreateMsg(clientHandle, MSG_SPAWN_NATIVE_PROCESS, 0); + + AppSpawnResult result = {}; ret = AppSpawnClientSendMsg(clientHandle, reqHandle, &result); - APPSPAWN_LOGV("Send MSG_GET_RENDER_TERMINATION_STATUS %{public}d", ret); + APPSPAWN_CHECK(ret == 0 && result.pid > 0, ret = -1; + break, "Failed to send MSG_SPAWN_NATIVE_PROCESS, ret %{public}d pid %{public}d", ret, result.pid); + + ret = kill(result.pid, SIGKILL); + APPSPAWN_CHECK(ret == 0, break, "unable to kill pid %{public}d, err %{public}d", result.pid, errno); } while (0); AppSpawnClientDestroy(clientHandle); @@ -132,10 +192,11 @@ HWTEST_F(AppSpawnServiceTest, App_Spawn_002, TestSize.Level0) } /** - * @brief 模拟测试,MSG_GET_RENDER_TERMINATION_STATUS 关闭孵化进程 + * @brief appspawn孵化应用进程后,向appspawn发送MSG_DUMP类型的消息 + * @note 预期结果:appspawn接收到请求消息,dump打印出appQueue等信息 * */ -HWTEST_F(AppSpawnServiceTest, App_Spawn_003, TestSize.Level0) +HWTEST_F(AppSpawnServiceTest, App_Spawn_MSG_DUMP_001, TestSize.Level0) { int ret = 0; AppSpawnClientHandle clientHandle = nullptr; @@ -143,18 +204,15 @@ HWTEST_F(AppSpawnServiceTest, App_Spawn_003, TestSize.Level0) ret = AppSpawnClientInit(APPSPAWN_SERVER_NAME, &clientHandle); APPSPAWN_CHECK(ret == 0, break, "Failed to create client %{public}s", APPSPAWN_SERVER_NAME); AppSpawnReqMsgHandle reqHandle = testServer->CreateMsg(clientHandle, MSG_APP_SPAWN, 0); + AppSpawnResult result = {}; ret = AppSpawnClientSendMsg(clientHandle, reqHandle, &result); - APPSPAWN_LOGV("App_Spawn_003 recv result %{public}d %{public}d", result.result, result.pid); - if (ret != 0 || result.pid == 0) { - ret = -1; - break; - } - // MSG_GET_RENDER_TERMINATION_STATUS - ret = AppSpawnTerminateMsgCreate(result.pid, &reqHandle); - APPSPAWN_CHECK(ret == 0, break, "Failed to create termination msg %{public}s", APPSPAWN_SERVER_NAME); + APPSPAWN_CHECK(ret == 0 && result.pid > 0, ret = -1; + break, "Failed to send MSG_APP_SPAWN, ret %{public}d pid %{public}d", ret, result.pid); + + reqHandle = testServer->CreateMsg(clientHandle, MSG_DUMP, 0); ret = AppSpawnClientSendMsg(clientHandle, reqHandle, &result); - APPSPAWN_LOGV("Send MSG_GET_RENDER_TERMINATION_STATUS %{public}d", ret); + APPSPAWN_CHECK(ret == 0, break, "Failed to send MSG_DUMP, ret %{public}d", ret); } while (0); AppSpawnClientDestroy(clientHandle); @@ -162,51 +220,90 @@ HWTEST_F(AppSpawnServiceTest, App_Spawn_003, TestSize.Level0) } /** - * @brief dump 消息 + * @brief 非开发者模式下,向appspawn发送MSG_BEGET_CMD类型的消息 + * @note 预期结果:非开发者模式下,appspawn不支持处理该类型消息,不会根据消息中传入的pid进入应用沙箱 * */ -HWTEST_F(AppSpawnServiceTest, App_Spawn_004, TestSize.Level0) +HWTEST_F(AppSpawnServiceTest, App_Spawn_MSG_BEGET_CMD_001, TestSize.Level0) { int ret = 0; AppSpawnClientHandle clientHandle = nullptr; + SetDeveloperMode(false); do { ret = AppSpawnClientInit(APPSPAWN_SERVER_NAME, &clientHandle); APPSPAWN_CHECK(ret == 0, break, "Failed to create client %{public}s", APPSPAWN_SERVER_NAME); - AppSpawnReqMsgHandle reqHandle = testServer->CreateMsg(clientHandle, MSG_DUMP, 0); + AppSpawnReqMsgHandle reqHandle = testServer->CreateMsg(clientHandle, MSG_APP_SPAWN, 0); + AppSpawnResult result = {}; ret = AppSpawnClientSendMsg(clientHandle, reqHandle, &result); - APPSPAWN_CHECK(ret == 0, break, "Failed to send msg %{public}d", ret); + APPSPAWN_CHECK(ret == 0 && result.pid > 0, ret = -1; + break, "Failed to send MSG_APP_SPAWN, ret %{public}d pid %{public}d", ret, result.pid); + + reqHandle = testServer->CreateMsg(clientHandle, MSG_BEGET_CMD, 0); + ret = AppSpawnReqMsgSetAppFlag(reqHandle, APP_FLAGS_BEGETCTL_BOOT); + APPSPAWN_CHECK(ret == 0, break, "Failed to set msg flag 0x%{public}x", APP_FLAGS_BEGETCTL_BOOT); + ret = AppSpawnReqMsgAddStringInfo(reqHandle, MSG_EXT_NAME_BEGET_PID, std::to_string(result.pid).c_str()); + APPSPAWN_CHECK(ret == 0, break, "Failed to add MSG_EXT_NAME_BEGET_PID %{public}d", result.pid); + ret = AppSpawnReqMsgAddStringInfo(reqHandle, MSG_EXT_NAME_BEGET_PTY_NAME, "/dev/pts/1"); + APPSPAWN_CHECK(ret == 0, break, "Failed to add MSG_EXT_NAME_BEGET_PTY_NAME %{public}s", "/dev/pts/1"); + + ret = AppSpawnClientSendMsg(clientHandle, reqHandle, &result); + APPSPAWN_CHECK(ret == 0 && result.result == APPSPAWN_DEBUG_MODE_NOT_SUPPORT, ret = -1; + break, "Failed to send MSG_BEGET_CMD, ret %{public}d result %{public}d", ret, result.result); } while (0); + SetDeveloperMode(true); AppSpawnClientDestroy(clientHandle); ASSERT_EQ(ret, 0); } /** - * @brief MSG_SPAWN_NATIVE_PROCESS 正常消息发送和接收,完整应用孵化过程 + * @brief 向appspawn发送MSG_BEGET_SPAWNTIME类型的消息 + * @note 预期结果:appspawn接收到请求消息,获取appspawn启动时各hook执行的最小时间(result.result)和最大时间(result.pid) * */ -HWTEST_F(AppSpawnServiceTest, App_Spawn_005, TestSize.Level0) +HWTEST_F(AppSpawnServiceTest, App_Spawn_MSG_BEGET_SPAWNTIME_001, TestSize.Level0) { int ret = 0; AppSpawnClientHandle clientHandle = nullptr; + int minAppspawnTime = 0; + int maxAppspawnTime = APPSPAWN_MAX_TIME; do { ret = AppSpawnClientInit(APPSPAWN_SERVER_NAME, &clientHandle); APPSPAWN_CHECK(ret == 0, break, "Failed to create client %{public}s", APPSPAWN_SERVER_NAME); - AppSpawnReqMsgHandle reqHandle = testServer->CreateMsg(clientHandle, MSG_SPAWN_NATIVE_PROCESS, 0); + AppSpawnReqMsgHandle reqHandle = testServer->CreateMsg(clientHandle, MSG_BEGET_SPAWNTIME, 0); - AppSpawnReqMsgSetAppFlag(reqHandle, APP_FLAGS_DEBUGGABLE); - AppSpawnReqMsgSetAppFlag(reqHandle, APP_FLAGS_NATIVEDEBUG); - AppSpawnReqMsgSetAppFlag(reqHandle, APP_FLAGS_BUNDLE_RESOURCES); - AppSpawnReqMsgSetAppFlag(reqHandle, APP_FLAGS_ACCESS_BUNDLE_DIR); + AppSpawnResult result = {}; + ret = AppSpawnClientSendMsg(clientHandle, reqHandle, &result); + minAppspawnTime = result.result; + maxAppspawnTime = result.pid; + APPSPAWN_CHECK(ret == 0, break, "Failed to send MSG_BEGET_SPAWNTIME, ret %{public}d", ret); + } while (0); + + AppSpawnClientDestroy(clientHandle); + EXPECT_GT(minAppspawnTime, 0); + EXPECT_LT(maxAppspawnTime, APPSPAWN_MAX_TIME); + ASSERT_EQ(ret, 0); +} + +/** + * @brief 向appspawn发送MSG_UPDATE_MOUNT_POINTS类型的消息 + * @note 预期结果:appspawn接收到请求消息,遍历沙箱包名更新挂载点 + * + */ +HWTEST_F(AppSpawnServiceTest, App_Spawn_MSG_UPDATE_MOUNT_POINTS_001, TestSize.Level0) +{ + int ret = 0; + AppSpawnClientHandle clientHandle = nullptr; + do { + ret = AppSpawnClientInit(APPSPAWN_SERVER_NAME, &clientHandle); + APPSPAWN_CHECK(ret == 0, break, "Failed to create client %{public}s", APPSPAWN_SERVER_NAME); + AppSpawnReqMsgHandle reqHandle = testServer->CreateMsg(clientHandle, MSG_UPDATE_MOUNT_POINTS, 0); AppSpawnResult result = {}; ret = AppSpawnClientSendMsg(clientHandle, reqHandle, &result); - APPSPAWN_CHECK(ret == 0, break, "Failed to send msg %{public}d", ret); - if (ret == 0 && result.pid > 0) { - APPSPAWN_LOGI("App_Spawn_005 Kill pid %{public}d ", result.pid); - kill(result.pid, SIGKILL); - } + APPSPAWN_CHECK(ret == 0 && result.result == 0, ret = -1; + break, "Failed to send MSG_UPDATE_MOUNT_POINTS, ret %{public}d result %{public}d", ret, result.result); } while (0); AppSpawnClientDestroy(clientHandle); @@ -214,49 +311,193 @@ HWTEST_F(AppSpawnServiceTest, App_Spawn_005, TestSize.Level0) } /** - * @brief 多线程发送消息 + * @brief 向appspawn发送MSG_RESTART_SPAWNER类型的消息 + * @note 预期结果:appspawn不支持处理该类型消息,返回APPSPAWN_MSG_INVALID * */ -HWTEST_F(AppSpawnServiceTest, App_Spawn_006, TestSize.Level0) +HWTEST_F(AppSpawnServiceTest, App_Spawn_MSG_RESTART_SPAWNER_001, TestSize.Level0) { int ret = 0; AppSpawnClientHandle clientHandle = nullptr; do { ret = AppSpawnClientInit(APPSPAWN_SERVER_NAME, &clientHandle); APPSPAWN_CHECK(ret == 0, break, "Failed to create client %{public}s", APPSPAWN_SERVER_NAME); - auto sendMsg = [this](AppSpawnClientHandle clientHandle) { - AppSpawnReqMsgHandle reqHandle = testServer->CreateMsg(clientHandle, MSG_SPAWN_NATIVE_PROCESS, 0); + AppSpawnReqMsgHandle reqHandle = testServer->CreateMsg(clientHandle, MSG_RESTART_SPAWNER, 0); - AppSpawnReqMsgSetAppFlag(reqHandle, APP_FLAGS_DEBUGGABLE); - AppSpawnReqMsgSetAppFlag(reqHandle, APP_FLAGS_NATIVEDEBUG); - AppSpawnReqMsgSetAppFlag(reqHandle, APP_FLAGS_BUNDLE_RESOURCES); - AppSpawnReqMsgSetAppFlag(reqHandle, APP_FLAGS_ACCESS_BUNDLE_DIR); + AppSpawnResult result = {}; + ret = AppSpawnClientSendMsg(clientHandle, reqHandle, &result); + APPSPAWN_CHECK(ret == 0 && result.result == APPSPAWN_MSG_INVALID, ret = -1; + break, "Failed to send MSG_RESTART_SPAWNER, ret %{public}d result %{public}d", ret, result.result); + } while (0); - AppSpawnResult result = {}; - int ret = AppSpawnClientSendMsg(clientHandle, reqHandle, &result); - APPSPAWN_CHECK(ret == 0, return, "Failed to send msg %{public}d", ret); - if (ret == 0 && result.pid > 0) { - printf("App_Spawn_006 Kill pid %d \n", result.pid); - kill(result.pid, SIGKILL); - } - ASSERT_EQ(ret, 0); - }; - std::thread thread1(sendMsg, clientHandle); - std::thread thread2(sendMsg, clientHandle); - std::thread thread3(sendMsg, clientHandle); - std::thread thread4(sendMsg, clientHandle); - std::thread thread5(sendMsg, clientHandle); + AppSpawnClientDestroy(clientHandle); + ASSERT_EQ(ret, 0); +} - thread1.join(); - thread2.join(); - thread3.join(); - thread4.join(); - thread5.join(); +/** + * @brief appspawn孵化debuggable应用后,向appspawn发送MSG_DEVICE_DEBUG类型的消息 + * @note 预期结果:appspawn接收到请求消息,根据消息中传入的debuggable应用pid和signal杀死先前孵化的应用 + * + */ +HWTEST_F(AppSpawnServiceTest, App_Spawn_MSG_DEVICE_DEBUG_001, TestSize.Level0) +{ + int ret = 0; + AppSpawnClientHandle clientHandle = nullptr; + do { + ret = AppSpawnClientInit(APPSPAWN_SERVER_NAME, &clientHandle); + APPSPAWN_CHECK(ret == 0, break, "Failed to create client %{public}s", APPSPAWN_SERVER_NAME); + AppSpawnReqMsgHandle reqHandle = testServer->CreateMsg(clientHandle, MSG_APP_SPAWN, 0); + ret = AppSpawnReqMsgSetAppFlag(reqHandle, APP_FLAGS_DEBUGGABLE); + APPSPAWN_CHECK(ret == 0, break, "Failed to set msg flag 0x%{public}x", APP_FLAGS_DEBUGGABLE); + + AppSpawnResult result = {}; + ret = AppSpawnClientSendMsg(clientHandle, reqHandle, &result); + APPSPAWN_CHECK(ret == 0 && result.pid > 0, ret = -1; + break, "Failed to send MSG_APP_SPAWN, ret %{public}d pid %{public}d", ret, result.pid); + + reqHandle = testServer->CreateMsg(clientHandle, MSG_DEVICE_DEBUG, 0); + char buffer[256] = {0}; + ret = snprintf_s(buffer, sizeof(buffer), sizeof(buffer) - 1, + "{ \"app\": %d, \"op\": \"kill\", \"args\": { \"signal\": 9 } }", result.pid); + APPSPAWN_CHECK(ret > 0, ret = -1; + break, "Failed to snprintf_s devicedebug extra info, err %{public}d", errno); + ret = AppSpawnReqMsgAddStringInfo(reqHandle, "devicedebug", buffer); + APPSPAWN_CHECK(ret == 0, break, "Failed to add devicedebug extra info %{public}s", buffer); + + ret = AppSpawnClientSendMsg(clientHandle, reqHandle, &result); + APPSPAWN_CHECK(ret == 0 && result.result == 0, ret = -1; + break, "Failed to send MSG_DEVICE_DEBUG, ret %{public}d result %{public}d", ret, result.result); + } while (0); + + AppSpawnClientDestroy(clientHandle); + ASSERT_EQ(ret, 0); +} + +/** + * @brief appspawn孵化非debuggable应用后,向appspawn发送MSG_DEVICE_DEBUG类型的消息 + * @note 预期结果:appspawn接收到请求消息,但不支持向非debuggable应用发送signal + * + */ +HWTEST_F(AppSpawnServiceTest, App_Spawn_MSG_DEVICE_DEBUG_002, TestSize.Level0) +{ + int ret = 0; + AppSpawnClientHandle clientHandle = nullptr; + do { + ret = AppSpawnClientInit(APPSPAWN_SERVER_NAME, &clientHandle); + APPSPAWN_CHECK(ret == 0, break, "Failed to create client %{public}s", APPSPAWN_SERVER_NAME); + AppSpawnReqMsgHandle reqHandle = testServer->CreateMsg(clientHandle, MSG_APP_SPAWN, 0); + + AppSpawnResult result = {}; + ret = AppSpawnClientSendMsg(clientHandle, reqHandle, &result); + APPSPAWN_CHECK(ret == 0 && result.pid > 0, ret = -1; + break, "Failed to send MSG_APP_SPAWN, ret %{public}d pid %{public}d", ret, result.pid); + + reqHandle = testServer->CreateMsg(clientHandle, MSG_DEVICE_DEBUG, 0); + char buffer[256] = {0}; + ret = snprintf_s(buffer, sizeof(buffer), sizeof(buffer) - 1, + "{ \"app\": %d, \"op\": \"kill\", \"args\": { \"signal\": 9 } }", result.pid); + APPSPAWN_CHECK(ret > 0, ret = -1; + break, "Failed to snprintf_s devicedebug extra info, err %{public}d", errno); + ret = AppSpawnReqMsgAddStringInfo(reqHandle, "devicedebug", buffer); + APPSPAWN_CHECK(ret == 0, break, "Failed to add devicedebug extra info %{public}s", buffer); + + ret = AppSpawnClientSendMsg(clientHandle, reqHandle, &result); + APPSPAWN_CHECK(ret == 0 && result.result == APPSPAWN_DEVICEDEBUG_ERROR_APP_NOT_DEBUGGABLE, ret = -1; + break, "Failed to send MSG_DEVICE_DEBUG, ret %{public}d result %{public}d", ret, result.result); + } while (0); + + AppSpawnClientDestroy(clientHandle); + ASSERT_EQ(ret, 0); +} + +/** + * @brief appspawn孵化带debug沙箱的应用后,向appspawn发送MSG_UNINSTALL_DEBUG_HAP类型的消息 + * @note 预期结果:appspawn接收到请求消息,卸载掉指定用户下的所有debug沙箱 + * + */ +HWTEST_F(AppSpawnServiceTest, App_Spawn_MSG_UNINSTALL_DEBUG_HAP_001, TestSize.Level0) +{ + int ret = 0; + AppSpawnClientHandle clientHandle = nullptr; + do { + ret = AppSpawnClientInit(APPSPAWN_SERVER_NAME, &clientHandle); + APPSPAWN_CHECK(ret == 0, break, "Failed to create client %{public}s", APPSPAWN_SERVER_NAME); + AppSpawnReqMsgHandle reqHandle = testServer->CreateMsg(clientHandle, MSG_APP_SPAWN, 0); + ret = AppSpawnReqMsgAddStringInfo(reqHandle, MSG_EXT_NAME_PROVISION_TYPE, "debug"); + APPSPAWN_CHECK(ret == 0, break, "Failed to add MSG_EXT_NAME_PROVISION_TYPE %{public}s", "debug"); + + AppSpawnResult result = {}; + ret = AppSpawnClientSendMsg(clientHandle, reqHandle, &result); + APPSPAWN_CHECK(ret == 0 && result.pid > 0, ret = -1; + break, "Failed to send MSG_APP_SPAWN, ret %{public}d pid %{public}d", ret, result.pid); + + reqHandle = testServer->CreateMsg(clientHandle, MSG_UNINSTALL_DEBUG_HAP, 0); + ret = AppSpawnReqMsgAddStringInfo(reqHandle, MSG_EXT_NAME_USERID, "100"); + APPSPAWN_CHECK(ret == 0, break, "Failed to add MSG_EXT_NAME_USERID %{public}s", "100"); + + ret = AppSpawnClientSendMsg(clientHandle, reqHandle, &result); + APPSPAWN_CHECK(ret == 0 && result.result == 0, ret = -1; + break, "Failed to send MSG_UNINSTALL_DEBUG_HAP, ret %{public}d result %{public}d", ret, result.result); } while (0); + AppSpawnClientDestroy(clientHandle); ASSERT_EQ(ret, 0); } +/** + * @brief 向appspawn发送MSG_LOCK_STATUS类型的消息 + * @note 预期结果:appspawn接收到请求消息,根据消息中的传入的解锁状态对lockstatus参数进行设值 + * + */ +HWTEST_F(AppSpawnServiceTest, App_Spawn_MSG_LOCK_STATUS_001, TestSize.Level0) +{ + int ret = 0; + AppSpawnClientHandle clientHandle = nullptr; + do { + ret = AppSpawnClientInit(APPSPAWN_SERVER_NAME, &clientHandle); + APPSPAWN_CHECK(ret == 0, break, "Failed to create client %{public}s", APPSPAWN_SERVER_NAME); + AppSpawnReqMsgHandle reqHandle = testServer->CreateMsg(clientHandle, MSG_LOCK_STATUS, 0); + + char lockstatus[8] = {0}; + ret = snprintf_s(lockstatus, sizeof(lockstatus), sizeof(lockstatus) - 1, "%u:%d", 100, 0); + APPSPAWN_CHECK(ret > 0, ret = -1; + break, "Failed to snprintf_s lockstatus extra info, err %{public}d", errno); + ret = AppSpawnReqMsgAddStringInfo(reqHandle, "lockstatus", lockstatus); + APPSPAWN_CHECK(ret == 0, break, "Failed to add lockstatus extra info %{public}s", lockstatus); + + AppSpawnResult result = {}; + ret = AppSpawnClientSendMsg(clientHandle, reqHandle, &result); + APPSPAWN_CHECK(ret == 0 && result.result == 0, ret = -1; + break, "Failed to send MSG_LOCK_STATUS, ret %{public}d result %{public}d", ret, result.result); + } while (0); + + AppSpawnClientDestroy(clientHandle); + ASSERT_EQ(ret, 0); +} + +/** + * @brief 向appspawn发送MAX_TYPE_INVALID类型的消息 + * @note 预期结果:不支持创建该类型消息,发送失败,appspawn接收不到该消息请求 + * + */ +HWTEST_F(AppSpawnServiceTest, App_Spawn_MAX_TYPE_INVALID_001, TestSize.Level0) +{ + int ret = 0; + AppSpawnClientHandle clientHandle = nullptr; + do { + ret = AppSpawnClientInit(APPSPAWN_SERVER_NAME, &clientHandle); + APPSPAWN_CHECK(ret == 0, break, "Failed to create client %{public}s", APPSPAWN_SERVER_NAME); + AppSpawnReqMsgHandle reqHandle = testServer->CreateMsg(clientHandle, MAX_TYPE_INVALID, 0); + + AppSpawnResult result = {}; + ret = AppSpawnClientSendMsg(clientHandle, reqHandle, &result); + APPSPAWN_CHECK(ret == APPSPAWN_ARG_INVALID, break, "Failed to send MAX_TYPE_INVALID, ret %{public}d", ret); + } while (0); + + AppSpawnClientDestroy(clientHandle); + ASSERT_EQ(ret, APPSPAWN_ARG_INVALID); +} + HWTEST_F(AppSpawnServiceTest, App_Spawn_Msg_001, TestSize.Level0) { int ret = -1; diff --git a/test/unittest/app_spawn_standard_test/app_spawn_silk_test.cpp b/test/unittest/app_spawn_standard_test/app_spawn_silk_test.cpp index a95e9db0e6e86e280842e8c5b0b7f75ba24cdc8d..475eb46342e004c0e7115db9f1f5fe04af4c5476 100644 --- a/test/unittest/app_spawn_standard_test/app_spawn_silk_test.cpp +++ b/test/unittest/app_spawn_standard_test/app_spawn_silk_test.cpp @@ -75,3 +75,13 @@ HWTEST_F(ParseSilkConfigTest, Parse_Silk_Config_002, TestSize.Level0) ASSERT_EQ(g_silkConfig.configItems, NULL); ASSERT_EQ(g_silkConfig.configCursor, 0); } + +HWTEST_F(ParseSilkConfigTest, Parse_Silk_Config_003, TestSize.Level0) +{ + const char *silkJsonStr = "{\"enabled_app_list0\":[\"com.taobao.taobao\",\"com.tencent.mm\"]}"; + cJSON *root = cJSON_Parse(silkJsonStr); + const char* testEnableSilkProcessName = NULL; + bool ret = ParseSilkConfig(root, &g_silkConfig); + cJSON_Delete(root); + ASSERT_EQ(ret, false); +} diff --git a/test/unittest/single_test/hnp_installer/BUILD.gn b/test/unittest/single_test/hnp_installer/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..066a44127f2fc71caa65dc4f630ea41a28f8cd32 --- /dev/null +++ b/test/unittest/single_test/hnp_installer/BUILD.gn @@ -0,0 +1,63 @@ +# Copyright (c) 2025 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import("//base/startup/appspawn/appspawn.gni") +import("//build/test.gni") + +if (!defined(ohos_lite)) { + ohos_unittest("hnp_installer_test") { + module_out_path = "appspawn/appspawn" + cflags = [ + "-Wno-implicit-fallthrough", + "-Wno-unused-function", + "-Dprivate=public", + "-Dprotected=public", + ] + + cflags_cc = [ + "-Wno-implicit-fallthrough", + "-fexceptions", + ] + + include_dirs = [ + "${appspawn_path}/service/hnp/base", + "${appspawn_path}/service/hnp/pack/include", + "${appspawn_path}/service/hnp/installer/include", + "${appspawn_path}/interfaces/innerkits/hnp/include", + "${appspawn_path}/util/include", + "include", + ] + + sources = [ + "${appspawn_path}/service/hnp/base/hnp_log.c", + "${appspawn_path}/service/hnp/installer/src/hnp_installer.c", + "src/hnp_installer_test.cpp", + ] + + defines = [ "APPSPAWN_TEST" ] + + deps = [ "${appspawn_path}/util:libappspawn_util" ] + + external_deps = [ + "bounds_checking_function:libsec_shared", + "cJSON:cjson", + "hilog:libhilog", + "init:libbegetutil", + "selinux_adapter:librestorecon", + "zlib:shared_libz", + ] + + if (appspawn_support_code_signature) { + external_deps += [ "code_signature:libcode_sign_utils" ] + } + } +} diff --git a/test/unittest/single_test/hnp_installer/include/hnp_installer_test.h b/test/unittest/single_test/hnp_installer/include/hnp_installer_test.h new file mode 100644 index 0000000000000000000000000000000000000000..7100ccefbc80c1be94390bbbb69c0439071c7493 --- /dev/null +++ b/test/unittest/single_test/hnp_installer/include/hnp_installer_test.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef HNP_INSTALL_TEST_H +#define HNP_INSTALL_TEST_H + +#ifdef __cplusplus +extern "C" { +#endif + +void ClearSoftLink(int uid); + +#ifdef __cplusplus +} +#endif +#endif \ No newline at end of file diff --git a/test/unittest/single_test/hnp_installer/src/hnp_installer_test.cpp b/test/unittest/single_test/hnp_installer/src/hnp_installer_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e7c1d7f5c36dfbb0fd93b234816f16b50e7594cd --- /dev/null +++ b/test/unittest/single_test/hnp_installer/src/hnp_installer_test.cpp @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "hnp_installer_test.h" +#include + +#include +#include +#include +#include +#include +#include "hnp_installer.h" + + +using namespace testing; +using namespace testing::ext; + + +#ifdef __cplusplus + extern "C" { +#endif + +#ifdef __cplusplus + } +#endif + +namespace OHOS { +class InitFirststageTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void InitFirststageTest::SetUpTestCase() +{ + GTEST_LOG_(INFO) << "Hnp_Installer_TEST SetUpTestCase"; +} + +void InitFirststageTest::TearDownTestCase() +{ + GTEST_LOG_(INFO) << "Hnp_Installer_TEST TearDownTestCase"; +} + +void InitFirststageTest::SetUp() +{ + GTEST_LOG_(INFO) << "Hnp_Installer_TEST SetUp"; +} + +void InitFirststageTest::TearDown() +{ + GTEST_LOG_(INFO) << "Hnp_Installer_TEST TearDown"; +} + +static void MakeDirRecursive(const std::string &path, mode_t mode) +{ + size_t size = path.size(); + if (size == 0) { + return; + } + + size_t index = 0; + do { + size_t pathIndex = path.find_first_of('/', index); + index = pathIndex == std::string::npos ? size : pathIndex + 1; + std::string dir = path.substr(0, index); + if (access(dir.c_str(), F_OK) < 0) { + int ret = mkdir(dir.c_str(), mode); + if (ret != 0) { + return; + } + } + } while (index < size); +} + +static void CreateTestFile(const char *fileName, const char *data) +{ + FILE *tmpFile = fopen(fileName, "wr"); + if (tmpFile != nullptr) { + fprintf(tmpFile, "%s", data); + (void)fflush(tmpFile); + fclose(tmpFile); + } +} + +HWTEST_F(InitFirststageTest, hnp_clearSoftLink_001, TestSize.Level0) +{ + GTEST_LOG_(INFO) << "hnp_clearSoftLink_001 start"; + + const std::string binDir = HNP_DEFAULT_INSTALL_ROOT_PATH"/100/hnppublic/bin"; + const std::string fileDir = HNP_DEFAULT_INSTALL_ROOT_PATH"/100/hnppublic/test.org/bin"; + + MakeDirRecursive(binDir, 0711); + MakeDirRecursive(fileDir, 0711); + + const std::string lnkFile = HNP_DEFAULT_INSTALL_ROOT_PATH"/100/hnppublic/bin/test"; + const std::string sourceFile = "../test.org/bin/test"; + + CreateTestFile(HNP_DEFAULT_INSTALL_ROOT_PATH"/100/hnppublic/test.org/bin/test", "test"); + symlink(sourceFile.c_str(), lnkFile.c_str()); + + ClearSoftLink(100); + int ret = access(lnkFile.c_str(), F_OK); + EXPECT_EQ(ret, 0); + + remove(HNP_DEFAULT_INSTALL_ROOT_PATH"/100/hnppublic/test.org/bin/test"); + ClearSoftLink(100); + + ret = access(lnkFile.c_str(), F_OK); + EXPECT_NE(ret, 0); +} + +} \ No newline at end of file diff --git a/util/include/appspawn_utils.h b/util/include/appspawn_utils.h index 1fe1c99c70200187d741f3972420034d0e02690d..3317f1bacd41632b38669a4e89b39c7510a795ba 100644 --- a/util/include/appspawn_utils.h +++ b/util/include/appspawn_utils.h @@ -115,9 +115,9 @@ typedef enum { APPSPAWN_TLV_NONE, APPSPAWN_SANDBOX_NONE, APPSPAWN_SANDBOX_LOAD_FAIL, - APPSPAWN_SANDBOX_MOUNT_FAIL, // 0xD00000a - APPSPAWN_SPAWN_TIMEOUT, // 0xD00000a - APPSPAWN_CHILD_CRASH, // 0xD00000b + APPSPAWN_SANDBOX_MOUNT_FAIL, + APPSPAWN_SPAWN_TIMEOUT, + APPSPAWN_CHILD_CRASH, APPSPAWN_NATIVE_NOT_SUPPORT, APPSPAWN_ACCESS_TOKEN_INVALID, APPSPAWN_PERMISSION_NOT_SUPPORT, diff --git a/util/src/appspawn_utils.c b/util/src/appspawn_utils.c index 774b11f82e4883a31a0a317033900b0c092cc9b3..20d8ca2e0c125943322d2d02f967666afb70ee61 100644 --- a/util/src/appspawn_utils.c +++ b/util/src/appspawn_utils.c @@ -38,9 +38,9 @@ #include "securec.h" static const AppSpawnCommonEnv COMMON_ENV[] = { - {"HNP_PRIVATE_HOME", "/data/app", true}, - {"HNP_PUBLIC_HOME", "/data/service/hnp", true}, - {"PATH", "${HNP_PRIVATE_HOME}/bin:${HNP_PUBLIC_HOME}/bin:${PATH}", true}, + {"HNP_PRIVATE_HOME", "/data/app", false}, + {"HNP_PUBLIC_HOME", "/data/service/hnp", false}, + {"PATH", "${HNP_PRIVATE_HOME}/bin:${HNP_PUBLIC_HOME}/bin:${PATH}", false}, {"HOME", "/storage/Users/currentUser", false}, {"TMPDIR", "/data/storage/el2/base/cache", false}, {"SHELL", "/bin/sh", false},