diff --git a/begetd.gni b/begetd.gni index bb947f852767dabdb85d1d592af7332320e287ea..5748ca4cefb4c5785ef38f6f36d3fa577ef8c445 100755 --- a/begetd.gni +++ b/begetd.gni @@ -13,8 +13,12 @@ declare_args() { param_feature_watcher = true + param_feature_deviceinfo = true param_test = true - + param_begetctl_liteos_support = false + enable_ohos_startup_init_lite_use_thirdparty_mbedtls = true + enable_ohos_startup_init_lite_use_posix_file_api = false + config_ohos_startup_init_lite_data_path = "" if (defined(product_name) && product_name == "rk3568") { boot_kernel_extended_cmdline = "hardware=rk3568 default_boot_device=fe310000.sdhci" diff --git a/bundle.json b/bundle.json index 1439e5e7ac8b4658b0d74e32f24d4940d3990808..0f63f424dfc1dc7593f507fa5f662362aba822c8 100755 --- a/bundle.json +++ b/bundle.json @@ -22,7 +22,7 @@ "deps": { "components": [ "selinux", - "ipc", + "ipc", "safwk", "samgr_standard", "utils_base", @@ -43,7 +43,7 @@ "//base/startup/init_lite/services/begetctl:paramshell", "//base/startup/init_lite/services/plugin:plugin", "//base/startup/init_lite/interfaces/innerkits:libbegetutil", - "//base/startup/init_lite/interfaces/kits:deviceinfo_ndk", + "//base/startup/init_lite/interfaces/kits/syscap:deviceinfo_ndk", "//base/startup/init_lite/interfaces/innerkits:libbeget_proxy", "//base/startup/init_lite/interfaces/innerkits/file:libfile", "//base/startup/init_lite/interfaces/innerkits/socket:libsocket", @@ -64,7 +64,12 @@ "init_reboot.h", "service_control.h", "beget_ext.h", - "systemcapability.h" + "systemcapability.h", + "syspara/parameter.h", + "syspara/parameters.h", + "syspara/param_wrapper.h", + "syspara/sysparam_errno.h", + "syspara/sysversion.h" ] }, "name": "//base/startup/init_lite/interfaces/innerkits:libbegetutil" @@ -73,7 +78,9 @@ "header": { "header_base": "//base/startup/init_lite/interfaces/innerkits/include/", "header_files": [ - "service_watcher.h" + "service_watcher.h", + "syspara/parameter.h", + "syspara/sysparam_errno.h" ] }, "name": "//base/startup/init_lite/interfaces/innerkits:libbeget_proxy" diff --git a/device_info/BUILD.gn b/device_info/BUILD.gn index 3d71e9b9fda5724d0a89b0857948b84db6e9a428..6553ec4f5623d5ad0d385da49cd9fd823fba0996 100644 --- a/device_info/BUILD.gn +++ b/device_info/BUILD.gn @@ -10,6 +10,7 @@ # 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/init_lite/begetd.gni") import("//build/ohos.gni") import("//build/ohos/sa_profile/sa_profile.gni") @@ -25,19 +26,27 @@ ohos_prebuilt_etc("device_info.cfg") { } ohos_shared_library("deviceinfoservice") { - sources = [ "device_info_stub.cpp" ] + sources = [ + "//base/startup/init_lite/interfaces/innerkits/syspara/param_comm.c", + "device_info_stub.cpp", + ] - defines = [ "DINFO_LABEL=\"DeviceInfoService\"" ] include_dirs = [ ".", + "//base/startup/init_lite/services/include/param", "//base/startup/init_lite/interfaces/innerkits/include", - "//base/startup/syspara_lite/hals/parameter/include", + "//base/startup/init_lite/interfaces/innerkits/include/syspara", + "//base/startup/init_lite/interfaces/innerkits/syspara", ] deps = [ "//base/startup/init_lite/services/log:agent_log", - "//base/startup/syspara_lite/hals/parameter:sysparam_hal", + "//base/startup/init_lite/services/loopevent:loopevent", + "//base/startup/init_lite/services/param:param_client", + "//base/startup/init_lite/services/utils:libinit_tools", + "//base/startup/init_lite/services/utils:libinit_utils", "//third_party/bounds_checking_function:libsec_shared", + "//third_party/openssl:libcrypto_shared", ] external_deps = [ @@ -53,9 +62,11 @@ ohos_shared_library("deviceinfoservice") { } group("device_info_group") { - deps = [ - ":device_info.cfg", - ":device_info_profile", - ":deviceinfoservice", - ] + if (param_feature_deviceinfo) { + deps = [ + ":device_info.cfg", + ":device_info_profile", + ":deviceinfoservice", + ] + } } diff --git a/device_info/device_info.cpp b/device_info/device_info.cpp new file mode 100755 index 0000000000000000000000000000000000000000..7640d9d50a82f32c8d860315eb3367f18b53fe59 --- /dev/null +++ b/device_info/device_info.cpp @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2021 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 "beget_ext.h" +#ifdef PARAM_FEATURE_DEVICEINFO +#include "device_info_kits.h" +#endif +#include "param_comm.h" +#include "securec.h" + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +int AclGetDevUdid(char *udid, int size) +{ + if (udid == nullptr || size < UDID_LEN) { + return -1; + } +#ifdef PARAM_FEATURE_DEVICEINFO + std::string result = {}; + OHOS::device_info::DeviceInfoKits &instance = OHOS::device_info::DeviceInfoKits::GetInstance(); + int ret = instance.GetUdid(result); + if (ret == 0) { + ret = strcpy_s(udid, size, result.c_str()); + } +#else + int ret = GetDevUdid_(udid, size); +#endif + BEGET_LOGI("AclGetDevUdid %s", udid); + return ret; +} + +const char *AclGetSerial(void) +{ + static char serialNumber[MAX_SERIAL_LEN] = {"1234567890"}; +#ifdef PARAM_FEATURE_DEVICEINFO + std::string result = {}; + OHOS::device_info::DeviceInfoKits &instance = OHOS::device_info::DeviceInfoKits::GetInstance(); + int ret = instance.GetSerialID(result); + if (ret == 0) { + ret = strcpy_s(serialNumber, sizeof(serialNumber), result.c_str()); + BEGET_ERROR_CHECK(ret == 0, return nullptr, "Failed to copy"); + } +#else + const char *tmpSerial = GetSerial_(); + if (tmpSerial != nullptr) { + int ret = strcpy_s(serialNumber, sizeof(serialNumber), tmpSerial); + BEGET_ERROR_CHECK(ret == 0, return nullptr, "Failed to copy"); + } +#endif + BEGET_LOGI("AclGetSerial %s", serialNumber); + return serialNumber; +} + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ \ No newline at end of file diff --git a/device_info/device_info_kits.cpp b/device_info/device_info_kits.cpp index fca182a5782457e10f3267c3621dc8a646ba34c2..1d157f88a4273753af09a36cd3c093506ed6746a 100644 --- a/device_info/device_info_kits.cpp +++ b/device_info/device_info_kits.cpp @@ -22,11 +22,6 @@ #include "system_ability_definition.h" #include "securec.h" -namespace { -static constexpr int UDID_LEN = 65; -static constexpr int MAX_SERIAL_LEN = 65; -} // namespace name - namespace OHOS { namespace device_info { DeviceInfoKits::DeviceInfoKits() {} @@ -96,48 +91,3 @@ int32_t DeviceInfoKits::GetSerialID(std::string& result) } } // namespace device_info } // namespace OHOS - -#ifdef __cplusplus -#if __cplusplus -extern "C" { -#endif -#endif /* __cplusplus */ - -int AclGetDevUdid(char *udid, int size) -{ - if (udid == nullptr || size < UDID_LEN) { - return -1; - } - printf("AclGetDevUdid \n"); - DINFO_LOGI("AclGetDevUdid"); - std::string result = {}; - OHOS::device_info::DeviceInfoKits &instance = OHOS::device_info::DeviceInfoKits::GetInstance(); - int ret = instance.GetUdid(result); - if (ret == 0) { - ret = strcpy_s(udid, size, result.c_str()); - } - printf("GetDevUdid %s \n", udid); - DINFO_LOGI("GetDevUdid %s", udid); - return ret; -} - -const char *AclGetSerial(void) -{ - DINFO_LOGI("AclGetSerial"); - static char serialNumber[MAX_SERIAL_LEN] = {"1234567890"}; - std::string result = {}; - OHOS::device_info::DeviceInfoKits &instance = OHOS::device_info::DeviceInfoKits::GetInstance(); - int ret = instance.GetSerialID(result); - if (ret == 0) { - ret = strcpy_s(serialNumber, sizeof(serialNumber), result.c_str()); - DINFO_CHECK(ret == 0, return nullptr, "Failed to copy"); - } - DINFO_LOGI("GetSerial %s", serialNumber); - return serialNumber; -} - -#ifdef __cplusplus -#if __cplusplus -} -#endif -#endif /* __cplusplus */ \ No newline at end of file diff --git a/device_info/device_info_stub.cpp b/device_info/device_info_stub.cpp index 8752c0b3c2862acd029b463bf78768b1e2a11659..fb6d6536e1c80cc83e2c07bc09b04de45d6d62b8 100644 --- a/device_info/device_info_stub.cpp +++ b/device_info/device_info_stub.cpp @@ -19,16 +19,12 @@ #include "idevice_info.h" #include "ipc_skeleton.h" #include "accesstoken_kit.h" -#include "parameter_hal.h" #include "parcel.h" #include "string_ex.h" #include "system_ability_definition.h" +#include "param_comm.h" using std::u16string; -namespace { -static constexpr int UDID_LEN = 65; -} // namespace name - namespace OHOS { using namespace Security; using namespace Security::AccessToken; @@ -50,7 +46,7 @@ int32_t DeviceInfoStub::OnRemoteRequest(uint32_t code, return ERR_FAIL; } char localDeviceInfo[UDID_LEN] = {0}; - ret = HalGetDevUdid(localDeviceInfo, UDID_LEN); + ret = GetDevUdid_(localDeviceInfo, UDID_LEN); DINFO_CHECK(ret == 0, break, "Failed to get dev udid"); reply.WriteString16(Str8ToStr16(localDeviceInfo)); break; @@ -59,9 +55,10 @@ int32_t DeviceInfoStub::OnRemoteRequest(uint32_t code, if (!CheckPermission(data, PERMISSION_UDID)) { return ERR_FAIL; } - const char *serialNumber = HalGetSerial(); + const char *serialNumber = GetSerial_(); DINFO_CHECK(serialNumber != nullptr, break, "Failed to get serialNumber"); reply.WriteString16(Str8ToStr16(serialNumber)); + free((void *)serialNumber); break; } default: { diff --git a/initsync/BUILD.gn b/initsync/BUILD.gn index 0b82490ee14d12e8a475de043796f652c3878cb5..4248b73159796f3f07af7fe577d4b5cc5c07b8c9 100644 --- a/initsync/BUILD.gn +++ b/initsync/BUILD.gn @@ -22,7 +22,7 @@ shared_library("libinitsync_shared") { cflags = [ "-Wall" ] include_dirs = [ "//base/startup/init_lite/initsync/include", - "//base/startup/init_lite/interfaces/kits", + "//base/startup/init_lite/interfaces/kits/syscap", "//base/startup/init_lite/services/log", "//base/startup/init_lite/interfaces/innerkits/include", ] @@ -37,7 +37,7 @@ static_library("libinitsync_static") { cflags = [ "-Wall" ] include_dirs = [ "//base/startup/init_lite/initsync/include", - "//base/startup/init_lite/interfaces/kits", + "//base/startup/init_lite/interfaces/kits/syscap", "//base/startup/init_lite/services/log", "//base/startup/init_lite/interfaces/innerkits/include", ] diff --git a/interfaces/innerkits/BUILD.gn b/interfaces/innerkits/BUILD.gn index 4c415e2181e653fc2dbd2e87235f50564054e569..4f006f5cab8679ad10e60b0cfbbaeeba8c2e0245 100644 --- a/interfaces/innerkits/BUILD.gn +++ b/interfaces/innerkits/BUILD.gn @@ -10,37 +10,134 @@ # 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/init_lite/begetd.gni") +if (!defined(ohos_lite) || ohos_kernel_type != "liteos_m") { + syspara_sources = [ + "syscap/init_syscap.c", + "syspara/param_comm.c", + "syspara/parameter.c", + "syspara/sysversion.c", + ] +} + +config("exported_header_files") { + visibility = [ ":*" ] + include_dirs = [ + "//base/startup/init_lite/interfaces/innerkits/include", + "//base/startup/init_lite/interfaces/innerkits/include/syspara", + "//base/startup/init_lite/interfaces/innerkits/include/token", + ] +} if (defined(ohos_lite)) { - static_library("libbegetutil") { - sources = [ "//base/startup/init_lite/services/log/init_log.c" ] - defines = [ - "_GNU_SOURCE", - "OHOS_LITE", - "INIT_LOG_INIT=3", - ] - include_dirs = [ - "./include", - "//third_party/bounds_checking_function/include", - "//base/startup/init_lite/services/include", - "//base/startup/init_lite/services/include/param", - "//base/startup/init_lite/interfaces/innerkits/fd_holder", - ] - deps = [ - "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", - "//base/startup/init_lite/services/loopevent:loopevent", - "//base/startup/init_lite/services/utils:libinit_tools", - "//third_party/bounds_checking_function:libsec_static", - ] + import("//build/lite/config/component/lite_component.gni") + import("//build/lite/ndk/ndk.gni") + + if (ohos_kernel_type == "liteos_a" || ohos_kernel_type == "linux") { + shared_library("libbegetutil") { + sources = [ "//base/startup/init_lite/services/log/init_log.c" ] + sources += syspara_sources + + public_configs = [ ":exported_header_files" ] + cflags = [ "-fPIC" ] + defines = [ + "_GNU_SOURCE", + "INIT_LOG_INIT=3", + "OHOS_LITE", + ] + include_dirs = [ + "./include", + "//base/hiviewdfx/hilog_lite/interfaces/native/kits", + "//third_party/bounds_checking_function/include", + "//base/startup/init_lite/services/include", + "//base/startup/init_lite/services/include/param", + "//base/startup/init_lite/interfaces/innerkits/fd_holder", + "//base/startup/init_lite/services/param/include", + "//base/startup/init_lite/interfaces/innerkits/include", + ] + deps = [ + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", + "//base/startup/init_lite/services/utils:libinit_tools", + "//third_party/bounds_checking_function:libsec_shared", + "//third_party/mbedtls:mbedtls", + ] + + defines += [ + "INCREMENTAL_VERSION=\"${ohos_version}\"", + "BUILD_TYPE=\"${ohos_build_type}\"", + "BUILD_USER=\"${ohos_build_user}\"", + "BUILD_TIME=\"${ohos_build_time}\"", + "BUILD_HOST=\"${ohos_build_host}\"", + "BUILD_ROOTHASH=\"${ohos_build_roothash}\"", + "USE_MBEDTLS", + ] + deps += [ "//base/startup/init_lite/services/param:param_client" ] + if (ohos_kernel_type == "liteos_a") { + defines += [ "__LITEOS_A__" ] + } else if (ohos_kernel_type == "linux") { + defines += [ "__LINUX__" ] + deps += [ "//base/startup/init_lite/services/loopevent:loopevent" ] + } + } + } + if (ohos_kernel_type == "liteos_m") { + static_library("libbegetutil") { + sources = [ "//base/startup/init_lite/services/log/init_log.c" ] + sources += [ "syscap/init_syscap.c" ] + public_configs = [ ":exported_header_files" ] + + defines = [ + "_GNU_SOURCE", + "INIT_LOG_INIT=3", + "OHOS_LITE", + "__LITEOS_M__", + ] + include_dirs = [ + "./include", + "//base/hiviewdfx/hilog_lite/interfaces/native/kits", + "//third_party/bounds_checking_function/include", + "//base/startup/init_lite/services/include", + "//base/startup/init_lite/services/include/param", + "//base/startup/init_lite/interfaces/innerkits/fd_holder", + "//base/startup/init_lite/services/param/include", + "//base/startup/init_lite/interfaces/innerkits/include", + ] + deps = [ + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_static", + "//base/startup/init_lite/services/utils:libinit_tools", + "//third_party/bounds_checking_function:libsec_static", + ] + + defines += [ + "INCREMENTAL_VERSION=\"${ohos_version}\"", + "BUILD_TYPE=\"${ohos_build_type}\"", + "BUILD_USER=\"${ohos_build_user}\"", + "BUILD_TIME=\"${ohos_build_time}\"", + "BUILD_HOST=\"${ohos_build_host}\"", + "BUILD_ROOTHASH=\"${ohos_build_roothash}\"", + ] + if (enable_ohos_startup_init_lite_use_thirdparty_mbedtls) { + deps += [ "//third_party/mbedtls:mbedtls" ] + defines += [ "USE_MBEDTLS" ] + } + deps += [ "//base/startup/init_lite/services/param:param_client" ] + } + } + + lite_component("parameter") { + features = [ ":libbegetutil" ] } -} else { - import("//base/startup/init_lite/begetd.gni") - import("//build/ohos.gni") - config("exported_header_files") { - visibility = [ ":*" ] - include_dirs = [ "include/" ] + ndk_lib("parameter_notes") { + if (ohos_kernel_type != "liteos_m") { + lib_extension = ".so" + } + deps = [ ":libbegetutil" ] + head_files = + [ "//base/startup/init_lite/interfaces/innerkits/include/syspara" ] } +} else { + import("//build/ohos.gni") fs_manager_sources = [ "fs_manager/fstab.c", @@ -56,24 +153,34 @@ if (defined(ohos_lite)) { "reboot/init_reboot_innerkits.c", "service_control/service_control.c", "socket/init_socket.c", - "syscap/init_syscap.c", ] sources += fs_manager_sources - defines = [ "INIT_AGENT" ] + sources += syspara_sources + sources += [ "syspara/param_wrapper.cpp" ] + defines = [ + "INIT_AGENT", + "INIT_FILE", + "_GNU_SOURCE", + "INIT_FILE", + ] include_dirs = [ "./include", "//third_party/bounds_checking_function/include", "//base/startup/init_lite/services/include", "//base/startup/init_lite/services/include/param", + "//base/startup/init_lite/services/param/include", "//base/startup/init_lite/interfaces/innerkits/fd_holder", + "//base/startup/init_lite/interfaces/innerkits/include", ] deps = [ + "//base/startup/init_lite/interfaces/innerkits/sandbox:libsandbox", "//base/startup/init_lite/services/loopevent:loopevent", "//base/startup/init_lite/services/param:param_client", "//base/startup/init_lite/services/utils:libinit_tools", "//base/startup/init_lite/services/utils:libinit_utils", "//third_party/bounds_checking_function:libsec_shared", + "//third_party/openssl:libcrypto_shared", ] external_deps = [ "hilog_native:libhilog_base", @@ -89,9 +196,12 @@ if (defined(ohos_lite)) { # watcher lib must separate compilation avoid interdependence. ohos_shared_library("libbeget_proxy") { + defines = [ + "INIT_AGENT", + "_GNU_SOURCE", + ] sources = [ - "//base/startup/init_lite/device_info/device_info_kits.cpp", - "//base/startup/init_lite/device_info/device_info_proxy.cpp", + "//base/startup/init_lite/device_info/device_info.cpp", "//base/startup/init_lite/services/log/init_log.c", "service_watcher/service_watcher.c", ] @@ -100,18 +210,58 @@ if (defined(ohos_lite)) { "./include", "//base/startup/init_lite/device_info", "//base/startup/init_lite/interfaces/innerkits/include", + "//base/startup/init_lite/interfaces/innerkits/syspara", "//base/startup/init_lite/services/include", "//base/startup/init_lite/services/include/param", + "//base/startup/init_lite/services/param/include", "//third_party/bounds_checking_function/include", ] - defines = [ "INIT_AGENT" ] deps = [ - "//base/startup/init_lite/services/param/watcher:param_watcheragent", "//base/startup/init_lite/services/utils:libinit_utils", "//third_party/bounds_checking_function:libsec_shared", ] + if (param_feature_watcher) { + sources += [ + "//base/startup/init_lite/services/param/watcher/agent/watcher.cpp", + "//base/startup/init_lite/services/param/watcher/agent/watcher_manager_kits.cpp", + "//base/startup/init_lite/services/param/watcher/agent/watcher_manager_proxy.cpp", + "//base/startup/init_lite/services/param/watcher/agent/watcher_stub.cpp", + ] + include_dirs += [ + "//base/startup/init_lite/services/param/watcher/include", + "//base/startup/init_lite/services/log", + ] + deps += [ + "//base/startup/init_lite/services/param:param_client", + "//base/startup/init_lite/services/utils:libinit_tools", + "//base/startup/init_lite/services/utils:libinit_utils", + "//third_party/openssl:libcrypto_shared", + ] + } else { + defines += [ "NO_PARAM_WATCHER" ] + } + + if (param_feature_deviceinfo) { + sources += [ + "//base/startup/init_lite/device_info/device_info_kits.cpp", + "//base/startup/init_lite/device_info/device_info_proxy.cpp", + ] + defines += [ "PARAM_FEATURE_DEVICEINFO" ] + } else { + sources += [ + "//base/startup/init_lite/interfaces/innerkits/syspara/param_comm.c", + ] + deps += [ + "//base/startup/init_lite/services/loopevent:loopevent", + "//base/startup/init_lite/services/param:param_client", + "//base/startup/init_lite/services/utils:libinit_tools", + "//base/startup/init_lite/services/utils:libinit_utils", + "//third_party/openssl:libcrypto_shared", + ] + } + external_deps = [ "hilog_native:libhilog_base", "ipc:ipc_core", @@ -119,6 +269,7 @@ if (defined(ohos_lite)) { "samgr_standard:samgr_proxy", "utils_base:utils", ] + public_configs = [ ":exported_header_files" ] part_name = "init" install_images = [ "system" ] } @@ -131,6 +282,7 @@ if (defined(ohos_lite)) { "//third_party/bounds_checking_function/include", "//base/startup/init_lite/services/log", "//base/startup/init_lite/services/include", + "//base/startup/init_lite/services/param/include", ] part_name = "init" diff --git a/interfaces/innerkits/file/BUILD.gn b/interfaces/innerkits/file/BUILD.gn index 66cb7413dc6b97452508e1c49d1ea949fdbbbd03..675d4908108d2e14b34b33adedc28598f1d55744 100644 --- a/interfaces/innerkits/file/BUILD.gn +++ b/interfaces/innerkits/file/BUILD.gn @@ -19,23 +19,26 @@ service_file_include = [ "//base/startup/init_lite/services/include", "//third_party/bounds_checking_function/include", ] -service_file_deps = [ - "//base/startup/init_lite/services/log:agent_log", - "//base/startup/init_lite/services/utils:libinit_utils", - "//third_party/bounds_checking_function:libsec_static", -] ohos_static_library("libfile_static") { sources = service_file_sources include_dirs = service_file_include - deps = service_file_deps + deps = [ + "//base/startup/init_lite/services/log:agent_log", + "//base/startup/init_lite/services/utils:libinit_utils", + "//third_party/bounds_checking_function:libsec_static", + ] part_name = "init" } ohos_shared_library("libfile") { sources = service_file_sources include_dirs = service_file_include - deps = service_file_deps + deps = [ + "//base/startup/init_lite/services/log:agent_log", + "//base/startup/init_lite/services/utils:libinit_utils", + "//third_party/bounds_checking_function:libsec_shared", + ] part_name = "init" install_images = [ "system" ] } diff --git a/interfaces/innerkits/include/beget_ext.h b/interfaces/innerkits/include/beget_ext.h index 1a3b22722c9d3e0a3c4f59b85a00aa370a44942e..3a8e270bd0f93313401bdeb984ced67741b107d3 100644 --- a/interfaces/innerkits/include/beget_ext.h +++ b/interfaces/innerkits/include/beget_ext.h @@ -15,6 +15,7 @@ #ifndef BEGET_EXT_API_H #define BEGET_EXT_API_H +#include #ifdef __cplusplus #if __cplusplus diff --git a/interfaces/innerkits/include/service_watcher.h b/interfaces/innerkits/include/service_watcher.h index 105c29a921d35e5b49fb27ed6222635777b7184f..7364bc37a28aa14150a8770f63892def73122553 100644 --- a/interfaces/innerkits/include/service_watcher.h +++ b/interfaces/innerkits/include/service_watcher.h @@ -16,7 +16,7 @@ #ifndef SERVICE_WATCH_API_H #define SERVICE_WATCH_API_H -#include "sys_param.h" +#include "init_param.h" #include "service_control.h" #ifdef __cplusplus diff --git a/interfaces/innerkits/include/syspara/param_wrapper.h b/interfaces/innerkits/include/syspara/param_wrapper.h new file mode 100755 index 0000000000000000000000000000000000000000..ab4a0baf15ce23e8d6c81d9624bacb5aad35759b --- /dev/null +++ b/interfaces/innerkits/include/syspara/param_wrapper.h @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2021 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 STARTUP_SYSVERSION_API_H +#define STARTUP_SYSVERSION_API_H + +#include + +namespace OHOS { +namespace system { +int GetStringParameter(const std::string key, std::string &value, const std::string def = ""); +int GetIntParameter(const std::string key, int def); +} +} + +#endif // STARTUP_SYSVERSION_API_H diff --git a/interfaces/innerkits/include/syspara/parameter.h b/interfaces/innerkits/include/syspara/parameter.h new file mode 100755 index 0000000000000000000000000000000000000000..3a5473f4dc9d3345fedea8c36a404d924901039c --- /dev/null +++ b/interfaces/innerkits/include/syspara/parameter.h @@ -0,0 +1,162 @@ +/* + * Copyright (c) 2021 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 STARTUP_SYSPARAM_PARAMETER_API_H +#define STARTUP_SYSPARAM_PARAMETER_API_H + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +#define PARAM_CONST_VALUE_LEN_MAX 4096 +#define PARAM_VALUE_LEN_MAX 96 +#define PARAM_NAME_LEN_MAX 96 +#define OS_FULL_NAME_LEN 128 +#define VERSION_ID_MAX_LEN 256 + +static const char EMPTY_STR[] = { "" }; + +/** + * @brief Obtains a system parameter matching the specified key. + * + * If no system parameter is found, the def parameter will be returned.\n + * + * @param key Indicates the key for the system parameter to query. + * The value can contain lowercase letters, digits, underscores (_), and dots (.). + * Its length cannot exceed 32 bytes (including the end-of-text character in the string). + * @param def Indicates the default value to return when no query result is found. + * This parameter is specified by the caller. + * @param value Indicates the data buffer that stores the query result. + * This parameter is applied for and released by the caller and can be used as an output parameter. + * @param len Indicates the length of the data in the buffer. + * @return Returns the number of bytes of the system parameter if the operation is successful; + * returns -9 if a parameter is incorrect; returns -1 in other scenarios. + * @since 1 + * @version 1 + */ +int GetParameter(const char *key, const char *def, char *value, unsigned int len); + +/** + * @brief Sets or updates a system parameter. + * + * You can use this function to set a system parameter that matches key as value.\n + * + * @param key Indicates the key for the parameter to set or update. + * The value can contain lowercase letters, digits, underscores (_), and dots (.). + * Its length cannot exceed 32 bytes (including the end-of-text character in the string). + * @param value Indicates the system parameter value. + * Its length cannot exceed 128 bytes (including the end-of-text character in the string). + * @return Returns 0 if the operation is successful; + * returns -9 if a parameter is incorrect; returns -1 in other scenarios. + * @since 1 + * @version 1 + */ +int SetParameter(const char *key, const char *value); + +/** + * @brief Wait for a system parameter with specified value. + * + * You can use this function to wait a system parameter that matches key as value.\n + * + * @param key Indicates the key for the parameter to wait. + * The value can contain lowercase letters, digits, underscores (_), and dots (.). + * Its length cannot exceed 96 bytes (including the end-of-text character in the string). + * @param value Indicates the system parameter value. + * Its length cannot exceed 96 bytes (including the end-of-text character in the string). + * value can use "*" to do arbitrary match. + * @param timeout Indicates the timeout value, in seconds. + * <=0 means wait for ever. + * >0 means wait for specified seconds + * @return Returns 0 if the operation is successful; + * returns -10 if timeout; returns -1 in other scenarios. + * @since 1.1 + * @version 1.1 + */ +int WaitParameter(const char *key, const char *value, int timeout); + +/** + * @brief Watch for system parameter values. + * + * You can use this function to watch system parameter values.\n + * + * @param keyprefix Indicates the key prefix for the parameter to be watched. + * If keyprefix is not a full name, "A.B." for example, it means to watch for all parameter started with "A.B.". + * @param callback Indicates value change callback. + * If callback is NULL, it means to cancel the watch. + * @return Returns 0 if the operation is successful; + * returns -1 in other scenarios. + * @since 1.1 + * @version 1.1 + */ +typedef void (*ParameterChgPtr)(const char *key, const char *value, void *context); +int WatchParameter(const char *keyprefix, ParameterChgPtr callback, void *context); + +const char *GetSecurityPatchTag(void); +const char *GetOSFullName(void); +const char *GetVersionId(void); +const char *GetBuildRootHash(void); +const char *GetOsReleaseType(void); +int GetSdkApiVersion(void); + +const char *GetDeviceType(void); +const char *GetProductModel(void); +const char *GetManufacture(void); +const char *GetBrand(void); +const char *GetMarketName(void); +const char *GetProductSeries(void); +const char *GetSoftwareModel(void); +const char *GetHardwareModel(void); +const char *GetHardwareProfile(void); +const char *GetSerial(void); +const char *GetAbiList(void); +const char *GetDisplayVersion(void); +const char *GetIncrementalVersion(void); +const char *GetBootloaderVersion(void); +const char *GetBuildType(void); +const char *GetBuildUser(void); +const char *GetBuildHost(void); +const char *GetBuildTime(void); +int GetFirstApiVersion(void); +int GetDevUdid(char *udid, int size); + +const char *AclGetSerial(void); +int AclGetDevUdid(char *udid, int size); + +/** + * @brief Obtains a system parameter matching the specified key. + * + * If no system parameter is found, return -1.\n + * + * @param key Indicates the key for the system parameter to find. + * @return Returns the index for parameter; + * returns handle if a parameter is correct; returns -1 in other scenarios. + * @since 1 + * @version 1 + */ +unsigned int FindParameter(const char *key); +unsigned int GetParameterCommitId(unsigned int handle); +int GetParameterName(unsigned int handle, char *key, unsigned int len); +int GetParameterValue(unsigned int handle, char *value, unsigned int len); +long long GetSystemCommitId(void); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif // STARTUP_SYSPARAM_PARAMETER_API_H diff --git a/interfaces/innerkits/include/syspara/parameters.h b/interfaces/innerkits/include/syspara/parameters.h new file mode 100755 index 0000000000000000000000000000000000000000..e06f4df2c0a7322f164b9133b5de6303d6472c3a --- /dev/null +++ b/interfaces/innerkits/include/syspara/parameters.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2021 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 SYSTEM_PARAMETERS_H +#define SYSTEM_PARAMETERS_H + +#include +#include + +namespace OHOS { +namespace system { +/* + * Returns the current value of the system parameter `key`. + * If the parameter is empty or doesn't exist, `def` will be returned. + */ +std::string GetParameter(const std::string& key, const std::string& def); + +/* + * Returns true if the system parameter `key` has the value "1", "y", "yes", "on", or "true", + * false for "0", "n", "no", "off", or "false", or `def` otherwise. + */ +bool GetBoolParameter(const std::string& key, bool def); + +/* + * Returns the signed integer corresponding to the system parameter `key`. + * If the parameter is empty, doesn't exist, doesn't have an integer value, or is outside + * the optional bounds, returns `def`. + */ +template +T GetIntParameter(const std::string& key, T def, T min = std::numeric_limits::min(), + T max = std::numeric_limits::max()); + +/* + * Returns the unsigned integer corresponding to the system parameter `key`. + * If the parameter is empty, doesn't exist, doesn't have an integer value, or is outside + * the optional bound, returns `def`. + */ +template +T GetUintParameter(const std::string& key, T def, T max = std::numeric_limits::max()); + +/* + * Sets the system parameter `key` to `value`. + * Note that system parameter setting is inherently asynchronous so a return value of `true` + * isn't particularly meaningful, and immediately reading back the value won't necessarily + * tell you whether or not your call succeeded. A `false` return value definitely means failure. + */ +bool SetParameter(const std::string& key, const std::string& value); + +/* + * Obtains the device type of your product represented by a string. + */ +std::string GetDeviceType(void); +} // namespace system +} // namespace OHOS + +#endif // SYSTEM_PARAMETERS_H \ No newline at end of file diff --git a/interfaces/innerkits/include/syspara/sysparam_errno.h b/interfaces/innerkits/include/syspara/sysparam_errno.h new file mode 100755 index 0000000000000000000000000000000000000000..6deb0e149af3d0a8127ef8110e8b78903996a94b --- /dev/null +++ b/interfaces/innerkits/include/syspara/sysparam_errno.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2021 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 OHOS_STARTUP_SYSPARAM_ERRNO_H +#define OHOS_STARTUP_SYSPARAM_ERRNO_H +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ +/* --------------------------------------------------------------------------------------------* + * Definition of error code. The error codes are applicable to both the application and kernel + * -------------------------------------------------------------------------------------------- */ +enum OHOSStartUpSysParamErrorCode { + EC_SUCCESS = 0, /* OK or No error */ + EC_FAILURE = -1, /* Execution failed */ + EC_INVALID = -9, /* Invalid argument */ + EC_SYSTEM_ERR = -10, /* system error */ +}; + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ +#endif // OHOS_STARTUP_SYSPARAM_ERRNO_H diff --git a/services/param/include/param_request.h b/interfaces/innerkits/include/syspara/sysversion.h old mode 100644 new mode 100755 similarity index 66% rename from services/param/include/param_request.h rename to interfaces/innerkits/include/syspara/sysversion.h index 67ade65af45dd9c331ffe4580bdb93bfaf8bbd2b..903d975f9e6feb292bb7aded69e3a6912354db8f --- a/services/param/include/param_request.h +++ b/interfaces/innerkits/include/syspara/sysversion.h @@ -1,40 +1,36 @@ - -/* - * Copyright (c) 2021 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 BASE_STARTUP_PARAM_REQUEST_H -#define BASE_STARTUP_PARAM_REQUEST_H -#include -#include "param_manager.h" -#include "sys_param.h" -#ifdef __cplusplus -#if __cplusplus -extern "C" { -#endif -#endif - -typedef struct { - ParamWorkSpace paramSpace; - int clientFd; - pthread_mutex_t mutex; -} ClientWorkSpace; - -int WatchParamCheck(const char *keyprefix); -#ifdef __cplusplus -#if __cplusplus -} -#endif -#endif -#endif +/* + * Copyright (c) 2021 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 STARTUP_SYSVERSION_API_H +#define STARTUP_SYSVERSION_API_H + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +int GetMajorVersion(void); +int GetSeniorVersion(void); +int GetFeatureVersion(void); +int GetBuildVersion(void); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif // STARTUP_SYSVERSION_API_H diff --git a/interfaces/innerkits/include/token/token.h b/interfaces/innerkits/include/token/token.h new file mode 100755 index 0000000000000000000000000000000000000000..152953611fe5d72c04c19a4466b042d7e6ff7c8e --- /dev/null +++ b/interfaces/innerkits/include/token/token.h @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2020 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 TOKEN_H +#define TOKEN_H + +#include + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +/** + * @brief Read token value form device. + * + * @param token The token value, len The token len. + * @returns 0 if it succeeds and get the update area token, + * 1 if it succeeds and get the pre-made token, + * -1 if it fails, -2 if it no pre-made token. + */ +int ReadToken(char *token, unsigned int len); + +/** + * @brief Write token value to device. + * + * @param token The token value, len The token len. + * @returns 0 if it succeeds, -1 if it fails. + */ +int WriteToken(const char *token, unsigned int len); + +/** + * @brief Get AcKey value form device. + * + * @param acKey The acKey value, len The acKey len. + * @returns 0 if it succeeds, -1 if it fails. + */ +int GetAcKey(char *acKey, unsigned int len); + +/** + * @brief Get ProdId value form device. + * + * @param productId The productId value, len The productId len. + * @returns 0 if it succeeds, -1 if it fails. + */ +int GetProdId(char *productId, unsigned int len); + +/** + * @brief Get ProdKey value form device. + * + * @param productKey The productKey value, len The productKey len. + * @returns 0 if it succeeds, -1 if it fails. + */ +int GetProdKey(char *productKey, unsigned int len); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif // TOKEN_H \ No newline at end of file diff --git a/interfaces/innerkits/reboot/init_reboot_innerkits.c b/interfaces/innerkits/reboot/init_reboot_innerkits.c index f17a7e9b82dc13710cbf2ab97e7b0994e145906a..bc396230053c8f5b742c3a844fcea25ec71da578 100644 --- a/interfaces/innerkits/reboot/init_reboot_innerkits.c +++ b/interfaces/innerkits/reboot/init_reboot_innerkits.c @@ -19,9 +19,8 @@ #include #include "beget_ext.h" -#include "param.h" #include "securec.h" -#include "sys_param.h" +#include "init_param.h" // Refer to parameter limit, value size should not bigger than 96 #define MAX_REBOOT_OPTION_SIZE PARAM_VALUE_LEN_MAX diff --git a/interfaces/innerkits/sandbox/BUILD.gn b/interfaces/innerkits/sandbox/BUILD.gn index 96cfb3014ad4047b5a4c2408a07e962c68053ab8..49c03171630394908a755a8d3253a47dfec8b548 100644 --- a/interfaces/innerkits/sandbox/BUILD.gn +++ b/interfaces/innerkits/sandbox/BUILD.gn @@ -58,7 +58,6 @@ ohos_static_library("libsandbox_static") { ] deps = [ "//base/startup/init_lite/services/utils:libinit_utils", - "//third_party/bounds_checking_function:libsec_static", "//third_party/cJSON:cjson_static", ] part_name = "init" diff --git a/interfaces/innerkits/service_control/service_control.c b/interfaces/innerkits/service_control/service_control.c index 6b232b7db6e8ef51940dbe905ed2b706e214e16e..2ac40a1a9a74aaf7e7211e500e76649a3c7e3712 100644 --- a/interfaces/innerkits/service_control/service_control.c +++ b/interfaces/innerkits/service_control/service_control.c @@ -23,7 +23,7 @@ #include "beget_ext.h" #include "init_utils.h" #include "securec.h" -#include "sys_param.h" +#include "init_param.h" static int StartProcess(const char *name, const char *extArgv[], int extArgc) { diff --git a/interfaces/innerkits/service_watcher/service_watcher.c b/interfaces/innerkits/service_watcher/service_watcher.c index 37ac58b5e82d2c9832ff0695195172b206916124..be780eaffa8f4aadeff8dfa44fa63b2a7ec0aa3c 100644 --- a/interfaces/innerkits/service_watcher/service_watcher.c +++ b/interfaces/innerkits/service_watcher/service_watcher.c @@ -21,8 +21,10 @@ #include "beget_ext.h" #include "init_utils.h" +#include "parameter.h" #include "securec.h" #include "service_control.h" +#include "sysparam_errno.h" static void ServiceStateChange(const char *key, const char *value, void *context) { @@ -55,3 +57,16 @@ int ServiceWatchForStatus(const char *serviceName, ServiceStatusChangePtr change } return 0; } + +int WatchParameter(const char *keyprefix, ParameterChgPtr callback, void *context) +{ + if (keyprefix == NULL) { + return EC_INVALID; + } +#ifdef NO_PARAM_WATCHER + printf("ParameterWatcher is disabled."); + return EC_INVALID; +#else + return SystemWatchParameter(keyprefix, callback, context); +#endif +} \ No newline at end of file diff --git a/interfaces/innerkits/socket/BUILD.gn b/interfaces/innerkits/socket/BUILD.gn index 435b6e625a34e6bd99af9f22398862cf2cc9c346..8445919387df35066b541c43b2f426aff9bd89d5 100644 --- a/interfaces/innerkits/socket/BUILD.gn +++ b/interfaces/innerkits/socket/BUILD.gn @@ -19,7 +19,7 @@ service_socket_include = [ "//third_party/bounds_checking_function/include", ] service_socket_deps = [ - "//base/startup/init_lite/services/log:agent_log", + "//base/startup/init_lite/services/log:init_log", "//third_party/bounds_checking_function:libsec_static", ] diff --git a/interfaces/innerkits/syscap/BUILD.gn b/interfaces/innerkits/syscap/BUILD.gn index 0b537f43ec879d67cc98cb9c986f8470f8171900..bec0497a39ef0fec2c4d8b8092ed4e5a93cbbe30 100755 --- a/interfaces/innerkits/syscap/BUILD.gn +++ b/interfaces/innerkits/syscap/BUILD.gn @@ -22,11 +22,10 @@ ohos_shared_library("syscap") { include_dirs = [ "../include", - "../../../services/include/param", + "//base/startup/init_lite/services/include/param", ] deps = [ - "../../../services/log:init_log", - "../../../services/param:param_client", + "//base/startup/init_lite/interfaces/innerkits:libbegetutil", "//third_party/bounds_checking_function:libsec_shared", ] diff --git a/interfaces/innerkits/syscap/init_syscap.c b/interfaces/innerkits/syscap/init_syscap.c index a5ca764b8a90b3673cfd42f1bf6fb5da5d8e46f5..cf43a369fd8561d717b95a1e8e45eb76a7013228 100644 --- a/interfaces/innerkits/syscap/init_syscap.c +++ b/interfaces/innerkits/syscap/init_syscap.c @@ -18,7 +18,7 @@ #include #include -#include "sys_param.h" +#include "init_param.h" #include "beget_ext.h" #include "securec.h" #include "systemcapability.h" diff --git a/interfaces/innerkits/syspara/param_comm.c b/interfaces/innerkits/syspara/param_comm.c new file mode 100755 index 0000000000000000000000000000000000000000..ee2b63fd9d766569d9a05568e86173b4bd5abfeb --- /dev/null +++ b/interfaces/innerkits/syspara/param_comm.c @@ -0,0 +1,226 @@ +/* + * Copyright (c) 2021 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 "param_comm.h" + +#include +#include +#include + +#include "init_param.h" +#include "parameter.h" +#include "sysparam_errno.h" +#ifdef USE_MBEDTLS +#include "mbedtls/sha256.h" +#elif !(defined OHOS_LITE) +#include "openssl/sha.h" +#endif +#include "securec.h" + +static const char *g_emptyStr = ""; + +int HalGetParameter(const char *key, const char *def, char *value, uint32_t len) +{ + if ((key == NULL) || (value == NULL)) { + return EC_INVALID; + } + uint32_t size = len; + int ret = SystemGetParameter(key, NULL, &size); + if ((size > len) || (ret != 0)) { + return strcpy_s(value, len, def); + } + size = len; + return (SystemGetParameter(key, value, &size) == 0) ? EC_SUCCESS : EC_FAILURE; +} + +const char *GetProperty(const char *key, const char **paramHolder) +{ + if (paramHolder == NULL) { + return NULL; + } + if (*paramHolder != NULL) { + return *paramHolder; + } + uint32_t len = 0; + int ret = SystemGetParameter(key, NULL, &len); + if (ret == 0 && len > 0) { + char *res = (char *)malloc(len + 1); + if (res == NULL) { + return g_emptyStr; + } + ret = SystemGetParameter(key, res, &len); + if (ret != 0) { + free(res); + return g_emptyStr; + } + *paramHolder = res; + } + return *paramHolder; +} + +int StringToLL(const char *str, long long int *out) +{ + const char* s = str; + while (isspace(*s)) { + s++; + } + + size_t len = strlen(str); + int positiveHex = (len > 1 && s[0] == '0' && (s[1] == 'x' || s[1] == 'X')); + int negativeHex = (len > 2 && s[0] == '-' && s[1] == '0' && (s[2] == 'x' || s[2] == 'X')); // 2: shorttest + int base = (positiveHex || negativeHex) ? HEX : DECIMAL; + char* end = NULL; + errno = 0; + *out = strtoll(s, &end, base); + if (errno != 0) { + return -1; + } + if (s == end || *end != '\0') { + return -1; + } + return 0; +} + +int StringToULL(const char *str, unsigned long long int *out) +{ + const char* s = str; + while (isspace(*s)) { + s++; + } + + if (s[0] == '-') { + return -1; + } + + int base = (s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) ? HEX : DECIMAL; + char* end = NULL; + errno = 0; + *out = strtoull(s, &end, base); + if (errno != 0) { + return -1; + } + if (end == s) { + return -1; + } + if (*end != '\0') { + return -1; + } + return 0; +} + +const char *GetProductModel_(void) +{ + static const char *productModel = NULL; + return GetProperty("const.product.model", &productModel); +} + +const char *GetManufacture_(void) +{ + static const char *productManufacture = NULL; + return GetProperty("const.product.manufacturer", &productManufacture); +} + +#ifdef USE_MBEDTLS +static int GetSha256Value(const char *input, char *udid, int udidSize) +{ + if (input == NULL) { + return EC_FAILURE; + } + char buf[DEV_BUF_LENGTH] = { 0 }; + unsigned char hash[HASH_LENGTH] = { 0 }; + + mbedtls_sha256_context context; + mbedtls_sha256_init(&context); + mbedtls_sha256_starts_ret(&context, 0); + mbedtls_sha256_update_ret(&context, (const unsigned char)input, strlen(input)); + mbedtls_sha256_finish_ret(&context, hash); + + for (size_t i = 0; i < HASH_LENGTH; i++) { + unsigned char value = hash[i]; + memset_s(buf, DEV_BUF_LENGTH, 0, DEV_BUF_LENGTH); + int len = sprintf_s(buf, sizeof(buf), "%02X", value); + if (len > 0 && strcat_s(udid, udidSize, buf) != 0) { + return EC_FAILURE; + } + } + return EC_SUCCESS; +} +#elif !(defined OHOS_LITE) +static int GetSha256Value(const char *input, char *udid, int udidSize) +{ + char buf[DEV_BUF_LENGTH] = { 0 }; + unsigned char hash[SHA256_DIGEST_LENGTH] = { 0 }; + SHA256_CTX sha256; + if ((SHA256_Init(&sha256) == 0) || (SHA256_Update(&sha256, input, strlen(input)) == 0) || + (SHA256_Final(hash, &sha256) == 0)) { + return -1; + } + + for (size_t i = 0; i < SHA256_DIGEST_LENGTH; i++) { + unsigned char value = hash[i]; + (void)memset_s(buf, DEV_BUF_LENGTH, 0, DEV_BUF_LENGTH); + int len = sprintf_s(buf, sizeof(buf), "%02X", value); + if (len > 0 && strcat_s(udid, udidSize, buf) != 0) { + return -1; + } + } + return 0; +} +#else +static int GetSha256Value(const char *input, char *udid, int udidSize) +{ + return EC_FAILURE; +} +#endif + +const char *GetSerial_(void) +{ + const char *serialNumberss = NULL; + GetProperty("ohos.boot.sn", &serialNumberss); + return serialNumberss; +} + +int GetDevUdid_(char *udid, int size) +{ + const char *manufacture = GetManufacture_(); + const char *model = GetProductModel_(); + const char *sn = GetSerial_(); + if (manufacture == NULL || model == NULL || sn == NULL) { + return -1; + } + int tmpSize = strlen(manufacture) + strlen(model) + strlen(sn) + 1; + if (tmpSize <= 0 || tmpSize > DEV_BUF_MAX_LENGTH) { + free((void *)sn); + return -1; + } + char *tmp = (char *)malloc(tmpSize); + if (tmp == NULL) { + free((void *)sn); + return -1; + } + + (void)memset_s(tmp, tmpSize, 0, tmpSize); + if ((strcat_s(tmp, tmpSize, manufacture) != 0) || (strcat_s(tmp, tmpSize, model) != 0) || + (strcat_s(tmp, tmpSize, sn) != 0)) { + free(tmp); + free((void *)sn); + return -1; + } + + int ret = GetSha256Value(tmp, udid, size); + free(tmp); + free((void *)sn); + return ret; +} \ No newline at end of file diff --git a/interfaces/innerkits/syspara/param_comm.h b/interfaces/innerkits/syspara/param_comm.h new file mode 100755 index 0000000000000000000000000000000000000000..f632c6747d00946b3088adc93e5e90704c3c0704 --- /dev/null +++ b/interfaces/innerkits/syspara/param_comm.h @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2021 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 INIT_PARAM_COMM_H +#define INIT_PARAM_COMM_H +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +#define UDID_LEN 65 +#define MAX_SERIAL_LEN 65 +#define HASH_LENGTH 32 +#define DEV_BUF_LENGTH 3 +#define DEV_BUF_MAX_LENGTH 1024 +#define DECIMAL 10 +#define HEX 16 + +const char *GetProperty(const char *key, const char **paramHolder); + +int StringToULL(const char *str, unsigned long long int *out); +int StringToLL(const char *str, long long int *out); +int HalGetParameter(const char *key, const char *def, char *value, unsigned int len); + +const char *GetProductModel_(void); +const char *GetManufacture_(void); +const char *GetSerial_(void); +int GetDevUdid_(char *udid, int size); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif // STARTUP_PARAM_COMM_H diff --git a/interfaces/innerkits/syspara/param_wrapper.cpp b/interfaces/innerkits/syspara/param_wrapper.cpp new file mode 100755 index 0000000000000000000000000000000000000000..db704db62fed329470f2c5823f29f6c54b286d56 --- /dev/null +++ b/interfaces/innerkits/syspara/param_wrapper.cpp @@ -0,0 +1,172 @@ +/* + * Copyright (c) 2021 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 "param_wrapper.h" + +#include +#include +#include + +#include "param_comm.h" +#include "init_param.h" +#include "sysparam_errno.h" +#include "securec.h" +#include "parameter.h" +#include "parameters.h" + +namespace OHOS { +namespace system { +bool SetParameter(const std::string& key, const std::string& value) +{ + int ret = SystemSetParameter(key.c_str(), value.c_str()); + return (ret == 0) ? EC_SUCCESS : EC_FAILURE; +} + +template +bool StringToInt(const std::string& str, T min, T max, T& out) +{ + long long int result = 0; + if (StringToLL(str.c_str(), &result) != 0) { + return false; + } + if (result < min || max < result) { + return false; + } + out = static_cast(result); + return true; +} + +template +bool StringToUint(const std::string& str, T max, T& out) +{ + unsigned long long int result = 0; + if (StringToULL(str.c_str(), &result) != 0) { + return false; + } + if (max < result) { + return false; + } + out = static_cast(result); + return true; +} + +std::string GetParameter(const std::string& key, const std::string& def) +{ + uint32_t size = 0; + int ret = SystemReadParam(key.c_str(), NULL, &size); + if (ret != 0) { + return std::string(def); + } + std::vector value(size + 1); + ret = SystemReadParam(key.c_str(), value.data(), &size); + if (ret == 0) { + return std::string(value.data()); + } + return std::string(def); +} + +bool GetBoolParameter(const std::string& key, bool def) +{ + static const std::string trueMap[] = { "1", "y", "yes", "on", "true" }; + static const std::string falseMap[] = { "0", "off", "n", "no", "false" }; + std::string value = GetParameter(key, ""); + for (size_t i = 0; i < sizeof(trueMap) / sizeof(trueMap[0]); i++) { + if (trueMap[i] == value) { + return true; + } + } + for (size_t i = 0; i < sizeof(falseMap) / sizeof(falseMap[0]); i++) { + if (falseMap[i] == value) { + return false; + } + } + return def; +} + +int GetStringParameter(const std::string key, std::string &value, const std::string def) +{ + uint32_t size = 0; + int ret = SystemReadParam(key.c_str(), NULL, &size); + if (ret != 0) { + value = def; + return EC_FAILURE; + } + value.resize(size + 1); + ret = SystemReadParam(key.c_str(), const_cast(value.data()), &size); + if (ret == 0) { + return EC_SUCCESS; + } + value = def; + return EC_FAILURE; +} + +template +T GetIntParameter(const std::string& key, T def, T min, T max) +{ + if (!std::is_signed::value) { + return def; + } + T result; + std::string value = GetParameter(key, ""); + if (!value.empty() && StringToInt(value, min, max, result)) { + return result; + } + return def; +} + +template int8_t GetIntParameter(const std::string&, int8_t, int8_t, int8_t); +template int16_t GetIntParameter(const std::string&, int16_t, int16_t, int16_t); +template int32_t GetIntParameter(const std::string&, int32_t, int32_t, int32_t); +template int64_t GetIntParameter(const std::string&, int64_t, int64_t, int64_t); + +template +T GetUintParameter(const std::string& key, T def, T max) +{ + if (!std::is_unsigned::value) { + return def; + } + T result; + std::string value = GetParameter(key, ""); + if (!value.empty() && StringToUint(value, max, result)) { + return result; + } + return def; +} + +template uint8_t GetUintParameter(const std::string&, uint8_t, uint8_t); +template uint16_t GetUintParameter(const std::string&, uint16_t, uint16_t); +template uint32_t GetUintParameter(const std::string&, uint32_t, uint32_t); +template uint64_t GetUintParameter(const std::string&, uint64_t, uint64_t); + +std::string GetDeviceType(void) +{ + std::unordered_map deviceTypeMap = { + {"watch", "wearable"}, + {"fitnessWatch", "liteWearable"}, + }; + static const char *productType = nullptr; + const char *type = GetProperty("const.build.characteristics", &productType); + if (deviceTypeMap.count(type) != 0) { + return deviceTypeMap[type]; + } + return std::string(type); +} + +int GetIntParameter(const std::string key, int def) +{ + return GetIntParameter(key, def, INT_MIN, INT_MAX); +} +} // namespace system +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/syspara/parameter.c b/interfaces/innerkits/syspara/parameter.c new file mode 100755 index 0000000000000000000000000000000000000000..83f3cc86fcd6282327414ca78738d2171405c642 --- /dev/null +++ b/interfaces/innerkits/syspara/parameter.c @@ -0,0 +1,346 @@ +/* + * Copyright (c) 2021 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 "parameter.h" + +#include +#include + +#include "param_comm.h" +#include "init_param.h" +#include "sysparam_errno.h" +#include "securec.h" +#include "sysversion.h" + +int WaitParameter(const char *key, const char *value, int timeout) +{ + if ((key == NULL) || (value == NULL)) { + return EC_INVALID; + } + return SystemWaitParameter(key, value, timeout); +} + +uint32_t FindParameter(const char *key) +{ + if (key == NULL) { + return (uint32_t)(-1); + } + uint32_t handle = 0; + int ret = SystemFindParameter(key, &handle); + if (ret != 0) { + return (uint32_t)(-1); + } + return handle; +} + +uint32_t GetParameterCommitId(uint32_t handle) +{ + uint32_t commitId = 0; + int ret = SystemGetParameterCommitId(handle, &commitId); + if (ret != 0) { + return (uint32_t)(-1); + } + return commitId; +} + +int GetParameterName(uint32_t handle, char *name, uint32_t len) +{ + if (name == NULL) { + return EC_INVALID; + } + int ret = SystemGetParameterName(handle, name, len); + return (ret != 0) ? EC_FAILURE : strlen(name); +} + +int GetParameterValue(uint32_t handle, char *value, uint32_t len) +{ + if (value == NULL) { + return EC_INVALID; + } + uint32_t size = len; + int ret = SystemGetParameterValue(handle, value, &size); + return (ret != 0) ? EC_FAILURE : strlen(value); +} + +int GetParameter(const char *key, const char *def, char *value, uint32_t len) +{ + if ((key == NULL) || (value == NULL)) { + return EC_INVALID; + } + int ret = HalGetParameter(key, def, value, len); + return (ret != 0) ? EC_INVALID : strlen(value); +} + +int GetIntParameter(const char *key, int def) +{ + int out = 0; + char value[32] = {0}; // 32 max for int + int ret = GetParameter(key, "0", value, sizeof(value)); + if (ret != 0) { + return out; + } + long long int result = 0; + if (StringToLL(value, &result) != 0) { + return def; + } + return (int32_t)result; +} + +int SetParameter(const char *key, const char *value) +{ + if ((key == NULL) || (value == NULL)) { + return EC_INVALID; + } + int ret = SystemSetParameter(key, value); + return (ret == 0) ? EC_SUCCESS : EC_FAILURE; +} + +const char *GetDeviceType(void) +{ + static const char *productType = NULL; + return GetProperty("const.build.characteristics", &productType); +} + +const char *GetProductModel(void) +{ + return GetProductModel_(); +} + +const char *GetManufacture(void) +{ + return GetManufacture_(); +} + +const char *GetBrand(void) +{ + static const char *productBrand = NULL; + return GetProperty("const.product.brand", &productBrand); +} + +const char *GetMarketName(void) +{ + static const char *marketName = NULL; + return GetProperty("const.product.name", &marketName); +} + +const char *GetProductSeries(void) +{ + static const char *productSeries = NULL; + return GetProperty("const.build.product", &productSeries); +} + +const char *GetSoftwareModel(void) +{ + static const char *softwareModel = NULL; + return GetProperty("const.software.model", &softwareModel); +} + +const char *GetHardwareModel(void) +{ + static const char *hardwareModel = NULL; + return GetProperty("const.product.hardwareversion", &hardwareModel); +} + +const char *GetHardwareProfile(void) +{ + static const char *hardwareProfile = NULL; + return GetProperty("const.product.hardwareprofile", &hardwareProfile); +} + +const char *GetAbiList(void) +{ + static const char *productAbiList = NULL; + return GetProperty("const.product.cpu.abilist", &productAbiList); +} + +const char *GetBootloaderVersion(void) +{ + static const char *productBootloader = NULL; + return GetProperty("const.product.bootloader.version", &productBootloader); +} + +int GetFirstApiVersion(void) +{ + static const char *firstApiVersion = NULL; + GetProperty("const.product.firstapiversion", &firstApiVersion); + if (firstApiVersion == NULL) { + return 0; + } + return atoi(firstApiVersion); +} + +const char *GetDisplayVersion(void) +{ + static const char *displayVersion = NULL; + return GetProperty("const.product.software.version", &displayVersion); +} + +const char *GetIncrementalVersion(void) +{ + static const char *incrementalVersion = NULL; + return GetProperty("const.product.incremental.version", &incrementalVersion); +} + +const char *HalGetOsReleaseType(void) +{ + static const char *osReleaseType = NULL; + return GetProperty("const.ohos.releasetype", &osReleaseType); +} + +const char *HalGetSdkApiVersion(void) +{ + static const char *sdkApiVersion = NULL; + return GetProperty("const.ohos.apiversion", &sdkApiVersion); +} + +const char *GetBuildType(void) +{ + static const char *buildType = NULL; + return GetProperty("const.product.build.type", &buildType); +} + +const char *GetBuildUser(void) +{ + static const char *buildUser = NULL; + return GetProperty("const.product.build.user", &buildUser); +} + +const char *GetBuildHost(void) +{ + static const char *buildHost = NULL; + return GetProperty("const.product.build.host", &buildHost); +} + +const char *GetBuildTime(void) +{ + static const char *buildTime = NULL; + return GetProperty("const.product.build.date", &buildTime); +} + +const char *GetSerial(void) +{ + static const char *ohos_serial = NULL; + return GetProperty("ohos.boot.sn", &ohos_serial); +} + +int GetDevUdid(char *udid, int size) +{ + return GetDevUdid_(udid, size); +} + +static const char *GetOSName(void) +{ + static const char *osName = NULL; + return GetProperty("const.ohos.name", &osName); +} + +static const char *BuildOSFullName(void) +{ + const char release[] = "Release"; + char value[OS_FULL_NAME_LEN]; + const char *releaseType = GetOsReleaseType(); + int length; + if ((releaseType == NULL) || (strncmp(releaseType, release, sizeof(release) - 1) == 0)) { + length = sprintf_s(value, OS_FULL_NAME_LEN, "%s-%d.%d.%d.%d", + GetOSName(), GetMajorVersion(), GetSeniorVersion(), GetFeatureVersion(), GetBuildVersion()); + } else { + length = sprintf_s(value, OS_FULL_NAME_LEN, "%s-%d.%d.%d.%d(%s)", + GetOSName(), GetMajorVersion(), GetSeniorVersion(), GetFeatureVersion(), GetBuildVersion(), releaseType); + } + if (length < 0) { + return EMPTY_STR; + } + const char *osFullName = strdup(value); + return osFullName; +} + +const char *GetOSFullName(void) +{ + static const char *osFullName = NULL; + if (osFullName != NULL) { + return osFullName; + } + osFullName = BuildOSFullName(); + if (osFullName == NULL) { + return EMPTY_STR; + } + return osFullName; +} + +static int GetSdkApiLevel(void) +{ + static const char *sdkApiLevel = NULL; + GetProperty("const.ohos.sdkapilevel", &sdkApiLevel); + if (sdkApiLevel == NULL) { + return 0; + } + return atoi(sdkApiLevel); +} + +static const char *BuildVersionId(void) +{ + char value[VERSION_ID_MAX_LEN]; + + int len = sprintf_s(value, VERSION_ID_MAX_LEN, "%s/%s/%s/%s/%s/%s/%s/%d/%s/%s", + GetDeviceType(), GetManufacture(), GetBrand(), GetProductSeries(), + GetOSFullName(), GetProductModel(), GetSoftwareModel(), + GetSdkApiLevel(), GetIncrementalVersion(), GetBuildType()); + if (len <= 0) { + return EMPTY_STR; + } + const char *versionId = strdup(value); + return versionId; +} + +const char *GetVersionId(void) +{ + static const char *ohosVersionId = NULL; + if (ohosVersionId != NULL) { + return ohosVersionId; + } + ohosVersionId = BuildVersionId(); + if (ohosVersionId == NULL) { + return EMPTY_STR; + } + return ohosVersionId; +} + +const char *GetOsReleaseType(void) +{ + static const char *osReleaseType = NULL; + return GetProperty("const.ohos.releasetype", &osReleaseType); +} + +int GetSdkApiVersion(void) +{ + static const char *sdkApiVersion = NULL; + GetProperty("const.ohos.apiversion", &sdkApiVersion); + if (sdkApiVersion == NULL) { + return 0; + } + return atoi(sdkApiVersion); +} + +const char *GetSecurityPatchTag(void) +{ + static const char *securityPatchTag = NULL; + return GetProperty("const.ohos.version.security_patch", &securityPatchTag); +} + +const char *GetBuildRootHash(void) +{ + static const char *buildRootHash = NULL; + return GetProperty("const.ohos.buildroothash", &buildRootHash); +} \ No newline at end of file diff --git a/interfaces/innerkits/syspara/sysversion.c b/interfaces/innerkits/syspara/sysversion.c new file mode 100755 index 0000000000000000000000000000000000000000..61b54cb5e9fdeb63d0ea0da77edf21875ce6686b --- /dev/null +++ b/interfaces/innerkits/syspara/sysversion.c @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2021 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 "sysversion.h" + +/* * + * Major(M) version number. + */ +static int g_majorVersion = 2; + +/* * + * Senior(S) version number. + */ +static int g_seniorVersion = 2; + +/* * + * Feature(F) version number. + */ +static int g_featureVersion = 0; + +/* * + * Build(B) version number. + */ +static int g_buildVersion = 0; + +/* * + * Obtains the major (M) version number, which increases with any updates to the overall architecture. + *

The M version number monotonically increases from 1 to 99. + * + * @return Returns the M version number. + * @since 4 + */ +int GetMajorVersion(void) +{ + return g_majorVersion; +} + +/* * + * Obtains the senior (S) version number, which increases with any updates to the partial + * architecture or major features. + *

The S version number monotonically increases from 0 to 99. + * + * @return Returns the S version number. + * @since 4 + */ +int GetSeniorVersion(void) +{ + return g_seniorVersion; +} + +/* * + * Obtains the feature (F) version number, which increases with any planned new features. + *

The F version number monotonically increases from 0 or 1 to 99. + * + * @return Returns the F version number. + * @since 3 + */ +int GetFeatureVersion(void) +{ + return g_featureVersion; +} + +/* * + * Obtains the build (B) version number, which increases with each new development build. + *

The B version number monotonically increases from 0 or 1 to 999. + * + * @return Returns the B version number. + * @since 3 + */ +int GetBuildVersion(void) +{ + return g_buildVersion; +} \ No newline at end of file diff --git a/interfaces/innerkits/token/BUILD.gn b/interfaces/innerkits/token/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..de2f039ec7a5851ee9cf014e7631fde07c338044 --- /dev/null +++ b/interfaces/innerkits/token/BUILD.gn @@ -0,0 +1,72 @@ +# +# Copyright (c) 2020 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("//build/lite/config/component/lite_component.gni") +import("//build/lite/ndk/ndk.gni") + +if (ohos_kernel_type == "liteos_a" || ohos_kernel_type == "linux") { + shared_library("token_shared") { + cflags = [ "-Wall" ] + include_dirs = [ + "//base/startup/init_lite/interfaces/innerkits/include", + "//base/startup/init_lite/interfaces/innerkits/include/token", + "//utils/native/lite/include", + "//base/startup/init_lite/interfaces/innerkits/token", + ] + sources = [ "src/token_impl_posix/token.c" ] + + public_deps = [ + "$ohos_product_adapter_dir/utils/token:haltoken_shared", + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", + ] + } +} + +if (ohos_kernel_type == "liteos_m") { + static_library("token_static") { + sources = [ "src/token_impl_hal/token.c" ] + + include_dirs = [ + "//base/startup/init_lite/interfaces/innerkits/include", + "//base/startup/init_lite/interfaces/innerkits/include/token", + "//utils/native/lite/include", + "//base/startup/init_lite/interfaces/innerkits/token", + "//base/hiviewdfx/hilog_lite/interfaces/native/kits/hilog_lite", + ] + + deps = [ "$ohos_product_adapter_dir/utils/token:hal_token_static" ] + } +} + +lite_component("token") { + features = [] + if (ohos_kernel_type == "liteos_a" || ohos_kernel_type == "linux") { + features += [ ":token_shared" ] + } + if (ohos_kernel_type == "liteos_m") { + features += [ ":token_static" ] + } +} + +ndk_lib("token_notes1") { + if (ohos_kernel_type != "liteos_m") { + lib_extension = ".so" + } + deps = [] + if (ohos_kernel_type != "liteos_m") { + deps += + [ "//base/startup/init_lite/interfaces/innerkits/token:token_shared" ] + } + head_files = [ "//base/startup/init_lite/interfaces/include/token" ] +} diff --git a/interfaces/innerkits/token/hal_token.h b/interfaces/innerkits/token/hal_token.h new file mode 100755 index 0000000000000000000000000000000000000000..7ba2fd7db002a9771708109a2fb19f3f9747b8ba --- /dev/null +++ b/interfaces/innerkits/token/hal_token.h @@ -0,0 +1,83 @@ +/* +* Copyright (c) 2020 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 HAL_TOKEN_H +#define HAL_TOKEN_H + +#include + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif /* __cplusplus */ + +#define KIT_FRAMEWORK_UID_MAX 1000 + +/** + * @brief Read token value from device. + * + * @param token the result token value, if read successfully. + * @param len length of the token. + * @returns 0 if success and get the update area token, + * 1 if success and get the pre-made token, + * -1 if failed, + * -2 if no pre-made token. + */ +int HalReadToken(char *token, unsigned int len); + +/** + * @brief Write token value to device. + * + * @param token the token to write. + * @param len length of the token. + * @returns 0 if success, otherwise -1. + */ +int HalWriteToken(const char *token, unsigned int len); + +/** + * @brief Get AcKey value from device. + * + * @param acKey the result acKey, if get successfully. + * @param len length of the acKey. + * @returns 0 if success, otherwise -1. + */ +int HalGetAcKey(char *acKey, unsigned int len); + +/** + * @brief Get ProdId value from device. + * + * @param productId product IDs to be populated with. + * @param len length of the productId. + * @returns 0 if success, otherwise -1. + */ +int HalGetProdId(char *productId, unsigned int len); + +/** + * @brief Get ProdKey value from device. + * + * @param productKey The productKey value + * @param len The productKey len. + * @returns 0 if success, otherwise -1. + */ +int HalGetProdKey(char *productKey, unsigned int len); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif /* __cplusplus */ + +#endif // HAL_TOKEN_H diff --git a/interfaces/innerkits/token/src/token_impl_hal/token.c b/interfaces/innerkits/token/src/token_impl_hal/token.c new file mode 100755 index 0000000000000000000000000000000000000000..bb6fee581ef6dcc1a64c84a757254f4689aafd1e --- /dev/null +++ b/interfaces/innerkits/token/src/token_impl_hal/token.c @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2020 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 "token.h" +#include "hal_token.h" +#include "log.h" +#include "ohos_errno.h" + +int ReadToken(char *token, unsigned int len) +{ + if (token == NULL) { + HILOG_ERROR(HILOG_MODULE_HIVIEW, "token is nullptr\n"); + return EC_FAILURE; + } + + return HalReadToken(token, len); +} + +int WriteToken(const char *token, unsigned int len) +{ + if (token == NULL) { + HILOG_ERROR(HILOG_MODULE_HIVIEW, "token is nullptr\n"); + return EC_FAILURE; + } + + return HalWriteToken(token, len); +} + +int GetAcKey(char *acKey, unsigned int len) +{ + if (acKey == NULL) { + HILOG_ERROR(HILOG_MODULE_HIVIEW, "acKey is nullptr"); + return EC_FAILURE; + } + + return HalGetAcKey(acKey, len); +} + +int GetProdId(char *productId, unsigned int len) +{ + if (productId == NULL) { + HILOG_ERROR(HILOG_MODULE_HIVIEW, "productId is nullptr"); + return EC_FAILURE; + } + + return HalGetProdId(productId, len); +} + +int GetProdKey(char *productKey, unsigned int len) +{ + if (productKey == NULL) { + HILOG_ERROR(HILOG_MODULE_HIVIEW, "productKey is nullptr"); + return EC_FAILURE; + } + + return HalGetProdKey(productKey, len); +} \ No newline at end of file diff --git a/interfaces/innerkits/token/src/token_impl_posix/token.c b/interfaces/innerkits/token/src/token_impl_posix/token.c new file mode 100755 index 0000000000000000000000000000000000000000..8c1f032f9f7c8a0b2fea11c1bf3aa88c7609fd29 --- /dev/null +++ b/interfaces/innerkits/token/src/token_impl_posix/token.c @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2020 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 "token.h" +#include +#include +#include +#include +#include "hal_token.h" +#include "log.h" +#include "ohos_errno.h" + +static pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER; + +static int UidVerify(void) +{ + uid_t uid; + + uid = getuid(); + if (uid >= KIT_FRAMEWORK_UID_MAX) { + HILOG_ERROR(HILOG_MODULE_HIVIEW, "uid verify failed, get uid:%d", uid); + return EC_FAILURE; + } + + return EC_SUCCESS; +} + +int ReadToken(char *token, unsigned int len) +{ + int ret; + + if (token == NULL) { + HILOG_ERROR(HILOG_MODULE_HIVIEW, "token is nullptr"); + return EC_FAILURE; + } + ret = UidVerify(); + if (ret != EC_SUCCESS) { + return EC_FAILURE; + } + + pthread_mutex_lock(&g_mutex); + ret = HalReadToken(token, len); + pthread_mutex_unlock(&g_mutex); + + return ret; +} + +int WriteToken(const char *token, unsigned int len) +{ + int ret; + + if (token == NULL) { + HILOG_ERROR(HILOG_MODULE_HIVIEW, "token is nullptr"); + return EC_FAILURE; + } + ret = UidVerify(); + if (ret != EC_SUCCESS) { + return EC_FAILURE; + } + + pthread_mutex_lock(&g_mutex); + ret = HalWriteToken(token, len); + pthread_mutex_unlock(&g_mutex); + + return ret; +} + +int GetAcKey(char *acKey, unsigned int len) +{ + if (acKey == NULL) { + HILOG_ERROR(HILOG_MODULE_HIVIEW, "acKey is nullptr"); + return EC_FAILURE; + } + int ret = UidVerify(); + if (ret != EC_SUCCESS) { + return EC_FAILURE; + } + + return HalGetAcKey(acKey, len); +} + +int GetProdId(char *productId, unsigned int len) +{ + if (productId == NULL) { + HILOG_ERROR(HILOG_MODULE_HIVIEW, "productId is nullptr"); + return EC_FAILURE; + } + + return HalGetProdId(productId, len); +} + +int GetProdKey(char *productKey, unsigned int len) +{ + if (productKey == NULL) { + HILOG_ERROR(HILOG_MODULE_HIVIEW, "productKey is nullptr"); + return EC_FAILURE; + } + + int ret = UidVerify(); + if (ret != EC_SUCCESS) { + return EC_FAILURE; + } + + return HalGetProdKey(productKey, len); +} \ No newline at end of file diff --git a/interfaces/kits/jskits/@ohos.deviceInfo.d.ts b/interfaces/kits/jskits/@ohos.deviceInfo.d.ts new file mode 100755 index 0000000000000000000000000000000000000000..38199d28f47a711da06a6231a0c6370ffaed8074 --- /dev/null +++ b/interfaces/kits/jskits/@ohos.deviceInfo.d.ts @@ -0,0 +1,245 @@ +/* + * Copyright (c) 2021 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. + */ + +/** + * A static class pertaining to the product information. + * + * @devices phone, tablet + * @since 6 + * @Syscap SystemCapability.Startup.SysInfo + */ +declare namespace deviceInfo { + /** + * Obtains the device type represented by a string, + * which can be {@code phone} (or {@code default} for phones), {@code wearable}, {@code liteWearable}, + * {@code tablet}, {@code tv}, {@code car}, or {@code smartVision}. + * + * @since 6 + */ + const deviceType: string; + + /** + * Obtains the device manufacturer represented by a string. + * + * @since 6 + */ + const manufacture: string; + + /** + * Obtains the device brand represented by a string. + * + * @since 6 + */ + const brand: string; + + /** + * Obtains the external product series represented by a string. + * + * @since 6 + */ + const marketName: string; + + /** + * Obtains the product series represented by a string. + * + * @since 6 + */ + const productSeries: string; + + /** + * Obtains the product model represented by a string. + * + * @since 6 + */ + const productModel: string; + + /** + * Obtains the software model represented by a string. + * + * @since 6 + */ + const softwareModel: string; + + /** + * Obtains the hardware model represented by a string. + * + * @since 6 + */ + const hardwareModel: string; + + /** + * Obtains the hardware profile represented by a string. + * + * @since 6 + */ + const hardwareProfile: string; + + /** + * Obtains the device serial number represented by a string. + * + * @since 6 + */ + const serial: string; + + /** + * Obtains the bootloader version number represented by a string. + * + * @since 6 + */ + const bootloaderVersion: string; + + /** + * Obtains the application binary interface (Abi) list represented by a string. + * + * @since 6 + */ + const abiList: string; + + /** + * Obtains the security patch level represented by a string. + * + * @since 6 + */ + const securityPatchTag: string; + + /** + * Obtains the product version represented by a string. + * + * @since 6 + */ + const displayVersion: string; + + /** + * Obtains the incremental version represented by a string. + * + * @since 6 + */ + const incrementalVersion: string; + + /** + * Obtains the OS release type represented by a string. + * + *

The OS release category can be {@code Release}, {@code Beta}, or {@code Canary}. + * The specific release type may be {@code Release}, {@code Beta1}, or others alike. + * + * @since 6 + */ + const osReleaseType: string; + + /** + * Obtains the OS version represented by a string. + * + * @since 6 + */ + const osFullName: string; + + /** + * Obtains the major (M) version number, which increases with any updates to the overall architecture. + *

The M version number monotonically increases from 1 to 99. + * + * @since 6 + */ + const majorVersion: number; + + /** + * Obtains the senior (S) version number, which increases with any updates to the partial + * architecture or major features. + *

The S version number monotonically increases from 0 to 99. + * + * @since 6 + */ + const seniorVersion: number; + + /** + * Obtains the feature (F) version number, which increases with any planned new features. + *

The F version number monotonically increases from 0 or 1 to 99. + * + * @since 6 + */ + const featureVersion: number; + + /** + * Obtains the build (B) version number, which increases with each new development build. + *

The B version number monotonically increases from 0 or 1 to 999. + * + * @since 6 + */ + const buildVersion: number; + + /** + * Obtains the SDK API version number. + * + * @since 6 + */ + const sdkApiVersion: number; + + /** + * Obtains the first API version number. + * + * @since 6 + */ + const firstApiVersion: number; + + /** + * Obtains the version ID by a string. + * + * @since 6 + */ + const versionId: string; + + /** + * Obtains the build types of the same baseline code. + * + * @since 6 + */ + const buildType: string; + + /** + * Obtains the different build user of the same baseline code. + * + * @since 6 + */ + const buildUser: string; + + /** + * Obtains the different build host of the same baseline code. + * + * @since 6 + */ + const buildHost: string; + + /** + * Obtains the build time. + * + * @since 6 + */ + const buildTime: string; + + /** + * Obtains the version hash. + * + * @since 6 + */ + const buildRootHash: string; + + /** + * Obtains the device udid. + * + * @since 7 + */ + const udid: string; +} + +export default deviceInfo; diff --git a/interfaces/kits/jskits/@ohos.systemparameter.d.ts b/interfaces/kits/jskits/@ohos.systemparameter.d.ts new file mode 100755 index 0000000000000000000000000000000000000000..4bffed19aa3874e09f8b6e106a9eed3071f12ff6 --- /dev/null +++ b/interfaces/kits/jskits/@ohos.systemparameter.d.ts @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2021 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 { AsyncCallback, BusinessError } from './basic'; + + /** + * The interface of system parameters class. + * + * @devices phone, tablet + * @since 6 + * @Syscap SystemCapability.Startup.SysInfo + * @systemapi + */ +declare namespace systemParameter { + /** + * Gets the value of the attribute with the specified key. + * + * @param key Key of the system attribute. + * @param def Default value. + * @return if the parameter is empty or doesn't exist, empty string will be returned. + * @since 6 + */ + function getSync(key: string, def?: string): string; + + /** + * Gets the value of the attribute with the specified key. + * + * @param key Key of the system attribute. + * @param callback Callback function. + * @since 6 + */ + function get(key: string, callback: AsyncCallback): void; + + /** + * Gets the value of the attribute with the specified key. + * + * @param key Key of the system attribute. + * @param def Default value. + * @param callback Callback function. + * @since 6 + */ + function get(key: string, def: string, callback: AsyncCallback): void; + + /** + * Gets the value of the attribute with the specified key. + * + * @param key Key of the system attribute. + * @param def Default value. + * @return Promise, which is used to obtain the result asynchronously. + * @since 6 + */ + function get(key: string, def?: string): Promise; + + /** + * Sets a value for the attribute with the specified key. + * + * @param key Key of the system attribute. + * @param value System attribute value to set. + * @since 6 + */ + function setSync(key: string, value: string): void; + + /** + * Sets a value for the attribute with the specified key. + * + * @param key Key of the system attribute. + * @param value System attribute value to set. + * @param callback Callback function. + * @since 6 + */ + function set(key: string, value: string, callback: AsyncCallback): void; + + /** + * Sets a value for the attribute with the specified key. + * + * @param key Key of the system attribute. + * @param value Default value. + * @return Promise, which is used to obtain the result asynchronously. + * @since 6 + */ + function set(key: string, value: string): Promise; + + /** + * Wait for a parameter with specified value. + * + * @param key Key of the system parameter. + * @param value System parameter value to be wait. + * @param timeout Indicates the timeout value, in seconds. + * <=0 means wait for ever. + * >0 means wait for specified seconds + * @param callback Callback function. + * @since 7 + */ + function wait(key: string, value: string, timeout: number, callback: AsyncCallback): void; + + /** + * Sets a value for the parameter with the specified key. + * + * @param key Key of the system parameter. + * @param value System parameter value to be wait. + * @param timeout Indicates the timeout value, in seconds. + * <=0 means wait for ever. + * >0 means wait for specified seconds + * @return Promise, which is used to obtain the result asynchronously. + * @since 7 + */ + function wait(key: string, value: string, timeout: number): Promise; + + /** + * Wait for a parameter with specified value. + * + * @param keyPrefix Key prefix of the system parameters to be watched. + * @param callback Callback function. + * @since 7 + */ + function getWatcher(keyPrefix: string): Watcher; + + /** + * Called when the system parameter value changes. You need to implement this method in a child class. + * + * @param key Indicates changed system parameter key name. + * @param value Indicates changed system parameter value. + * @since 7 + */ + export interface ParameterChangeCallback { + (key: string, value: string): void; + } + + export interface Watcher { + /** + * Subscribe to parameter value changess + * + * @since 7 + */ + on(eventType: 'valueChange', callback: ParameterChangeCallback): void; + /** + * Unsubscribe to parameter value changess + * + * @since 7 + */ + off(eventType: 'valueChange', callback?: ParameterChangeCallback): void; + } +} + +export default systemParameter; diff --git a/interfaces/kits/jskits/BUILD.gn b/interfaces/kits/jskits/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..22e766da0cdf1a3338440719f9c0798578f4e06b --- /dev/null +++ b/interfaces/kits/jskits/BUILD.gn @@ -0,0 +1,67 @@ +# Copyright (c) 2021 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("//build/ohos.gni") + +ohos_shared_library("deviceinfo_init") { + include_dirs = [ "//base/startup/init_lite/interfaces/innerkits/include" ] + + sources = [ "src/native_deviceinfo_js.cpp" ] + + deps = [ + "//base/startup/init_lite/interfaces/innerkits:libbeget_proxy", + "//base/startup/init_lite/interfaces/innerkits:libbegetutil", + ] + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "napi:ace_napi", + ] + relative_install_dir = "module" + subsystem_name = "startup" + part_name = "startup_l2" +} + +ohos_shared_library("systemparameter_init") { + include_dirs = [ "src" ] + + sources = [ + "src/native_parameters_js.cpp", + "src/native_parameters_watch.cpp", + ] + + deps = [ + "//base/startup/init_lite/interfaces/innerkits:libbeget_proxy", + "//base/startup/init_lite/interfaces/innerkits:libbegetutil", + ] + + external_deps = [ + "hiviewdfx_hilog_native:libhilog", + "napi:ace_napi", + ] + relative_install_dir = "module" + subsystem_name = "startup" + part_name = "startup_l2" +} + +group("syspara_js_init") { + deps = [ + "//base/startup/init_lite/interfaces/innerkits:libbeget_proxy", + "//base/startup/init_lite/interfaces/innerkits:libbegetutil", + ] + if (support_jsapi) { + deps += [ + ":deviceinfo_init", + ":systemparameter_init", + ] + } +} diff --git a/interfaces/kits/jskits/src/native_deviceinfo_js.cpp b/interfaces/kits/jskits/src/native_deviceinfo_js.cpp new file mode 100755 index 0000000000000000000000000000000000000000..033033da8e0c9d01500ffa019bda309eac56055f --- /dev/null +++ b/interfaces/kits/jskits/src/native_deviceinfo_js.cpp @@ -0,0 +1,362 @@ +/* + * Copyright (c) 2021 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 "napi/native_api.h" +#include "napi/native_node_api.h" +#include "parameter.h" +#include "sysversion.h" + +const int UDID_LEN = 65; + +static napi_value GetDeviceType(napi_env env, napi_callback_info info) +{ + napi_value deviceType = nullptr; + const char *value = GetDeviceType(); + + NAPI_CALL(env, napi_create_string_utf8(env, value, strlen(value), &deviceType)); + return deviceType; +} + +static napi_value GetManufacture(napi_env env, napi_callback_info info) +{ + napi_value napiValue = nullptr; + const char *manfactureName = GetManufacture(); + + NAPI_CALL(env, napi_create_string_utf8(env, manfactureName, strlen(manfactureName), &napiValue)); + return napiValue; +} + +static napi_value GetBrand(napi_env env, napi_callback_info info) +{ + napi_value napiValue = nullptr; + const char *productBrand = GetBrand(); + + NAPI_CALL(env, napi_create_string_utf8(env, productBrand, strlen(productBrand), &napiValue)); + return napiValue; +} + +static napi_value GetMarketName(napi_env env, napi_callback_info info) +{ + napi_value napiValue = nullptr; + const char *marketName = GetMarketName(); + + NAPI_CALL(env, napi_create_string_utf8(env, marketName, strlen(marketName), &napiValue)); + return napiValue; +} + +static napi_value GetProductSeries(napi_env env, napi_callback_info info) +{ + napi_value napiValue = nullptr; + const char *productSeries = GetProductSeries(); + + NAPI_CALL(env, napi_create_string_utf8(env, productSeries, strlen(productSeries), &napiValue)); + return napiValue; +} + +static napi_value GetProductModel(napi_env env, napi_callback_info info) +{ + napi_value napiValue = nullptr; + const char *productModel = GetProductModel(); + + NAPI_CALL(env, napi_create_string_utf8(env, productModel, strlen(productModel), &napiValue)); + return napiValue; +} + +static napi_value GetSoftwareModel(napi_env env, napi_callback_info info) +{ + napi_value napiValue = nullptr; + const char *softwareModel = GetSoftwareModel(); + + NAPI_CALL(env, napi_create_string_utf8(env, softwareModel, strlen(softwareModel), &napiValue)); + return napiValue; +} + +static napi_value GetHardwareModel(napi_env env, napi_callback_info info) +{ + napi_value napiValue = nullptr; + const char *hardwareModel = GetHardwareModel(); + + NAPI_CALL(env, napi_create_string_utf8(env, hardwareModel, strlen(hardwareModel), &napiValue)); + return napiValue; +} + +static napi_value GetHardwareProfile(napi_env env, napi_callback_info info) +{ + napi_value napiValue = nullptr; + const char *hardwareProfile = GetHardwareProfile(); + + NAPI_CALL(env, napi_create_string_utf8(env, hardwareProfile, strlen(hardwareProfile), &napiValue)); + return napiValue; +} + +static napi_value GetSerial(napi_env env, napi_callback_info info) +{ + napi_value napiValue = nullptr; + const char *serialNumber = AclGetSerial(); + + NAPI_CALL(env, napi_create_string_utf8(env, serialNumber, strlen(serialNumber), &napiValue)); + return napiValue; +} + +static napi_value GetBootloaderVersion(napi_env env, napi_callback_info info) +{ + napi_value napiValue = nullptr; + const char *bootloaderVersion = GetBootloaderVersion(); + + NAPI_CALL(env, napi_create_string_utf8(env, bootloaderVersion, strlen(bootloaderVersion), &napiValue)); + return napiValue; +} + +static napi_value GetAbiList(napi_env env, napi_callback_info info) +{ + napi_value napiValue = nullptr; + const char *abiList = GetAbiList(); + + NAPI_CALL(env, napi_create_string_utf8(env, abiList, strlen(abiList), &napiValue)); + return napiValue; +} + +static napi_value GetSecurityPatchTag(napi_env env, napi_callback_info info) +{ + napi_value napiValue = nullptr; + const char *securityPatchTag = GetSecurityPatchTag(); + + NAPI_CALL(env, napi_create_string_utf8(env, securityPatchTag, strlen(securityPatchTag), &napiValue)); + return napiValue; +} + +static napi_value GetDisplayVersion(napi_env env, napi_callback_info info) +{ + napi_value napiValue = nullptr; + const char *productVersion = GetDisplayVersion(); + + NAPI_CALL(env, napi_create_string_utf8(env, productVersion, strlen(productVersion), &napiValue)); + return napiValue; +} + +static napi_value GetIncrementalVersion(napi_env env, napi_callback_info info) +{ + napi_value napiValue = nullptr; + const char *incrementalVersion = GetIncrementalVersion(); + + NAPI_CALL(env, napi_create_string_utf8(env, incrementalVersion, strlen(incrementalVersion), &napiValue)); + return napiValue; +} + +static napi_value GetOsReleaseType(napi_env env, napi_callback_info info) +{ + napi_value napiValue = nullptr; + const char *osReleaseType = GetOsReleaseType(); + + NAPI_CALL(env, napi_create_string_utf8(env, osReleaseType, strlen(osReleaseType), &napiValue)); + return napiValue; +} + +static napi_value GetOSFullName(napi_env env, napi_callback_info info) +{ + napi_value napiValue = nullptr; + const char *osVersion = GetOSFullName(); + + NAPI_CALL(env, napi_create_string_utf8(env, osVersion, strlen(osVersion), &napiValue)); + return napiValue; +} + +static napi_value GetMajorVersion(napi_env env, napi_callback_info info) +{ + napi_value napiValue = nullptr; + int majorVersion = GetMajorVersion(); + + NAPI_CALL(env, napi_create_int32(env, majorVersion, &napiValue)); + return napiValue; +} + +static napi_value GetSeniorVersion(napi_env env, napi_callback_info info) +{ + napi_value napiValue = nullptr; + int seniorVersion = GetSeniorVersion(); + + NAPI_CALL(env, napi_create_int32(env, seniorVersion, &napiValue)); + return napiValue; +} + +static napi_value GetFeatureVersion(napi_env env, napi_callback_info info) +{ + napi_value napiValue = nullptr; + int featureVersion = GetFeatureVersion(); + + NAPI_CALL(env, napi_create_int32(env, featureVersion, &napiValue)); + return napiValue; +} + +static napi_value GetBuildVersion(napi_env env, napi_callback_info info) +{ + napi_value napiValue = nullptr; + int buildVersion = GetBuildVersion(); + + NAPI_CALL(env, napi_create_int32(env, buildVersion, &napiValue)); + return napiValue; +} + +static napi_value GetSdkApiVersion(napi_env env, napi_callback_info info) +{ + napi_value napiValue = nullptr; + int sdkApiVersion = GetSdkApiVersion(); + + NAPI_CALL(env, napi_create_int32(env, sdkApiVersion, &napiValue)); + return napiValue; +} + +static napi_value GetFirstApiVersion(napi_env env, napi_callback_info info) +{ + napi_value napiValue = nullptr; + int firstApiVersion = GetFirstApiVersion(); + + NAPI_CALL(env, napi_create_int32(env, firstApiVersion, &napiValue)); + return napiValue; +} + +static napi_value GetVersionId(napi_env env, napi_callback_info info) +{ + napi_value napiValue = nullptr; + const char *versionId = GetVersionId(); + + NAPI_CALL(env, napi_create_string_utf8(env, versionId, strlen(versionId), &napiValue)); + return napiValue; +} + +static napi_value GetBuildType(napi_env env, napi_callback_info info) +{ + napi_value napiValue = nullptr; + const char *buildType = GetBuildType(); + + NAPI_CALL(env, napi_create_string_utf8(env, buildType, strlen(buildType), &napiValue)); + return napiValue; +} + +static napi_value GetBuildUser(napi_env env, napi_callback_info info) +{ + napi_value napiValue = nullptr; + const char *buildUser = GetBuildUser(); + + NAPI_CALL(env, napi_create_string_utf8(env, buildUser, strlen(buildUser), &napiValue)); + return napiValue; +} + +static napi_value GetBuildHost(napi_env env, napi_callback_info info) +{ + napi_value napiValue = nullptr; + const char *buildHost = GetBuildHost(); + + NAPI_CALL(env, napi_create_string_utf8(env, buildHost, strlen(buildHost), &napiValue)); + return napiValue; +} + +static napi_value GetBuildTime(napi_env env, napi_callback_info info) +{ + napi_value napiValue = nullptr; + const char *buildTime = GetBuildTime(); + + NAPI_CALL(env, napi_create_string_utf8(env, buildTime, strlen(buildTime), &napiValue)); + return napiValue; +} + +static napi_value GetBuildRootHash(napi_env env, napi_callback_info info) +{ + napi_value napiValue = nullptr; + const char *buildRootHash = GetBuildRootHash(); + + NAPI_CALL(env, napi_create_string_utf8(env, buildRootHash, strlen(buildRootHash), &napiValue)); + return napiValue; +} + +static napi_value GetDevUdid(napi_env env, napi_callback_info info) +{ + napi_value napiValue = nullptr; + char localDeviceId[UDID_LEN] = {0}; + AclGetDevUdid(localDeviceId, UDID_LEN); + + NAPI_CALL(env, napi_create_string_utf8(env, localDeviceId, strlen(localDeviceId), &napiValue)); + return napiValue; +} + +EXTERN_C_START +/* + * Module init + */ +static napi_value Init(napi_env env, napi_value exports) +{ + /* + * Attribute definition + */ + napi_property_descriptor desc[] = { + {"deviceType", nullptr, nullptr, GetDeviceType, nullptr, nullptr, napi_default, nullptr}, + {"manufacture", nullptr, nullptr, GetManufacture, nullptr, nullptr, napi_default, nullptr}, + {"brand", nullptr, nullptr, GetBrand, nullptr, nullptr, napi_default, nullptr}, + {"marketName", nullptr, nullptr, GetMarketName, nullptr, nullptr, napi_default, nullptr}, + {"productSeries", nullptr, nullptr, GetProductSeries, nullptr, nullptr, napi_default, nullptr}, + {"productModel", nullptr, nullptr, GetProductModel, nullptr, nullptr, napi_default, nullptr}, + {"softwareModel", nullptr, nullptr, GetSoftwareModel, nullptr, nullptr, napi_default, nullptr}, + {"hardwareModel", nullptr, nullptr, GetHardwareModel, nullptr, nullptr, napi_default, nullptr}, + {"hardwareProfile", nullptr, nullptr, GetHardwareProfile, nullptr, nullptr, napi_default, nullptr}, + {"serial", nullptr, nullptr, GetSerial, nullptr, nullptr, napi_default, nullptr}, + {"bootloaderVersion", nullptr, nullptr, GetBootloaderVersion, nullptr, nullptr, napi_default, nullptr}, + {"abiList", nullptr, nullptr, GetAbiList, nullptr, nullptr, napi_default, nullptr}, + {"securityPatchTag", nullptr, nullptr, GetSecurityPatchTag, nullptr, nullptr, napi_default, nullptr}, + {"displayVersion", nullptr, nullptr, GetDisplayVersion, nullptr, nullptr, napi_default, nullptr}, + {"incrementalVersion", nullptr, nullptr, GetIncrementalVersion, nullptr, nullptr, napi_default, nullptr}, + {"osReleaseType", nullptr, nullptr, GetOsReleaseType, nullptr, nullptr, napi_default, nullptr}, + {"osFullName", nullptr, nullptr, GetOSFullName, nullptr, nullptr, napi_default, nullptr}, + {"majorVersion", nullptr, nullptr, GetMajorVersion, nullptr, nullptr, napi_default, nullptr}, + {"seniorVersion", nullptr, nullptr, GetSeniorVersion, nullptr, nullptr, napi_default, nullptr}, + {"featureVersion", nullptr, nullptr, GetFeatureVersion, nullptr, nullptr, napi_default, nullptr}, + {"buildVersion", nullptr, nullptr, GetBuildVersion, nullptr, nullptr, napi_default, nullptr}, + {"sdkApiVersion", nullptr, nullptr, GetSdkApiVersion, nullptr, nullptr, napi_default, nullptr}, + {"firstApiVersion", nullptr, nullptr, GetFirstApiVersion, nullptr, nullptr, napi_default, nullptr}, + {"versionId", nullptr, nullptr, GetVersionId, nullptr, nullptr, napi_default, nullptr}, + {"buildType", nullptr, nullptr, GetBuildType, nullptr, nullptr, napi_default, nullptr}, + {"buildUser", nullptr, nullptr, GetBuildUser, nullptr, nullptr, napi_default, nullptr}, + {"buildHost", nullptr, nullptr, GetBuildHost, nullptr, nullptr, napi_default, nullptr}, + {"buildTime", nullptr, nullptr, GetBuildTime, nullptr, nullptr, napi_default, nullptr}, + {"buildRootHash", nullptr, nullptr, GetBuildRootHash, nullptr, nullptr, napi_default, nullptr}, + {"udid", nullptr, nullptr, GetDevUdid, nullptr, nullptr, napi_default, nullptr}, + }; + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(napi_property_descriptor), desc)); + + return exports; +} +EXTERN_C_END + +/* + * Module definition + */ +static napi_module _module = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = NULL, + .nm_register_func = Init, + .nm_modname = "deviceInfo", + .nm_priv = ((void *)0), + .reserved = { 0 } +}; +/* + * Module registration function + */ +extern "C" __attribute__((constructor)) void RegisterModule(void) +{ + napi_module_register(&_module); +} diff --git a/interfaces/kits/jskits/src/native_parameters_js.cpp b/interfaces/kits/jskits/src/native_parameters_js.cpp new file mode 100755 index 0000000000000000000000000000000000000000..5ac99215f3f19a6869d1636034732c898aa1fe88 --- /dev/null +++ b/interfaces/kits/jskits/src/native_parameters_js.cpp @@ -0,0 +1,348 @@ +/* + * Copyright (c) 2021 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 "native_parameters_js.h" + +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, 0, "StartupParametersJs" }; +using namespace OHOS::HiviewDFX; +static constexpr int MAX_LENGTH = 128; +static constexpr int ARGC_NUMBER = 2; +static constexpr int ARGC_THREE_NUMBER = 3; +static constexpr int BUF_LENGTH = 256; + +using StorageAsyncContext = struct { + napi_env env = nullptr; + napi_async_work work = nullptr; + + char key[BUF_LENGTH] = { 0 }; + size_t keyLen = 0; + char value[BUF_LENGTH] = { 0 }; + size_t valueLen = 0; + napi_deferred deferred = nullptr; + napi_ref callbackRef = nullptr; + + int status = -1; + std::string getValue; +}; + +using StorageAsyncContextPtr = StorageAsyncContext *; + +static void SetCallbackWork(napi_env env, StorageAsyncContextPtr asyncContext) +{ + napi_value resource = nullptr; + napi_create_string_utf8(env, "JSStartupSet", NAPI_AUTO_LENGTH, &resource); + napi_create_async_work( + env, nullptr, resource, + [](napi_env env, void *data) { + StorageAsyncContext *asyncContext = (StorageAsyncContext *)data; + asyncContext->status = SetParameter(asyncContext->key, asyncContext->value); + HiLog::Debug(LABEL, + "JSApp set::asyncContext-> status = %{public}d, asyncContext->key = %{public}s, asyncContext->value = " + "%{public}s.", + asyncContext->status, asyncContext->key, asyncContext->value); + }, + [](napi_env env, napi_status status, void *data) { + StorageAsyncContext *asyncContext = (StorageAsyncContext *)data; + napi_value result[ARGC_NUMBER] = { 0 }; + if (asyncContext->status == 0) { + napi_get_undefined(env, &result[0]); + napi_get_undefined(env, &result[1]); + } else { + napi_value value = nullptr; + napi_create_object(env, &result[0]); + napi_create_int32(env, asyncContext->status, &value); + napi_set_named_property(env, result[0], "code", value); + napi_get_undefined(env, &result[1]); + } + + if (asyncContext->deferred) { + if (asyncContext->status == 0) { + napi_resolve_deferred(env, asyncContext->deferred, result[1]); + } else { + napi_reject_deferred(env, asyncContext->deferred, result[0]); + } + } else { + napi_value callback = nullptr; + napi_value callResult = nullptr; + napi_get_reference_value(env, asyncContext->callbackRef, &callback); + napi_call_function(env, nullptr, callback, ARGC_NUMBER, result, &callResult); + napi_delete_reference(env, asyncContext->callbackRef); + } + napi_delete_async_work(env, asyncContext->work); + delete asyncContext; + }, + (void *)asyncContext, &asyncContext->work); + napi_queue_async_work(env, asyncContext->work); +} + +static napi_value Set(napi_env env, napi_callback_info info) +{ + size_t argc = ARGC_THREE_NUMBER; + napi_value argv[ARGC_THREE_NUMBER] = { nullptr }; + napi_value thisVar = nullptr; + void *data = nullptr; + napi_get_cb_info(env, info, &argc, argv, &thisVar, &data); + NAPI_ASSERT(env, argc >= ARGC_NUMBER, "requires 2 parameter"); + StorageAsyncContextPtr asyncContext = new StorageAsyncContext(); + asyncContext->env = env; + for (size_t i = 0; i < argc; i++) { + napi_valuetype valueType = napi_null; + napi_typeof(env, argv[i], &valueType); + + if (i == 0 && valueType == napi_string) { + napi_get_value_string_utf8(env, argv[i], asyncContext->key, + BUF_LENGTH - 1, &asyncContext->keyLen); + } else if (i == 1 && valueType == napi_string) { + napi_get_value_string_utf8(env, argv[i], asyncContext->value, + BUF_LENGTH - 1, &asyncContext->valueLen); + } else if (i == ARGC_NUMBER && valueType == napi_function) { + napi_create_reference(env, argv[i], 1, &asyncContext->callbackRef); + } else { + delete asyncContext; + NAPI_ASSERT(env, false, "type mismatch"); + } + } + + napi_value result = nullptr; + if (asyncContext->callbackRef == nullptr) { + napi_create_promise(env, &asyncContext->deferred, &result); + } else { + napi_get_undefined(env, &result); + } + + SetCallbackWork(env, asyncContext); + return result; +} + +static napi_value SetSync(napi_env env, napi_callback_info info) +{ + size_t argc = ARGC_NUMBER; + napi_value args[ARGC_NUMBER] = { nullptr }; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); + NAPI_ASSERT(env, argc == ARGC_NUMBER, "Wrong number of arguments"); + napi_valuetype valuetype0 = napi_null; + NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); + napi_valuetype valuetype1 = napi_null; + NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1)); + NAPI_ASSERT(env, valuetype0 == napi_string && valuetype1 == napi_string, "Wrong argument type. string expected."); + + char keyBuf[BUF_LENGTH] = { 0 }; + size_t keySize = 0; + NAPI_CALL(env, napi_get_value_string_utf8(env, args[0], keyBuf, BUF_LENGTH - 1, &keySize)); + if (keySize >= MAX_LENGTH) { + return nullptr; + } + + char valueBuf[BUF_LENGTH] = { 0 }; + size_t valueSize = 0; + NAPI_CALL(env, napi_get_value_string_utf8(env, args[1], valueBuf, BUF_LENGTH - 1, &valueSize)); + if (valueSize >= MAX_LENGTH) { + return nullptr; + } + + std::string keyStr = keyBuf; + std::string valueStr = valueBuf; + int setResult = SetParameter(keyStr.c_str(), valueStr.c_str()); + HiLog::Debug(LABEL, "JSApp SetSync::setResult = %{public}d, input keyBuf = %{public}s.", setResult, keyBuf); + + napi_value napiValue = nullptr; + if (setResult != 0) { // set failed + std::stringstream ss; + ss << "set: " << keyStr << " failed, error code: " << setResult; + napi_throw_error((env), nullptr, ss.str().c_str()); + } else { + napi_get_undefined(env, &napiValue); + } + return napiValue; +} + +static napi_value GetSync(napi_env env, napi_callback_info info) +{ + size_t argc = ARGC_NUMBER; + napi_value args[ARGC_NUMBER] = { nullptr }; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, nullptr, nullptr)); + NAPI_ASSERT(env, argc == 1 || argc == ARGC_NUMBER, "Wrong number of arguments"); + napi_valuetype valuetype0 = napi_null; + NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); + NAPI_ASSERT(env, valuetype0 == napi_string, "Wrong argument type. Numbers expected."); + if (argc == ARGC_NUMBER) { + napi_valuetype valuetype1 = napi_null; + NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1)); + NAPI_ASSERT(env, valuetype1 == napi_string, "Wrong argument type. string expected."); + } + + char keyBuf[BUF_LENGTH] = { 0 }; + size_t keySize = 0; + NAPI_CALL(env, napi_get_value_string_utf8(env, args[0], keyBuf, BUF_LENGTH - 1, &keySize)); + if (keySize >= MAX_LENGTH) { + return nullptr; + } + + std::string keyStr = keyBuf; + std::string valueStr = ""; + std::string getValue = ""; + if (argc == ARGC_NUMBER) { + char valueBuf[BUF_LENGTH] = { 0 }; + size_t valueSize = 0; + NAPI_CALL(env, napi_get_value_string_utf8(env, args[1], valueBuf, BUF_LENGTH - 1, &valueSize)); + if (valueSize >= MAX_LENGTH) { + return nullptr; + } + valueStr = valueBuf; + } + int ret = OHOS::system::GetStringParameter(keyStr, getValue, valueStr); + HiLog::Debug(LABEL, "JSApp GetSync::getValue = %{public}s, input keyStr = %{public}s.", getValue.c_str(), keyBuf); + + napi_value napiValue = nullptr; + if (ret == 0) { + const char *value = getValue.c_str(); + NAPI_CALL(env, napi_create_string_utf8(env, value, strlen(value), &napiValue)); + } + return napiValue; +} + +static void GetCallbackWork(napi_env env, StorageAsyncContextPtr asyncContext) +{ + napi_value resource = nullptr; + napi_create_string_utf8(env, "JSStartupGet", NAPI_AUTO_LENGTH, &resource); + napi_create_async_work( + env, nullptr, resource, + [](napi_env env, void *data) { + StorageAsyncContext *asyncContext = (StorageAsyncContext *)data; + asyncContext->status = + OHOS::system::GetStringParameter(asyncContext->key, asyncContext->getValue, asyncContext->value); + HiLog::Debug(LABEL, + "JSApp get::asyncContext->status = %{public}d, asyncContext->getValue = %{public}s, asyncContext->key " + "= %{public}s, value = %{public}s.", + asyncContext->status, asyncContext->getValue.c_str(), asyncContext->key, asyncContext->value); + }, + [](napi_env env, napi_status status, void *data) { + StorageAsyncContext *asyncContext = (StorageAsyncContext *)data; + napi_value result[ARGC_NUMBER] = { 0 }; + if (asyncContext->status == 0) { + napi_get_undefined(env, &result[0]); + napi_create_string_utf8(env, asyncContext->getValue.c_str(), strlen(asyncContext->getValue.c_str()), + &result[1]); + } else { + napi_value message = nullptr; + napi_create_object(env, &result[0]); + napi_create_int32(env, asyncContext->status, &message); + napi_set_named_property(env, result[0], "code", message); + napi_get_undefined(env, &result[1]); + } + + if (asyncContext->deferred) { + if (asyncContext->status == 0) { + napi_resolve_deferred(env, asyncContext->deferred, result[1]); + } else { + napi_reject_deferred(env, asyncContext->deferred, result[0]); + } + } else { + napi_value callback = nullptr; + napi_value callResult = nullptr; + napi_get_reference_value(env, asyncContext->callbackRef, &callback); + napi_call_function(env, nullptr, callback, ARGC_NUMBER, result, &callResult); + napi_delete_reference(env, asyncContext->callbackRef); + } + napi_delete_async_work(env, asyncContext->work); + delete asyncContext; + }, + (void *)asyncContext, &asyncContext->work); + napi_queue_async_work(env, asyncContext->work); +} + +static napi_value Get(napi_env env, napi_callback_info info) +{ + size_t argc = ARGC_THREE_NUMBER; + napi_value argv[ARGC_THREE_NUMBER] = { nullptr }; + napi_value thisVar = nullptr; + void *data = nullptr; + napi_get_cb_info(env, info, &argc, argv, &thisVar, &data); + NAPI_ASSERT(env, argc >= 1, "requires 1 parameter"); + StorageAsyncContextPtr asyncContext = new StorageAsyncContext(); + asyncContext->env = env; + for (size_t i = 0; i < argc; i++) { + napi_valuetype valueType = napi_null; + napi_typeof(env, argv[i], &valueType); + + if (i == 0 && valueType == napi_string) { + napi_get_value_string_utf8(env, argv[i], asyncContext->key, + BUF_LENGTH - 1, &asyncContext->keyLen); + } else if (i == 1 && valueType == napi_string) { + napi_get_value_string_utf8(env, argv[i], asyncContext->value, + BUF_LENGTH - 1, &asyncContext->valueLen); + } else if (i == 1 && valueType == napi_function) { + napi_create_reference(env, argv[i], 1, &asyncContext->callbackRef); + break; + } else if (i == ARGC_NUMBER && valueType == napi_function) { + napi_create_reference(env, argv[i], 1, &asyncContext->callbackRef); + } else { + delete asyncContext; + NAPI_ASSERT(env, false, "type mismatch"); + } + } + + napi_value result = nullptr; + if (asyncContext->callbackRef == nullptr) { + napi_create_promise(env, &asyncContext->deferred, &result); + } else { + napi_get_undefined(env, &result); + } + + GetCallbackWork(env, asyncContext); + return result; +} + +EXTERN_C_START +/* + * Module init + */ +static napi_value Init(napi_env env, napi_value exports) +{ + /* + * Attribute definition + */ + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("set", Set), + DECLARE_NAPI_FUNCTION("setSync", SetSync), + DECLARE_NAPI_FUNCTION("get", Get), + DECLARE_NAPI_FUNCTION("getSync", GetSync), + DECLARE_NAPI_FUNCTION("wait", ParamWait), + DECLARE_NAPI_FUNCTION("getWatcher", GetWatcher) + }; + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(napi_property_descriptor), desc)); + return RegisterWatcher(env, exports); +} +EXTERN_C_END + +/* + * Module definition + */ +static napi_module _module = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = NULL, + .nm_register_func = Init, + .nm_modname = "systemParameter", + .nm_priv = ((void *)0), + .reserved = { 0 } +}; + +/* + * Module registration function + */ +extern "C" __attribute__((constructor)) void RegisterModule(void) +{ + napi_module_register(&_module); +} diff --git a/interfaces/kits/jskits/src/native_parameters_js.h b/interfaces/kits/jskits/src/native_parameters_js.h new file mode 100755 index 0000000000000000000000000000000000000000..8c5e9e093e8a456675fac1f04684f15f60fcda2a --- /dev/null +++ b/interfaces/kits/jskits/src/native_parameters_js.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2021 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 NATIVE_PARAMETERS_JS_H +#define NATIVE_PARAMETERS_JS_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "hilog/log.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include "param_wrapper.h" +#include "parameter.h" + +#define PARAM_JS_CHECK(retCode, exper, ...) \ + if (!(retCode)) { \ + HiLog::Error(LABEL, __VA_ARGS__); \ + exper; \ + } + +EXTERN_C_START +napi_value GetWatcher(napi_env env, napi_callback_info info); +napi_value ParamWait(napi_env env, napi_callback_info info); +napi_value RegisterWatcher(napi_env env, napi_value exports); +EXTERN_C_END + +#endif // NATIVE_PARAMETERS_JS_H \ No newline at end of file diff --git a/interfaces/kits/jskits/src/native_parameters_watch.cpp b/interfaces/kits/jskits/src/native_parameters_watch.cpp new file mode 100755 index 0000000000000000000000000000000000000000..741260668d38ffb101b53140ed7ded6329cf5317 --- /dev/null +++ b/interfaces/kits/jskits/src/native_parameters_watch.cpp @@ -0,0 +1,531 @@ +/* + * Copyright (c) 2021 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 "native_parameters_js.h" +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, 0, "StartupParametersJs" }; +using namespace OHOS::HiviewDFX; +using namespace OHOS::system; +static constexpr int ARGC_NUMBER = 2; +static constexpr int BUF_LENGTH = 128; + +static napi_ref g_paramWatchRef; + +using ParamAsyncContext = struct { + napi_env env = nullptr; + napi_async_work work = nullptr; + + char key[BUF_LENGTH] = { 0 }; + size_t keyLen = 0; + char value[BUF_LENGTH] = { 0 }; + size_t valueLen = 0; + int32_t timeout = 0; + napi_deferred deferred = nullptr; + napi_ref callbackRef = nullptr; + + int status = -1; + std::string getValue; +}; + +using ParamWatcher = struct { + napi_env env = nullptr; + napi_ref thisVarRef = nullptr; + char keyPrefix[BUF_LENGTH] = { 0 }; + size_t keyLen = 0; + bool notifySwitch = false; + bool startWatch = false; + std::mutex mutex {}; + napi_ref currCallbackRef = nullptr; + std::map callbackReferences {}; +}; + +using ParamWatcherWork = struct { + napi_async_work work = nullptr; + ParamWatcher *watcher = nullptr; + bool startWatch = false; +}; + +using ParamAsyncContextPtr = ParamAsyncContext *; +using ParamWatcherPtr = ParamWatcher *; + +static napi_value NapiGetNull(napi_env env) +{ + napi_value result = 0; + napi_get_null(env, &result); + return result; +} + +static napi_value GetNapiValue(napi_env env, int val) +{ + napi_value result = nullptr; + napi_create_int32(env, val, &result); + return result; +} + +static int GetParamValue(napi_env env, napi_value arg, napi_valuetype valueType, char *buffer, size_t &buffLen) +{ + napi_valuetype type = napi_null; + napi_typeof(env, arg, &type); + PARAM_JS_CHECK(type == valueType, return -1, "Invalid type %d %d", type, valueType); + napi_status status = napi_ok; + if (valueType == napi_string) { + status = napi_get_value_string_utf8(env, arg, buffer, buffLen, &buffLen); + } else if (valueType == napi_number) { + status = napi_get_value_int32(env, arg, (int *)buffer); + } + return status; +} + +static void WaitCallbackWork(napi_env env, ParamAsyncContextPtr asyncContext) +{ + napi_value resource = nullptr; + napi_create_string_utf8(env, "JSStartupGet", NAPI_AUTO_LENGTH, &resource); + napi_create_async_work( + env, nullptr, resource, + [](napi_env env, void *data) { + ParamAsyncContext *asyncContext = (ParamAsyncContext *)data; + asyncContext->status = WaitParameter(asyncContext->key, asyncContext->value, asyncContext->timeout); + HiLog::Debug(LABEL, "JSApp Wait status: %{public}d, key: %{public}s", + asyncContext->status, asyncContext->key); + }, + [](napi_env env, napi_status status, void *data) { + ParamAsyncContext *asyncContext = (ParamAsyncContext *)data; + napi_value result[ARGC_NUMBER] = { 0 }; + napi_value message = nullptr; + napi_create_object(env, &result[0]); + napi_create_int32(env, asyncContext->status, &message); + napi_set_named_property(env, result[0], "code", message); + napi_get_undefined(env, &result[1]); // only one param + + HiLog::Debug(LABEL, "JSApp Wait status: %{public}d, key: %{public}s ", + asyncContext->status, asyncContext->key); + if (asyncContext->deferred) { + if (asyncContext->status == 0) { + napi_resolve_deferred(env, asyncContext->deferred, result[1]); + } else { + napi_reject_deferred(env, asyncContext->deferred, result[0]); + } + } else { + napi_value callbackRef = nullptr; + napi_value callResult = nullptr; + napi_status status = napi_get_reference_value(env, asyncContext->callbackRef, &callbackRef); + PARAM_JS_CHECK(status == 0 && callbackRef != nullptr, return, "Failed to get reference "); + napi_value undefined; + napi_get_undefined(env, &undefined); + napi_call_function(env, undefined, callbackRef, ARGC_NUMBER, result, &callResult); + napi_delete_reference(env, asyncContext->callbackRef); + } + napi_delete_async_work(env, asyncContext->work); + delete asyncContext; + }, + (void *)asyncContext, &asyncContext->work); + napi_queue_async_work(env, asyncContext->work); +} + +napi_value ParamWait(napi_env env, napi_callback_info info) +{ + constexpr int PARAM_TIMEOUT_INDEX = 2; + constexpr int ARGC_THREE_NUMBER = 3; + size_t argc = ARGC_THREE_NUMBER + 1; + napi_value argv[ARGC_THREE_NUMBER + 1]; + napi_value thisVar = nullptr; + napi_status status = napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr); + PARAM_JS_CHECK(status == napi_ok, return GetNapiValue(env, status), "Failed to get cb info"); + PARAM_JS_CHECK(argc >= ARGC_THREE_NUMBER, return GetNapiValue(env, status), "Failed to get argc"); + + ParamAsyncContextPtr asyncContext = new ParamAsyncContext(); + PARAM_JS_CHECK(asyncContext != nullptr, return GetNapiValue(env, status), "Failed to create context"); + asyncContext->env = env; + + // get param key + asyncContext->keyLen = BUF_LENGTH - 1; + asyncContext->valueLen = BUF_LENGTH - 1; + size_t len = sizeof(asyncContext->timeout); + int ret = GetParamValue(env, argv[0], napi_string, asyncContext->key, asyncContext->keyLen); + PARAM_JS_CHECK(ret == 0, delete asyncContext; + return GetNapiValue(env, ret), "Invalid param for wait"); + ret = GetParamValue(env, argv[1], napi_string, asyncContext->value, asyncContext->valueLen); + PARAM_JS_CHECK(ret == 0, delete asyncContext; + return GetNapiValue(env, ret), "Invalid param for wait"); + ret = GetParamValue(env, argv[PARAM_TIMEOUT_INDEX], napi_number, (char *)&asyncContext->timeout, len); + PARAM_JS_CHECK(ret == 0, delete asyncContext; + return GetNapiValue(env, ret), "Invalid param for wait"); + if (argc > ARGC_THREE_NUMBER) { + napi_valuetype valueType = napi_null; + napi_typeof(env, argv[ARGC_THREE_NUMBER], &valueType); + PARAM_JS_CHECK(valueType == napi_function, delete asyncContext; + return GetNapiValue(env, ret), "Invalid param for wait callbackRef"); + napi_create_reference(env, argv[ARGC_THREE_NUMBER], 1, &asyncContext->callbackRef); + } + HiLog::Debug(LABEL, "JSApp Wait key: %{public}s, value: %{public}s timeout %{public}d.", + asyncContext->key, asyncContext->value, asyncContext->timeout); + + napi_value result = nullptr; + if (asyncContext->callbackRef == nullptr) { + napi_create_promise(env, &asyncContext->deferred, &result); + } else { + result = GetNapiValue(env, 0); + } + WaitCallbackWork(env, asyncContext); + return result; +} + +static bool GetFristRefence(ParamWatcherPtr watcher, uint32_t &next) +{ + std::lock_guard lock(watcher->mutex); + auto iter = watcher->callbackReferences.begin(); + if (iter != watcher->callbackReferences.end()) { + next = watcher->callbackReferences.begin()->first; + return true; + } + return false; +} + +static napi_ref GetWatcherReference(ParamWatcherPtr watcher, uint32_t next) +{ + std::lock_guard lock(watcher->mutex); + auto iter = watcher->callbackReferences.find(next); + if (iter != watcher->callbackReferences.end()) { + return iter->second; + } + return nullptr; +} + +static uint32_t GetNextRefence(ParamWatcherPtr watcher, uint32_t &next) +{ + std::lock_guard lock(watcher->mutex); + auto iter = watcher->callbackReferences.upper_bound(next); + if (iter == watcher->callbackReferences.end()) { + return false; + } + next = iter->first; + return true; +} + +static void AddWatcherCallback(ParamWatcherPtr watcher, napi_ref callbackRef) +{ + static uint32_t watcherId = 0; + std::lock_guard lock(watcher->mutex); + watcherId++; + watcher->callbackReferences[watcherId] = callbackRef; + HiLog::Debug(LABEL, "JSApp watcher add watcher callback %{public}s %{public}u.", + watcher->keyPrefix, watcherId); +} + +static void DelWatcherCallback(ParamWatcherPtr watcher, uint32_t next) +{ + HiLog::Debug(LABEL, "JSApp watcher key %{public}s delete callack %{public}u", watcher->keyPrefix, next); + std::lock_guard lock(watcher->mutex); + watcher->callbackReferences.erase(next); +} + +static void DelCallbackRef(napi_env env, ParamWatcherPtr watcher, napi_ref callbackRef, uint32_t id) +{ + std::lock_guard lock(watcher->mutex); + if (callbackRef == watcher->currCallbackRef) { + HiLog::Debug(LABEL, "JSApp watcher key %{public}s has been callbacked %{public}u.", + watcher->keyPrefix, id); + watcher->currCallbackRef = nullptr; + } else { + napi_delete_reference(env, callbackRef); + } + watcher->callbackReferences.erase(id); +} + +static void DelCallback(napi_env env, napi_value callback, ParamWatcherPtr watcher) +{ + bool isEquals = false; + uint32_t next = 0; + bool ret = GetFristRefence(watcher, next); + while (ret) { + napi_ref callbackRef = GetWatcherReference(watcher, next); + if (callbackRef == nullptr) { + HiLog::Debug(LABEL, "JSApp watcher key %{public}s callbackRef has been deleted %{public}d.", + watcher->keyPrefix, next); + DelWatcherCallback(watcher, next); + } else if (callback != nullptr) { + napi_value handler = nullptr; + napi_get_reference_value(env, callbackRef, &handler); + napi_strict_equals(env, handler, callback, &isEquals); + if (isEquals) { + DelCallbackRef(env, watcher, callbackRef, next); + break; + } + } else { + DelCallbackRef(env, watcher, callbackRef, next); + } + ret = GetNextRefence(watcher, next); + } +} + +static bool CheckCallbackEqual(napi_env env, napi_value callback, ParamWatcherPtr watcher) +{ + bool isEquals = false; + uint32_t next = 0; + bool ret = GetFristRefence(watcher, next); + while (ret) { + napi_ref callbackRef = GetWatcherReference(watcher, next); + if (callbackRef != nullptr) { + napi_value handler = nullptr; + napi_get_reference_value(env, callbackRef, &handler); + napi_strict_equals(env, handler, callback, &isEquals); + if (isEquals) { + return true; + } + } + ret = GetNextRefence(watcher, next); + } + return false; +} + +static napi_value ParamWatchConstructor(napi_env env, napi_callback_info info) +{ + size_t argc = 1; + napi_value argv[1]; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr)); + ParamWatcherPtr watcher = new ParamWatcher(); + PARAM_JS_CHECK(watcher != nullptr, return NapiGetNull(env), "Failed to create param watcher"); + napi_status status = napi_create_reference(env, thisVar, 1, &watcher->thisVarRef); + PARAM_JS_CHECK(status == 0, delete watcher; + return NapiGetNull(env), "Failed to create reference %d", status); + + napi_wrap( + env, thisVar, watcher, + [](napi_env env, void *data, void *hint) { + ParamWatcherPtr watcher = static_cast(data); + if (watcher) { + DelCallback(env, nullptr, watcher); + WatchParameter(watcher->keyPrefix, nullptr, nullptr); + delete watcher; + watcher = nullptr; + } + }, + nullptr, nullptr); + return thisVar; +} + +napi_value GetWatcher(napi_env env, napi_callback_info info) +{ + size_t argc = 1; + napi_value argv[1]; + napi_value thisVar = nullptr; + void *data = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, &data)); + + napi_value obj = thisVar; + ParamWatcherPtr watcher = nullptr; + napi_unwrap(env, thisVar, (void **)&watcher); + if (watcher == nullptr) { // check if watcher exist + napi_value constructor = nullptr; + int status = napi_get_reference_value(env, g_paramWatchRef, &constructor); + PARAM_JS_CHECK(status == 0, return NapiGetNull(env), "Failed to get reference"); + status = napi_new_instance(env, constructor, 0, nullptr, &obj); + PARAM_JS_CHECK(status == 0, return NapiGetNull(env), "Failed to create instance for watcher"); + napi_unwrap(env, obj, (void **)&watcher); + } + if (watcher != nullptr) { + watcher->keyLen = BUF_LENGTH; + int ret = GetParamValue(env, argv[0], napi_string, watcher->keyPrefix, watcher->keyLen); + PARAM_JS_CHECK(ret == 0, return NapiGetNull(env), "Failed to get key prefix"); + HiLog::Debug(LABEL, "JSApp watcher keyPrefix = %{public}s ", watcher->keyPrefix); + ret = WatchParameter(watcher->keyPrefix, nullptr, watcher); + PARAM_JS_CHECK(ret == 0, return NapiGetNull(env), "Failed to get watcher ret %{public}d", ret); + } + return obj; +} + +static ParamWatcherPtr GetWatcherInfo(napi_env env, napi_callback_info info, napi_value *callback) +{ + size_t argc = ARGC_NUMBER; + napi_value argv[ARGC_NUMBER]; + napi_value thisVar = nullptr; + void *data = nullptr; + napi_get_cb_info(env, info, &argc, argv, &thisVar, &data); + + size_t typeLen = BUF_LENGTH - 1; + std::vector eventType(typeLen, 0); + int ret = GetParamValue(env, argv[0], napi_string, eventType.data(), typeLen); + PARAM_JS_CHECK(ret == 0, return nullptr, "Failed to get event type"); + if (strcmp(eventType.data(), "valueChange") != 0) { + return nullptr; + } + // argv[1]:callbackRef + if (argc > 1) { + napi_valuetype valuetype; + napi_status status = napi_typeof(env, argv[1], &valuetype); + PARAM_JS_CHECK(status == 0, return nullptr, "Failed to get type"); + PARAM_JS_CHECK(valuetype == napi_function, return nullptr, "Invalid type %d", valuetype); + *callback = argv[1]; + } + ParamWatcherPtr watcher = nullptr; + napi_unwrap(env, thisVar, (void **)&watcher); + return watcher; +} + +static void NotifyValueChange(ParamWatcherPtr watcher, uint32_t id, napi_value thisVar, const napi_value result[]) +{ + napi_ref callbackRef = GetWatcherReference(watcher, id); + PARAM_JS_CHECK(callbackRef != nullptr, return, + "Failed to get callback for %{public}s %{public}d", watcher->keyPrefix, id); + napi_value callbackFunc = nullptr; + napi_status status = napi_get_reference_value(watcher->env, callbackRef, &callbackFunc); + PARAM_JS_CHECK(status == 0 && callbackFunc != nullptr, return, + "Failed to get callback for %{public}s %{public}d", watcher->keyPrefix, id); + { + std::lock_guard lock(watcher->mutex); + watcher->currCallbackRef = callbackRef; + } + + napi_value callbackResult = nullptr; + napi_call_function(watcher->env, thisVar, callbackFunc, ARGC_NUMBER, result, &callbackResult); + + { + std::lock_guard lock(watcher->mutex); + if (watcher->currCallbackRef == nullptr) { + HiLog::Debug(LABEL, "JSApp watcher notify key %{public}s callback deleted watcherId %{public}u", + watcher->keyPrefix, id); + napi_delete_reference(watcher->env, callbackRef); + } + watcher->currCallbackRef = nullptr; + } +} + +static void ProcessParamChange(const char *key, const char *value, void *context) +{ + ParamWatcherPtr watcher = static_cast(context); + PARAM_JS_CHECK(watcher != nullptr && watcher->env != nullptr, return, "Invalid param"); + PARAM_JS_CHECK(watcher->callbackReferences.size() > 0, return, "No callback for watcher"); + + napi_handle_scope scope = nullptr; + napi_status status = napi_open_handle_scope(watcher->env, &scope); + PARAM_JS_CHECK(status == 0, return, "Failed to get reference "); + napi_value result[ARGC_NUMBER] = { 0 }; + napi_create_string_utf8(watcher->env, key, strlen(key), &result[0]); + napi_create_string_utf8(watcher->env, value, strlen(value), &result[1]); + napi_value thisVar = nullptr; + status = napi_get_reference_value(watcher->env, watcher->thisVarRef, &thisVar); + PARAM_JS_CHECK(status == 0 && thisVar != nullptr, napi_close_handle_scope(watcher->env, scope); + return, "Failed to get reference "); + uint32_t next = 0; + bool ret = GetFristRefence(watcher, next); + while (ret) { + NotifyValueChange(watcher, next, thisVar, result); + ret = GetNextRefence(watcher, next); + } + napi_close_handle_scope(watcher->env, scope); + HiLog::Debug(LABEL, "JSApp watcher ProcessParamChange %{public}s finish", key); +} + +static void WatchCallbackWork(napi_env env, ParamWatcherPtr watcher) +{ + HiLog::Debug(LABEL, "JSApp WatchCallbackWork key: %{public}s", watcher->keyPrefix); + ParamWatcherWork *worker = new ParamWatcherWork(); + PARAM_JS_CHECK(worker != nullptr, return, "Failed to create worker "); + worker->watcher = watcher; + worker->work = nullptr; + worker->startWatch = watcher->startWatch; + + napi_value resource = nullptr; + napi_create_string_utf8(env, "JSStartupWatch", NAPI_AUTO_LENGTH, &resource); + napi_create_async_work(env, nullptr, resource, + [](napi_env env, void *data) { + ParamWatcherWork *worker = (ParamWatcherWork *)data; + PARAM_JS_CHECK(worker != nullptr && worker->watcher != nullptr, return, "Invalid worker "); + int status = WatchParameter(worker->watcher->keyPrefix, + worker->startWatch ? ProcessParamChange : nullptr, worker->watcher); + HiLog::Debug(LABEL, "JSApp WatchCallbackWork %{public}s status: %{public}d, key: %{public}s", + worker->startWatch ? "on" : "off", status, worker->watcher->keyPrefix); + }, + [](napi_env env, napi_status status, void *data) { + ParamWatcherWork *worker = (ParamWatcherWork *)data; + HiLog::Debug(LABEL, "JSApp WatchCallbackWork delete %{public}s key: %{public}s", + worker->startWatch ? "on" : "off", worker->watcher->keyPrefix); + napi_delete_async_work(env, worker->work); + delete worker; + }, + (void *)worker, &worker->work); + napi_queue_async_work(env, worker->work); +} + +static napi_value SwithWatchOn(napi_env env, napi_callback_info info) +{ + napi_value callback = nullptr; + ParamWatcherPtr watcher = GetWatcherInfo(env, info, &callback); + PARAM_JS_CHECK(watcher != nullptr, return GetNapiValue(env, -1), "Failed to get watcher swith param"); + + if (CheckCallbackEqual(env, callback, watcher)) { + HiLog::Warn(LABEL, "JSApp watcher repeater switch on %{public}s", watcher->keyPrefix); + return 0; + } + HiLog::Debug(LABEL, "JSApp watcher on %{public}s", watcher->keyPrefix); + // save callback + napi_ref callbackRef; + napi_create_reference(env, callback, 1, &callbackRef); + AddWatcherCallback(watcher, callbackRef); + watcher->env = env; + { + std::lock_guard lock(watcher->mutex); + if (watcher->startWatch) { + return GetNapiValue(env, 0); + } + watcher->startWatch = true; + } + + HiLog::Debug(LABEL, "JSApp watcher add %{public}s", watcher->keyPrefix); + WatchCallbackWork(env, watcher); + HiLog::Debug(LABEL, "JSApp watcher on %{public}s finish", watcher->keyPrefix); + return GetNapiValue(env, 0); +} + +static napi_value SwithWatchOff(napi_env env, napi_callback_info info) +{ + napi_value callback = nullptr; + ParamWatcherPtr watcher = GetWatcherInfo(env, info, &callback); + PARAM_JS_CHECK(watcher != nullptr, return GetNapiValue(env, -1), "Failed to get watcher"); + HiLog::Debug(LABEL, "JSApp watcher off %{public}s", watcher->keyPrefix); + DelCallback(env, callback, watcher); + { + std::lock_guard lock(watcher->mutex); + if (watcher->callbackReferences.size() == 0) { + watcher->startWatch = false; + WatchCallbackWork(env, watcher); + } + } + return GetNapiValue(env, 0); +} + +napi_value RegisterWatcher(napi_env env, napi_value exports) +{ + napi_property_descriptor properties[] = { + DECLARE_NAPI_FUNCTION("on", SwithWatchOn), + DECLARE_NAPI_FUNCTION("off", SwithWatchOff), + }; + + napi_value result = nullptr; + NAPI_CALL(env, + napi_define_class(env, + "paramWatcher", + NAPI_AUTO_LENGTH, + ParamWatchConstructor, + nullptr, + sizeof(properties) / sizeof(*properties), + properties, + &result)); + napi_set_named_property(env, exports, "paramWatcher", result); + napi_create_reference(env, result, 1, &g_paramWatchRef); + return exports; +} \ No newline at end of file diff --git a/interfaces/kits/BUILD.gn b/interfaces/kits/syscap/BUILD.gn old mode 100644 new mode 100755 similarity index 100% rename from interfaces/kits/BUILD.gn rename to interfaces/kits/syscap/BUILD.gn diff --git a/interfaces/kits/include/syscap_ndk.h b/interfaces/kits/syscap/include/syscap_ndk.h old mode 100644 new mode 100755 similarity index 100% rename from interfaces/kits/include/syscap_ndk.h rename to interfaces/kits/syscap/include/syscap_ndk.h diff --git a/interfaces/kits/init_sync.h b/interfaces/kits/syscap/init_sync.h old mode 100644 new mode 100755 similarity index 100% rename from interfaces/kits/init_sync.h rename to interfaces/kits/syscap/init_sync.h diff --git a/interfaces/kits/libdeviceinfo.ndk.json b/interfaces/kits/syscap/libdeviceinfo.ndk.json similarity index 100% rename from interfaces/kits/libdeviceinfo.ndk.json rename to interfaces/kits/syscap/libdeviceinfo.ndk.json diff --git a/interfaces/kits/src/syscap_ndk.c b/interfaces/kits/syscap/src/syscap_ndk.c old mode 100644 new mode 100755 similarity index 100% rename from interfaces/kits/src/syscap_ndk.c rename to interfaces/kits/syscap/src/syscap_ndk.c diff --git a/scripts/param_cfg_to_code.py b/scripts/param_cfg_to_code.py new file mode 100755 index 0000000000000000000000000000000000000000..560b079a4f17b75b0ff73cb12176309a5d2c21f7 --- /dev/null +++ b/scripts/param_cfg_to_code.py @@ -0,0 +1,156 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +# +# Copyright (c) 2022 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 argparse +import os +import sys + +def DecodeCfgLine(data): + data.replace('\n', '').replace('\r', '') + data = data.strip() + if (len(data) == 0 or data[0] == '#'): + return "", "" + strs = data.split('=') + if len(strs) <= 1: + return "", "" + return strs[0].strip(), strs[1].strip() + +def GetParamFromCfg(cfgName): + dict = {} + with open(cfgName) as afile: + data = afile.readline() + while data: + name, value = DecodeCfgLine(data) + if len(name) != 0 and len(value) != 0: + dict[name] = value + print("sample file name={%s %s}"%(name, value)) + data = afile.readline() + return dict + +def DecodeCodeLine(data): + data.replace('\n', '').replace('\r', '') + data = data.strip() + if (not data.startswith("PARAM_MAP")): + return "", "" + dataLen = len(data) + data = data[len("PARAM_MAP") + 1 : dataLen - 1] + data = data.strip() + strs = data.split(',') + if len(strs) <= 1: + return "", "" + return strs[0].strip(), strs[1].strip() + +def GetParamFromCCode(codeName): + dict = {} + with open(codeName) as afile: + data = afile.readline() + while data: + name, value = DecodeCodeLine(data) + if len(name) != 0 and len(value) != 0: + dict[name] = value + data = afile.readline() + return dict + +def WriteMapToCode(codeName, dict): + try: + f = open(codeName, 'w+') + # write file header + f.write('#ifndef PARAM_LITE_DEF_CFG_' + os.linesep) + f.write('#define PARAM_LITE_DEF_CFG_' + os.linesep) + f.write('#include ' + os.linesep + os.linesep) + f.write('#ifdef __cplusplus' + os.linesep) + f.write('#if __cplusplus' + os.linesep) + f.write('extern "C" {' + os.linesep) + f.write('#endif' + os.linesep) + f.write('#endif' + os.linesep + os.linesep) + + #define struct + f.write('typedef struct Node_ {' + os.linesep) + f.write(' const char *name;' + os.linesep) + f.write(' const char *value;' + os.linesep) + f.write('} Node;' + os.linesep + os.linesep) + f.write('#define PARAM_MAP(name, value) {(const char *)#name, (const char *)#value},') + f.write(os.linesep + os.linesep) + # write data + f.write('static Node g_paramDefCfgNodes[] = {' + os.linesep) + for name, value in dict.items(): + str = " PARAM_MAP({0}, {1})".format(name, value) + f.write(str + os.linesep) + f.write('};' + os.linesep + os.linesep) + + #end + f.write('#ifdef __cplusplus' + os.linesep) + f.write('#if __cplusplus' + os.linesep) + f.write('}' + os.linesep) + f.write('#endif' + os.linesep) + f.write('#endif' + os.linesep) + f.write('#endif // PARAM_LITE_DEF_CFG_' + os.linesep) + except IOError: + print("Error: open or write file %s fail"%{codeName}) + else: + f.close() + return 0 + +def AddToCodeDict(codeDict, cfgDict, high = True): + for name, value in cfgDict.items(): + # check if name exit + hasKey = name in codeDict #codeDict.has_key(name) + if hasKey and high: + codeDict[name] = value + elif not hasKey: + codeDict[name] = value + return codeDict + +def main(): + parser = argparse.ArgumentParser( + description='A common change param.para file to h.') + parser.add_argument( + '--source', + help='The source to change.', + required=True) + parser.add_argument( + '--dest_dir', + help='Path that the source should be changed to.', + required=True) + parser.add_argument( + '--priority', + help='If priority is 1, replace the parameter if it exist.', + required=True) + args = parser.parse_args() + + out_dir = args.dest_dir + if not os.path.exists(out_dir): + os.makedirs(out_dir, exist_ok=True) + print(out_dir) + + source = args.source + assert os.path.exists(source) + + srcDict = GetParamFromCfg(source) + dst = out_dir + "param_cfg.h" + if os.path.exists(dst): + dstDict = GetParamFromCCode(dst) + else: + dstDict = {} + dstDict = AddToCodeDict(dstDict, srcDict, True) + WriteMapToCode(dst, dstDict) + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/services/BUILD.gn b/services/BUILD.gn index 7dd9032b52f34297d9b2040191ee145fd76518ab..ad3b0671e571da52a745e5920081e1e4dabe8ebd 100755 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -25,13 +25,13 @@ init_common_sources = [ if (defined(ohos_lite)) { # feature: init - executable("init_lite") { + executable("lite_init") { output_name = "init" defines = [ - "_GNU_SOURCE", #syscall function need this macro definition + "_GNU_SOURCE", "OHOS_LITE", + "__MUSL__", ] - defines += [ "__MUSL__" ] sources = [ "init/adapter/init_adapter.c", "init/lite/init.c", @@ -40,49 +40,49 @@ if (defined(ohos_lite)) { "init/lite/init_reboot.c", "init/lite/init_service.c", "init/lite/init_signal_handler.c", - "log/init_log.c", - "utils/init_hashmap.c", - "utils/init_utils.c", - "utils/list.c", ] - sources += init_common_sources include_dirs = [ "//base/startup/init_lite/services/include", + "//base/startup/init_lite/services/include/param", "//base/startup/init_lite/services/init/include", "//base/startup/init_lite/services/log", "//base/startup/init_lite/services/loopevent/include", "//base/startup/init_lite/interfaces/innerkits/include", "//third_party/cJSON", "//third_party/bounds_checking_function/include", - "//base/startup/syspara_lite/interfaces/kits", "//base/hiviewdfx/hilog_lite/interfaces/native/kits", "//base/startup/init_lite/interfaces/innerkits/fd_holder", ] cflags = [ "-Wall" ] - + ldflags = [] deps = [ "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", - "//base/startup/init_lite/initsync:initsync", + "//base/startup/init_lite/services/log:init_log", "//base/startup/init_lite/services/loopevent:loopevent", - "//base/startup/syspara_lite/frameworks/parameter:parameter", - "//build/lite/config/component/cJSON:cjson_shared", - "//third_party/bounds_checking_function:libsec_shared", + "//base/startup/init_lite/services/param:param_init", + "//base/startup/init_lite/services/utils:libinit_tools", + "//build/lite/config/component/cJSON:cjson_static", + "//third_party/bounds_checking_function:libsec_static", ] - ldflags = [] + if (ohos_kernel_type == "liteos_a") { + defines += [ "__LITEOS_A__" ] include_dirs += [ "//kernel/liteos_a/syscall", - "//base/startup/init_lite/interfaces/kits", + "//kernel/liteos_a/kernel/include", + "//base/startup/init_lite/interfaces/kits/syscap", "//base/startup/init_lite/initsync/include", ] deps += [ "//base/startup/init_lite/initsync:initsync" ] } if (ohos_kernel_type == "linux") { - defines += [ "NEED_EXEC_RCS_LINUX" ] - defines += [ "_GNU_SOURCE" ] + defines += [ + "NEED_EXEC_RCS_LINUX", + "__LINUX__", + ] ldflags += [ "-lm", "-lpthread", @@ -96,7 +96,46 @@ if (defined(ohos_lite)) { if (ohos_build_type == "debug") { group("unittest") { - deps = [ "//base/startup/init_lite/test/unittest/common:unittest" ] + deps = [ "//base/startup/init_lite/test/unittest/lite:init_test" ] + } + } + + copy("ohos.para") { + sources = [ "//base/startup/init_lite/services/etc/param/ohos.para" ] + outputs = [ "$root_out_dir/system/etc/param/ohos.para" ] + } + + copy("ohos.para.dac") { + sources = [ "//base/startup/init_lite/services/etc/param/ohos.para.dac" ] + outputs = [ "$root_out_dir/system/etc/param/ohos.para.dac" ] + } + copy("ohos.const") { + sources = + [ "//base/startup/init_lite/services/etc/param/ohos_const/ohos.para" ] + outputs = [ "$root_out_dir/system/etc/param/ohos_const/ohos.para" ] + } + + copy("ohos.passwd") { + sources = [ "//base/startup/init_lite/services/etc_lite/passwd" ] + outputs = [ "$root_out_dir/etc/passwd" ] + } + copy("ohos.group") { + sources = [ "//base/startup/init_lite/services/etc_lite/group" ] + outputs = [ "$root_out_dir/etc/group" ] + } + + group("init_lite") { + deps = [ + ":lite_init", + ":ohos.const", + ":ohos.para", + ":ohos.para.dac", + ] + if (ohos_kernel_type == "linux") { + deps += [ + ":ohos.group", + ":ohos.passwd", + ] } } } else { @@ -148,7 +187,7 @@ if (defined(ohos_lite)) { "//base/startup/init_lite/interfaces/innerkits/sandbox:libsandbox_static", "//base/startup/init_lite/services/log:init_log", "//base/startup/init_lite/services/loopevent:loopevent", - "//base/startup/init_lite/services/param:param_service", + "//base/startup/init_lite/services/param:param_init", "//base/startup/init_lite/services/utils:libinit_tools", "//base/startup/init_lite/services/utils:libinit_utils", "//base/startup/init_lite/ueventd:libueventd_ramdisk_static", @@ -180,7 +219,7 @@ if (defined(ohos_lite)) { cflags += [ "-DWITH_SELINUX" ] } - defines = [] + defines = [ "PARAM_SUPPORT_TRIGGER" ] if (param_test) { defines += [ "OHOS_SERVICE_DUMP", @@ -218,13 +257,12 @@ if (defined(ohos_lite)) { ":init", ":init_etc", "//base/startup/init_lite/services/param:param_client", - "//base/startup/init_lite/services/param:param_service", + "//base/startup/init_lite/services/param:param_init", ] if (param_feature_watcher) { deps += [ "//base/startup/init_lite/services/param/watcher:param_watcher", "//base/startup/init_lite/services/param/watcher:param_watcher.rc", - "//base/startup/init_lite/services/param/watcher:param_watcheragent", "//base/startup/init_lite/services/param/watcher/sa_profile:param_watcher_profile", ] } diff --git a/services/begetctl/BUILD.gn b/services/begetctl/BUILD.gn index 7998f3f8934fb3114dca8b920722535d651c56ab..426c1254654d8010d47511f1cc2dc88f4c4d0fc6 100644 --- a/services/begetctl/BUILD.gn +++ b/services/begetctl/BUILD.gn @@ -11,134 +11,182 @@ # See the License for the specific language governing permissions and # limitations under the License. import("//base/startup/init_lite/begetd.gni") -import("//build/ohos.gni") - -ohos_executable("begetctl") { - sources = [ - "bootchart_cmd.c", - "init_cmd_reboot.c", - "main.c", - "misc_daemon.cpp", - "param_cmd.c", - "sandbox.cpp", - "service_control.c", - "shell/shell_bas.c", - ] - - defines = [ "INIT_AGENT" ] - - if (defined(product_name) && product_name == "rk3568") { - defines += [ "PRODUCT_RK" ] - } - include_dirs = [ - ".", - "shell", - "//base/startup/init_lite/services/include", - "//base/startup/init_lite/services/log", - "//base/startup/init_lite/interfaces/innerkits/include", - "//base/startup/init_lite/services/include/param/", - "//base/startup/init_lite/services/param/include", - "//base/startup/init_lite/services/loopevent/include", - "//third_party/bounds_checking_function/include", - "//base/startup/init_lite/interfaces/innerkits/sandbox/include", - ] - deps = [ - "//base/startup/init_lite/interfaces/innerkits:libbegetutil", - "//base/startup/init_lite/interfaces/innerkits/sandbox:libsandbox_static", - "//base/startup/init_lite/services/log:agent_log", - "//base/startup/init_lite/services/param:param_client", - "//third_party/bounds_checking_function:libsec_static", - ] - - external_deps = [ "utils_base:utils" ] - if (param_test) { - sources += [ "//base/startup/init_lite/test/plugintest/plugin_param_cmd.c" ] - deps += [ - "//base/startup/init_lite/interfaces/innerkits:libbeget_proxy", - "//base/startup/init_lite/services/loopevent:loopevent", - "//base/startup/init_lite/services/param/watcher:param_watcheragent", - "//base/startup/init_lite/services/utils:libinit_tools", - "//base/startup/init_lite/services/utils:libinit_utils", +if (defined(ohos_lite)) { + executable("begetctl") { + output_name = "begetctl" + sources = [ + "main.c", + "param_cmd.c", + "shell/shell_bas.c", ] - defines += [ - "OHOS_SERVICE_DUMP", - "INIT_TEST", + defines = [ + "_GNU_SOURCE", #syscall function need this macro definition + "__MUSL__", + ] + include_dirs = [ + ".", + "shell", + "//base/startup/init_lite/services/include", + "//base/startup/init_lite/services/log", + "//base/startup/init_lite/interfaces/innerkits/include", + "//base/startup/init_lite/services/include/param/", + "//base/startup/init_lite/services/param/include", + "//base/startup/init_lite/services/loopevent/include", + "//third_party/bounds_checking_function/include", + "//base/startup/init_lite/interfaces/innerkits/sandbox/include", + "//third_party/cJSON", + ] + deps = [ + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", + "//base/startup/init_lite/interfaces/innerkits:libbegetutil", + "//base/startup/init_lite/services/utils:libinit_tools", + "//build/lite/config/component/cJSON:cjson_static", + "//third_party/bounds_checking_function:libsec_static", ] - external_deps += [ "startup_l2:syspara" ] } - - if (build_selinux) { - include_dirs += [ "//third_party/selinux/libselinux/include/" ] - deps += [ "//third_party/selinux:libselinux" ] - external_deps += [ "selinux:libparaperm_checker" ] - defines += [ "WITH_SELINUX" ] + group("begetctl_cmd") { + if (param_begetctl_liteos_support) { + deps = [ ":begetctl" ] + } } +} else { + import("//build/ohos.gni") - symlink_target_name = [ - "misc_daemon", - "reboot", - "devctl", - "service", - "service_control", - "start_service", - "stop_service", - "service", - "param", - "sandbox", - ] - - install_images = [ "system" ] - install_enable = true - - part_name = "init" -} + ohos_executable("begetctl") { + sources = [ + "bootchart_cmd.c", + "init_cmd_reboot.c", + "main.c", + "misc_daemon.cpp", + "param_cmd.c", + "sandbox.cpp", + "service_control.c", + "shell/shell_bas.c", + ] -ohos_executable("paramshell") { - sources = [ - "param_cmd.c", - "shell/shell_bas.c", - "shell/shell_main.c", - ] - - defines = [ "INIT_AGENT" ] - - include_dirs = [ - ".", - "shell", - "//base/startup/init_lite/services/include", - "//base/startup/init_lite/services/log", - "//base/startup/init_lite/interfaces/innerkits/include", - "//base/startup/syspara_lite/interfaces/innerkits/native/syspara/include", - "//base/startup/init_lite/services/include/param/", - "//base/startup/init_lite/services/loopevent/include", - "//base/startup/init_lite/services/param/include", - "//third_party/bounds_checking_function/include", - ] - deps = [ - "//base/startup/init_lite/services/log:agent_log", - "//base/startup/init_lite/services/param:param_client", - "//third_party/bounds_checking_function:libsec_static", - ] - - if (param_test) { - sources += [ "//base/startup/init_lite/test/plugintest/plugin_param_cmd.c" ] - deps += [ - "//base/startup/init_lite/interfaces/innerkits:libbeget_proxy", - "//base/startup/init_lite/services/loopevent:loopevent", - "//base/startup/init_lite/services/param/watcher:param_watcheragent", - "//base/startup/init_lite/services/utils:libinit_tools", - "//base/startup/init_lite/services/utils:libinit_utils", - "//base/startup/syspara_lite/interfaces/innerkits/native/syspara:syspara", + defines = [ "_GNU_SOURCE" ] + + if (defined(product_name) && product_name == "rk3568") { + defines += [ "PRODUCT_RK" ] + } + + include_dirs = [ + ".", + "shell", + "//base/startup/init_lite/services/include", + "//base/startup/init_lite/services/log", + "//base/startup/init_lite/interfaces/innerkits/include", + "//base/startup/init_lite/services/include/param/", + "//base/startup/init_lite/services/param/include", + "//base/startup/init_lite/services/loopevent/include", + "//third_party/bounds_checking_function/include", + "//base/startup/init_lite/interfaces/innerkits/sandbox/include", + ] + deps = [ + "//base/startup/init_lite/interfaces/innerkits:libbegetutil", + "//base/startup/init_lite/interfaces/innerkits/sandbox:libsandbox", + "//base/startup/init_lite/services/log:agent_log", + "//base/startup/init_lite/services/param:param_client", + "//third_party/bounds_checking_function:libsec_shared", ] - defines += [ - "OHOS_SERVICE_DUMP", - "INIT_TEST", + external_deps = [ "utils_base:utils" ] + + if (param_test) { + sources += + [ "//base/startup/init_lite/test/plugintest/plugin_param_cmd.c" ] + deps += [ + "//base/startup/init_lite/interfaces/innerkits:libbeget_proxy", + "//base/startup/init_lite/services/loopevent:loopevent", + "//base/startup/init_lite/services/utils:libinit_tools", + "//base/startup/init_lite/services/utils:libinit_utils", + ] + defines += [ + "OHOS_SERVICE_DUMP", + "INIT_TEST", + ] + } + + if (build_selinux) { + include_dirs += [ + "//third_party/selinux/libselinux/include/", + "//base/security/selinux/interfaces/policycoreutils/include/", + ] + deps += [ "//third_party/selinux:libselinux" ] + external_deps += [ "selinux:libparaperm_checker" ] + defines += [ "PARAM_SUPPORT_SELINUX" ] + } + + symlink_target_name = [ + "misc_daemon", + "reboot", + "devctl", + "service", + "service_control", + "start_service", + "stop_service", + "service", + "param", + "sandbox", ] + + install_images = [ "system" ] + install_enable = true + + part_name = "init" } - install_images = [ "system" ] - install_enable = true + ohos_executable("paramshell") { + sources = [ + "param_cmd.c", + "shell/shell_bas.c", + "shell/shell_main.c", + ] + + defines = [ "_GNU_SOURCE" ] - part_name = "init" + include_dirs = [ + ".", + "shell", + "//base/startup/init_lite/services/include", + "//base/startup/init_lite/services/log", + "//base/startup/init_lite/interfaces/innerkits/include", + "//base/startup/init_lite/services/include/param/", + "//base/startup/init_lite/services/loopevent/include", + "//base/startup/init_lite/services/param/include", + "//third_party/bounds_checking_function/include", + ] + deps = [ + "//base/startup/init_lite/interfaces/innerkits:libbegetutil", + "//base/startup/init_lite/services/log:agent_log", + "//base/startup/init_lite/services/param:param_client", + "//third_party/bounds_checking_function:libsec_static", + ] + + if (build_selinux) { + deps += [ "//third_party/selinux:libselinux" ] + external_deps = [ "selinux:libparaperm_checker" ] + defines += [ "PARAM_SUPPORT_SELINUX" ] + } + + if (param_test) { + sources += + [ "//base/startup/init_lite/test/plugintest/plugin_param_cmd.c" ] + deps += [ + "//base/startup/init_lite/interfaces/innerkits:libbeget_proxy", + "//base/startup/init_lite/services/loopevent:loopevent", + "//base/startup/init_lite/services/utils:libinit_tools", + "//base/startup/init_lite/services/utils:libinit_utils", + ] + defines += [ + "OHOS_SERVICE_DUMP", + "INIT_TEST", + ] + } + + install_images = [ "system" ] + install_enable = true + + part_name = "init" + } } diff --git a/services/begetctl/bootchart_cmd.c b/services/begetctl/bootchart_cmd.c index b0ab4f754a0a6698e80fe7255bfb76b68a34c845..00c7be2fd77900bcb5b7a36aea0fd2b62586388c 100644 --- a/services/begetctl/bootchart_cmd.c +++ b/services/begetctl/bootchart_cmd.c @@ -17,7 +17,7 @@ #include #include "begetctl.h" -#include "sys_param.h" +#include "init_param.h" static int bootchartCmdEnable(BShellHandle shell, int argc, char **argv) { diff --git a/services/begetctl/main.c b/services/begetctl/main.c index c062ab84f243e92577963bc916351c7bc1f67731..5a06fa35679828c1b91435e93cef3e8553196076 100644 --- a/services/begetctl/main.c +++ b/services/begetctl/main.c @@ -19,7 +19,7 @@ #include "begetctl.h" #include "shell.h" #include "shell_utils.h" -#include "sys_param.h" +#include "init_param.h" static BShellHandle g_handle = NULL; static int32_t ShellOuput(const char *data, int32_t len) @@ -69,12 +69,17 @@ int main(int argc, char *argv[]) printf("Failed to copy\n"); } } + BShellHandle handle = GetShellHandle(); + if (handle == NULL) { + printf("Failed to get shell handle \n"); + return 0; + } SetInitLogLevel(0); - BShellParamCmdRegister(g_handle, 0); + BShellParamCmdRegister(handle, 0); #ifdef INIT_TEST - BShellCmdRegister(g_handle, 0); + BShellCmdRegister(handle, 0); #endif - BShellEnvDirectExecute(g_handle, number, args); + BShellEnvDirectExecute(handle, number, args); demoExit(); return 0; } diff --git a/services/begetctl/misc_daemon.cpp b/services/begetctl/misc_daemon.cpp index 5872b2d2bc4e006173d0ea1ff22aefc32005cce4..496b63d7f3ce6a819793ec5434d7f1e1bf76b71c 100644 --- a/services/begetctl/misc_daemon.cpp +++ b/services/begetctl/misc_daemon.cpp @@ -29,7 +29,7 @@ #include "fs_manager/fs_manager.h" #include "shell.h" #include "shell_utils.h" -#include "sys_param.h" +#include "init_param.h" constexpr int MAX_LOGO_SIZE = 1024 * 2038; constexpr int PARTITION_INFO_POS = 1144; diff --git a/services/begetctl/param_cmd.c b/services/begetctl/param_cmd.c index e3da1e90f3cbcf6d04ae0ab6b49ef873f10b31bf..3d0152cb56f0095490d7513fbde4e37555932418 100755 --- a/services/begetctl/param_cmd.c +++ b/services/begetctl/param_cmd.c @@ -27,12 +27,12 @@ #include "param_security.h" #include "param_utils.h" #include "shell_utils.h" -#include "sys_param.h" -#ifdef WITH_SELINUX +#include "init_param.h" +#ifdef PARAM_SUPPORT_SELINUX #include #include #include "selinux_parameter.h" -#endif // WITH_SELINUX +#endif // PARAM_SUPPORT_SELINUX #define MASK_LENGTH_MAX 4 pid_t g_shellPid = 0; @@ -160,30 +160,25 @@ static void ShowParam(BShellHandle shell, const char *name, const char *value) BSH_LOGE("Failed to get param security for %s", name); return; } + BShellEnvOutput(shell, "Parameter infomation:\r\n"); +#ifdef PARAM_SUPPORT_SELINUX + BShellEnvOutput(shell, "selinux : %s \r\n", auditData.label); +#endif char permissionStr[3][MASK_LENGTH_MAX] = {}; // 3 permission struct passwd *user = getpwuid(auditData.dacData.uid); struct group *group = getgrgid(auditData.dacData.gid); - if (user == NULL || group == NULL) { - BSH_LOGE("Failed to get group for user for %s", name); - return; - } - BShellEnvOutput(shell, "Parameter infomation:\r\n"); -#ifdef WITH_SELINUX - const char *context = NULL; - if (strcmp(name, "#") != 0) { - context = GetParamLabel(name); - } - if (context != NULL) { - BShellEnvOutput(shell, "selinux : %s \r\n", context); - } else { - BShellEnvOutput(shell, "selinux : null \r\n"); + if (user != NULL && group != NULL) { + BShellEnvOutput(shell, " dac : %s(%s) %s(%s) (%s) \r\n", + user->pw_name, + GetPermissionString(auditData.dacData.mode, 0, permissionStr[0], MASK_LENGTH_MAX), + group->gr_name, + GetPermissionString(auditData.dacData.mode,DAC_GROUP_START, permissionStr[1], MASK_LENGTH_MAX), + // 2 other + GetPermissionString(auditData.dacData.mode, DAC_OTHER_START, permissionStr[2], MASK_LENGTH_MAX)); + } + if (strcmp("#", name) != 0) { + BShellEnvOutput(shell, " name : %s\r\n", name); } -#endif - BShellEnvOutput(shell, " dac : %s(%s) %s(%s) (%s) \r\n", - user->pw_name, GetPermissionString(auditData.dacData.mode, 0, permissionStr[0], MASK_LENGTH_MAX), - group->gr_name, GetPermissionString(auditData.dacData.mode, DAC_GROUP_START, permissionStr[1], MASK_LENGTH_MAX), - GetPermissionString(auditData.dacData.mode, DAC_OTHER_START, permissionStr[2], MASK_LENGTH_MAX)); // 2 other - BShellEnvOutput(shell, " name : %s\r\n", name); if (value != NULL) { BShellEnvOutput(shell, " value: %s\r\n", value); } @@ -406,7 +401,7 @@ static int32_t BShellParamCmdShell(BShellHandle shell, int32_t argc, char *argv[ if (pid == 0) { setuid(2000); // 2000 shell group setgid(2000); // 2000 shell group -#ifdef WITH_SELINUX +#ifdef PARAM_SUPPORT_SELINUX setcon("u:r:normal_hap_domain:s0"); #endif if (argc >= 2) { // 2 min argc diff --git a/services/begetctl/service_control.c b/services/begetctl/service_control.c index da4e38af66477abb339a638a5278b4f5f45b72da..67699b270b1a5c7f6e4399aea50f414ece8d3020 100644 --- a/services/begetctl/service_control.c +++ b/services/begetctl/service_control.c @@ -19,7 +19,7 @@ #include #include "begetctl.h" -#include "sys_param.h" +#include "init_param.h" #include "init_utils.h" #define SERVICE_START_NUMBER 2 diff --git a/services/begetctl/shell/shell_main.c b/services/begetctl/shell/shell_main.c index 53e6c7e9cc4a6a53ceeab87ce3ed05351a7ecead..929da598366983a74f249d0df01b7ea118c6ed76 100644 --- a/services/begetctl/shell/shell_main.c +++ b/services/begetctl/shell/shell_main.c @@ -76,25 +76,26 @@ int main(int argc, char *args[]) SetInitLogLevel(0); BSH_LOGV("BShellEnvStart %d", argc); do { - if (g_handle == NULL) { - BShellInfo info = {PARAM_SHELL_DEFAULT_PROMPT, ShellInput, ShellOuput}; - BShellEnvInit(&g_handle, &info); + BShellHandle handle = GetShellHandle(); + if (handle == NULL) { + printf("Failed to get shell handle \n"); + return 0; } - const ParamInfo *param = BShellEnvGetReservedParam(g_handle, PARAM_REVERESD_NAME_CURR_PARAMETER); + const ParamInfo *param = BShellEnvGetReservedParam(handle, PARAM_REVERESD_NAME_CURR_PARAMETER); BSH_CHECK(param != NULL && param->type == PARAM_STRING, break, "Failed to get revered param"); - BShellEnvSetParam(g_handle, param->name, param->desc, param->type, (void *)""); + BShellEnvSetParam(handle, param->name, param->desc, param->type, (void *)""); if (argc > 1) { - int ret = SetParamShellPrompt(g_handle, args[1]); + int ret = SetParamShellPrompt(handle, args[1]); if (ret != 0) { break; } } - BShellParamCmdRegister(g_handle, 1); + BShellParamCmdRegister(handle, 1); #ifdef INIT_TEST - BShellCmdRegister(g_handle, 1); + BShellCmdRegister(handle, 1); #endif - BShellEnvStart(g_handle); - BShellEnvLoop(g_handle); + BShellEnvStart(handle); + BShellEnvLoop(handle); } while (0); demoExit(); tcsetattr(0, TCSAFLUSH, &terminalState); diff --git a/services/etc/param/ohos.para.dac b/services/etc/param/ohos.para.dac index ede2ce163b0362410eadeb2c6dcbe6370873997f..888ddcaea55d9c323c0b2a0e634c22545f25c5f3 100755 --- a/services/etc/param/ohos.para.dac +++ b/services/etc/param/ohos.para.dac @@ -28,3 +28,10 @@ persist.sys.usb.config = root:root:0777 # default forbit other user to start service ohos.servicectrl. = system:servicectrl:0775 +#permission for system +persist.window.boot. = root:system:0775 + +#permission for log +debug.bytrace. = root:system:0775 + +persist.distributed_hardware.device_manager. = system:system:0775 \ No newline at end of file diff --git a/services/etc_lite/group b/services/etc_lite/group new file mode 100755 index 0000000000000000000000000000000000000000..21443c612f6c901d720439519b7599d58949f51f --- /dev/null +++ b/services/etc_lite/group @@ -0,0 +1,5 @@ +root:x:0: +bin:x:2: +system:x:1000: +servicectrl:x:1050:root,shell,system,samgr,hdf_devmgr +shell:x:2000: \ No newline at end of file diff --git a/services/etc_lite/passwd b/services/etc_lite/passwd new file mode 100755 index 0000000000000000000000000000000000000000..0605711f7ec6a8dfdf86044825f90950de41e798 --- /dev/null +++ b/services/etc_lite/passwd @@ -0,0 +1,4 @@ +root:x:0:0:::/bin/false +bin:x:2:2:::/bin/false +system:x:1000:1000:::/bin/false +shell:x:2000:2000:::/bin/false diff --git a/services/include/init_utils.h b/services/include/init_utils.h index d97fa2637f2c3795f70d4ae6daaaafb933a47285..9c93bb880258d7832af3a1a51e112c75292cb8b5 100644 --- a/services/include/init_utils.h +++ b/services/include/init_utils.h @@ -36,9 +36,17 @@ typedef struct { #define WAIT_MAX_SECOND 5 #define MAX_BUFFER_LEN 256 #define CMDLINE_VALUE_LEN_MAX 512 -#define PARAM_CMD_LINE "/proc/cmdline" #define ARRAY_LENGTH(array) (sizeof((array)) / sizeof((array)[0])) +#ifndef STARTUP_INIT_UT_PATH +#ifdef STARTUP_INIT_TEST // ut +#define STARTUP_INIT_UT_PATH "/data/init_ut" +#else +#define STARTUP_INIT_UT_PATH "" +#endif +#endif +#define BOOT_CMD_LINE STARTUP_INIT_UT_PATH"/proc/cmdline" + uid_t DecodeUid(const char *name); char *ReadFileToBuf(const char *configFile); int GetProcCmdlineValue(const char *name, const char *buffer, char *value, int length); @@ -61,6 +69,7 @@ int StringReplaceChr(char *strl, char oldChr, char newChr); int GetMapValue(const char *name, const InitArgInfo *infos, int argNum, int defValue); const InitArgInfo *GetServieStatusMap(int *size); +unsigned int GetRandom(void); #ifdef __cplusplus #if __cplusplus } diff --git a/services/include/param/init_param.h b/services/include/param/init_param.h index 6d5b51f9f114b9ae3107613e723d6252fc2b4e45..9ff66da9c0f93b362e33f30c44e509a0d4240e61 100644 --- a/services/include/param/init_param.h +++ b/services/include/param/init_param.h @@ -17,14 +17,52 @@ #define BASE_STARTUP_INIT_PARAM_H #include #include - +#ifdef PARAM_SUPPORT_TRIGGER #include "cJSON.h" -#include "param.h" +#endif #ifdef __cplusplus #if __cplusplus extern "C" { #endif #endif + +#define DEFAULT_PARAM_WAIT_TIMEOUT 30 // 30s +#define DEFAULT_PARAM_SET_TIMEOUT 10 // 10s + +#ifndef PARAM_NAME_LEN_MAX +#define PARAM_CONST_VALUE_LEN_MAX 4096 +#define PARAM_VALUE_LEN_MAX 96 +#define PARAM_NAME_LEN_MAX 96 +#endif + +typedef uint32_t ParamHandle; + +typedef enum { + PARAM_CODE_ERROR = -1, + PARAM_CODE_SUCCESS = 0, + PARAM_CODE_INVALID_PARAM = 100, + PARAM_CODE_INVALID_NAME, + PARAM_CODE_INVALID_VALUE, + PARAM_CODE_REACHED_MAX, + PARAM_CODE_NOT_SUPPORT, + PARAM_CODE_TIMEOUT, + PARAM_CODE_NOT_FOUND, + PARAM_CODE_READ_ONLY, + PARAM_CODE_FAIL_CONNECT, + PARAM_CODE_NODE_EXIST, + PARAM_CODE_MAX +} PARAM_CODE; + +typedef enum { + EVENT_TRIGGER_PARAM, + EVENT_TRIGGER_BOOT, + EVENT_TRIGGER_PARAM_WAIT, + EVENT_TRIGGER_PARAM_WATCH +} EventType; + +#define LOAD_PARAM_NORMAL 0x00 +#define LOAD_PARAM_ONLY_ADD 0x01 + /** * Init 接口 * 初始化参数服务 @@ -55,7 +93,7 @@ int LoadDefaultParams(const char *fileName, unsigned int mode); /** * Init 接口 - * 加载默认参数。 + * 加载持久化参数。 * */ int LoadPersistParams(void); @@ -74,22 +112,23 @@ int SystemWriteParam(const char *name, const char *value); */ int SystemReadParam(const char *name, char *value, unsigned int *len); +#ifdef PARAM_SUPPORT_TRIGGER /** - * 对Init接口 + * 对外接口 * 触发一个trigger操作。 * */ void PostTrigger(EventType type, const char *content, uint32_t contentLen); /** - * 对Init接口 + * 对外接口 * 解析trigger文件。 * */ int ParseTriggerConfig(const cJSON *fileRoot, int (*checkJobValid)(const char *jobName)); /** - * 对Init接口 + * 对外接口 * 按名字执行对应的trigger。 * */ @@ -97,20 +136,94 @@ void DoTriggerExec(const char *triggerName); void DoJobExecNow(const char *triggerName); /** - * 对Init接口 + * 对外接口 * 按名字添加一个job,用于group支持。 * */ int AddCompleteJob(const char *name, const char *condition, const char *cmdContent); +void RegisterBootStateChange(void (*bootStateChange)(const char *)); + /** - * 对Init接口 + * 对外接口 * dump 参数和trigger信息 * */ -void DumpParametersAndTriggers(void); +void SystemDumpTriggers(int verbose); +#endif + +/** + * 对外接口 + * 设置参数,主要用于其他进程使用,通过管道修改参数。 + * + */ +int SystemSetParameter(const char *name, const char *value); + +/** + * 对外接口 + * 查询参数,主要用于其他进程使用,需要给定足够的内存保存参数。 + * 如果 value == null,获取value的长度 + * 否则value的大小认为是len + * + */ +#define SystemGetParameter SystemReadParam + +/** + * 对外接口 + * 查询参数,主要用于其他进程使用,找到对应属性的handle。 + * + */ +int SystemFindParameter(const char *name, ParamHandle *handle); + +/** + * 对外接口 + * 根据handle获取对应数据的修改标识。 + * commitId 获取计数变化 + * + */ +int SystemGetParameterCommitId(ParamHandle handle, uint32_t *commitId); + +/** + * 外部接口 + * 遍历参数。 + * + */ +int SystemTraversalParameter(const char *prefix, + void (*traversalParameter)(ParamHandle handle, void *cookie), void *cookie); + +/** + * 外部接口 + * 查询参数,主要用于其他进程使用,需要给定足够的内存保存参数。 + * 如果 value == null,获取value的长度 + * 否则value的大小认为是len + * + */ +int SystemGetParameterName(ParamHandle handle, char *name, unsigned int len); + +/** + * 外部接口 + * 获取参数值。 + * + */ +int SystemGetParameterValue(ParamHandle handle, char *value, unsigned int *len); + +/** + * 外部接口 + * 等待某个参数值被修改,阻塞直到参数值被修改或超时 + * + */ +int SystemWaitParameter(const char *name, const char *value, int32_t timeout); + +typedef void (*ParameterChangePtr)(const char *key, const char *value, void *context); +int SystemWatchParameter(const char *keyprefix, ParameterChangePtr change, void *context); + +int SysCheckParamExist(const char *name); +long long GetSystemCommitId(void); + +void SystemDumpParameters(int verbose); + +int WatchParamCheck(const char *keyprefix); -void RegisterBootStateChange(void (*bootStateChange)(const char *)); #ifdef __cplusplus #if __cplusplus } diff --git a/services/include/param/param.h b/services/include/param/param.h deleted file mode 100644 index f20a34dfd7942b64f8035e28f8b780143fb73dd4..0000000000000000000000000000000000000000 --- a/services/include/param/param.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2021 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 BASE_STARTUP_PARAM_H -#define BASE_STARTUP_PARAM_H -#include -#include - -#ifdef __cplusplus -#if __cplusplus -extern "C" { -#endif -#endif - -#define PARAM_CONST_VALUE_LEN_MAX 4096 -#define PARAM_VALUE_LEN_MAX 96 -#define PARAM_NAME_LEN_MAX 96 -typedef uint32_t ParamHandle; - -typedef enum { - PARAM_CODE_ERROR = -1, - PARAM_CODE_SUCCESS = 0, - PARAM_CODE_INVALID_PARAM = 100, - PARAM_CODE_INVALID_NAME, - PARAM_CODE_INVALID_VALUE, - PARAM_CODE_REACHED_MAX, - PARAM_CODE_NOT_SUPPORT, - PARAM_CODE_TIMEOUT, - PARAM_CODE_NOT_FOUND, - PARAM_CODE_READ_ONLY, - PARAM_CODE_FAIL_CONNECT, - PARAM_CODE_NODE_EXIST, - PARAM_CODE_MAX -} PARAM_CODE; - -typedef enum { - EVENT_TRIGGER_PARAM, - EVENT_TRIGGER_BOOT, - EVENT_TRIGGER_PARAM_WAIT, - EVENT_TRIGGER_PARAM_WATCH -} EventType; - -#define LOAD_PARAM_NORMAL 0x00 -#define LOAD_PARAM_ONLY_ADD 0x01 -#ifdef __cplusplus -#if __cplusplus -} -#endif -#endif -#endif \ No newline at end of file diff --git a/services/include/param/sys_param.h b/services/include/param/sys_param.h deleted file mode 100644 index b7ce94f2a419976810e03639cd95ad94e4dbb2e0..0000000000000000000000000000000000000000 --- a/services/include/param/sys_param.h +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (c) 2021 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 BASE_STARTUP_SYS_PARAM_H -#define BASE_STARTUP_SYS_PARAM_H -#include -#include -#include - -#include "param.h" -#ifdef __cplusplus -#if __cplusplus -extern "C" { -#endif -#endif - -#define DEFAULT_PARAM_WAIT_TIMEOUT 30 // 30s -#define DEFAULT_PARAM_SET_TIMEOUT 10 // 10s - -/** - * 对外接口 - * 设置参数,主要用于其他进程使用,通过管道修改参数。 - * - */ -int SystemSetParameter(const char *name, const char *value); - -/** - * 对外接口 - * 查询参数,主要用于其他进程使用,需要给定足够的内存保存参数。 - * 如果 value == null,获取value的长度 - * 否则value的大小认为是len - * - */ -int SystemGetParameter(const char *name, char *value, unsigned int *len); - -/** - * 对外接口 - * 查询参数,主要用于其他进程使用,找到对应属性的handle。 - * - */ -int SystemFindParameter(const char *name, ParamHandle *handle); - -/** - * 对外接口 - * 根据handle获取对应数据的修改标识。 - * commitId 获取计数变化 - * - */ -int SystemGetParameterCommitId(ParamHandle handle, uint32_t *commitId); - -/** - * 外部接口 - * 遍历参数。 - * - */ -int SystemTraversalParameter(const char *prefix, - void (*traversalParameter)(ParamHandle handle, void *cookie), void *cookie); - -/** - * 外部接口 - * 查询参数,主要用于其他进程使用,需要给定足够的内存保存参数。 - * 如果 value == null,获取value的长度 - * 否则value的大小认为是len - * - */ -int SystemGetParameterName(ParamHandle handle, char *name, unsigned int len); - -/** - * 外部接口 - * 获取参数值。 - * - */ -int SystemGetParameterValue(ParamHandle handle, char *value, unsigned int *len); - -/** - * 外部接口 - * 等待某个参数值被修改,阻塞直到参数值被修改或超时 - * - */ -int SystemWaitParameter(const char *name, const char *value, int32_t timeout); - -typedef void (*ParameterChangePtr)(const char *key, const char *value, void *context); -int SystemWatchParameter(const char *keyprefix, ParameterChangePtr change, void *context); - -void SystemDumpParameters(int verbose); - -int SysCheckParamExist(const char *name); -long long GetSystemCommitId(void); -#ifdef __cplusplus -#if __cplusplus -} -#endif -#endif -#endif \ No newline at end of file diff --git a/services/init/include/init_cmds.h b/services/init/include/init_cmds.h index c56bb66087bcc4cf86e3d98038f0cb89830aa564..0c681950009da6e818ba63f740a6a31d2caba260 100644 --- a/services/init/include/init_cmds.h +++ b/services/init/include/init_cmds.h @@ -82,6 +82,8 @@ void ExecReboot(const char *value); char *BuildStringFromCmdArg(const struct CmdArgs *ctx, int startIndex); void ExecCmd(const struct CmdTable *cmd, const char *cmdContent); int FileCryptEnable(char *fileCryptOption); + +void OpenHidebug(const char *name); #ifdef __cplusplus #if __cplusplus } diff --git a/services/init/include/init_group_manager.h b/services/init/include/init_group_manager.h index 9f95ae7fc9144e4abcbfd8c3f7312e3548b86242..478cb3f2450d19fc5a90c02105e44d68365898d7 100644 --- a/services/init/include/init_group_manager.h +++ b/services/init/include/init_group_manager.h @@ -29,13 +29,8 @@ extern "C" { #define GROUP_IMPORT_MAX_LEVEL 5 #define GROUP_NAME_MAX_LENGTH 64 #define GROUP_HASHMAP_BUCKET 32 -#ifdef STARTUP_INIT_TEST -#define GROUP_DEFAULT_PATH "/data/init_ut" -#define BOOT_CMD_LINE "/data/init_ut/cmdline" -#else -#define GROUP_DEFAULT_PATH "/system/etc" -#define BOOT_CMD_LINE "/proc/cmdline" -#endif + +#define GROUP_DEFAULT_PATH STARTUP_INIT_UT_PATH"/system/etc" #define BOOT_GROUP_NAME "bootgroup" #define BOOT_GROUP_DEFAULT "device.boot.group" diff --git a/services/init/include/init_service_socket.h b/services/init/include/init_service_socket.h index d4f0a0adea642f62b10eedec7518c7398c9db112..f09b6f9b61f9e6f589a77da50dc79403b2d25164 100644 --- a/services/init/include/init_service_socket.h +++ b/services/init/include/init_service_socket.h @@ -14,7 +14,7 @@ */ #ifndef INIT_SERVICE_SOCKET_ #define INIT_SERVICE_SOCKET_ -#ifndef __LITEOS__ +#ifndef __LITEOS_A__ #include #endif #include @@ -51,7 +51,7 @@ struct Service_; #define SOCKET_OPTION_RCVBUFFORCE 0x004 // SO_RCVBUFFORCE typedef union { -#ifndef __LITEOS__ +#ifndef __LITEOS_A__ struct sockaddr_nl addrnl; #endif struct sockaddr_un addrun; diff --git a/services/init/init_common_service.c b/services/init/init_common_service.c index a900de364cde86f05e209c3ede5203bf2c4aeb1f..f6ec09a262ce46957b564086ec4767ca91af73d6 100644 --- a/services/init/init_common_service.c +++ b/services/init/init_common_service.c @@ -248,7 +248,7 @@ static int BindCpuCore(Service *service) if (CPU_COUNT(&service->cpuSet) == 0) { return SERVICE_SUCCESS; } -#ifndef __LITEOS__ +#ifndef __LITEOS_A__ int pid = getpid(); if (sched_setaffinity(pid, sizeof(service->cpuSet), &service->cpuSet) != 0) { INIT_LOGE("%s set affinity between process(pid=%d) with CPU's core failed", service->name, pid); @@ -459,7 +459,6 @@ void ServiceReap(Service *service) if (!CalculateCrashTime(service, service->crashTime, service->crashCount)) { INIT_LOGE("Critical service \" %s \" crashed %d times, rebooting system", service->name, service->crashCount); - ServiceStop(GetServiceByName("appspawn")); ExecReboot("reboot"); } } else if (!(service->attribute & SERVICE_ATTR_NEED_RESTART)) { diff --git a/services/init/init_config.c b/services/init/init_config.c index 9237e10fa80625be1bc3e16644ad2a4231826f96..bb69c2571fb6c876bf69fe27d135b26c01891c0a 100644 --- a/services/init/init_config.c +++ b/services/init/init_config.c @@ -17,6 +17,7 @@ #include "init_log.h" #include "init_service_manager.h" #include "init_utils.h" +#include "init_param.h" static void ParseAllImports(const cJSON *root); @@ -93,7 +94,11 @@ static void ParseAllImports(const cJSON *root) void ReadConfig(void) { // parse cfg - if (InChargerMode() == 1) { + char buffer[32] = {0}; // 32 reason max leb + uint32_t len = sizeof(buffer); + SystemReadParam("ohos.boot.reboot_reason", buffer, &len); + INIT_LOGV("ohos.boot.reboot_reason %s", buffer); + if (strcmp(buffer, "poweroff_charge") == 0) { ParseInitCfg(INIT_CONFIGURATION_FILE, NULL); ReadFileInDir(OTHER_CHARGE_PATH, ".cfg", ParseInitCfg, NULL); } else if (InUpdaterMode() == 0) { diff --git a/services/init/init_group_manager.c b/services/init/init_group_manager.c index 86f8ba93ffcbbda890b931e7e576ae353267fb2f..07e41bb4f393826932d96a5121971fbd1208a45c 100644 --- a/services/init/init_group_manager.c +++ b/services/init/init_group_manager.c @@ -49,6 +49,7 @@ static int ParseGroupCfgItem(cJSON *root, int type, const char *itemName) { int itemNumber = 0; cJSON *json = GetArrayItem(root, &itemNumber, itemName); + INIT_LOGI("ParseGroupCfgItem %s itemNumber %d", itemName, itemNumber); if (json == NULL) { return 0; } @@ -66,7 +67,7 @@ static int ParseGroupCfgItem(cJSON *root, int type, const char *itemName) static int InitParseGroupCfg_(const char *groupCfg) { INIT_LOGI("Parse group config %s", groupCfg); - char *fileBuf = ReadFileToBuf(groupCfg); + char *fileBuf = ReadFileData(groupCfg); INIT_ERROR_CHECK(fileBuf != NULL, return -1, "Failed to read file content %s", groupCfg); cJSON *fileRoot = cJSON_Parse(fileBuf); INIT_ERROR_CHECK(fileRoot != NULL, free(fileBuf); @@ -181,22 +182,17 @@ void InitServiceSpace(void) for (int i = 0; i < NODE_TYPE_MAX; i++) { g_initWorkspace.groupNodes[i] = NULL; } - // get boot mode + // get boot mode, set default mode + strcpy_s(g_initWorkspace.groupModeStr, sizeof(g_initWorkspace.groupModeStr), BOOT_GROUP_DEFAULT); char *data = ReadFileData(BOOT_CMD_LINE); if (data != NULL) { int ret = GetProcCmdlineValue(BOOT_GROUP_NAME, data, g_initWorkspace.groupModeStr, sizeof(g_initWorkspace.groupModeStr)); if (ret != 0) { INIT_LOGE("%s", "Failed to get boot group"); -#ifdef INIT_TEST if (GetBootModeFromMisc() == GROUP_CHARING) { strcpy_s(g_initWorkspace.groupModeStr, sizeof(g_initWorkspace.groupModeStr), "device.charing.group"); - } else { - strcpy_s(g_initWorkspace.groupModeStr, sizeof(g_initWorkspace.groupModeStr), BOOT_GROUP_DEFAULT); } -#else - strcpy_s(g_initWorkspace.groupModeStr, sizeof(g_initWorkspace.groupModeStr), BOOT_GROUP_DEFAULT); -#endif } free(data); } diff --git a/services/init/init_service_manager.c b/services/init/init_service_manager.c index de2bda03fcabb9d79dcd9dc20ec030b6fd20ae3a..adab7a8af184ceaea25f37e674a3fa52e0311569 100644 --- a/services/init/init_service_manager.c +++ b/services/init/init_service_manager.c @@ -403,7 +403,7 @@ static int ParseSocketProtocol(cJSON *json, ServiceSocket *sockopt) if (strncmp(stringValue, "default", strLen) == 0) { sockopt->protocol = 0; } else if (strncmp(stringValue, "NETLINK_KOBJECT_UEVENT", strLen) == 0) { -#ifndef __LITEOS__ +#ifndef __LITEOS_A__ sockopt->protocol = NETLINK_KOBJECT_UEVENT; #else return -1; diff --git a/services/init/init_service_socket.c b/services/init/init_service_socket.c index a7b70ba1d5ebb9c45e7b853d4e3a07eaeefba66b..026b78638cb8da0f13e41b62b3e10e2ebb0d8053 100644 --- a/services/init/init_service_socket.c +++ b/services/init/init_service_socket.c @@ -47,7 +47,7 @@ static int SetSocketAddr(ServiceSocket *sockopt, sockaddr_union *addr) { int ret = 0; if (sockopt->family == AF_NETLINK) { -#ifndef __LITEOS__ +#ifndef __LITEOS_A__ if (memset_s(&(addr->addrnl), sizeof(addr->addrnl), 0, sizeof(addr->addrnl)) != EOK) { INIT_LOGE("Faild to clear socket address"); return -1; @@ -92,7 +92,7 @@ static int SetSocketOptionAndBind(ServiceSocket *sockopt) return -1; } if (sockopt->family == AF_NETLINK) { -#ifndef __LITEOS__ +#ifndef __LITEOS_A__ if (bind(sockopt->sockFd, (struct sockaddr *)&(addr.addrnl), sizeof(addr.addrnl))) { INIT_LOGE("Create socket for service %s failed: %d", sockopt->name, errno); return -1; diff --git a/services/init/lite/bundle.json b/services/init/lite/bundle.json index e3dd5312583e471cecf2e6035a3b00413c5b64a2..01875f1e8b0040c8a63d90cb1b508a9c37b55073 100644 --- a/services/init/lite/bundle.json +++ b/services/init/lite/bundle.json @@ -21,7 +21,6 @@ "ram": "~200KB", "deps": { "components": [ - "syspara_lite" ], "third_party": [ "cJSON", @@ -30,12 +29,30 @@ }, "build": { "sub_component": [ + "//base/startup/init_lite/interfaces/innerkits:libbegetutil", "//base/startup/init_lite/services:init_lite", + "//base/startup/init_lite/services/begetctl:begetctl_cmd", "//base/startup/init_lite/watchdog:watchdog", "//base/startup/init_lite/ueventd:ueventd" ], + "inner_kits": [ + { + "header": { + "header_base": "//base/startup/init_lite/interfaces/innerkits/include/", + "header_files": [ + "beget_ext.h", + "syspara/parameter.h", + "syspara/parameters.h", + "syspara/param_wrapper.h", + "syspara/sysparam_errno.h", + "syspara/sysversion.h" + ] + }, + "name": "//base/startup/init_lite/interfaces/innerkits:libbegetutil" + } + ], "test": [ - "//base/startup/init_lite/test/unittest/common:unittest" + "//base/startup/init_lite/test/unittest/lite:init_test" ] } } diff --git a/services/init/lite/init.c b/services/init/lite/init.c index 49eafb612a24a7ab99b453bcfce1a6d0aa42f7d5..e3dbb0d4c3acd71bf40b7db50b5c83226938acdc 100644 --- a/services/init/lite/init.c +++ b/services/init/lite/init.c @@ -13,6 +13,12 @@ * limitations under the License. */ #include "init.h" + +#include +#include +#ifdef __LINUX__ +#include +#endif #include "init_group_manager.h" #include "init_jobs_internal.h" #include "init_log.h" @@ -20,17 +26,8 @@ #ifndef __LINUX__ #include "init_stage.h" #endif +#include "init_param.h" #include "loop_event.h" -#include "parameter.h" - -static void PrintSysInfo(void) -{ - const char *sysInfo = GetVersionId(); - if (sysInfo != NULL) { - INIT_LOGE("%s", sysInfo); - return; - } -} void SystemInit(void) { @@ -40,17 +37,31 @@ void SystemInit(void) void LogInit(void) { +#ifdef __LINUX__ + int ret = mknod("/dev/kmsg", S_IFCHR | S_IWUSR | S_IRUSR, makedev(MEM_MAJOR, 11)); + if (ret == 0) { + OpenLogDevice(); + } +#endif return; } void SystemPrepare(void) { - PrintSysInfo(); } void SystemConfig(void) { InitServiceSpace(); +#ifdef LITEOS_SUPPORT_PARAM + InitParamService(); + // parse parameters + LoadDefaultParams("/system/etc/param/ohos_const", LOAD_PARAM_NORMAL); + LoadDefaultParams("/vendor/etc/param", LOAD_PARAM_NORMAL); + LoadDefaultParams("/system/etc/param", LOAD_PARAM_ONLY_ADD); + + LoadPersistParams(); +#endif // read config ReadConfig(); @@ -80,7 +91,7 @@ void SystemConfig(void) void SystemRun(void) { -#ifndef __LITEOS__ +#ifndef __LITEOS_A__ LE_RunLoop(LE_GetDefaultLoop()); #else while (1) { diff --git a/services/init/standard/init.c b/services/init/standard/init.c index faf8a2988f379e3b08cd555e306f58f9a02380d0..240f7796bf7f3639fd769d8caae4028d64808b97 100644 --- a/services/init/standard/init.c +++ b/services/init/standard/init.c @@ -261,7 +261,8 @@ static int SystemDump(int id, const char *name, int argc, const char **argv) INIT_ERROR_CHECK(argv != NULL && argc >= 1, return 0, "Invalid install parameter"); INIT_LOGI("Dump system info %s", argv[0]); DumpAllServices(); - DumpParametersAndTriggers(); + SystemDumpParameters(1); + SystemDumpTriggers(1); return 0; } #endif @@ -284,12 +285,6 @@ static void IsEnableSandbox(void) } } -// Init provide this function for static lib link -__attribute__((weak)) int SystemGetParameter(const char *name, char *value, unsigned int *len) -{ - return SystemReadParam(name, value, len); -} - static void InitLoadParamFiles(void) { // Load const params, these can't be override! diff --git a/services/init/standard/init_cmds.c b/services/init/standard/init_cmds.c index 4fdddd5c20cbcbf36868dd5a0d3b7044e6b5a762..106b6ab90aeebd401f2704f4ed1e3695e52b33db 100644 --- a/services/init/standard/init_cmds.c +++ b/services/init/standard/init_cmds.c @@ -44,8 +44,6 @@ #include #endif -#define ARRAY_LEN(array) (sizeof(array) / (sizeof(array[0]))) - static const char *g_fscryptPolicyKey = "fscrypt.policy.config"; int GetParamValue(const char *symValue, unsigned int symLen, char *paramValue, unsigned int paramLen) @@ -183,36 +181,7 @@ static void DoExec(const struct CmdArgs *ctx) INIT_ERROR_CHECK(pid >= 0, return, "DoExec: failed to fork child process to exec \"%s\"", ctx->argv[0]); if (pid == 0) { -#ifdef SUPPORT_PROFILER_HIDEBUG - do { -#ifdef __aarch64__ - const char *debugSoPath = "/system/lib64/libhidebug.so"; -#else - const char *debugSoPath = "/system/lib/libhidebug.so"; -#endif - if (access(debugSoPath, F_OK) != 0) { - INIT_LOGE("access failed, errno = %d\n", errno); - break; - } - void* handle = dlopen(debugSoPath, RTLD_LAZY); - if (handle == NULL) { - INIT_LOGE("Failed to dlopen libhidebug.so, %s\n", dlerror()); - break; - } - bool (* initParam)(); - initParam = (bool (*)())dlsym(handle, "InitEnvironmentParam"); - if (initParam == NULL) { - INIT_LOGE("Failed to dlsym InitEnvironmentParam, %s\n", dlerror()); - dlclose(handle); - break; - } - bool ret = (*initParam)(ctx->argv[0]); - if (!ret) { - INIT_LOGE("init parameters failed.\n"); - } - dlclose(handle); - } while (0); -#endif + OpenHidebug(ctx->argv[0]); int ret = execv(ctx->argv[0], ctx->argv); if (ret == -1) { INIT_LOGE("DoExec: execute \"%s\" failed: %d.", ctx->argv[0], errno); @@ -454,7 +423,7 @@ static void DoInitGlobalKey(const struct CmdArgs *ctx) "init_global_key", NULL }; - int argc = ARRAY_LEN(argv); + int argc = ARRAY_LENGTH(argv); int ret = SyncExecCommand(argc, argv); INIT_LOGI("DoInitGlobalKey: end, ret = %d", ret); } @@ -472,7 +441,7 @@ static void DoInitMainUser(const struct CmdArgs *ctx) "init_main_user", NULL }; - int argc = ARRAY_LEN(argv); + int argc = ARRAY_LENGTH(argv); int ret = SyncExecCommand(argc, argv); INIT_LOGI("DoInitMainUser: end, ret = %d", ret); } @@ -506,7 +475,7 @@ static void DoMkswap(const struct CmdArgs *ctx) ctx->argv[0], NULL }; - int argc = ARRAY_LEN(argv); + int argc = ARRAY_LENGTH(argv); int ret = SyncExecCommand(argc, argv); INIT_LOGI("DoMkswap: end, ret = %d", ret); } @@ -523,7 +492,7 @@ static void DoSwapon(const struct CmdArgs *ctx) ctx->argv[0], NULL }; - int argc = ARRAY_LEN(argv); + int argc = ARRAY_LENGTH(argv); int ret = SyncExecCommand(argc, argv); INIT_LOGI("DoSwapon: end, ret = %d", ret); } @@ -588,3 +557,37 @@ const struct CmdTable *GetCmdTable(int *number) *number = (int)ARRAY_LENGTH(g_cmdTable); return g_cmdTable; } + +void OpenHidebug(const char *name) +{ +#ifdef SUPPORT_PROFILER_HIDEBUG +#ifdef __aarch64__ + const char *debugSoPath = "/system/lib64/libhidebug.so"; +#else + const char *debugSoPath = "/system/lib/libhidebug.so"; +#endif + do { + if (access(debugSoPath, F_OK) != 0) { + INIT_LOGE("access failed, errno = %d\n", errno); + break; + } + void* handle = dlopen(debugSoPath, RTLD_LAZY); + if (handle == NULL) { + INIT_LOGE("Failed to dlopen libhidebug.so, %s\n", dlerror()); + break; + } + bool (* initParam)(); + initParam = (bool (*)())dlsym(handle, "InitEnvironmentParam"); + if (initParam == NULL) { + INIT_LOGE("Failed to dlsym InitEnvironmentParam, %s\n", dlerror()); + dlclose(handle); + break; + } + bool ret = (*initParam)(name); + if (!ret) { + INIT_LOGV("init parameters failed.\n"); + } + dlclose(handle); + } while (0); +#endif +} \ No newline at end of file diff --git a/services/init/standard/init_service.c b/services/init/standard/init_service.c index 5e530aee2990b4da7fc8487616faa9ba67fe7625..de6d70c73046ab7e14bb2f11816450a323dee698 100644 --- a/services/init/standard/init_service.c +++ b/services/init/standard/init_service.c @@ -87,36 +87,7 @@ int ServiceExec(const Service *service) } } INIT_CHECK_ONLY_ELOG(unsetenv("UV_THREADPOOL_SIZE") == 0, "set UV_THREADPOOL_SIZE error : %d.", errno); -#ifdef SUPPORT_PROFILER_HIDEBUG - do { -#ifdef __aarch64__ - const char *debugSoPath = "/system/lib64/libhidebug.so"; -#else - const char *debugSoPath = "/system/lib/libhidebug.so"; -#endif - if (access(debugSoPath, F_OK) != 0) { - INIT_LOGE("access failed, errno = %d\n", errno); - break; - } - void* handle = dlopen(debugSoPath, RTLD_LAZY); - if (handle == NULL) { - INIT_LOGE("Failed to dlopen libhidebug.so, %s\n", dlerror()); - break; - } - bool (* initParam)(); - initParam = (bool (*)())dlsym(handle, "InitEnvironmentParam"); - if (initParam == NULL) { - INIT_LOGE("Failed to dlsym InitEnvironmentParam, %s\n", dlerror()); - dlclose(handle); - break; - } - bool ret = (*initParam)(service->name); - if (!ret) { - INIT_LOGE("init parameters failed.\n"); - } - dlclose(handle); - } while (0); -#endif + OpenHidebug(service->name); // L2 Can not be reset env if (service->extraArgs.argv != NULL && service->extraArgs.count > 0) { INIT_CHECK_ONLY_ELOG(execv(service->extraArgs.argv[0], service->extraArgs.argv) == 0, diff --git a/services/log/BUILD.gn b/services/log/BUILD.gn index ab63760bb7f7eba2f17986fe5f987d523d17eaa4..edca0a36d5f64fae8459a382054ad602542c8748 100755 --- a/services/log/BUILD.gn +++ b/services/log/BUILD.gn @@ -15,34 +15,44 @@ if (defined(ohos_lite)) { sources = [ "init_log.c" ] defines = [ "_GNU_SOURCE", - "OHOS_LITE", "INIT_LOG_INIT=1", + "OHOS_LITE", ] + + if (ohos_kernel_type == "linux") { + defines += [ "INIT_DMESG" ] + } include_dirs = [ "//base/hiviewdfx/hilog_lite/interfaces/native/kits", "//base/startup/init_lite/interfaces/innerkits/include", + "//third_party/bounds_checking_function/include", ] - deps = [ - "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_static", - "//third_party/bounds_checking_function:libsec_static", - ] + deps = [ "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_static" ] } } else { import("//build/ohos.gni") ohos_static_library("init_log") { sources = [ "init_log.c" ] defines = [ "INIT_DMESG" ] - deps = [ "//third_party/bounds_checking_function:libsec_static" ] - include_dirs = [ "//base/startup/init_lite/interfaces/innerkits/include" ] + include_dirs = [ + "//base/startup/init_lite/interfaces/innerkits/include", + "//third_party/bounds_checking_function/include", + ] part_name = "startup" subsystem_name = "startup" } ohos_shared_library("agent_log") { sources = [ "init_log.c" ] - defines = [ "INIT_AGENT" ] - deps = [ "//third_party/bounds_checking_function:libsec_static" ] - include_dirs = [ "//base/startup/init_lite/interfaces/innerkits/include" ] + defines = [ + "INIT_AGENT", + "INIT_FILE", + ] + deps = [ "//third_party/bounds_checking_function:libsec_shared" ] + include_dirs = [ + "//base/startup/init_lite/interfaces/innerkits/include", + "//third_party/bounds_checking_function/include", + ] part_name = "startup" install_images = [ "system", diff --git a/services/log/init_log.c b/services/log/init_log.c index d810700b486e2b0bdbd1636c7ba88b08eee38cad..11e004480c2e3d600b02cdbe559f5bd2befac352 100644 --- a/services/log/init_log.c +++ b/services/log/init_log.c @@ -62,7 +62,6 @@ static void LogToFile(const char *logFile, const char *tag, const char *info) #endif #ifdef INIT_DMESG -#ifndef OHOS_LITE static int g_fd = -1; void OpenLogDevice(void) { @@ -98,7 +97,6 @@ void LogToDmesg(InitLogLevel logLevel, const char *tag, const char *info) return; } #endif -#endif void InitLog(InitLogLevel logLevel, unsigned int domain, const char *tag, const char *fmt, ...) { @@ -116,12 +114,10 @@ void InitLog(InitLogLevel logLevel, unsigned int domain, const char *tag, const #ifdef OHOS_LITE static LogLevel LOG_LEVEL[] = { LOG_DEBUG, LOG_INFO, LOG_WARN, LOG_ERROR, LOG_FATAL }; (void)HiLogPrint(INIT_LOG_INIT, LOG_LEVEL[logLevel], domain, tag, "%{public}s", tmpFmt); -#else +#endif #ifdef INIT_DMESG LogToDmesg(logLevel, tag, tmpFmt); #endif -#endif - #ifdef INIT_AGENT static LogLevel LOG_LEVEL[] = { LOG_DEBUG, LOG_INFO, LOG_WARN, LOG_ERROR, LOG_FATAL }; HiLogBasePrint(LOG_CORE, LOG_LEVEL[logLevel], domain, tag, "%{public}s", tmpFmt); diff --git a/services/loopevent/BUILD.gn b/services/loopevent/BUILD.gn index ecdb5d223dabef24ead8cf78e5df0e1f602c1e71..cc53c402e818c69ad0f092394fb34054c445afe6 100644 --- a/services/loopevent/BUILD.gn +++ b/services/loopevent/BUILD.gn @@ -28,6 +28,7 @@ common_include = [ "//base/startup/init_lite/services/log", "//base/startup/init_lite/interfaces/innerkits/include", "//base/startup/init_lite/services/include", + "//third_party/bounds_checking_function/include", "include", "loop", "socket", @@ -43,7 +44,6 @@ if (defined(ohos_lite)) { include_dirs = common_include defines = [ "_GNU_SOURCE" ] - deps = [ "//third_party/bounds_checking_function:libsec_static" ] } } else { import("//build/ohos.gni") @@ -53,7 +53,6 @@ if (defined(ohos_lite)) { include_dirs = common_include defines = [ "_GNU_SOURCE" ] - deps = [ "//third_party/bounds_checking_function:libsec_static" ] part_name = "init" subsystem_name = "startup" } diff --git a/services/loopevent/include/loop_event.h b/services/loopevent/include/loop_event.h index 779feb9067beb14cc492677c916008970d8d0a24..cfa3a78c0e3356faabbc0ba75971ff54952ee03c 100644 --- a/services/loopevent/include/loop_event.h +++ b/services/loopevent/include/loop_event.h @@ -48,7 +48,8 @@ typedef enum { LE_FAILURE = 10000, LE_INVALID_PARAM, LE_NO_MEMORY, - LE_DIS_CONNECTED + LE_DIS_CONNECTED, + LE_INVALID_TASK } LE_STATUS; typedef struct { diff --git a/services/loopevent/loop/le_epoll.c b/services/loopevent/loop/le_epoll.c index 2e082c6d83538155f84a3079c884a6c749aad203..b5d940307260b72de843c685b5a5cb3364d48d25 100644 --- a/services/loopevent/loop/le_epoll.c +++ b/services/loopevent/loop/le_epoll.c @@ -102,6 +102,14 @@ static LE_STATUS RunLoop_(const EventLoop *loop) if ((epoll->waitEvents[index].events & EPOLLOUT) == EPOLLOUT) { ProcessEvent(loop, epoll->waitEvents[index].data.fd, Event_Write); } + if ((epoll->waitEvents[index].events & EPOLLERR) == EPOLLERR) { + LE_LOGV("RunLoop_ error %d", epoll->waitEvents[index].data.fd); + ProcessEvent(loop, epoll->waitEvents[index].data.fd, Event_Error); + } + if ((epoll->waitEvents[index].events & EPOLLHUP) == EPOLLHUP) { + LE_LOGV("RunLoop_ error %d", epoll->waitEvents[index].data.fd); + ProcessEvent(loop, epoll->waitEvents[index].data.fd, Event_Error); + } } if (loop->stop) { break; @@ -121,6 +129,8 @@ LE_STATUS CreateEpollLoop(EventLoop **loop, uint32_t maxevents, uint32_t timeout return LE_FAILURE, "Failed to create epoll"); *loop = (EventLoop *)epoll; + epoll->loop.maxevents = maxevents; + epoll->loop.timeout = timeout; epoll->loop.close = Close_; epoll->loop.runLoop = RunLoop_; epoll->loop.delEvent = DelEvent_; diff --git a/services/loopevent/loop/le_loop.c b/services/loopevent/loop/le_loop.c index 17bc34d95b6e8ab21cebaadf031feacc61217248..ecdbfd026d0866561e888ce5a4b451cdd448384a 100644 --- a/services/loopevent/loop/le_loop.c +++ b/services/loopevent/loop/le_loop.c @@ -87,6 +87,9 @@ LE_STATUS ProcessEvent(const EventLoop *loop, int fd, uint32_t oper) { BaseTask *task = GetTaskByFd((EventLoop *)loop, fd); if (task != NULL) { + if (oper & Event_Error) { + task->flags |= TASK_FLAGS_INVALID; + } task->handleEvent((LoopHandle)loop, (TaskHandle)task, oper); } else { LE_LOGE("ProcessEvent can not find task for %d", fd); diff --git a/services/loopevent/loop/le_loop.h b/services/loopevent/loop/le_loop.h index 709ec417d9689a3113e654b4c1b58cc0034ce270..80dd85502ef3b562303b736976cf1fd22bfd40f6 100644 --- a/services/loopevent/loop/le_loop.h +++ b/services/loopevent/loop/le_loop.h @@ -37,7 +37,11 @@ typedef struct EventLoop_ { uint32_t maxevents; uint32_t timeout; uint32_t stop; +#ifdef LOOP_EVENT_USE_MUTEX LoopMutex mutex; +#else + char mutex; +#endif HashMapHandle taskMap; } EventLoop; diff --git a/services/loopevent/socket/le_socket.c b/services/loopevent/socket/le_socket.c index d808ee3b1896f6faebc8feb1d53be184766db184..150479344d98b1598af06939a722e983d73ae6b0 100644 --- a/services/loopevent/socket/le_socket.c +++ b/services/loopevent/socket/le_socket.c @@ -32,28 +32,28 @@ static int CreatePipeServerSocket_(const char *server, int maxClient) { int listenfd = socket(PF_UNIX, SOCK_STREAM, 0); - LE_CHECK(listenfd > 0, return listenfd, "Failed to create socket"); + LE_CHECK(listenfd > 0, return listenfd, "Failed to create socket errno %d", errno); unlink(server); struct sockaddr_un serverAddr; int ret = memset_s(&serverAddr, sizeof(serverAddr), 0, sizeof(serverAddr)); LE_CHECK(ret == 0, close(listenfd); - return ret, "Failed to memory set. error: %s", strerror(errno)); + return ret, "Failed to memory set. error: %d", errno); serverAddr.sun_family = AF_UNIX; ret = strcpy_s(serverAddr.sun_path, sizeof(serverAddr.sun_path), server); LE_CHECK(ret == 0, close(listenfd); - return ret, "Failed to copy. error: %s", strerror(errno)); + return ret, "Failed to copy. error: %d", errno); uint32_t size = offsetof(struct sockaddr_un, sun_path) + strlen(server); ret = bind(listenfd, (struct sockaddr *)&serverAddr, size); LE_CHECK(ret >= 0, close(listenfd); - return ret, "Failed to bind socket. error: %s", strerror(errno)); + return ret, "Failed to bind socket. error: %d", errno); SetNoBlock(listenfd); ret = listen(listenfd, maxClient); LE_CHECK(ret >= 0, close(listenfd); - return ret, "Failed to listen socket error: %s", strerror(errno)); + return ret, "Failed to listen socket error: %d", errno); ret = chmod(server, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH); - LE_CHECK(ret == 0, return ret, "Failed to chmod %s, err %d. ", server, errno); + LE_CHECK(ret == 0, return -1, "Failed to chmod %s, err %d. ", server, errno); LE_LOGV("CreatePipeSocket listen fd: %d server:%s ", listenfd, serverAddr.sun_path); return listenfd; } @@ -166,7 +166,7 @@ int CreateSocket(int flags, const char *server) { int fd = -1; int type = flags & 0x0000ff00; - LE_LOGV("CreateSocket flags %#x type %#x server %s", flags, type, server); + LE_LOGV("CreateSocket flags %x type %x server %s", flags, type, server); if (type == TASK_TCP) { if (LE_TEST_FLAGS(flags, TASK_SERVER)) { fd = CreateTcpServerSocket_(server, LOOP_MAX_CLIENT); diff --git a/services/loopevent/task/le_asynctask.c b/services/loopevent/task/le_asynctask.c index 88292089b83cca85179fab92c3eb21f07ca4075c..094728d8e7225587469d631bc0d49a49e273edbf 100644 --- a/services/loopevent/task/le_asynctask.c +++ b/services/loopevent/task/le_asynctask.c @@ -47,7 +47,7 @@ static LE_STATUS HandleAsyncEvent_(const LoopHandle loopHandle, const TaskHandle if (LE_TEST_FLAGS(oper, Event_Read)) { uint64_t eventId = 0; int ret = read(GetSocketFd(taskHandle), &eventId, sizeof(eventId)); - LE_LOGV("HandleAsyncEvent_ read fd:%d ret: %d eventId %lu", GetSocketFd(taskHandle), ret, eventId); + LE_LOGV("HandleAsyncEvent_ read fd:%d ret: %d eventId %llu", GetSocketFd(taskHandle), ret, eventId); DoAsyncEvent_(loopHandle, asyncTask); if (IsBufferEmpty(&asyncTask->stream)) { loop->modEvent(loop, (const BaseTask *)taskHandle, Event_Read); diff --git a/services/loopevent/task/le_streamtask.c b/services/loopevent/task/le_streamtask.c index 85e5a9d2d8ad3af0152f8414c82a2cc440372040..c827ad139576b4e7bc2c6113955c9b1379d6d0cb 100644 --- a/services/loopevent/task/le_streamtask.c +++ b/services/loopevent/task/le_streamtask.c @@ -84,21 +84,21 @@ static LE_STATUS HandleStreamEvent_(const LoopHandle loopHandle, const TaskHandl StreamConnectTask *stream = (StreamConnectTask *)handle; LE_LOGV("HandleStreamEvent_ fd:%d oper 0x%x", GetSocketFd(handle), oper); - LE_STATUS statue = LE_SUCCESS; + LE_STATUS status = LE_SUCCESS; if (LE_TEST_FLAGS(oper, Event_Write)) { - statue = HandleSendMsg_(loopHandle, handle, stream->sendMessageComplete); + status = HandleSendMsg_(loopHandle, handle, stream->sendMessageComplete); } if (LE_TEST_FLAGS(oper, Event_Read)) { - statue = HandleRecvMsg_(loopHandle, handle, stream->recvMessage); + status = HandleRecvMsg_(loopHandle, handle, stream->recvMessage); } - if (statue == LE_DIS_CONNECTED) { + if (status == LE_DIS_CONNECTED) { loop->delEvent(loop, GetSocketFd(handle), Event_Read | Event_Write); if (stream->disConntectComplete) { stream->disConntectComplete(handle); } LE_CloseStreamTask(loopHandle, handle); } - return statue; + return status; } static LE_STATUS HandleClientEvent_(const LoopHandle loopHandle, const TaskHandle handle, uint32_t oper) @@ -106,25 +106,25 @@ static LE_STATUS HandleClientEvent_(const LoopHandle loopHandle, const TaskHandl StreamClientTask *client = (StreamClientTask *)handle; LE_LOGV("HandleClientEvent_ fd:%d oper 0x%x", GetSocketFd(handle), oper); - LE_STATUS statue = LE_SUCCESS; + LE_STATUS status = LE_SUCCESS; if (LE_TEST_FLAGS(oper, Event_Write)) { if (client->connected == 0 && client->connectComplete) { client->connectComplete(handle); } client->connected = 1; - statue = HandleSendMsg_(loopHandle, handle, client->sendMessageComplete); + status = HandleSendMsg_(loopHandle, handle, client->sendMessageComplete); } if (LE_TEST_FLAGS(oper, Event_Read)) { - statue = HandleRecvMsg_(loopHandle, handle, client->recvMessage); + status = HandleRecvMsg_(loopHandle, handle, client->recvMessage); } - if (statue == LE_DIS_CONNECTED) { + if (status == LE_DIS_CONNECTED) { if (client->disConntectComplete) { client->disConntectComplete(handle); } client->connected = 0; LE_CloseStreamTask(loopHandle, handle); } - return statue; + return status; } static void HandleStreamTaskClose_(const LoopHandle loopHandle, const TaskHandle taskHandle) diff --git a/services/loopevent/task/le_task.c b/services/loopevent/task/le_task.c index a4be38f868e45a7173718026b57b84ed3f1b9339..1a286b537ad2531974b1960fc57429246dd99780 100644 --- a/services/loopevent/task/le_task.c +++ b/services/loopevent/task/le_task.c @@ -175,6 +175,10 @@ LE_STATUS LE_Send(const LoopHandle loopHandle, const TaskHandle taskHandle, const BufferHandle buffHandle, uint32_t buffLen) { EventLoop *loop = (EventLoop *)loopHandle; + if (((BaseTask *)taskHandle)->flags & TASK_FLAGS_INVALID) { + LE_FreeBuffer(loopHandle, taskHandle, buffHandle); + return LE_INVALID_TASK; + } LE_Buffer *buffer = (LE_Buffer *)buffHandle; buffer->dataSize = buffLen; if (CheckTaskFlags((BaseTask *)taskHandle, TASK_STREAM | TASK_CONNECT)) { diff --git a/services/loopevent/task/le_task.h b/services/loopevent/task/le_task.h index 6995f8fedcce8dbe417e331b3d48a3a4bd81cf36..24bf371bcea2d6aedb4f16c1f7e7a2b86559a30f 100644 --- a/services/loopevent/task/le_task.h +++ b/services/loopevent/task/le_task.h @@ -23,10 +23,9 @@ #include "loop_event.h" #ifndef LOOP_EVENT_USE_MUTEX -#define LoopMutex char -#define LoopMutexInit(x) -#define LoopMutexLock(x) -#define LoopMutexUnlock(x) +#define LoopMutexInit(x) (void)(x) +#define LoopMutexLock(x) (void)(x) +#define LoopMutexUnlock(x) (void)(x) #else #include #define LoopMutex pthread_mutex_t @@ -48,6 +47,7 @@ typedef struct { uint8_t data[0]; } LE_Buffer; +#define TASK_FLAGS_INVALID 0x80000000 typedef LE_STATUS (*HandleTaskEvent)(const LoopHandle loop, const TaskHandle task, uint32_t oper); typedef void (*HandleTaskClose)(const LoopHandle loop, const TaskHandle task); #define TASKINFO \ @@ -78,7 +78,11 @@ typedef struct { typedef struct { BaseTask base; +#ifdef LOOP_EVENT_USE_MUTEX LoopMutex mutex; +#else + char mutex; +#endif ListHead buffHead; } StreamTask; diff --git a/services/loopevent/timer/le_timer.c b/services/loopevent/timer/le_timer.c index 05ecff4dbcd8b7ecab853485e683170d3d1da171..81f8715b66d705d0d6b4bf6ea38d74b934470c62 100644 --- a/services/loopevent/timer/le_timer.c +++ b/services/loopevent/timer/le_timer.c @@ -33,7 +33,7 @@ static LE_STATUS SetTimer_(int tfd, uint64_t timeout) timeValue.it_interval.tv_nsec = nsec; timeValue.it_value.tv_sec = sec; timeValue.it_value.tv_nsec = nsec; - LE_LOGV("SetTimer_ sec %lu tv_nsec %lu", sec, nsec); + LE_LOGV("SetTimer_ sec %llu tv_nsec %lu", sec, nsec); int ret = timerfd_settime(tfd, 0, &timeValue, NULL); LE_CHECK(ret == 0, return LE_FAILURE, "Failed to set timer %d", errno); return 0; diff --git a/services/param/BUILD.gn b/services/param/BUILD.gn index 15b2c1739e53e1b02587325eaa3f85bed104741f..caac05e9f2b9d37769401ec6b792729cb2e88842 100755 --- a/services/param/BUILD.gn +++ b/services/param/BUILD.gn @@ -11,116 +11,204 @@ # See the License for the specific language governing permissions and # limitations under the License. import("//base/startup/init_lite/begetd.gni") -import("//build/ohos.gni") -declare_args() { - param_security = "dac" -} +param_comm_sources = [ + "adapter/param_dac.c", + "manager/param_manager.c", + "manager/param_trie.c", + "manager/param_utils.c", +] -ohos_static_library("param_service") { - sources = [ - "adapter/param_libuvadp.c", +if (!defined(ohos_lite) || ohos_kernel_type == "linux") { + param_service_sources = [ "adapter/param_persistadp.c", - "manager/param_manager.c", - "manager/param_message.c", - "manager/param_trie.c", - "manager/param_utils.c", - "service/param_persist.c", - "service/param_service.c", + "linux/param_message.c", + "linux/param_msgadp.c", + "linux/param_osadp.c", + "linux/param_service.c", + "manager/param_persist.c", + ] + + param_trigger_sources = [ "trigger/trigger_checker.c", "trigger/trigger_manager.c", "trigger/trigger_processor.c", ] +} - include_dirs = [ - "include", - "adapter", - "//base/startup/init_lite/services/include/param", - "//base/startup/init_lite/services/include", - "//base/startup/init_lite/services/init/include", - "//base/startup/init_lite/services/log", - "//base/startup/init_lite/interfaces/innerkits/include", - "//base/startup/init_lite/services/loopevent/include", - "//base/security/selinux/interfaces/policycoreutils/include", - "//third_party/cJSON", +action("lite_const_param_to") { + script = "//base/startup/init_lite/scripts/param_cfg_to_code.py" + args = [ + "--source", + rebase_path( + "//base/startup/init_lite/services/etc/param/ohos_const/ohos.para"), + "--dest_dir", + rebase_path("$root_out_dir/gen/init_lite/"), + "--priority", + "0", ] + outputs = [ "$target_gen_dir/${target_name}_param_cfg_to_code.log" ] +} - defines = [ "PARAM_SUPPORT_SAVE_PERSIST" ] - if (build_selinux) { - defines += [ "WITH_SELINUX" ] - } +action("lite_ohos_param_to") { + script = "//base/startup/init_lite/scripts/param_cfg_to_code.py" + args = [ + "--source", + rebase_path("//base/startup/init_lite/services/etc/param/ohos.para"), + "--dest_dir", + rebase_path("$root_out_dir/gen/init_lite/"), + "--priority", + "0", + ] + outputs = [ "$target_gen_dir/${target_name}_param_cfg_to_code.log" ] +} + +param_include_dirs = [ + "include", + "adapter", + "linux", + "//base/startup/init_lite/services/include/param", + "//base/startup/init_lite/services/include", + "//base/startup/init_lite/services/init/include", + "//base/startup/init_lite/services/log", + "//base/startup/init_lite/interfaces/innerkits/include", + "//base/startup/init_lite/services/loopevent/include", + "//base/security/selinux/interfaces/policycoreutils/include", + "//third_party/libuv/include", + "//third_party/bounds_checking_function/include", + "//third_party/cJSON", +] - if (defined(boot_kernel_extended_cmdline)) { - defines += [ "BOOT_EXTENDED_CMDLINE=\"${boot_kernel_extended_cmdline}\"" ] +if (defined(ohos_lite)) { + static_library("param_init") { + defines = [] + deps = [] + sources = param_comm_sources + include_dirs = param_include_dirs + if (defined(boot_kernel_extended_cmdline)) { + defines += [ "BOOT_EXTENDED_CMDLINE=\"${boot_kernel_extended_cmdline}\"" ] + } + defines += [ "_GNU_SOURCE" ] + if (ohos_kernel_type == "linux") { + sources += param_service_sources + sources += param_trigger_sources + defines += [ "__LINUX__" ] + } else if (ohos_kernel_type == "liteos_a") { + sources += [ + "adapter/param_persistadp.c", + "liteos/param_osadp.c", + "liteos/param_service.c", + "manager/param_persist.c", + ] + defines += [ + "WORKSPACE_AREA_NEED_MUTEX", + "PARAM_PERSIST_SAVE_MUTEX", + "PARAMWORKSPACE_NEED_MUTEX", + "__LITEOS_A__", + "PARAM_SUPPORT_CYCLE_CHECK", + ] + deps += [ + ":lite_const_param_to", + ":lite_ohos_param_to", + ] + include_dirs += [ "$root_out_dir/gen/init_lite" ] + defines += [ "PARAM_LOAD_CFG_FROM_CODE" ] + } } - if (param_security == "selinux") { - sources += [ "adapter/param_selinux.c" ] - defines += [ "PARAM_SUPPORT_SELINUX" ] - } else { - sources += [ "adapter/param_dac.c" ] - defines += [ "PARAM_SUPPORT_DAC" ] - if (use_musl) { - defines += [ "PARAM_SUPPORT_DAC_CHECK" ] + static_library("param_client") { + sources = param_comm_sources + include_dirs = param_include_dirs + defines = [ "_GNU_SOURCE" ] + if (ohos_kernel_type == "linux") { + sources += [ + "linux/param_message.c", + "linux/param_osadp.c", + "linux/param_request.c", + ] + defines += [ "__LINUX__" ] + } else if (ohos_kernel_type == "liteos_a") { + sources += [ + "adapter/param_persistadp.c", + "liteos/param_client.c", + "liteos/param_osadp.c", + "manager/param_persist.c", + ] + defines += [ + "__LITEOS_A__", + "WORKSPACE_AREA_NEED_MUTEX", + "PARAM_PERSIST_SAVE_MUTEX", + "PARAMWORKSPACE_NEED_MUTEX", + ] + } else if (ohos_kernel_type == "liteos_m") { + sources += [ + "adapter/param_persistadp.c", + "liteos/param_client.c", + "liteos/param_osadp.c", + "manager/param_persist.c", + ] + defines += [ + "__LITEOS_M__", + "WORKSPACE_AREA_NEED_MUTEX", + "PARAM_PERSIST_SAVE_MUTEX", + "PARAMWORKSPACE_NEED_MUTEX", + "DATA_PATH=\"${config_ohos_startup_init_lite_data_path}\"", + ] + deps = [ + ":lite_const_param_to", + ":lite_ohos_param_to", + ] + include_dirs += [ "$root_out_dir/gen/init_lite" ] + defines += [ "PARAM_LOAD_CFG_FROM_CODE" ] } } +} else { + import("//build/ohos.gni") - deps = [ - "//base/startup/init_lite/services/log:init_log", - "//base/startup/init_lite/services/loopevent:loopevent", - "//base/startup/init_lite/services/utils:libinit_tools", - "//base/startup/init_lite/services/utils:libinit_utils", - "//third_party/bounds_checking_function:libsec_static", - ] - part_name = "init" - subsystem_name = "startup" -} + ohos_static_library("param_init") { + sources = param_comm_sources + sources += param_service_sources + sources += param_trigger_sources + include_dirs = param_include_dirs -ohos_shared_library("param_client") { - sources = [ - "//base/startup/init_lite/services/utils/init_utils.c", - "client/param_request.c", - "manager/param_manager.c", - "manager/param_message.c", - "manager/param_trie.c", - "manager/param_utils.c", - ] + defines = [ "_GNU_SOURCE" ] - include_dirs = [ - "include", - "//base/startup/init_lite/services/include/param", - "//base/startup/init_lite/services/include", - "//base/startup/init_lite/services/log", - "//base/startup/init_lite/interfaces/innerkits/include", - "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", - "//base/security/selinux/interfaces/policycoreutils/include", - "//base/startup/init_lite/services/loopevent/include", - ] + if (defined(boot_kernel_extended_cmdline)) { + defines += [ "BOOT_EXTENDED_CMDLINE=\"${boot_kernel_extended_cmdline}\"" ] + } - defines = [ "_GNU_SOURCE" ] + if (build_selinux) { + sources += [ "adapter/param_selinux.c" ] + defines += [ "PARAM_SUPPORT_SELINUX" ] + } - if (build_selinux) { - defines += [ "WITH_SELINUX" ] + deps = [ + "//base/startup/init_lite/services/log:init_log", + "//base/startup/init_lite/services/loopevent:loopevent", + "//base/startup/init_lite/services/utils:libinit_tools", + "//base/startup/init_lite/services/utils:libinit_utils", + ] + part_name = "init" + subsystem_name = "startup" } - if (param_security == "selinux") { - sources += [ "adapter/param_selinux.c" ] - defines += [ "PARAM_SUPPORT_SELINUX" ] - } else { - sources += [ "adapter/param_dac.c" ] - defines += [ "PARAM_SUPPORT_DAC" ] - if (use_musl) { - defines += [ "PARAM_SUPPORT_DAC_CHECK" ] - } - } + ohos_static_library("param_client") { + sources = param_comm_sources + sources += [ + "linux/param_message.c", + "linux/param_osadp.c", + "linux/param_request.c", + ] + include_dirs = param_include_dirs - deps = [ "//third_party/bounds_checking_function:libsec_static" ] - if (is_standard_system) { - deps += [ "//base/startup/init_lite/services/log:agent_log" ] + defines = [ "_GNU_SOURCE" ] + if (build_selinux) { + sources += [ "adapter/param_selinux.c" ] + defines += [ + "PARAM_SUPPORT_SELINUX", + "PARAMWORKSPACE_NEED_MUTEX", + ] + } + part_name = "init" } - install_images = [ - "system", - "updater", - ] - part_name = "init" } diff --git a/services/param/adapter/param_dac.c b/services/param/adapter/param_dac.c index b2f3dd9cd4a38d4f4e3ecc77c23063f2bfc486f9..937e51bf3f92bc905b0969d39c6513e8261e647f 100644 --- a/services/param/adapter/param_dac.c +++ b/services/param/adapter/param_dac.c @@ -19,12 +19,15 @@ #include #include "init_utils.h" +#include "param_manager.h" #include "param_security.h" +#include "param_trie.h" #include "param_utils.h" -#define OCT_BASE 8 -static ParamSecurityLabel g_localSecurityLabel = {}; +#define USER_BUFFER_LEN 64 +#define GROUP_FORMAT "ohos.group" +#define OCT_BASE 8 static void GetUserIdByName(uid_t *uid, const char *name, uint32_t nameLen) { *uid = -1; @@ -73,18 +76,20 @@ static int GetParamDacData(ParamDacData *dacData, const char *value) return 0; } -static int InitLocalSecurityLabel(ParamSecurityLabel **security, int isInit) +static int InitLocalSecurityLabel(ParamSecurityLabel *security, int isInit) { UNUSED(isInit); - PARAM_LOGV("InitLocalSecurityLabel uid:%d gid:%d euid: %d egid: %d ", getuid(), getgid(), geteuid(), getegid()); - g_localSecurityLabel.cred.pid = getpid(); - g_localSecurityLabel.cred.uid = geteuid(); - g_localSecurityLabel.cred.gid = getegid(); - *security = &g_localSecurityLabel; + PARAM_CHECK(security != NULL, return -1, "Invalid security"); + security->cred.pid = getpid(); +#if defined __LITEOS_A__ || defined __LITEOS_M__ + security->cred.uid = getuid(); + security->cred.gid = 0; + security->flags[PARAM_SECURITY_DAC] |= LABEL_CHECK_IN_ALL_PROCESS; +#else + security->cred.uid = geteuid(); + security->cred.gid = getegid(); // support check write permission in client - (*security)->flags |= LABEL_CHECK_FOR_ALL_PROCESS; -#ifdef WITH_SELINUX - (*security)->flags = 0; + security->flags[PARAM_SECURITY_DAC] |= LABEL_CHECK_IN_ALL_PROCESS; #endif return 0; } @@ -94,59 +99,25 @@ static int FreeLocalSecurityLabel(ParamSecurityLabel *srcLabel) return 0; } -static int EncodeSecurityLabel(const ParamSecurityLabel *srcLabel, char *buffer, uint32_t *bufferSize) -{ - PARAM_CHECK(bufferSize != NULL, return -1, "Invalid param"); - if (buffer == NULL) { - *bufferSize = sizeof(ParamSecurityLabel); - return 0; - } - PARAM_CHECK(*bufferSize >= sizeof(ParamSecurityLabel), return -1, "Invalid buffersize %u", *bufferSize); - *bufferSize = sizeof(ParamSecurityLabel); - return memcpy_s(buffer, *bufferSize, srcLabel, sizeof(ParamSecurityLabel)); -} - -static int DecodeSecurityLabel(ParamSecurityLabel **srcLabel, const char *buffer, uint32_t bufferSize) -{ - PARAM_CHECK(bufferSize >= sizeof(ParamSecurityLabel), return -1, "Invalid buffersize %u", bufferSize); - PARAM_CHECK(srcLabel != NULL && buffer != NULL, return -1, "Invalid param"); - *srcLabel = (ParamSecurityLabel *)buffer; - return 0; -} - -typedef struct { - SecurityLabelFunc label; - void *context; -} LoadContext; - -static int LoadOneParam_ (const uint32_t *context, const char *name, const char *value) +static int LoadOneParam_(const uint32_t *context, const char *name, const char *value) { - LoadContext *loadContext = (LoadContext *)context; ParamAuditData auditData = {0}; auditData.name = name; -#ifdef STARTUP_INIT_TEST - auditData.label = value; -#endif int ret = GetParamDacData(&auditData.dacData, value); PARAM_CHECK(ret == 0, return -1, "Failed to get param info %d %s", ret, name); - ret = loadContext->label(&auditData, loadContext->context); - PARAM_CHECK(ret == 0, return -1, "Failed to write param info %d \"%s\"", ret, name); + AddSecurityLabel(&auditData); return 0; } -static int LoadParamLabels(const char *fileName, SecurityLabelFunc label, void *context) +static int LoadParamLabels(const char *fileName) { - LoadContext loadContext = { - label, context - }; uint32_t infoCount = 0; FILE *fp = fopen(fileName, "r"); - const uint32_t buffSize = PARAM_NAME_LEN_MAX + PARAM_CONST_VALUE_LEN_MAX + 10; // 10 size - char *buff = (char *)calloc(1, buffSize); + const uint32_t buffSize = PARAM_NAME_LEN_MAX + PARAM_CONST_VALUE_LEN_MAX + 10; // 10 size + char *buff = (char *)calloc(1, buffSize); while (fp != NULL && buff != NULL && fgets(buff, buffSize, fp) != NULL) { buff[buffSize - 1] = '\0'; - - int ret = SpliteString(buff, NULL, 0, LoadOneParam_, (uint32_t *)&loadContext); + int ret = SpliteString(buff, NULL, 0, LoadOneParam_, NULL); if (ret != 0) { PARAM_LOGE("Failed to splite string %s fileName %s", buff, fileName); continue; @@ -165,20 +136,19 @@ static int LoadParamLabels(const char *fileName, SecurityLabelFunc label, void * static int ProcessParamFile(const char *fileName, void *context) { - LabelFuncContext *cxt = (LabelFuncContext *)context; - return LoadParamLabels(fileName, cxt->label, cxt->context); + UNUSED(context); + return LoadParamLabels(fileName); } -static int GetParamSecurityLabel(SecurityLabelFunc label, const char *path, void *context) +static int DacGetParamSecurityLabel(const char *path) { - PARAM_CHECK(label != NULL && path != NULL, return -1, "Invalid param"); + PARAM_CHECK(path != NULL, return -1, "Invalid param"); struct stat st; - LabelFuncContext cxt = {label, context}; if ((stat(path, &st) == 0) && !S_ISDIR(st.st_mode)) { - return ProcessParamFile(path, &cxt); + return ProcessParamFile(path, NULL); } - PARAM_LOGV("GetParamSecurityLabel %s ", path); - return ReadFileInDir(path, ".para.dac", ProcessParamFile, &cxt); + PARAM_LOGV("DacGetParamSecurityLabel %s ", path); + return ReadFileInDir(path, ".para.dac", ProcessParamFile, NULL); } static int CheckFilePermission(const ParamSecurityLabel *localLabel, const char *fileName, int flags) @@ -188,99 +158,116 @@ static int CheckFilePermission(const ParamSecurityLabel *localLabel, const char return 0; } -#ifdef PARAM_SUPPORT_DAC_CHECK -static int CheckUserInGroup(gid_t groupId, uid_t uid) +static int CheckUserInGroup(WorkSpace *space, gid_t groupId, uid_t uid) { - static char buffer[255] = {0}; // 255 max size - static char userBuff[255] = {0}; // 255 max size - struct group *grpResult = NULL; - struct group grp = {}; - int ret = getgrgid_r(groupId, &grp, buffer, sizeof(buffer), &grpResult); - if (ret != 0 || grpResult == NULL || grpResult->gr_name == NULL) { - return -1; - } - struct passwd data = {}; - struct passwd *userResult = NULL; - ret = getpwuid_r(uid, &data, userBuff, sizeof(userBuff), &userResult); - if (ret != 0 || userResult == NULL || userResult->pw_name == NULL) { - return -1; - } - - PARAM_LOGV("CheckUserInGroup pw_name %s ", userResult->pw_name); - if (strcmp(grpResult->gr_name, userResult->pw_name) == 0) { + static char buffer[USER_BUFFER_LEN] = {0}; + uint32_t labelIndex = 0; + int ret = sprintf_s(buffer, sizeof(buffer) - 1, "%s.%d.%d", GROUP_FORMAT, groupId, uid); + PARAM_CHECK(ret >= 0, return -1, "Failed to format name for %s.%d.%d", GROUP_FORMAT, groupId, uid); + (void)FindTrieNode(space, buffer, strlen(buffer), &labelIndex); + ParamSecruityNode *node = (ParamSecruityNode *)GetTrieNode(space, labelIndex); + PARAM_CHECK(node != NULL, return DAC_RESULT_FORBIDED, "Can not get security label %d", labelIndex); + PARAM_LOGV("CheckUserInGroup %s groupid %d uid %d", buffer, groupId, uid); + if (node->gid == groupId && node->uid == uid) { return 0; } - int index = 0; - while (grpResult->gr_mem[index]) { - PARAM_LOGV("CheckUserInGroup %s ", grpResult->gr_mem[index]); - if (strcmp(grpResult->gr_mem[index], userResult->pw_name) == 0) { - return 0; - } - index++; - } return -1; } -#endif -static int CheckParamPermission(const ParamSecurityLabel *srcLabel, const ParamAuditData *auditData, uint32_t mode) +static int DacCheckParamPermission(const ParamSecurityLabel *srcLabel, const char *name, uint32_t mode) { -#ifndef PARAM_SUPPORT_DAC_CHECK +#if defined(__LITEOS_A__) + uid_t uid = getuid(); + return uid <= SYS_UID_INDEX ? DAC_RESULT_PERMISSION : DAC_RESULT_FORBIDED; +#endif +#if defined(__LITEOS_M__) return DAC_RESULT_PERMISSION; -#else +#endif + int ret = DAC_RESULT_FORBIDED; - PARAM_CHECK(srcLabel != NULL && auditData != NULL && auditData->name != NULL, return ret, "Invalid param"); - PARAM_CHECK((mode & (DAC_READ | DAC_WRITE | DAC_WATCH)) != 0, return ret, "Invalid mode %x", mode); - if (srcLabel->cred.uid == 0) { - return DAC_RESULT_PERMISSION; - } + uint32_t labelIndex = 0; + // get dac label + WorkSpace *space = GetWorkSpace(WORKSPACE_NAME_DAC); + PARAM_CHECK(space != NULL, return DAC_RESULT_FORBIDED, "Failed to get dac space %s", name); + (void)FindTrieNode(space, name, strlen(name), &labelIndex); + ParamSecruityNode *node = (ParamSecruityNode *)GetTrieNode(space, labelIndex); + PARAM_CHECK(node != NULL, return DAC_RESULT_FORBIDED, "Can not get security label %d", labelIndex); /** - * DAC group 实现的label的定义 + * DAC group * user:group:read|write|watch */ uint32_t localMode; - if (srcLabel->cred.uid == auditData->dacData.uid) { + if (srcLabel->cred.uid == node->uid) { localMode = mode & (DAC_READ | DAC_WRITE | DAC_WATCH); - } else if (srcLabel->cred.gid == auditData->dacData.gid) { + } else if (srcLabel->cred.gid == node->gid) { localMode = (mode & (DAC_READ | DAC_WRITE | DAC_WATCH)) >> DAC_GROUP_START; - } else if (CheckUserInGroup(auditData->dacData.gid, srcLabel->cred.uid) == 0) { // user in group + } else if (CheckUserInGroup(space, node->gid, srcLabel->cred.uid) == 0) { // user in group localMode = (mode & (DAC_READ | DAC_WRITE | DAC_WATCH)) >> DAC_GROUP_START; } else { localMode = (mode & (DAC_READ | DAC_WRITE | DAC_WATCH)) >> DAC_OTHER_START; } - if ((auditData->dacData.mode & localMode) != 0) { + if ((node->mode & localMode) != 0) { ret = DAC_RESULT_PERMISSION; } - PARAM_LOGI("Src label gid:%d uid:%d ", srcLabel->cred.gid, srcLabel->cred.uid); - PARAM_LOGI("local label gid:%d uid:%d mode %o", - auditData->dacData.gid, auditData->dacData.uid, auditData->dacData.mode); - PARAM_LOGI("%s check %o localMode %o ret %d", auditData->name, mode, localMode, ret); + PARAM_LOGV("Param '%s' label gid:%d uid:%d mode 0%o", name, srcLabel->cred.gid, srcLabel->cred.uid, localMode); + PARAM_LOGV("Cfg label %d gid:%d uid:%d mode 0%o result %d", labelIndex, node->gid, node->uid, node->mode, ret); return ret; -#endif } -PARAM_STATIC int RegisterSecurityDacOps(ParamSecurityOps *ops, int isInit) +int RegisterSecurityDacOps(ParamSecurityOps *ops, int isInit) { PARAM_CHECK(ops != NULL, return -1, "Invalid param"); PARAM_LOGV("RegisterSecurityDacOps %d", isInit); + int ret = strcpy_s(ops->name, sizeof(ops->name), "dac"); ops->securityGetLabel = NULL; - ops->securityDecodeLabel = NULL; - ops->securityEncodeLabel = NULL; ops->securityInitLabel = InitLocalSecurityLabel; ops->securityCheckFilePermission = CheckFilePermission; - ops->securityCheckParamPermission = CheckParamPermission; + ops->securityCheckParamPermission = DacCheckParamPermission; ops->securityFreeLabel = FreeLocalSecurityLabel; if (isInit) { - ops->securityGetLabel = GetParamSecurityLabel; - ops->securityDecodeLabel = DecodeSecurityLabel; - } else { - ops->securityEncodeLabel = EncodeSecurityLabel; + ops->securityGetLabel = DacGetParamSecurityLabel; } - return 0; + return ret; } -#ifdef PARAM_SUPPORT_DAC -int RegisterSecurityOps(ParamSecurityOps *ops, int isInit) +static void AddGroupUser(int uid, int gid, int mode, const char *format) { - return RegisterSecurityDacOps(ops, isInit); + ParamAuditData auditData = {0}; + char buffer[USER_BUFFER_LEN] = {0}; + int ret = sprintf_s(buffer, sizeof(buffer) - 1, "%s.%d.%d", format, gid, uid); + PARAM_CHECK(ret >= 0, return, "Failed to format name for %s.%d.%d", format, gid, uid); + auditData.name = buffer; + auditData.dacData.uid = uid; + auditData.dacData.gid = gid; + auditData.dacData.mode = mode; + AddSecurityLabel(&auditData); } + +void LoadGroupUser(void) +{ +#if !(defined __LITEOS_A__ || defined __LITEOS_M__) + PARAM_LOGV("LoadGroupUser "); + uid_t uid = 0; + struct group *data = NULL; + while ((data = getgrent()) != NULL) { + if (data->gr_name == NULL || data->gr_mem == NULL) { + continue; + } + if (data->gr_mem[0] == NULL) { // default user in group + GetUserIdByName(&uid, data->gr_name, strlen(data->gr_name)); + PARAM_LOGV("LoadGroupUser %s gid %d uid %d", data->gr_name, data->gr_gid, uid); + AddGroupUser(uid, data->gr_gid, 0550, GROUP_FORMAT); // 0550 read and watch + continue; + } + int index = 0; + while (data->gr_mem[index]) { // user in this group + GetUserIdByName(&uid, data->gr_mem[index], strlen(data->gr_mem[index])); + PARAM_LOGV("LoadGroupUser %s gid %d uid %d user %s", data->gr_name, data->gr_gid, uid, data->gr_mem[index]); + AddGroupUser(uid, data->gr_gid, 0550, "ohos.group"); // 0550 read and watch + index++; + } + } + PARAM_LOGV("LoadGroupUser getgrent fail errnor %d ", errno); + endgrent(); #endif +} \ No newline at end of file diff --git a/services/param/adapter/param_persistadp.c b/services/param/adapter/param_persistadp.c index dede06c3793de86fa915d1ebc68680824de7742d..a054783ddb1bbd1751289489e06882b7468e1b5a 100644 --- a/services/param/adapter/param_persistadp.c +++ b/services/param/adapter/param_persistadp.c @@ -19,6 +19,7 @@ #include #include "init_utils.h" +#include "param_manager.h" #include "param_persist.h" #include "param_utils.h" @@ -27,49 +28,77 @@ typedef struct { PersistParamGetPtr persistParamGet; } PersistAdpContext; -static int LoadPersistParam(PersistParamGetPtr persistParamGet, void *context) +// for linux, no mutex +static ParamMutex g_saveMutex = {}; + +static int LoadOnePersistParam_(const uint32_t *context, const char *name, const char *value) +{ + uint32_t dataIndex = 0; + int ret = WriteParam(name, value, &dataIndex, 0); + PARAM_CHECK(ret == 0, return ret, "Failed to write param %d name:%s %s", ret, name, value); + return 0; +} + +static int LoadPersistParam() { CheckAndCreateDir(PARAM_PERSIST_SAVE_PATH); int updaterMode = InUpdaterMode(); char *tmpPath = (updaterMode == 0) ? PARAM_PERSIST_SAVE_TMP_PATH : "/param/tmp_persist_parameters"; FILE *fp = fopen(tmpPath, "r"); if (fp == NULL) { - fp = fopen((updaterMode == 0) ? PARAM_PERSIST_SAVE_PATH : "/param/persist_parameters", "r"); + tmpPath = (updaterMode == 0) ? PARAM_PERSIST_SAVE_PATH : "/param/persist_parameters"; + fp = fopen(tmpPath, "r"); PARAM_LOGI("LoadPersistParam open file %s", PARAM_PERSIST_SAVE_PATH); } PARAM_CHECK(fp != NULL, return -1, "No valid persist parameter file %s", PARAM_PERSIST_SAVE_PATH); - char *buff = (char *)calloc(1, PARAM_BUFFER_SIZE); - SubStringInfo *info = calloc(1, sizeof(SubStringInfo) * (SUBSTR_INFO_VALUE + 1)); - while (info != NULL && buff != NULL && fgets(buff, PARAM_BUFFER_SIZE, fp) != NULL) { - buff[PARAM_BUFFER_SIZE - 1] = '\0'; - int subStrNumber = GetSubStringInfo(buff, strlen(buff), '=', info, SUBSTR_INFO_VALUE + 1); - if (subStrNumber <= SUBSTR_INFO_VALUE) { - continue; - } - int ret = persistParamGet(info[0].value, info[1].value, context); - PARAM_CHECK(ret == 0, continue, "Failed to set param %d %s", ret, buff); - } - if (info != NULL) { - free(info); + const int buffSize = PARAM_NAME_LEN_MAX + PARAM_CONST_VALUE_LEN_MAX + 10; // 10 max len + char *buffer = malloc(buffSize); + if (buffer == NULL) { + (void)fclose(fp); + return -1; } - if (buff != NULL) { - free(buff); + uint32_t paramNum = 0; + while (fgets(buffer, buffSize, fp) != NULL) { + buffer[buffSize - 1] = '\0'; + int ret = SpliteString(buffer, NULL, 0, LoadOnePersistParam_, NULL); + PARAM_CHECK(ret == 0, continue, "Failed to set param %d %s", ret, buffer); + paramNum++; } (void)fclose(fp); + free(buffer); + PARAM_LOGI("LoadPersistParam from file %s paramNum %d", tmpPath, paramNum); return 0; } static int SavePersistParam(const char *name, const char *value) { - PARAM_LOGV("SavePersistParam %s=%s", name, value); - return 0; + ParamMutexPend(&g_saveMutex); + char *path = (InUpdaterMode() == 0) ? PARAM_PERSIST_SAVE_PATH : "/param/persist_parameters"; + FILE *fp = fopen(path, "a+"); + int ret = -1; + if (fp != NULL) { + ret = fprintf(fp, "%s=%s\n", name, value); + (void)fclose(fp); + } + ParamMutexPost(&g_saveMutex); + if (ret <= 0) { + PARAM_LOGE("Failed to save persist param %s", name); + } + return ret; } static int BatchSavePersistParamBegin(PERSIST_SAVE_HANDLE *handle) { - FILE *fp = fopen((InUpdaterMode() == 0) ? PARAM_PERSIST_SAVE_TMP_PATH : "/param/tmp_persist_parameters", "w"); - PARAM_CHECK(fp != NULL, return -1, "Open file %s fail error %d", PARAM_PERSIST_SAVE_TMP_PATH, errno); + ParamMutexPend(&g_saveMutex); + char *path = (InUpdaterMode() == 0) ? PARAM_PERSIST_SAVE_TMP_PATH : "/param/tmp_persist_parameters"; + unlink(path); + FILE *fp = fopen(path, "w"); + if (fp == NULL) { + ParamMutexPost(&g_saveMutex); + PARAM_LOGE("Open file %s fail error %d", path, errno); + return -1; + } *handle = (PERSIST_SAVE_HANDLE)fp; return 0; } @@ -95,11 +124,13 @@ static void BatchSavePersistParamEnd(PERSIST_SAVE_HANDLE handle) unlink("/param/persist_parameters"); ret = rename("/param/tmp_persist_parameters", "/param/persist_parameters"); } + ParamMutexPost(&g_saveMutex); PARAM_CHECK(ret == 0, return, "BatchSavePersistParamEnd %s fail error %d", PARAM_PERSIST_SAVE_TMP_PATH, errno); } int RegisterPersistParamOps(PersistParamOps *ops) { + ParamMutexCeate(&g_saveMutex); PARAM_CHECK(ops != NULL, return -1, "Invalid ops"); ops->save = SavePersistParam; ops->load = LoadPersistParam; diff --git a/services/param/adapter/param_selinux.c b/services/param/adapter/param_selinux.c index 6d55167572f10796910a7e65dc8f91e027f3bf1b..b89d159896e5fc7e85871c950f9a7694cd0a50fb 100644 --- a/services/param/adapter/param_selinux.c +++ b/services/param/adapter/param_selinux.c @@ -12,29 +12,63 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +#include #include +#include #include "init_utils.h" +#include "param_manager.h" #include "param_security.h" #include "param_utils.h" +#ifdef PARAM_SUPPORT_SELINUX +#include "selinux_parameter.h" +#endif -#define SELINUX_LABEL_LEN 128 -typedef struct SELinuxSecurityLabel { - ParamSecurityLabel securityLabel; - char label[SELINUX_LABEL_LEN]; -} SELinuxSecurityLabel; - -static SELinuxSecurityLabel g_localSecurityLabel = {}; - -static int InitLocalSecurityLabel(ParamSecurityLabel **security, int isInit) +static SelinuxSpace g_selinuxSpace = {0}; +static int InitLocalSecurityLabel(ParamSecurityLabel *security, int isInit) { UNUSED(isInit); - PARAM_LOGI("TestDacGetLabel uid:%d gid:%d euid: %d egid: %d ", getuid(), getgid(), geteuid(), getegid()); - g_localSecurityLabel.securityLabel.cred.pid = getpid(); - g_localSecurityLabel.securityLabel.cred.uid = geteuid(); - g_localSecurityLabel.securityLabel.cred.gid = getegid(); - *security = &g_localSecurityLabel.securityLabel; + PARAM_CHECK(security != NULL, return -1, "Invalid security"); + security->cred.pid = getpid(); + security->cred.uid = geteuid(); + security->cred.gid = getegid(); + security->flags[PARAM_SECURITY_SELINUX] = 0; +#if !(defined STARTUP_INIT_TEST || defined LOCAL_TEST) + if (g_selinuxSpace.selinuxHandle == NULL) { + g_selinuxSpace.selinuxHandle = dlopen("/system/lib/libparaperm_checker.z.so", RTLD_LAZY); + PARAM_CHECK(g_selinuxSpace.selinuxHandle != NULL, + return -1, "Failed to dlsym selinuxHandle, %s", dlerror()); + } + void *handle = g_selinuxSpace.selinuxHandle; + if (g_selinuxSpace.setSelinuxLogCallback == NULL) { + g_selinuxSpace.setSelinuxLogCallback = (void (*)())dlsym(handle, "SetSelinuxLogCallback"); + PARAM_CHECK(g_selinuxSpace.setSelinuxLogCallback != NULL, + return -1, "Failed to dlsym setSelinuxLogCallback %s", dlerror()); + } + if (g_selinuxSpace.setParamCheck == NULL) { + g_selinuxSpace.setParamCheck = (SelinuxSetParamCheck)dlsym(handle, "SetParamCheck"); + PARAM_CHECK(g_selinuxSpace.setParamCheck != NULL, return -1, "Failed to dlsym setParamCheck %s", dlerror()); + } + if (g_selinuxSpace.getParamList == NULL) { + g_selinuxSpace.getParamList = (ParamContextsList *(*)()) dlsym(handle, "GetParamList"); + PARAM_CHECK(g_selinuxSpace.getParamList != NULL, return -1, "Failed to dlsym getParamList %s", dlerror()); + } + if (g_selinuxSpace.getParamLabel == NULL) { + g_selinuxSpace.getParamLabel = (const char * (*)(const char *))dlsym(handle, "GetParamLabel"); + PARAM_CHECK(g_selinuxSpace.getParamLabel != NULL, return -1, "Failed to dlsym getParamLabel %s", dlerror()); + } + if (g_selinuxSpace.readParamCheck == NULL) { + g_selinuxSpace.readParamCheck = (int (*)(const char *))dlsym(handle, "ReadParamCheck"); + PARAM_CHECK(g_selinuxSpace.readParamCheck != NULL, return -1, "Failed to dlsym readParamCheck %s", dlerror()); + } + if (g_selinuxSpace.destroyParamList == NULL) { + g_selinuxSpace.destroyParamList = + (void (*)(ParamContextsList **))dlsym(handle, "DestroyParamList"); + PARAM_CHECK(g_selinuxSpace.destroyParamList != NULL, + return -1, "Failed to dlsym destroyParamList %s", dlerror()); + } +#endif + PARAM_LOGV("Load sulinux lib success."); return 0; } @@ -43,76 +77,31 @@ static int FreeLocalSecurityLabel(ParamSecurityLabel *srcLabel) return 0; } -static int EncodeSecurityLabel(const ParamSecurityLabel *srcLabel, char *buffer, uint32_t *bufferSize) -{ - PARAM_CHECK(bufferSize != NULL, return -1, "Invalid param"); - if (buffer == NULL) { - *bufferSize = sizeof(SELinuxSecurityLabel); - return 0; - } - PARAM_CHECK(*bufferSize >= sizeof(SELinuxSecurityLabel), return -1, "Invalid buffersize %u", *bufferSize); - *bufferSize = sizeof(SELinuxSecurityLabel); - return memcpy_s(buffer, *bufferSize, srcLabel, sizeof(SELinuxSecurityLabel)); -} - -static int DecodeSecurityLabel(ParamSecurityLabel **srcLabel, const char *buffer, uint32_t bufferSize) -{ - PARAM_CHECK(bufferSize >= sizeof(SELinuxSecurityLabel), return -1, "Invalid buffersize %u", bufferSize); - PARAM_CHECK(srcLabel != NULL && buffer != NULL, return -1, "Invalid param"); - *srcLabel = &((SELinuxSecurityLabel *)buffer)->securityLabel; - return 0; -} - -static int LoadParamLabels(const char *fileName, SecurityLabelFunc label, void *context) +static int SelinuxGetParamSecurityLabel(const char *path) { - FILE *fp = fopen(fileName, "r"); - PARAM_CHECK(fp != NULL, return -1, "Open file %s fail", fileName); - - SubStringInfo *info = calloc(1, sizeof(SubStringInfo) * (SUBSTR_INFO_DAC + 1)); - char *buff = (char *)calloc(1, PARAM_BUFFER_SIZE); - int infoCount = 0; - ParamAuditData auditData = {0}; - while (info != NULL && buff != NULL && fgets(buff, PARAM_BUFFER_SIZE, fp) != NULL) { - buff[PARAM_BUFFER_SIZE - 1] = '\0'; - int subStrNumber = GetSubStringInfo(buff, strlen(buff), ' ', info, SUBSTR_INFO_DAC + 1); - if (subStrNumber <= SUBSTR_INFO_DAC) { + UNUSED(path); + PARAM_CHECK(g_selinuxSpace.getParamList != NULL, return DAC_RESULT_FORBIDED, "Invalid getParamList"); + ParamContextsList *head = g_selinuxSpace.getParamList(); + ParamContextsList *node = head; + int count = 0; + while (node != NULL) { + PARAM_LOGV("GetParamSecurityLabel name %s content %s", node->info.paraName, node->info.paraContext); + if (node->info.paraContext == NULL || node->info.paraName == NULL) { + node = node->next; continue; } - auditData.name = info[SUBSTR_INFO_NAME].value; - auditData.label = info[SUBSTR_INFO_LABEL].value; - int ret = label(&auditData, context); - PARAM_CHECK(ret == 0, continue, "Failed to write param info %d %s", ret, buff); - infoCount++; - } - if (buff != NULL) { - free(buff); + int ret = AddWorkSpace(node->info.paraContext, 0, PARAM_WORKSPACE_DEF); + PARAM_CHECK(ret == 0, continue, + "Failed to add selinx workspace %s %s", node->info.paraName, node->info.paraContext); + node = node->next; + count++; } - if (info != NULL) { - free(info); - } - (void)fclose(fp); - PARAM_LOGI("Load parameter info %d success %s", infoCount, fileName); - return 0; -} + g_selinuxSpace.destroyParamList(&head); + int ret = AddWorkSpace(WORKSPACE_NAME_DEF_SELINUX, 0, PARAM_WORKSPACE_MAX); + PARAM_CHECK(ret == 0, return -1, + "Failed to add selinx workspace %s %s", node->info.paraName, node->info.paraContext); -static int ProcessParamFile(const char *fileName, void *context) -{ - LabelFuncContext *cxt = (LabelFuncContext *)context; - return LoadParamLabels(fileName, cxt->label, cxt->context); -} - -static int GetParamSecurityLabel(SecurityLabelFunc label, const char *path, void *context) -{ - PARAM_CHECK(label != NULL, return -1, "Invalid param"); - int ret; - struct stat st; - LabelFuncContext cxt = { label, context }; - if ((stat(path, &st) == 0) && !S_ISDIR(st.st_mode)) { - ret = ProcessParamFile(path, &cxt); - } else { - ret = ReadFileInDir(path, ".para.selinux", ProcessParamFile, &cxt); - } - return ret; + return 0; } static int CheckFilePermission(const ParamSecurityLabel *localLabel, const char *fileName, int flags) @@ -122,34 +111,64 @@ static int CheckFilePermission(const ParamSecurityLabel *localLabel, const char return 0; } -static int CheckParamPermission(const ParamSecurityLabel *srcLabel, const ParamAuditData *auditData, uint32_t mode) +static int SelinuxCheckParamPermission(const ParamSecurityLabel *srcLabel, const char *name, uint32_t mode) { - PARAM_LOGI("CheckParamPermission "); - PARAM_CHECK(srcLabel != NULL && auditData != NULL && auditData->name != NULL, return -1, "Invalid param"); - return 0; + int ret = DAC_RESULT_FORBIDED; + PARAM_CHECK(g_selinuxSpace.setSelinuxLogCallback != NULL, return ret, "Invalid setSelinuxLogCallback"); + PARAM_CHECK(g_selinuxSpace.setParamCheck != NULL, return ret, "Invalid setParamCheck"); + PARAM_CHECK(g_selinuxSpace.readParamCheck != NULL, return ret, "Invalid readParamCheck"); + // log + g_selinuxSpace.setSelinuxLogCallback(); + + // check + struct ucred uc; + uc.pid = srcLabel->cred.pid; + uc.uid = srcLabel->cred.uid; + uc.gid = srcLabel->cred.gid; + if (mode == DAC_WRITE) { + ret = g_selinuxSpace.setParamCheck(name, &uc); + } else { + ret = g_selinuxSpace.readParamCheck(name); + } + if (ret != 0) { + PARAM_LOGI("Selinux check name %s pid %d uid %d %d result %d", name, uc.pid, uc.uid, uc.gid, ret); + } + return ret; } -PARAM_STATIC int RegisterSecuritySelinuxOps(ParamSecurityOps *ops, int isInit) +int RegisterSecuritySelinuxOps(ParamSecurityOps *ops, int isInit) { PARAM_CHECK(ops != NULL, return -1, "Invalid param"); + int ret = strcpy_s(ops->name, sizeof(ops->name), "selinux"); ops->securityGetLabel = NULL; - ops->securityDecodeLabel = NULL; - ops->securityEncodeLabel = NULL; ops->securityInitLabel = InitLocalSecurityLabel; ops->securityCheckFilePermission = CheckFilePermission; - ops->securityCheckParamPermission = CheckParamPermission; + ops->securityCheckParamPermission = SelinuxCheckParamPermission; ops->securityFreeLabel = FreeLocalSecurityLabel; if (isInit) { - ops->securityGetLabel = GetParamSecurityLabel; - ops->securityDecodeLabel = DecodeSecurityLabel; - } else { - ops->securityEncodeLabel = EncodeSecurityLabel; + ops->securityGetLabel = SelinuxGetParamSecurityLabel; } - return 0; + return ret; } -#ifdef PARAM_SUPPORT_SELINUX -int RegisterSecurityOps(ParamSecurityOps *ops, int isInit) + +const char *GetSelinuxContent(const char *name) +{ + PARAM_CHECK(g_selinuxSpace.getParamLabel != NULL, return NULL, "Invalid getParamLabel"); + PARAM_CHECK(g_selinuxSpace.setSelinuxLogCallback != NULL, return NULL, "Invalid setSelinuxLogCallback"); + // log + g_selinuxSpace.setSelinuxLogCallback(); + + return g_selinuxSpace.getParamLabel(name); +} + +#if defined STARTUP_INIT_TEST || defined LOCAL_TEST +void SetSelinuxOps(const SelinuxSpace *space) { - return RegisterSecuritySelinuxOps(ops, isInit); + g_selinuxSpace.setSelinuxLogCallback = space->setSelinuxLogCallback; + g_selinuxSpace.setParamCheck = space->setParamCheck; + g_selinuxSpace.getParamLabel = space->getParamLabel; + g_selinuxSpace.readParamCheck = space->readParamCheck; + g_selinuxSpace.getParamList = space->getParamList; + g_selinuxSpace.destroyParamList = space->destroyParamList; } #endif \ No newline at end of file diff --git a/services/param/client/param_request.c b/services/param/client/param_request.c deleted file mode 100644 index 9a9a8d97a24615a118ae675372ce0774b08cbbe1..0000000000000000000000000000000000000000 --- a/services/param/client/param_request.c +++ /dev/null @@ -1,394 +0,0 @@ -/* - * Copyright (c) 2021 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 "param_request.h" - -#include -#include -#include -#include -#include -#include - -#include "init_utils.h" -#include "param_manager.h" -#include "param_message.h" -#include "param_security.h" - -#define INVALID_SOCKET (-1) -#define INIT_PROCESS_PID 1 - -static const uint32_t RECV_BUFFER_MAX = 5 * 1024; - -static atomic_uint g_requestId = ATOMIC_VAR_INIT(1); -static ClientWorkSpace g_clientSpace = { {}, -1, {} }; - -__attribute__((constructor)) static void ClientInit(void); -__attribute__((destructor)) static void ClientDeinit(void); - -static int InitParamClient(void) -{ - if (getpid() == INIT_PROCESS_PID) { - PARAM_LOGI("Init process, do not init client"); - return 0; - } - if (PARAM_TEST_FLAG(g_clientSpace.paramSpace.flags, WORKSPACE_FLAGS_INIT)) { - return 0; - } - PARAM_LOGV("InitParamClient"); - pthread_mutex_init(&g_clientSpace.mutex, NULL); - g_clientSpace.clientFd = INVALID_SOCKET; - return InitParamWorkSpace(&g_clientSpace.paramSpace, 1); -} - -void ClientInit(void) -{ - PARAM_LOGV("ClientInit"); - (void)InitParamClient(); -} - -void ClientDeinit(void) -{ - CloseParamWorkSpace(&g_clientSpace.paramSpace); -} - -static ParamSecurityOps *GetClientParamSecurityOps(void) -{ - return &g_clientSpace.paramSpace.paramSecurityOps; -} - -static int FillLabelContent(const ParamMessage *request, uint32_t *start, uint32_t length) -{ - uint32_t bufferSize = request->msgSize - sizeof(ParamMessage); - uint32_t offset = *start; - PARAM_CHECK((offset + sizeof(ParamMsgContent) + length) <= bufferSize, - return -1, "Invalid msgSize %u offset %u", request->msgSize, offset); - ParamMsgContent *content = (ParamMsgContent *)(request->data + offset); - content->type = PARAM_LABEL; - content->contentSize = 0; - ParamSecurityOps *ops = GetClientParamSecurityOps(); - if (length != 0 && ops != NULL && ops->securityEncodeLabel != NULL) { - int ret = ops->securityEncodeLabel(g_clientSpace.paramSpace.securityLabel, content->content, &length); - PARAM_CHECK(ret == 0, return -1, "Failed to get label length"); - content->contentSize = length; - } - offset += sizeof(ParamMsgContent) + PARAM_ALIGN(content->contentSize); - *start = offset; - return 0; -} - -static int ProcessRecvMsg(const ParamMessage *recvMsg) -{ - PARAM_LOGV("ProcessRecvMsg type: %u msgId: %u name %s", recvMsg->type, recvMsg->id.msgId, recvMsg->key); - int result = PARAM_CODE_INVALID_PARAM; - switch (recvMsg->type) { - case MSG_SET_PARAM: - result = ((ParamResponseMessage *)recvMsg)->result; - break; - case MSG_NOTIFY_PARAM: { - uint32_t offset = 0; - ParamMsgContent *valueContent = GetNextContent(recvMsg, &offset); - PARAM_CHECK(valueContent != NULL, return PARAM_CODE_TIMEOUT, "Invalid msg"); - result = 0; - break; - } - default: - break; - } - return result; -} - -static int StartRequest(int *fd, ParamMessage *request, int timeout) -{ - int ret = 0; - struct timeval time; -#ifndef STARTUP_INIT_TEST - time.tv_sec = timeout; -#else - time.tv_sec = 1; -#endif - time.tv_usec = 0; - do { - int clientFd = *fd; - if (clientFd == INVALID_SOCKET) { - clientFd = socket(AF_UNIX, SOCK_STREAM, 0); - PARAM_CHECK(clientFd >= 0, return PARAM_CODE_FAIL_CONNECT, "Failed to create socket"); - ret = ConntectServer(clientFd, CLIENT_PIPE_NAME); - PARAM_CHECK(ret == 0, close(clientFd); - return PARAM_CODE_FAIL_CONNECT, "Failed to connect server"); - setsockopt(clientFd, SOL_SOCKET, SO_SNDTIMEO, (char *)&time, sizeof(struct timeval)); - setsockopt(clientFd, SOL_SOCKET, SO_RCVTIMEO, (char *)&time, sizeof(struct timeval)); - *fd = clientFd; - } - ssize_t recvLen = 0; - ssize_t sendLen = send(clientFd, (char *)request, request->msgSize, 0); - if (sendLen > 0) { - recvLen = recv(clientFd, (char *)request, RECV_BUFFER_MAX, 0); - if (recvLen > 0) { - break; - } - } - ret = errno; - close(clientFd); - *fd = INVALID_SOCKET; - if (errno == EAGAIN || recvLen <= 0) { - ret = PARAM_CODE_TIMEOUT; - break; - } - PARAM_LOGE("Send or recv msg fail errno %d %zd %zd", errno, sendLen, recvLen); - } while (1); - - if (ret == 0) { // check result - ret = ProcessRecvMsg(request); - } - return ret; -} - -static int NeedCheckParamPermission(const char *name) -{ - static char *ctrlParam[] = { - "ohos.ctl.start", - "ohos.ctl.stop", - "ohos.startup.powerctrl" - }; - for (size_t i = 0; i < ARRAY_LENGTH(ctrlParam); i++) { - if (strcmp(name, ctrlParam[i]) == 0) { - return 0; - } - } - ParamSecurityLabel *securityLabel = g_clientSpace.paramSpace.securityLabel; - if (securityLabel != NULL && - ((securityLabel->flags & LABEL_CHECK_FOR_ALL_PROCESS) == LABEL_CHECK_FOR_ALL_PROCESS) && - ((securityLabel->flags & LABEL_ALL_PERMISSION) != LABEL_ALL_PERMISSION)) { - return 1; - } - return 0; -} - -int SystemSetParameter(const char *name, const char *value) -{ - InitParamClient(); - PARAM_CHECK(name != NULL && value != NULL, return -1, "Invalid name or value"); - int ret = CheckParamName(name, 0); - PARAM_CHECK(ret == 0, return ret, "Illegal param name %s", name); - ret = CheckParamValue(&g_clientSpace.paramSpace.paramSpace, NULL, name, value); - PARAM_CHECK(ret == 0, return ret, "Illegal param value %s", value); - - uint32_t msgSize = sizeof(ParamMessage) + sizeof(ParamMsgContent) + PARAM_ALIGN(strlen(value) + 1); - uint32_t labelLen = 0; - ParamSecurityOps *ops = GetClientParamSecurityOps(); - if (NeedCheckParamPermission(name) == 1) { - ret = CheckParamPermission(&g_clientSpace.paramSpace, g_clientSpace.paramSpace.securityLabel, name, DAC_WRITE); - PARAM_CHECK(ret == 0, return ret, "Forbit to set parameter %s", name); - } else if (!LABEL_IS_ALL_PERMITTED(g_clientSpace.paramSpace.securityLabel)) { // check local can check permissions - PARAM_CHECK(ops != NULL && ops->securityEncodeLabel != NULL, return -1, "Invalid securityEncodeLabel"); - ret = ops->securityEncodeLabel(g_clientSpace.paramSpace.securityLabel, NULL, &labelLen); - PARAM_CHECK(ret == 0, return -1, "Failed to get label length"); - } - msgSize += sizeof(ParamMsgContent) + labelLen; - msgSize = (msgSize < RECV_BUFFER_MAX) ? RECV_BUFFER_MAX : msgSize; - - ParamMessage *request = (ParamMessage *)CreateParamMessage(MSG_SET_PARAM, name, msgSize); - PARAM_CHECK(request != NULL, return -1, "Failed to malloc for connect"); - uint32_t offset = 0; - ret = FillParamMsgContent(request, &offset, PARAM_VALUE, value, strlen(value)); - PARAM_CHECK(ret == 0, free(request); - return -1, "Failed to fill value"); - ret = FillLabelContent(request, &offset, labelLen); - PARAM_CHECK(ret == 0, free(request); - return -1, "Failed to fill label"); - request->msgSize = offset + sizeof(ParamMessage); - request->id.msgId = atomic_fetch_add(&g_requestId, 1); - - pthread_mutex_lock(&g_clientSpace.mutex); - ret = StartRequest(&g_clientSpace.clientFd, request, DEFAULT_PARAM_SET_TIMEOUT); - pthread_mutex_unlock(&g_clientSpace.mutex); - free(request); - return ret; -} - -int SystemWaitParameter(const char *name, const char *value, int32_t timeout) -{ - InitParamClient(); - PARAM_CHECK(name != NULL, return -1, "Invalid name"); - int ret = CheckParamName(name, 0); - PARAM_CHECK(ret == 0, return ret, "Illegal param name %s", name); - ParamHandle handle = 0; - ret = ReadParamWithCheck(&g_clientSpace.paramSpace, name, DAC_READ, &handle); - if (ret != PARAM_CODE_NOT_FOUND && ret != 0 && ret != PARAM_CODE_NODE_EXIST) { - PARAM_CHECK(ret == 0, return ret, "Forbid to wait parameter %s", name); - } - if (timeout <= 0) { - timeout = DEFAULT_PARAM_WAIT_TIMEOUT; - } - uint32_t msgSize = sizeof(ParamMessage) + sizeof(ParamMsgContent) + sizeof(ParamMsgContent) + sizeof(uint32_t); - msgSize = (msgSize < RECV_BUFFER_MAX) ? RECV_BUFFER_MAX : msgSize; - uint32_t offset = 0; - ParamMessage *request = NULL; - if (value != NULL && strlen(value) > 0) { - msgSize += PARAM_ALIGN(strlen(value) + 1); - request = (ParamMessage *)CreateParamMessage(MSG_WAIT_PARAM, name, msgSize); - PARAM_CHECK(request != NULL, return -1, "Failed to malloc for wait"); - ret = FillParamMsgContent(request, &offset, PARAM_VALUE, value, strlen(value)); - } else { - msgSize += PARAM_ALIGN(1); - request = (ParamMessage *)CreateParamMessage(MSG_WAIT_PARAM, name, msgSize); - PARAM_CHECK(request != NULL, return -1, "Failed to malloc for wait"); - ret = FillParamMsgContent(request, &offset, PARAM_VALUE, "*", 1); - } - PARAM_CHECK(ret == 0, free(request); - return -1, "Failed to fill value"); - ParamMsgContent *content = (ParamMsgContent *)(request->data + offset); - content->type = PARAM_WAIT_TIMEOUT; - content->contentSize = sizeof(uint32_t); - *((uint32_t *)(content->content)) = timeout; - offset += sizeof(ParamMsgContent) + sizeof(uint32_t); - - request->msgSize = offset + sizeof(ParamMessage); - request->id.waitId = atomic_fetch_add(&g_requestId, 1); - int fd = INVALID_SOCKET; - ret = StartRequest(&fd, request, timeout); - if (fd != INVALID_SOCKET) { - close(fd); - } - free(request); - PARAM_LOGI("SystemWaitParameter %s value %s result %d ", name, value, ret); - return ret; -} - -int SystemGetParameter(const char *name, char *value, unsigned int *len) -{ - InitParamClient(); - PARAM_CHECK(name != NULL && len != NULL, return -1, "The name or value is null"); - ParamHandle handle = 0; - int ret = ReadParamWithCheck(&g_clientSpace.paramSpace, name, DAC_READ, &handle); - if (ret != PARAM_CODE_NOT_FOUND && ret != 0 && ret != PARAM_CODE_NODE_EXIST) { - PARAM_CHECK(ret == 0, return ret, "Forbid to get parameter %s", name); - } - return ReadParamValue(&g_clientSpace.paramSpace, handle, value, len); -} - -int SystemFindParameter(const char *name, ParamHandle *handle) -{ - InitParamClient(); - PARAM_CHECK(name != NULL && handle != NULL, return -1, "The name or handle is null"); - int ret = ReadParamWithCheck(&g_clientSpace.paramSpace, name, DAC_READ, handle); - if (ret != PARAM_CODE_NOT_FOUND && ret != 0 && ret != PARAM_CODE_NODE_EXIST) { - PARAM_CHECK(ret == 0, return ret, "Forbid to access parameter %s", name); - } - return ret; -} - -int SysCheckParamExist(const char *name) -{ - InitParamClient(); - PARAM_CHECK(name != NULL, return -1, "The name or handle is null"); - ParamHandle handle; - int ret = ReadParamWithCheck(&g_clientSpace.paramSpace, name, DAC_READ, &handle); - PARAM_LOGI("SysCheckParamExist %s result %d", name, ret); - if (ret == PARAM_CODE_NODE_EXIST) { - return 0; - } - PARAM_CHECK(ret == 0, return ret, "Forbid to access parameter %s", name); - return ret; -} - -int SystemGetParameterCommitId(ParamHandle handle, uint32_t *commitId) -{ - PARAM_CHECK(handle != 0 || commitId != NULL, return -1, "The handle is null"); - return ReadParamCommitId(&g_clientSpace.paramSpace, handle, commitId); -} - -long long GetSystemCommitId(void) -{ - PARAM_CHECK(g_clientSpace.paramSpace.paramSpace.area != NULL, return 0, "The handle is null"); - return g_clientSpace.paramSpace.paramSpace.area->commitId; -} - -int SystemGetParameterName(ParamHandle handle, char *name, unsigned int len) -{ - PARAM_CHECK(name != NULL && handle != 0, return -1, "The name is null"); - return ReadParamName(&g_clientSpace.paramSpace, handle, name, len); -} - -int SystemGetParameterValue(ParamHandle handle, char *value, unsigned int *len) -{ - PARAM_CHECK(len != NULL && handle != 0, return -1, "The value is null"); - return ReadParamValue(&g_clientSpace.paramSpace, handle, value, len); -} - -int SystemTraversalParameter(const char *prefix, - void (*traversalParameter)(ParamHandle handle, void *cookie), void *cookie) -{ - InitParamClient(); - PARAM_CHECK(traversalParameter != NULL, return -1, "The param is null"); - ParamHandle handle = 0; - // check default dac - const char *tmp = (prefix == NULL || strlen(prefix) == 0) ? "#" : prefix; - int ret = ReadParamWithCheck(&g_clientSpace.paramSpace, tmp, DAC_READ, &handle); - if (ret != PARAM_CODE_NOT_FOUND && ret != 0 && ret != PARAM_CODE_NODE_EXIST) { - PARAM_CHECK(ret == 0, return ret, "Forbid to traversal parameters"); - } - return TraversalParam(&g_clientSpace.paramSpace, tmp, traversalParameter, cookie); -} - -void SystemDumpParameters(int verbose) -{ - InitParamClient(); - // check default dac - ParamHandle handle = 0; - int ret = ReadParamWithCheck(&g_clientSpace.paramSpace, "#", DAC_READ, &handle); - if (ret != PARAM_CODE_NOT_FOUND && ret != 0 && ret != PARAM_CODE_NODE_EXIST) { - PARAM_CHECK(ret == 0, return, "Forbid to dump parameters"); - } - DumpParameters(&g_clientSpace.paramSpace, verbose); -} - -int WatchParamCheck(const char *keyprefix) -{ - InitParamClient(); - PARAM_CHECK(keyprefix != NULL, return PARAM_CODE_INVALID_PARAM, "Invalid keyprefix"); - int ret = CheckParamName(keyprefix, 0); - PARAM_CHECK(ret == 0, return ret, "Illegal param name %s", keyprefix); - ParamHandle handle = 0; - ret = ReadParamWithCheck(&g_clientSpace.paramSpace, keyprefix, DAC_WATCH, &handle); - if (ret != PARAM_CODE_NOT_FOUND && ret != 0 && ret != PARAM_CODE_NODE_EXIST) { - PARAM_CHECK(ret == 0, return ret, "Forbid to watch parameter %s", keyprefix); - } - return 0; -} - -int GetParamSecurityAuditData(const char *name, int type, ParamAuditData *auditData) -{ - uint32_t labelIndex = 0; - FindTrieNode(&g_clientSpace.paramSpace.paramSpace, name, strlen(name), &labelIndex); - ParamSecruityNode *node = (ParamSecruityNode *)GetTrieNode(&g_clientSpace.paramSpace.paramSpace, labelIndex); - PARAM_CHECK(node != NULL, return DAC_RESULT_FORBIDED, "Can not get security label %d", labelIndex); - - auditData->name = name; - auditData->dacData.uid = node->uid; - auditData->dacData.gid = node->gid; - auditData->dacData.mode = node->mode; - if (node->length > 0) { - auditData->label = strdup(node->data); - } - return 0; -} - -#if (defined STARTUP_INIT_TEST || defined PARAM_TEST) -ParamWorkSpace *GetClientParamWorkSpace(void) -{ - return &g_clientSpace.paramSpace; -} -#endif \ No newline at end of file diff --git a/services/param/include/param_manager.h b/services/param/include/param_manager.h index c66a8d6d3f0310a5b135324630c3ad9e332383b8..b4832ca4301fc1672fff1739fc8bb4d17590decc 100644 --- a/services/param/include/param_manager.h +++ b/services/param/include/param_manager.h @@ -15,15 +15,17 @@ #ifndef BASE_STARTUP_PARAM_MANAGER_H #define BASE_STARTUP_PARAM_MANAGER_H +#include #include #include -#include "param_message.h" +#include "init_param.h" +#include "list.h" +#include "param_osadp.h" #include "param_persist.h" #include "param_security.h" #include "param_trie.h" #include "param_utils.h" -#include "sys_param.h" #ifdef __cplusplus #if __cplusplus @@ -31,53 +33,97 @@ extern "C" { #endif #endif -#define futex(addr1, op, val, rel, addr2, val3) syscall(SYS_futex, addr1, op, val, rel, addr2, val3) -#define futex_wait_always(addr1) syscall(SYS_futex, addr1, FUTEX_WAIT, *(int *)(addr1), 0, 0, 0) -#define futex_wake_single(addr1) syscall(SYS_futex, addr1, FUTEX_WAKE, 1, 0, 0, 0) +#define WORKSPACE_NAME_DAC "param_sec_dac" +#define WORKSPACE_NAME_NORMAL "param_storage" +#define WORKSPACE_NAME_DEF_SELINUX "u:object_r:default_param:s0" + +#define PARAM_NEED_CHECK_IN_SERVICE 0x2 +#define PARAM_CTRL_SERVICE 0x1 + +#define PARAM_WORKSPACE_CHECK(space, exper, ...) \ + if (((*space).flags & WORKSPACE_FLAGS_INIT) != WORKSPACE_FLAGS_INIT) { \ + PARAM_LOGE(__VA_ARGS__); \ + exper; \ + } typedef struct { uint32_t flags; - WorkSpace paramSpace; - ParamSecurityLabel *securityLabel; - ParamSecurityOps paramSecurityOps; + ParamSecurityLabel securityLabel; + ParamSecurityOps paramSecurityOps[PARAM_SECURITY_MAX]; + HashMapHandle workSpaceHashHandle; + ListHead workSpaceList; +#ifdef PARAMWORKSPACE_NEED_MUTEX + ParamRWMutex rwlock; +#endif +} ParamWorkSpace; + +typedef struct { ParamTaskPtr serverTask; ParamTaskPtr timer; ParamTaskPtr watcherTask; - char buffer[PARAM_NAME_LEN_MAX + PARAM_CONST_VALUE_LEN_MAX + 10]; // 10 max len -} ParamWorkSpace; +} ParamService; typedef struct { uint32_t flags; + long long commitId; ParamTaskPtr saveTimer; time_t lastSaveTimer; PersistParamOps persistParamOps; } ParamPersistWorkSpace; -int InitParamWorkSpace(ParamWorkSpace *workSpace, int onlyRead); -void CloseParamWorkSpace(ParamWorkSpace *workSpace); +typedef struct { + uint32_t flags; + int clientFd; + pthread_mutex_t mutex; +} ClientWorkSpace; -int ReadParamWithCheck(const ParamWorkSpace *workSpace, const char *name, uint32_t op, ParamHandle *handle); -int ReadParamValue(const ParamWorkSpace *workSpace, ParamHandle handle, char *value, uint32_t *len); -int ReadParamName(const ParamWorkSpace *workSpace, ParamHandle handle, char *name, uint32_t len); -int ReadParamCommitId(const ParamWorkSpace *workSpace, ParamHandle handle, uint32_t *commitId); +int InitParamWorkSpace(int onlyRead); +void CloseParamWorkSpace(void); +WorkSpace *GetWorkSpace(const char *name); +int AddWorkSpace(const char *name, int onlyRead, uint32_t spacesize); +WorkSpace *GetFristWorkSpace(void); +WorkSpace *GetNextWorkSpace(WorkSpace *curr); -int CheckParamValue(const WorkSpace *workSpace, const ParamTrieNode *node, const char *name, const char *value); +ParamTrieNode *GetTrieNodeByHandle(ParamHandle handle); + +int CheckParameterSet(const char *name, const char *value, const ParamSecurityLabel *srcLabel, int *ctrlService); + +int ReadParamWithCheck(const char *name, uint32_t op, ParamHandle *handle); +int ReadParamValue(ParamHandle handle, char *value, uint32_t *len); +int ReadParamName(ParamHandle handle, char *name, uint32_t len); +int ReadParamCommitId(ParamHandle handle, uint32_t *commitId); + +int CheckParamValue(const ParamTrieNode *node, const char *name, const char *value); int CheckParamName(const char *name, int paramInfo); -int CheckParamPermission(const ParamWorkSpace *workSpace, - const ParamSecurityLabel *srcLabel, const char *name, uint32_t mode); +int CheckParamPermission(const ParamSecurityLabel *srcLabel, const char *name, uint32_t mode); +ParamNode *SystemCheckMatchParamWait(const char *name, const char *value); + +int WriteParam(const char *name, const char *value, uint32_t *dataIndex, int onlyAdd); +int AddSecurityLabel(const ParamAuditData *auditData); +int LoadSecurityLabel(const char *fileName); +ParamSecurityLabel *GetParamSecurityLabel(void); typedef void (*TraversalParamPtr)(ParamHandle handle, void *context); typedef struct { TraversalParamPtr traversalParamPtr; void *context; - const char *prefix; + char *prefix; } ParamTraversalContext; -int TraversalParam(const ParamWorkSpace *workSpace, - const char *prefix, TraversalParamPtr walkFunc, void *cookie); -ParamWorkSpace *GetParamWorkSpace(void); -ParamWorkSpace *GetClientParamWorkSpace(void); -void DumpParameters(const ParamWorkSpace *workSpace, int verbose); +const char *GetSelinuxContent(const char *name); + +int LoadParamFromCmdLine(void); +void LoadSelinuxLabel(void); + +int InitPersistParamWorkSpace(void); +void ClosePersistParamWorkSpace(void); +int WritePersistParam(const char *name, const char *value); +long long GetPersistCommitId(void); +void UpdatePersistCommitId(void); + +#ifdef STARTUP_INIT_TEST +ParamService *GetParamService(); +#endif #ifdef __cplusplus #if __cplusplus } diff --git a/services/param/include/param_osadp.h b/services/param/include/param_osadp.h new file mode 100755 index 0000000000000000000000000000000000000000..dac88d0b465b0dbd2c351effa1e90c18b23dddb6 --- /dev/null +++ b/services/param/include/param_osadp.h @@ -0,0 +1,180 @@ +/* + * Copyright (c) 2021 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 BASE_STARTUP_PARAM_OS_ADAPTER_H +#define BASE_STARTUP_PARAM_OS_ADAPTER_H +#include +#include +#include +#include +#include +#include + +#include "param_utils.h" +#include "securec.h" +#if !(defined __LITEOS_A__ || defined __LITEOS_M__) +#include "loop_event.h" +#else +#include +#endif + +#ifndef __LITEOS_M__ +#include +#endif + +#if defined FUTEX_WAIT || defined FUTEX_WAKE +#include +#endif + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +#if (defined __LITEOS_A__ || defined __LITEOS_M__) +#define DAC_DEFAULT_MODE 0777 +#ifdef STARTUP_INIT_TEST +#define PARAM_WORKSPACE_MAX (1024 * 50) +#else +#define PARAM_WORKSPACE_MAX (1024 * 30) +#endif +#define PARAM_WORKSPACE_SMALL PARAM_WORKSPACE_MAX +#define PARAM_WORKSPACE_DEF PARAM_WORKSPACE_MAX +#else +#define PARAM_WORKSPACE_MAX (80 * 1024) +#define PARAM_WORKSPACE_SMALL (1024 * 10) +#ifdef STARTUP_INIT_TEST +#define DAC_DEFAULT_MODE 0777 +#define PARAM_WORKSPACE_DEF (1024 * 50) +#else +#define DAC_DEFAULT_MODE 0774 +#define PARAM_WORKSPACE_DEF (1024 * 30) +#endif +#endif + +// support futex +#ifndef __NR_futex +#define PARAM_NR_FUTEX 202 /* syscall number */ +#else +#define PARAM_NR_FUTEX __NR_futex +#endif + +#if !(defined FUTEX_WAIT || defined FUTEX_WAKE) +#define FUTEX_WAIT 0 +#define FUTEX_WAKE 1 + +#ifndef __LITEOS_M__ +#define PARAM_FUTEX(ftx, op, value, timeout, bitset) \ + do { \ + struct timespec d_timeout = { 0, 1000 * 1000 * (timeout) }; \ + syscall(PARAM_NR_FUTEX, ftx, op, value, &d_timeout, NULL, bitset); \ + } while (0) + +#define futex_wake(ftx, count) PARAM_FUTEX(ftx, FUTEX_WAKE, count, 0, 0) +#define futex_wait(ftx, value) PARAM_FUTEX(ftx, FUTEX_WAIT, value, 100, 0) +#else +#define futex_wake(ftx, count) (void)(ftx) +#define futex_wait(ftx, value) (void)(ftx) +#endif +#endif + +// support timer +#if defined __LITEOS_A__ || defined __LITEOS_M__ +struct ParamTimer_; +typedef void (*ProcessTimer)(const struct ParamTimer_ *taskHandle, void *context); +typedef struct ParamTimer_ { + timer_t timerId; + uint64_t repeat; + ProcessTimer timeProcessor; + void *context; +} ParamTimer; + +typedef ParamTimer *ParamTaskPtr; +#else +typedef LoopBase *ParamTaskPtr; +typedef void (*ProcessTimer)(const ParamTaskPtr taskHandle, void *context); +#endif + +int ParamTimerCreate(ParamTaskPtr *timer, ProcessTimer process, void *context); +int ParamTimerStart(const ParamTaskPtr timer, uint64_t timeout, uint64_t repeat); +void ParamTimerClose(ParamTaskPtr timer); + +// support mutex +#ifndef __LITEOS_M__ +typedef struct { + pthread_rwlock_t rwlock; +} ParamRWMutex; + +typedef struct { + pthread_mutex_t mutex; +} ParamMutex; +#else +typedef struct { + uint32_t mutex; +} ParamRWMutex; + +typedef struct { + uint32_t mutex; +} ParamMutex; +#endif + +int ParamRWMutexCreate(ParamRWMutex *lock); +int ParamRWMutexWRLock(ParamRWMutex *lock); +int ParamRWMutexRDLock(ParamRWMutex *lock); +int ParamRWMutexUnlock(ParamRWMutex *lock); +int ParamRWMutexDelete(ParamRWMutex *lock); + +int ParamMutexCeate(ParamMutex *mutex); +int ParamMutexPend(ParamMutex *mutex); +int ParamMutexPost(ParamMutex *mutex); +int ParamMutexDelete(ParamMutex *mutex); + +#ifdef WORKSPACE_AREA_NEED_MUTEX +#define PARAMSPACE_AREA_INIT_LOCK(workspace) ParamRWMutexCreate(&workspace->rwlock) +#define PARAMSPACE_AREA_RW_LOCK(workspace) ParamRWMutexWRLock(&workspace->rwlock) +#define PARAMSPACE_AREA_RD_LOCK(workspace) ParamRWMutexRDLock(&workspace->rwlock) +#define PARAMSPACE_AREA_RW_UNLOCK(workspace) ParamRWMutexUnlock(&workspace->rwlock) +#else +#define PARAMSPACE_AREA_INIT_LOCK(rwlock) (void)(rwlock) +#define PARAMSPACE_AREA_RW_LOCK(rwlock) (void)(rwlock) +#define PARAMSPACE_AREA_RD_LOCK(rwlock) (void)(rwlock) +#define PARAMSPACE_AREA_RW_UNLOCK(rwlock) (void)(rwlock) +#endif + +#ifdef PARAMWORKSPACE_NEED_MUTEX +#define WORKSPACE_INIT_LOCK(workspace) ParamRWMutexCreate(&(workspace).rwlock) +#define WORKSPACE_RW_LOCK(workspace) ParamRWMutexWRLock(&(workspace).rwlock) +#define WORKSPACE_RD_LOCK(workspace) ParamRWMutexRDLock(&(workspace).rwlock) +#define WORKSPACE_RW_UNLOCK(workspace) ParamRWMutexUnlock(&(workspace).rwlock) +#else +#define WORKSPACE_INIT_LOCK(workspace) (void)(workspace) +#define WORKSPACE_RW_LOCK(workspace) (void)(workspace) +#define WORKSPACE_RD_LOCK(workspace) (void)(workspace) +#define WORKSPACE_RW_UNLOCK(workspace) (void)(workspace) +#endif + +typedef struct { + int shmid; +} MemHandle; +void *GetSharedMem(const char *fileName, MemHandle *handle, uint32_t spaceSize, int readOnly); +void FreeSharedMem(const MemHandle *handle, void *mem, uint32_t dataSize); + +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif +#endif // BASE_STARTUP_PARAM_MESSAGE_H \ No newline at end of file diff --git a/services/param/include/param_persist.h b/services/param/include/param_persist.h index 23628ab018aed77e2bba5cda0ca33a6836efd5a2..9a57e0510e65817e42041099b34dc902530390f9 100644 --- a/services/param/include/param_persist.h +++ b/services/param/include/param_persist.h @@ -17,6 +17,9 @@ #define BASE_STARTUP_PARAM_PERSIST_H #include #include + +#include "param_osadp.h" + #ifdef __cplusplus #if __cplusplus extern "C" { @@ -27,25 +30,20 @@ typedef int (*PersistParamGetPtr)(const char *name, const char *value, void *con typedef void *PERSIST_SAVE_HANDLE; typedef struct { - int (*load)(PersistParamGetPtr persistParamGet, void *context); + int (*load)(); int (*save)(const char *name, const char *value); int (*batchSaveBegin)(PERSIST_SAVE_HANDLE *handle); int (*batchSave)(PERSIST_SAVE_HANDLE handle, const char *name, const char *value); void (*batchSaveEnd)(PERSIST_SAVE_HANDLE handle); } PersistParamOps; -#ifndef PARAM_SUPPORT_SAVE_PERSIST -#define PARAM_SUPPORT_SAVE_PERSIST 1 // default -#endif - -#ifdef PARAM_SUPPORT_SAVE_PERSIST int RegisterPersistParamOps(PersistParamOps *ops); -#endif #ifndef STARTUP_INIT_TEST #define PARAM_MUST_SAVE_PARAM_DIFF 10 // 10s #else #define PARAM_MUST_SAVE_PARAM_DIFF 1 +void TimerCallbackForSave(ParamTaskPtr timer, void *context); #endif #ifdef __cplusplus diff --git a/services/param/include/param_security.h b/services/param/include/param_security.h index 26cb0edbf0a2a3dd3723fd33339808728e9d61bb..bcc633fdf0073ad75d2228769fa178a3136f49a2 100644 --- a/services/param/include/param_security.h +++ b/services/param/include/param_security.h @@ -16,7 +16,17 @@ #ifndef BASE_STARTUP_PARAM_SECURITY_H #define BASE_STARTUP_PARAM_SECURITY_H #include +#ifndef __LINUX__ +#include +#endif #include +#ifdef PARAM_SUPPORT_SELINUX +#include "selinux_parameter.h" +#else +typedef struct ParamContextsList_ { +} ParamContextsList; +#endif + #ifdef __cplusplus #if __cplusplus extern "C" { @@ -25,21 +35,17 @@ extern "C" { #define DAC_GROUP_START 3 #define DAC_OTHER_START 6 -#define DAC_READ 0x0100 -#define DAC_WRITE 0x0080 -#define DAC_WATCH 0x0040 +#define DAC_READ 0x0100 // 4 +#define DAC_WRITE 0x0080 // 2 +#define DAC_WATCH 0x0040 // 1 #define DAC_ALL_PERMISSION 0777 #define LABEL_ALL_PERMISSION 0x04 -#define LABEL_CHECK_FOR_ALL_PROCESS 0x02 +#define LABEL_CHECK_IN_ALL_PROCESS 0x02 #define LABEL_INIT_FOR_INIT 0x01 -#define LABEL_IS_CLIENT_CHECK_PERMITTED(label) \ - ((label) != NULL) && ((((label)->flags & (LABEL_CHECK_FOR_ALL_PROCESS)) == (LABEL_CHECK_FOR_ALL_PROCESS)) && \ - (((label)->flags & (LABEL_ALL_PERMISSION)) != (LABEL_ALL_PERMISSION))) - -#define LABEL_IS_ALL_PERMITTED(label) \ - (((label) == NULL) || ((label)->flags & LABEL_ALL_PERMISSION) == (LABEL_ALL_PERMISSION)) +#define SELINUX_CONTENT_LEN 64 +#define SYS_UID_INDEX 1000 typedef enum { DAC_RESULT_PERMISSION = 0, @@ -53,54 +59,68 @@ typedef struct UserCred { gid_t gid; } UserCred; +typedef enum { + PARAM_SECURITY_DAC = 0, +#ifdef PARAM_SUPPORT_SELINUX + PARAM_SECURITY_SELINUX, +#endif + PARAM_SECURITY_MAX +} ParamSecurityType; + typedef struct { - uint32_t flags; UserCred cred; + uint32_t flags[PARAM_SECURITY_MAX]; } ParamSecurityLabel; typedef struct { pid_t pid; uid_t uid; gid_t gid; - uint32_t mode; // 访问权限 + uint32_t mode; } ParamDacData; typedef struct { ParamDacData dacData; const char *name; - const char *label; +#ifdef PARAM_SUPPORT_SELINUX + char label[SELINUX_CONTENT_LEN]; +#endif } ParamAuditData; -typedef int (*SecurityLabelFunc)(const ParamAuditData *auditData, void *context); - typedef struct { - int (*securityInitLabel)(ParamSecurityLabel **label, int isInit); - int (*securityGetLabel)(SecurityLabelFunc label, const char *path, void *context); + char name[10]; + int (*securityInitLabel)(ParamSecurityLabel *label, int isInit); + int (*securityGetLabel)(const char *path); int (*securityCheckFilePermission)(const ParamSecurityLabel *label, const char *fileName, int flags); - int (*securityCheckParamPermission)(const ParamSecurityLabel *srcLabel, - const ParamAuditData *auditData, uint32_t mode); - int (*securityEncodeLabel)(const ParamSecurityLabel *srcLabel, char *buffer, uint32_t *bufferSize); - int (*securityDecodeLabel)(ParamSecurityLabel **srcLabel, const char *buffer, uint32_t bufferSize); + int (*securityCheckParamPermission)(const ParamSecurityLabel *srcLabel, const char *name, uint32_t mode); int (*securityFreeLabel)(ParamSecurityLabel *srcLabel); } ParamSecurityOps; typedef int (*RegisterSecurityOpsPtr)(ParamSecurityOps *ops, int isInit); -int RegisterSecurityOps(ParamSecurityOps *ops, int isInit); - -typedef struct { - SecurityLabelFunc label; - void *context; -} LabelFuncContext; - int GetParamSecurityAuditData(const char *name, int type, ParamAuditData *auditData); +int RegisterSecurityDacOps(ParamSecurityOps *ops, int isInit); +void LoadGroupUser(void); + +typedef int (*SelinuxSetParamCheck)(const char *paraName, struct ucred *uc); +typedef struct SelinuxSpace_ { + void *selinuxHandle; + void (*setSelinuxLogCallback)(); + int (*setParamCheck)(const char *paraName, struct ucred *uc); + const char *(*getParamLabel)(const char *paraName); + int (*readParamCheck)(const char *paraName); + ParamContextsList *(*getParamList)(); + void (*destroyParamList)(ParamContextsList **list); +} SelinuxSpace; #ifdef PARAM_SUPPORT_SELINUX -#ifdef PARAM_SUPPORT_DAC -#error param security only support one. +int RegisterSecuritySelinuxOps(ParamSecurityOps *ops, int isInit); #endif -#else -#define PARAM_SUPPORT_DAC 1 // default support dac + +#if defined STARTUP_INIT_TEST || defined LOCAL_TEST +ParamSecurityOps *GetParamSecurityOps(int type); +int RegisterSecurityOps(int onlyRead); +void SetSelinuxOps(const SelinuxSpace *space); #endif #ifdef __cplusplus @@ -108,4 +128,4 @@ int GetParamSecurityAuditData(const char *name, int type, ParamAuditData *auditD } #endif #endif -#endif // BASE_STARTUP_PARAM_SECURITY_H \ No newline at end of file +#endif // BASE_STARTUP_PARAM_SECURITY_H \ No newline at end of file diff --git a/services/param/include/param_service.h b/services/param/include/param_service.h deleted file mode 100644 index 00f72a08499b59bcc8bd1c7984f63e124e9339dd..0000000000000000000000000000000000000000 --- a/services/param/include/param_service.h +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2021 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 BASE_STARTUP_PARAM_SERVICE_H -#define BASE_STARTUP_PARAM_SERVICE_H -#include -#include - -#include "param_manager.h" -#include "sys_param.h" - -#ifdef __cplusplus -#if __cplusplus -extern "C" { -#endif -#endif - -#define PARAM_WATCH_FLAGS_WAIT 0x01 -struct CmdLineEntry { - char *key; - int set; -}; - -typedef struct cmdLineInfo { - const char* name; - int (*processor)(const char* name, const char* value, int); -} cmdLineInfo; - -int WriteParam(const WorkSpace *workSpace, const char *name, const char *value, uint32_t *dataIndex, int onlyAdd); - -int InitPersistParamWorkSpace(const ParamWorkSpace *workSpace); -void ClosePersistParamWorkSpace(void); -int LoadPersistParam(ParamWorkSpace *workSpace); -int WritePersistParam(ParamWorkSpace *workSpace, const char *name, const char *value); - -#ifdef STARTUP_INIT_TEST -int ProcessMessage(const ParamTaskPtr worker, const ParamMessage *msg); -int AddSecurityLabel(const ParamAuditData *auditData, void *context); -int OnIncomingConnect(LoopHandle loop, TaskHandle server); -PARAM_STATIC void ProcessBeforeEvent(const ParamTaskPtr stream, - uint64_t eventId, const uint8_t *content, uint32_t size); -#endif - -int ProcessParamWaitAdd(ParamWorkSpace *worksapce, const ParamTaskPtr worker, const ParamMessage *msg); -int ProcessParamWatchAdd(ParamWorkSpace *worksapce, const ParamTaskPtr worker, const ParamMessage *msg); -#ifdef __cplusplus -#if __cplusplus -} -#endif -#endif -#endif \ No newline at end of file diff --git a/services/param/include/param_trie.h b/services/param/include/param_trie.h index 3e158cf7a91c236bea45f94c62c03b6f2bbae118..07ac9b97a8db1fb548704a8b7dca8c82f6fbef0c 100644 --- a/services/param/include/param_trie.h +++ b/services/param/include/param_trie.h @@ -17,34 +17,13 @@ #define BASE_STARTUP_PARAM_TRIE_H #include #include -#include -#include +#include "init_hashmap.h" +#include "init_param.h" +#include "list.h" +#include "param_osadp.h" #include "param_security.h" #include "securec.h" -#include "sys_param.h" - -#ifndef __NR_futex -#define PARAM_NR_FUTEX 202 /* syscall number */ -#else -#define PARAM_NR_FUTEX __NR_futex -#endif - -#if defined FUTEX_WAIT || defined FUTEX_WAKE -#include -#else -#define FUTEX_WAIT 0 -#define FUTEX_WAKE 1 - -#define PARAM_FUTEX(ftx, op, value, timeout, bitset) \ - do { \ - struct timespec d_timeout = { 0, 1000 * 1000 * (timeout) }; \ - syscall(PARAM_NR_FUTEX, ftx, op, value, &d_timeout, NULL, bitset); \ - } while (0) - -#define futex_wake(ftx, count) PARAM_FUTEX(ftx, FUTEX_WAKE, count, 0, 0) -#define futex_wait(ftx, value) PARAM_FUTEX(ftx, FUTEX_WAIT, value, 100, 0) -#endif #ifdef __cplusplus #if __cplusplus @@ -52,8 +31,12 @@ extern "C" { #endif #endif -#define PARAM_WORKSPACE_MAX (80 * 1024) -#define FILENAME_LEN_MAX 255 +#ifdef PARAM_SUPPORT_SELINUX +#define HASH_BUTT 32 +#else +#define HASH_BUTT 1 +#endif + typedef struct { uint32_t left; uint32_t right; @@ -86,36 +69,44 @@ typedef struct { typedef struct { atomic_llong commitId; + atomic_llong commitPersistId; uint32_t trieNodeCount; uint32_t paramNodeCount; uint32_t securityNodeCount; + uint32_t startIndex; uint32_t currOffset; uint32_t firstNode; uint32_t dataSize; - uint32_t reserved_[28]; char data[0]; } ParamTrieHeader; struct WorkSpace_; typedef struct WorkSpace_ { - char fileName[FILENAME_LEN_MAX + 1]; + int flags; + HashNode hashNode; + ListNode node; uint32_t (*allocTrieNode)(struct WorkSpace_ *workSpace, const char *key, uint32_t keyLen); int (*compareTrieNode)(const ParamTrieNode *node, const char *key2, uint32_t key2Len); + MemHandle memHandle; ParamTrieHeader *area; +#ifdef WORKSPACE_AREA_NEED_MUTEX + ParamRWMutex rwlock; +#endif + char fileName[0]; } WorkSpace; -int InitWorkSpace(const char *fileName, WorkSpace *workSpace, int onlyRead); +int InitWorkSpace(WorkSpace *workSpace, int onlyRead, uint32_t spaceSize); void CloseWorkSpace(WorkSpace *workSpace); ParamTrieNode *GetTrieNode(const WorkSpace *workSpace, uint32_t offset); void SaveIndex(uint32_t *index, uint32_t offset); ParamTrieNode *AddTrieNode(WorkSpace *workSpace, const char *key, uint32_t keyLen); -ParamTrieNode *FindTrieNode(const WorkSpace *workSpace, const char *key, uint32_t keyLen, uint32_t *matchLabel); +ParamTrieNode *FindTrieNode(WorkSpace *workSpace, const char *key, uint32_t keyLen, uint32_t *matchLabel); -typedef int (*TraversalTrieNodePtr)(const WorkSpace *workSpace, const ParamTrieNode *node, void *cookie); +typedef int (*TraversalTrieNodePtr)(const WorkSpace *workSpace, const ParamTrieNode *node, const void *cookie); int TraversalTrieNode(const WorkSpace *workSpace, - const ParamTrieNode *subTrie, TraversalTrieNodePtr walkFunc, void *cookie); + const ParamTrieNode *subTrie, TraversalTrieNodePtr walkFunc, const void *cookie); uint32_t AddParamSecruityNode(WorkSpace *workSpace, const ParamAuditData *auditData); uint32_t AddParamNode(WorkSpace *workSpace, const char *key, uint32_t keyLen, const char *value, uint32_t valueLen); @@ -124,4 +115,4 @@ uint32_t AddParamNode(WorkSpace *workSpace, const char *key, uint32_t keyLen, co } #endif #endif -#endif // BASE_STARTUP_PARAM_TRIE_H \ No newline at end of file +#endif // BASE_STARTUP_PARAM_TRIE_H \ No newline at end of file diff --git a/services/param/include/param_utils.h b/services/param/include/param_utils.h index 66a2d55556641604fb8070b6f3d58e7606627697..6d297adb37eac2f2d9dd7c3e8a1d2ce720b914b3 100644 --- a/services/param/include/param_utils.h +++ b/services/param/include/param_utils.h @@ -19,8 +19,9 @@ #include #include "init_log.h" +#include "init_param.h" +#include "init_utils.h" #include "securec.h" -#include "sys_param.h" #ifdef __cplusplus #if __cplusplus @@ -33,6 +34,17 @@ typedef enum { PARAM_CODE_ERROR_MAP_FILE, } PARAM_INNER_CODE; +struct CmdLineEntry { + char *key; + int set; +}; + +typedef struct cmdLineInfo { + const char *name; + int (*processor)(const char *name, const char *value, int); +} cmdLineInfo; + +#define FILENAME_LEN_MAX 255 #define MS_UNIT 1000 #define UNUSED(x) (void)(x) #define PARAM_ALIGN(len) (((len) + 0x03) & (~0x03)) @@ -48,28 +60,29 @@ typedef enum { #define OHOS_SERVICE_CTRL_PREFIX "ohos.servicectrl." #define OHOS_BOOT "ohos.boot." -#define CLIENT_PIPE_NAME "/dev/unix/socket/paramservice" -#define CLIENT_PARAM_STORAGE_PATH "/dev/__parameters__/param_storage" - #ifdef STARTUP_INIT_TEST #define PARAM_STATIC -#define PARAM_DEFAULT_PATH "/data/init_ut" -#define PIPE_NAME PARAM_DEFAULT_PATH"/param/paramservice" -#define PARAM_STORAGE_PATH PARAM_DEFAULT_PATH "/__parameters__/param_storage" -#define PARAM_PERSIST_SAVE_PATH PARAM_DEFAULT_PATH "/param/persist_parameters" -#define PARAM_PERSIST_SAVE_TMP_PATH PARAM_DEFAULT_PATH "/param/tmp_persist_parameters" #else -#define PARAM_DEFAULT_PATH "" #define PARAM_STATIC static -#define PIPE_NAME "/dev/unix/socket/paramservice" -#define PARAM_STORAGE_PATH "/dev/__parameters__/param_storage" -#define PARAM_PERSIST_SAVE_PATH "/data/parameters/persist_parameters" -#define PARAM_PERSIST_SAVE_TMP_PATH "/data/parameters/tmp_persist_parameters" #endif -#define PARAM_CMD_LINE "/proc/cmdline" -#define GROUP_FILE_PATH "/etc/group" -#define USER_FILE_PATH "/etc/passwd" +#ifndef DATA_PATH +#if defined __LITEOS_M__ +#define DATA_PATH "" +#elif defined __LITEOS_A__ +#define DATA_PATH STARTUP_INIT_UT_PATH"/storage/data/system/param/" +#elif defined __LINUX__ +#define DATA_PATH STARTUP_INIT_UT_PATH"/storage/data/system/param/" +#else +#define DATA_PATH STARTUP_INIT_UT_PATH"/data/parameters/" +#endif +#endif + +#define CLIENT_PIPE_NAME "/dev/unix/socket/paramservice" +#define PIPE_NAME STARTUP_INIT_UT_PATH "/dev/unix/socket/paramservice" +#define PARAM_STORAGE_PATH STARTUP_INIT_UT_PATH "/dev/__parameters__" +#define PARAM_PERSIST_SAVE_PATH DATA_PATH "persist_parameters" +#define PARAM_PERSIST_SAVE_TMP_PATH DATA_PATH "tmp_persist_parameters" #define WORKSPACE_FLAGS_INIT 0x01 #define WORKSPACE_FLAGS_LOADED 0x02 @@ -94,6 +107,11 @@ typedef enum { exper; \ } +#define PARAM_ONLY_CHECK(retCode, exper) \ + if (!(retCode)) { \ + exper; \ + } + #ifdef INIT_AGENT #define PARAM_DUMP printf #else @@ -113,13 +131,8 @@ typedef enum { #define SUBSTR_INFO_DAC 1 #endif -typedef struct { - int length; - char value[PARAM_BUFFER_SIZE]; -} SubStringInfo; - +char *GetServiceCtrlName(const char *name, const char *value); void CheckAndCreateDir(const char *fileName); -int GetSubStringInfo(const char *buff, uint32_t buffLen, char delimiter, SubStringInfo *info, int subStrNumber); int SpliteString(char *line, const char *exclude[], uint32_t count, int (*result)(const uint32_t *context, const char *name, const char *value), const uint32_t *context); #ifdef __cplusplus diff --git a/services/param/include/trigger_manager.h b/services/param/include/trigger_manager.h index 871decfe1cc2f5912b84077257826e315f273f3b..70d1e606ffd9677d9a9174218b8dfb8166160c77 100644 --- a/services/param/include/trigger_manager.h +++ b/services/param/include/trigger_manager.h @@ -187,7 +187,6 @@ void ClearTrigger(const TriggerWorkSpace *workSpace, int8_t type); int AddCommand(JobNode *trigger, uint32_t cmdIndex, const char *content); CommandNode *GetNextCmdNode(const JobNode *trigger, const CommandNode *curr); -void DumpTrigger(const TriggerWorkSpace *workSpace); void PostParamTrigger(int type, const char *name, const char *value); void ClearWatchTrigger(ParamWatcher *watcher, int type); @@ -196,6 +195,10 @@ int CheckWatchTriggerTimeout(void); const char *GetTriggerName(const TriggerNode *trigger); void RegisterTriggerExec(int type, int32_t (*executeTrigger)(const TriggerNode *, const char *, uint32_t)); + +#ifdef STARTUP_INIT_TEST +void ProcessBeforeEvent(const ParamTaskPtr stream, uint64_t eventId, const uint8_t *content, uint32_t size); +#endif #ifdef __cplusplus #if __cplusplus } diff --git a/services/param/manager/param_message.c b/services/param/linux/param_message.c old mode 100644 new mode 100755 similarity index 91% rename from services/param/manager/param_message.c rename to services/param/linux/param_message.c index da8058178665f528480fc601f800e7b898199780..c4410979dc7e84ed06b4a6f1af68d66b7fd90c22 --- a/services/param/manager/param_message.c +++ b/services/param/linux/param_message.c @@ -12,7 +12,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - #include "param_message.h" #include @@ -22,6 +21,9 @@ #include #include +#include "param_message.h" +#include "param_utils.h" + int ConntectServer(int fd, const char *servername) { PARAM_CHECK(fd >= 0, return -1, "Invalid fd %d", fd); @@ -38,6 +40,7 @@ int ConntectServer(int fd, const char *servername) int len = offsetof(struct sockaddr_un, sun_path) + strlen(addr.sun_path); ret = connect(fd, (struct sockaddr *)&addr, len); PARAM_CHECK(ret != -1, return -1, "Failed to connect server %s %d", servername, errno); + PARAM_LOGV("ConntectServer %s success", servername); return 0; } @@ -63,14 +66,15 @@ int FillParamMsgContent(const ParamMessage *request, uint32_t *start, int type, ParamMessage *CreateParamMessage(int type, const char *name, uint32_t msgSize) { PARAM_CHECK(name != NULL, return NULL, "Invalid name"); + uint32_t size = msgSize; if (msgSize < sizeof(ParamMessage)) { - msgSize = sizeof(ParamMessage); + size = sizeof(ParamMessage); } - ParamMessage *msg = (ParamMessage *)calloc(1, msgSize); + ParamMessage *msg = (ParamMessage *)calloc(1, size); PARAM_CHECK(msg != NULL, return NULL, "Failed to malloc message"); msg->type = type; msg->id.msgId = 0; - msg->msgSize = msgSize; + msg->msgSize = size; int ret = strcpy_s(msg->key, sizeof(msg->key) - 1, name); PARAM_CHECK(ret == EOK, free(msg); return NULL, "Failed to fill name"); diff --git a/services/param/include/param_message.h b/services/param/linux/param_message.h old mode 100644 new mode 100755 similarity index 88% rename from services/param/include/param_message.h rename to services/param/linux/param_message.h index e554e9bb6cef922bbd761d92738d073969bc248e..28e64a395fd10a2a38e26a109c220cfcef17c0f0 --- a/services/param/include/param_message.h +++ b/services/param/linux/param_message.h @@ -20,7 +20,7 @@ #include #include "loop_event.h" -#include "param.h" +#include "param_osadp.h" #include "param_utils.h" #include "securec.h" @@ -31,7 +31,6 @@ extern "C" { #endif #define PARAM_TEST_FLAGS 0x01 - typedef enum { MSG_SET_PARAM, MSG_WAIT_PARAM, @@ -72,7 +71,6 @@ typedef struct { int32_t result; } ParamResponseMessage; -typedef LoopBase *ParamTaskPtr; typedef int (*RecvMessage)(const ParamTaskPtr stream, const ParamMessage *msg); typedef struct { @@ -94,9 +92,6 @@ int ParamTaskSendMsg(const ParamTaskPtr stream, const ParamMessage *msg); int ParamEventTaskCreate(ParamTaskPtr *stream, LE_ProcessAsyncEvent eventProcess); int ParamEventSend(const ParamTaskPtr stream, uint64_t eventId, const char *content, uint32_t size); -int ParamTimerCreate(ParamTaskPtr *timer, LE_ProcessTimer process, void *context); -int ParamTimerStart(const ParamTaskPtr timer, uint64_t timeout, uint64_t repeat); - void *ParamGetTaskUserData(const ParamTaskPtr stream); int FillParamMsgContent(const ParamMessage *request, uint32_t *start, int type, const char *value, uint32_t length); @@ -105,6 +100,10 @@ ParamMessage *CreateParamMessage(int type, const char *name, uint32_t msgSize); int ConntectServer(int fd, const char *servername); +#ifdef STARTUP_INIT_TEST +int ProcessMessage(const ParamTaskPtr worker, const ParamMessage *msg); +int OnIncomingConnect(LoopHandle loop, TaskHandle server); +#endif #ifdef __cplusplus #if __cplusplus } diff --git a/services/param/adapter/param_libuvadp.c b/services/param/linux/param_msgadp.c old mode 100644 new mode 100755 similarity index 88% rename from services/param/adapter/param_libuvadp.c rename to services/param/linux/param_msgadp.c index b09aa6ac1de7240212f7c550e336183c8eab9aaa..5e793abc3e3aa7dcdcdec11fd6bf43ba7f4bdd64 --- a/services/param/adapter/param_libuvadp.c +++ b/services/param/linux/param_msgadp.c @@ -12,7 +12,15 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include "param_osadp.h" + +#include +#include +#include +#include + #include "param_message.h" +#include "param_utils.h" static const uint32_t RECV_BUFFER_MAX = 5 * 1024; @@ -86,8 +94,8 @@ int ParamTaskSendMsg(const ParamTaskPtr stream, const ParamMessage *msg) uint8_t *buffer = LE_GetBufferInfo(bufferHandle, NULL, NULL); int ret = memcpy_s(buffer, dataSize, msg, dataSize); free((void *)msg); - PARAM_CHECK(ret == EOK, LE_FreeBuffer(LE_GetDefaultLoop(), NULL, buffer); - return -1, "Failed to fill name"); + PARAM_CHECK(ret == EOK, LE_FreeBuffer(LE_GetDefaultLoop(), NULL, bufferHandle); + return -1, "Failed to copy message"); return LE_Send(LE_GetDefaultLoop(), stream, bufferHandle, dataSize); } @@ -111,10 +119,11 @@ int ParamTaskClose(const ParamTaskPtr stream) return 0; } -int ParamTimerCreate(ParamTaskPtr *timer, LE_ProcessTimer process, void *context) + +int ParamTimerCreate(ParamTaskPtr *timer, ProcessTimer process, void *context) { PARAM_CHECK(timer != NULL && process != NULL, return -1, "Invalid timer"); - LE_STATUS status = LE_CreateTimer(LE_GetDefaultLoop(), timer, process, context); + LE_STATUS status = LE_CreateTimer(LE_GetDefaultLoop(), timer, (LE_ProcessTimer)process, context); return (int)status; } @@ -124,6 +133,12 @@ int ParamTimerStart(const ParamTaskPtr timer, uint64_t timeout, uint64_t repeat) return LE_StartTimer(LE_GetDefaultLoop(), timer, timeout, repeat); } +void ParamTimerClose(ParamTaskPtr timer) +{ + PARAM_CHECK(timer != NULL, return, "Invalid param"); + LE_CloseTask(LE_GetDefaultLoop(), (ParamTaskPtr)timer); +} + int ParamServiceStart(void) { LE_RunLoop(LE_GetDefaultLoop()); @@ -134,4 +149,4 @@ int ParamServiceStop(void) { LE_StopLoop(LE_GetDefaultLoop()); return 0; -} +} \ No newline at end of file diff --git a/services/param/linux/param_osadp.c b/services/param/linux/param_osadp.c new file mode 100755 index 0000000000000000000000000000000000000000..54dc59c9486e14eb538607232fbf0c7c427266e8 --- /dev/null +++ b/services/param/linux/param_osadp.c @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2021 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 "param_osadp.h" + +#include +#include +#include +#include + +#include "param_message.h" +#include "param_utils.h" + +int ParamRWMutexCreate(ParamRWMutex *lock) +{ + return 0; +} +int ParamRWMutexWRLock(ParamRWMutex *lock) +{ + return 0; +} +int ParamRWMutexRDLock(ParamRWMutex *lock) +{ + return 0; +} +int ParamRWMutexUnlock(ParamRWMutex *lock) +{ + return 0; +} + +int ParamRWMutexDelete(ParamRWMutex *lock) +{ + return 0; +} + +int ParamMutexCeate(ParamMutex *mutex) +{ + return 0; +} +int ParamMutexPend(ParamMutex *mutex) +{ + return 0; +} +int ParamMutexPost(ParamMutex *mutex) +{ + return 0; +} +int ParamMutexDelete(ParamMutex *mutex) +{ + return 0; +} + +void *GetSharedMem(const char *fileName, MemHandle *handle, uint32_t spaceSize, int readOnly) +{ + PARAM_CHECK(fileName != NULL, return NULL, "Invalid filename or handle"); + int mode = readOnly ? O_RDONLY : O_CREAT | O_RDWR | O_TRUNC; + int fd = open(fileName, mode, S_IRWXU | S_IRWXG | S_IROTH); + PARAM_CHECK(fd >= 0, return NULL, "Open file %s mode %x fail error %d", fileName, mode, errno); + + int prot = PROT_READ; + if (!readOnly) { + prot = PROT_READ | PROT_WRITE; + ftruncate(fd, spaceSize); + } + void *areaAddr = (void *)mmap(NULL, spaceSize, prot, MAP_SHARED, fd, 0); + PARAM_CHECK(areaAddr != MAP_FAILED && areaAddr != NULL, close(fd); + return NULL, "Failed to map memory error %d areaAddr %p spaceSize %d", errno, areaAddr, spaceSize); + close(fd); + return areaAddr; +} + +void FreeSharedMem(const MemHandle *handle, void *mem, uint32_t dataSize) +{ + PARAM_CHECK(mem != NULL && handle != NULL, return, "Invalid mem or handle"); + munmap((char *)mem, dataSize); +} \ No newline at end of file diff --git a/services/param/linux/param_request.c b/services/param/linux/param_request.c new file mode 100755 index 0000000000000000000000000000000000000000..c5e3b4335afb590e9d79aa6d23d15cebe340392b --- /dev/null +++ b/services/param/linux/param_request.c @@ -0,0 +1,245 @@ +/* + * Copyright (c) 2021 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 "init_param.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "init_utils.h" +#include "param_manager.h" +#include "param_message.h" +#include "param_security.h" + +#define INVALID_SOCKET (-1) +#define INIT_PROCESS_PID 1 + +static const uint32_t RECV_BUFFER_MAX = 5 * 1024; + +static atomic_uint g_requestId = ATOMIC_VAR_INIT(1); +static ClientWorkSpace g_clientSpace = {}; + +__attribute__((constructor)) static void ClientInit(void); +__attribute__((destructor)) static void ClientDeinit(void); + +static int InitParamClient(void) +{ + if (getpid() == INIT_PROCESS_PID) { + PARAM_LOGI("Init process, do not init client"); + return 0; + } + if (PARAM_TEST_FLAG(g_clientSpace.flags, WORKSPACE_FLAGS_INIT)) { + return 0; + } + PARAM_LOGV("InitParamClient"); + pthread_mutex_init(&g_clientSpace.mutex, NULL); + g_clientSpace.clientFd = INVALID_SOCKET; + int ret = InitParamWorkSpace(1); + PARAM_CHECK(ret == 0, return -1, "Failed to init param workspace"); + PARAM_SET_FLAG(g_clientSpace.flags, WORKSPACE_FLAGS_INIT); + PARAM_LOGI("InitParamClient finish"); + return 0; +} + +void ClientInit(void) +{ + PARAM_LOGV("ClientInit"); +#ifndef STARTUP_INIT_TEST + (void)InitParamClient(); +#endif +} + +void ClientDeinit(void) +{ + if (PARAM_TEST_FLAG(g_clientSpace.flags, WORKSPACE_FLAGS_INIT)) { + CloseParamWorkSpace(); + } + PARAM_SET_FLAG(g_clientSpace.flags, 0); + pthread_mutex_destroy(&g_clientSpace.mutex); +} + +static int ProcessRecvMsg(const ParamMessage *recvMsg) +{ + PARAM_LOGV("ProcessRecvMsg type: %u msgId: %u name %s", recvMsg->type, recvMsg->id.msgId, recvMsg->key); + int result = PARAM_CODE_INVALID_PARAM; + switch (recvMsg->type) { + case MSG_SET_PARAM: + result = ((ParamResponseMessage *)recvMsg)->result; + break; + case MSG_NOTIFY_PARAM: { + uint32_t offset = 0; + ParamMsgContent *valueContent = GetNextContent(recvMsg, &offset); + PARAM_CHECK(valueContent != NULL, return PARAM_CODE_TIMEOUT, "Invalid msg"); + result = 0; + break; + } + default: + break; + } + return result; +} + +static int ReadMessage(int fd, char *buffer, int timeout) +{ + int ret = 0; + uint32_t diff = 0; + time_t startTime; + (void)time(&startTime); + do { + ssize_t recvLen = recv(fd, (char *)buffer, RECV_BUFFER_MAX, 0); + if (recvLen > 0) { + break; + } + time_t finishTime; + (void)time(&finishTime); + diff = (uint32_t)difftime(finishTime, startTime); + if (diff >= timeout) { + ret = PARAM_CODE_TIMEOUT; + break; + } + if (errno == EAGAIN || errno == EINTR) { + usleep(10*1000); // 10*1000 wait 10ms + continue; + } + } while (1); + PARAM_LOGE("ReadMessage errno %d diff %u timeout %d ret %d", errno, diff, timeout, ret); + return ret; +} + +static int StartRequest(int *fd, ParamMessage *request, int timeout) +{ + int ret = 0; + struct timeval time; +#ifndef STARTUP_INIT_TEST + time.tv_sec = timeout; +#else + time.tv_sec = 1; +#endif + time.tv_usec = 0; + int clientFd = *fd; + if (clientFd == INVALID_SOCKET) { + clientFd = socket(AF_UNIX, SOCK_STREAM, 0); + PARAM_CHECK(clientFd >= 0, return PARAM_CODE_FAIL_CONNECT, "Failed to create socket"); + ret = ConntectServer(clientFd, CLIENT_PIPE_NAME); + PARAM_CHECK(ret == 0, close(clientFd); + return PARAM_CODE_FAIL_CONNECT, "Failed to connect server"); + setsockopt(clientFd, SOL_SOCKET, SO_SNDTIMEO, (char *)&time, sizeof(struct timeval)); + setsockopt(clientFd, SOL_SOCKET, SO_RCVTIMEO, (char *)&time, sizeof(struct timeval)); + *fd = clientFd; + } + + ssize_t sendLen = send(clientFd, (char *)request, request->msgSize, 0); + PARAM_CHECK(sendLen >= 0, return PARAM_CODE_FAIL_CONNECT, "Failed to send message"); + PARAM_LOGV("sendMessage sendLen %zd", sendLen); + ret = ReadMessage(clientFd, (char *)request, timeout); + if (ret == 0) { + ret = ProcessRecvMsg(request); + } + return ret; +} + +int SystemSetParameter(const char *name, const char *value) +{ + (void)InitParamClient(); + PARAM_CHECK(name != NULL && value != NULL, return -1, "Invalid name or value"); + int ctrlService = 0; + int ret = CheckParameterSet(name, value, GetParamSecurityLabel(), &ctrlService); + PARAM_CHECK(ret == 0, return ret, "Forbid to set parameter %s", name); + + size_t msgSize = sizeof(ParamMsgContent); + msgSize = (msgSize < RECV_BUFFER_MAX) ? RECV_BUFFER_MAX : msgSize; + + ParamMessage *request = (ParamMessage *)CreateParamMessage(MSG_SET_PARAM, name, msgSize); + PARAM_CHECK(request != NULL, return -1, "Failed to malloc for connect"); + uint32_t offset = 0; + ret = FillParamMsgContent(request, &offset, PARAM_VALUE, value, strlen(value)); + PARAM_CHECK(ret == 0, free(request); + return -1, "Failed to fill value"); + request->msgSize = offset + sizeof(ParamMessage); + request->id.msgId = atomic_fetch_add(&g_requestId, 1); + + pthread_mutex_lock(&g_clientSpace.mutex); + ret = StartRequest(&g_clientSpace.clientFd, request, DEFAULT_PARAM_SET_TIMEOUT); + pthread_mutex_unlock(&g_clientSpace.mutex); + free(request); + return ret; +} + +int SystemWaitParameter(const char *name, const char *value, int32_t timeout) +{ + InitParamClient(); + PARAM_CHECK(name != NULL, return -1, "Invalid name"); + int ret = CheckParamName(name, 0); + PARAM_CHECK(ret == 0, return ret, "Illegal param name %s", name); + ParamHandle handle = 0; + ret = ReadParamWithCheck(name, DAC_READ, &handle); + if (ret != PARAM_CODE_NOT_FOUND && ret != 0 && ret != PARAM_CODE_NODE_EXIST) { + PARAM_CHECK(ret == 0, return ret, "Forbid to wait parameter %s", name); + } + if (timeout <= 0) { + timeout = DEFAULT_PARAM_WAIT_TIMEOUT; + } + uint32_t msgSize = sizeof(ParamMessage) + sizeof(ParamMsgContent) + sizeof(ParamMsgContent) + sizeof(uint32_t); + msgSize = (msgSize < RECV_BUFFER_MAX) ? RECV_BUFFER_MAX : msgSize; + uint32_t offset = 0; + ParamMessage *request = NULL; + if (value != NULL && strlen(value) > 0) { + msgSize += PARAM_ALIGN(strlen(value) + 1); + request = (ParamMessage *)CreateParamMessage(MSG_WAIT_PARAM, name, msgSize); + PARAM_CHECK(request != NULL, return -1, "Failed to malloc for wait"); + ret = FillParamMsgContent(request, &offset, PARAM_VALUE, value, strlen(value)); + } else { + msgSize += PARAM_ALIGN(1); + request = (ParamMessage *)CreateParamMessage(MSG_WAIT_PARAM, name, msgSize); + PARAM_CHECK(request != NULL, return -1, "Failed to malloc for wait"); + ret = FillParamMsgContent(request, &offset, PARAM_VALUE, "*", 1); + } + PARAM_CHECK(ret == 0, free(request); + return -1, "Failed to fill value"); + ParamMsgContent *content = (ParamMsgContent *)(request->data + offset); + content->type = PARAM_WAIT_TIMEOUT; + content->contentSize = sizeof(uint32_t); + *((uint32_t *)(content->content)) = timeout; + offset += sizeof(ParamMsgContent) + sizeof(uint32_t); + + request->msgSize = offset + sizeof(ParamMessage); + request->id.waitId = atomic_fetch_add(&g_requestId, 1); + int fd = INVALID_SOCKET; + ret = StartRequest(&fd, request, timeout); + if (fd != INVALID_SOCKET) { + close(fd); + } + free(request); + PARAM_LOGI("SystemWaitParameter %s value %s result %d ", name, value, ret); + return ret; +} + +int WatchParamCheck(const char *keyprefix) +{ + (void)InitParamClient(); + PARAM_CHECK(keyprefix != NULL, return PARAM_CODE_INVALID_PARAM, "Invalid keyprefix"); + int ret = CheckParamName(keyprefix, 0); + PARAM_CHECK(ret == 0, return ret, "Illegal param name %s", keyprefix); + ParamHandle handle = 0; + ret = ReadParamWithCheck(keyprefix, DAC_WATCH, &handle); + if (ret != PARAM_CODE_NOT_FOUND && ret != 0 && ret != PARAM_CODE_NODE_EXIST) { + PARAM_CHECK(ret == 0, return ret, "Forbid to watch parameter %s", keyprefix); + } + return 0; +} diff --git a/services/param/linux/param_service.c b/services/param/linux/param_service.c new file mode 100755 index 0000000000000000000000000000000000000000..57842993673efcda63d98c4d8c3c716cf6104119 --- /dev/null +++ b/services/param/linux/param_service.c @@ -0,0 +1,407 @@ +/* + * Copyright (c) 2021 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 +#include +#include + +#include "init_param.h" +#include "init_utils.h" +#include "loop_event.h" +#include "param_manager.h" +#include "param_message.h" +#include "trigger_manager.h" + +static ParamService g_paramService = {}; + +static void OnClose(ParamTaskPtr client) +{ + PARAM_LOGV("OnClose %p", client); + ParamWatcher *watcher = (ParamWatcher *)ParamGetTaskUserData(client); + if (client == g_paramService.watcherTask) { + ClearWatchTrigger(watcher, TRIGGER_PARAM_WATCH); + g_paramService.watcherTask = NULL; + } else { + ClearWatchTrigger(watcher, TRIGGER_PARAM_WAIT); + } +} + +static void TimerCallback(const ParamTaskPtr timer, void *context) +{ + UNUSED(context); + UNUSED(timer); + int ret = CheckWatchTriggerTimeout(); + // no wait node + if (ret == 0 && g_paramService.timer != NULL) { + ParamTaskClose(g_paramService.timer); + g_paramService.timer = NULL; + } +} + +static void CheckAndSendTrigger(uint32_t dataIndex, const char *name, const char *value) +{ + ParamNode *entry = (ParamNode *)GetTrieNode(GetWorkSpace(name), dataIndex); + PARAM_CHECK(entry != NULL, return, "Failed to get data %s ", name); + uint32_t trigger = 1; + if ((atomic_load_explicit(&entry->commitId, memory_order_relaxed) & PARAM_FLAGS_TRIGGED) != PARAM_FLAGS_TRIGGED) { + trigger = (CheckAndMarkTrigger(TRIGGER_PARAM, name) != 0) ? 1 : 0; + } + if (trigger) { + atomic_store_explicit(&entry->commitId, + atomic_load_explicit(&entry->commitId, memory_order_relaxed) | PARAM_FLAGS_TRIGGED, memory_order_release); + // notify event to process trigger + PostParamTrigger(EVENT_TRIGGER_PARAM, name, value); + } + + int wait = 1; + if ((atomic_load_explicit(&entry->commitId, memory_order_relaxed) & PARAM_FLAGS_WAITED) != PARAM_FLAGS_WAITED) { + wait = (CheckAndMarkTrigger(TRIGGER_PARAM_WAIT, name) != 0) ? 1 : 0; + } + if (wait) { + atomic_store_explicit(&entry->commitId, + atomic_load_explicit(&entry->commitId, memory_order_relaxed) | PARAM_FLAGS_WAITED, memory_order_release); + PostParamTrigger(EVENT_TRIGGER_PARAM_WAIT, name, value); + } + PostParamTrigger(EVENT_TRIGGER_PARAM_WATCH, name, value); +} + +static int SendResponseMsg(ParamTaskPtr worker, const ParamMessage *msg, int result) +{ + ParamResponseMessage *response = NULL; + response = (ParamResponseMessage *)CreateParamMessage(msg->type, msg->key, sizeof(ParamResponseMessage)); + PARAM_CHECK(response != NULL, return PARAM_CODE_ERROR, "Failed to alloc memory for response"); + response->msg.id.msgId = msg->id.msgId; + response->result = result; + response->msg.msgSize = sizeof(ParamResponseMessage); + ParamTaskSendMsg(worker, (ParamMessage *)response); + return 0; +} + +static int SendWatcherNotifyMessage(const TriggerExtInfo *extData, const char *content, uint32_t size) +{ + PARAM_CHECK(content != NULL, return -1, "Invalid content"); + PARAM_CHECK(extData != NULL && extData->stream != NULL, return -1, "Invalid extData"); + uint32_t msgSize = sizeof(ParamMessage) + PARAM_ALIGN(strlen(content) + 1); + ParamMessage *msg = (ParamMessage *)CreateParamMessage(MSG_NOTIFY_PARAM, "*", msgSize); + PARAM_CHECK(msg != NULL, return -1, "Failed to create msg "); + + uint32_t offset = 0; + int ret; + char *tmp = strstr(content, "="); + if (tmp != NULL) { + ret = strncpy_s(msg->key, sizeof(msg->key) - 1, content, tmp - content); + PARAM_CHECK(ret == 0, free(msg); + return -1, "Failed to fill value"); + tmp++; + ret = FillParamMsgContent(msg, &offset, PARAM_VALUE, tmp, strlen(tmp)); + PARAM_CHECK(ret == 0, free(msg); + return -1, "Failed to fill value"); + } else if (content != NULL && strlen(content) > 0) { + ret = FillParamMsgContent(msg, &offset, PARAM_VALUE, content, strlen(content)); + PARAM_CHECK(ret == 0, free(msg); + return -1, "Failed to fill value"); + } + + msg->id.msgId = 0; + if (extData->type == TRIGGER_PARAM_WAIT) { + msg->id.msgId = extData->info.waitInfo.waitId; + } else { + msg->id.msgId = extData->info.watchInfo.watchId; + } + msg->msgSize = sizeof(ParamMessage) + offset; + PARAM_LOGV("SendWatcherNotifyMessage cmd %s, id %d msgSize %d para: %s", + (extData->type == TRIGGER_PARAM_WAIT) ? "wait" : "watcher", + msg->id.msgId, msg->msgSize, content); + ParamTaskSendMsg(extData->stream, msg); + return 0; +} + +static int SystemSetParam(const char *name, const char *value, const ParamSecurityLabel *srcLabel) +{ + PARAM_LOGV("SystemWriteParam name %s value: %s", name, value); + int ctrlService = 0; + int ret = CheckParameterSet(name, value, srcLabel, &ctrlService); + PARAM_CHECK(ret == 0, return ret, "Forbit to set parameter %s", name); + + if (ctrlService & PARAM_CTRL_SERVICE) { // ctrl param + PostParamTrigger(EVENT_TRIGGER_PARAM, name, value); + } else { + uint32_t dataIndex = 0; + ret = WriteParam(name, value, &dataIndex, 0); + PARAM_CHECK(ret == 0, return ret, "Failed to set param %d name %s %s", ret, name, value); + ret = WritePersistParam(name, value); + PARAM_CHECK(ret == 0, return ret, "Failed to set persist param name %s", name); + CheckAndSendTrigger(dataIndex, name, value); + } + return ret; +} + +static int HandleParamSet(const ParamTaskPtr worker, const ParamMessage *msg) +{ + uint32_t offset = 0; + ParamMsgContent *valueContent = GetNextContent(msg, &offset); + PARAM_CHECK(valueContent != NULL, return -1, "Invalid msg for %s", msg->key); + ParamSecurityLabel srcLabel = {0}; + struct ucred cr = {-1, -1, -1}; + socklen_t crSize = sizeof(cr); + if (getsockopt(LE_GetSocketFd(worker), SOL_SOCKET, SO_PEERCRED, &cr, &crSize) < 0) { + PARAM_LOGE("Failed to get opt %d", errno); + return SendResponseMsg(worker, msg, -1); + } + srcLabel.cred.uid = cr.uid; + srcLabel.cred.pid = cr.pid; + srcLabel.cred.gid = cr.gid; + int ret = SystemSetParam(msg->key, valueContent->content, &srcLabel); + return SendResponseMsg(worker, msg, ret); +} + +static int32_t AddWatchNode(struct tagTriggerNode_ *trigger, const struct TriggerExtInfo_ *extInfo) +{ + ParamWatcher *watcher = NULL; + if (extInfo != NULL && extInfo->stream != NULL) { + watcher = (ParamWatcher *)ParamGetTaskUserData(extInfo->stream); + } + PARAM_CHECK(watcher != NULL, return -1, "Failed to get param watcher data"); + if (extInfo->type == TRIGGER_PARAM_WAIT) { + WaitNode *node = (WaitNode *)trigger; + ListInit(&node->item); + node->timeout = extInfo->info.waitInfo.timeout; + node->stream = extInfo->stream; + node->waitId = extInfo->info.waitInfo.waitId; + ListAddTail(&watcher->triggerHead, &node->item); + } else { + WatchNode *node = (WatchNode *)trigger; + ListInit(&node->item); + node->watchId = extInfo->info.watchInfo.watchId; + ListAddTail(&watcher->triggerHead, &node->item); + } + return 0; +} + +static TriggerNode *AddWatcherTrigger(int triggerType, const char *condition, const TriggerExtInfo *extData) +{ + TriggerWorkSpace *workSpace = GetTriggerWorkSpace(); + TriggerHeader *header = (TriggerHeader *)&workSpace->triggerHead[extData->type]; + return header->addTrigger(workSpace, condition, extData); +} + +static int32_t ExecuteWatchTrigger_(const struct tagTriggerNode_ *trigger, const char *content, uint32_t size) +{ + TriggerExtInfo extData = {}; + extData.type = trigger->type; + if (trigger->type == TRIGGER_PARAM_WAIT) { + WaitNode *node = (WaitNode *)trigger; + extData.stream = node->stream; + extData.info.waitInfo.waitId = node->waitId; + extData.info.waitInfo.timeout = node->timeout; + } else { + WatchNode *node = (WatchNode *)trigger; + extData.stream = g_paramService.watcherTask; + extData.info.watchInfo.watchId = node->watchId; + } + if (content == NULL) { + return SendWatcherNotifyMessage(&extData, "", 0); + } + return SendWatcherNotifyMessage(&extData, content, size); +} + +static int HandleParamWaitAdd(const ParamTaskPtr worker, const ParamMessage *msg) +{ + PARAM_CHECK(msg != NULL, return -1, "Invalid message"); + uint32_t offset = 0; + uint32_t timeout = DEFAULT_PARAM_WAIT_TIMEOUT; + ParamMsgContent *valueContent = GetNextContent(msg, &offset); + PARAM_CHECK(valueContent != NULL, return -1, "Invalid msg"); + PARAM_CHECK(valueContent->contentSize <= PARAM_CONST_VALUE_LEN_MAX, return -1, "Invalid msg"); + ParamMsgContent *timeoutContent = GetNextContent(msg, &offset); + if (timeoutContent != NULL) { + timeout = *((uint32_t *)(timeoutContent->content)); + } + + PARAM_LOGV("HandleParamWaitAdd name %s timeout %d", msg->key, timeout); + TriggerExtInfo extData = {}; + extData.addNode = AddWatchNode; + extData.type = TRIGGER_PARAM_WAIT; + extData.stream = worker; + extData.info.waitInfo.waitId = msg->id.watcherId; + extData.info.waitInfo.timeout = timeout; + // first check match, if match send response to client + ParamNode *param = SystemCheckMatchParamWait(msg->key, valueContent->content); + if (param != NULL) { + SendWatcherNotifyMessage(&extData, param->data, param->valueLength); + return 0; + } + + uint32_t buffSize = strlen(msg->key) + valueContent->contentSize + 1 + 1; + char *condition = calloc(1, buffSize); + PARAM_CHECK(condition != NULL, return -1, "Failed to create condition for %s", msg->key); + int ret = sprintf_s(condition, buffSize - 1, "%s=%s", msg->key, valueContent->content); + PARAM_CHECK(ret > EOK, free(condition); + return -1, "Failed to copy name for %s", msg->key); + TriggerNode *trigger = AddWatcherTrigger(TRIGGER_PARAM_WAIT, condition, &extData); + PARAM_CHECK(trigger != NULL, free(condition); + return -1, "Failed to add trigger for %s", msg->key); + free(condition); + if (g_paramService.timer == NULL) { + ret = ParamTimerCreate(&g_paramService.timer, TimerCallback, &g_paramService); + PARAM_CHECK(ret == 0, return 0, "Failed to create timer %s", msg->key); + ret = ParamTimerStart(g_paramService.timer, MS_UNIT, (uint64_t)-1); + PARAM_CHECK(ret == 0, + ParamTaskClose(g_paramService.timer); + g_paramService.timer = NULL; + return 0, "Failed to set timer %s", msg->key); + PARAM_LOGI("Start timer %p", g_paramService.timer); + } + return 0; +} + +static int HandleParamWatcherAdd(const ParamTaskPtr worker, const ParamMessage *msg) +{ + PARAM_CHECK(msg != NULL, return -1, "Invalid message"); + PARAM_CHECK((g_paramService.watcherTask == NULL) || + (g_paramService.watcherTask == worker), return -1, "Invalid watcher worker"); + g_paramService.watcherTask = worker; + TriggerExtInfo extData = {}; + extData.type = TRIGGER_PARAM_WATCH; + extData.addNode = AddWatchNode; + extData.stream = worker; + extData.info.watchInfo.watchId = msg->id.watcherId; + TriggerNode *trigger = AddWatcherTrigger(TRIGGER_PARAM_WATCH, msg->key, &extData); + if (trigger == NULL) { + PARAM_LOGE("Failed to add trigger for %s", msg->key); + return SendResponseMsg(worker, msg, -1); + } + PARAM_LOGV("HandleParamWatcherAdd name %s watcher: %d", msg->key, msg->id.watcherId); + return SendResponseMsg(worker, msg, 0); +} + +static int HandleParamWatcherDel(const ParamTaskPtr worker, const ParamMessage *msg) +{ + PARAM_CHECK(msg != NULL, return -1, "Invalid message"); + PARAM_LOGV("HandleParamWatcherDel name %s watcher: %d", msg->key, msg->id.watcherId); + DelWatchTrigger(TRIGGER_PARAM_WATCH, (const void *)&msg->id.watcherId); + return SendResponseMsg(worker, msg, 0); +} + +PARAM_STATIC int ProcessMessage(const ParamTaskPtr worker, const ParamMessage *msg) +{ + PARAM_CHECK((msg != NULL) && (msg->msgSize >= sizeof(ParamMessage)), return -1, "Invalid msg"); + PARAM_CHECK(worker != NULL, return -1, "Invalid worker"); + int ret = PARAM_CODE_INVALID_PARAM; + switch (msg->type) { + case MSG_SET_PARAM: + ret = HandleParamSet(worker, msg); + break; + case MSG_WAIT_PARAM: + ret = HandleParamWaitAdd(worker, msg); + break; + case MSG_ADD_WATCHER: + ret = HandleParamWatcherAdd(worker, msg); + break; + case MSG_DEL_WATCHER: + ret = HandleParamWatcherDel(worker, msg); + break; + default: + break; + } + PARAM_CHECK(ret == 0, return -1, "Failed to process message ret %d", ret); + return 0; +} + +PARAM_STATIC int OnIncomingConnect(LoopHandle loop, TaskHandle server) +{ + ParamStreamInfo info = {}; + info.server = NULL; + info.close = OnClose; + info.recvMessage = ProcessMessage; + info.incomingConnect = NULL; + ParamTaskPtr client = NULL; + int ret = ParamStreamCreate(&client, server, &info, sizeof(ParamWatcher)); + PARAM_CHECK(ret == 0, return -1, "Failed to create client"); + + ParamWatcher *watcher = (ParamWatcher *)ParamGetTaskUserData(client); + PARAM_CHECK(watcher != NULL, return -1, "Failed to get watcher"); + ListInit(&watcher->triggerHead); + watcher->stream = client; +#ifdef STARTUP_INIT_TEST + g_paramService.watcherTask = client; +#endif + return 0; +} + +void InitParamService(void) +{ + PARAM_LOGI("InitParamService pipe: %s.", PIPE_NAME); + CheckAndCreateDir(PIPE_NAME); + // param space + int ret = InitParamWorkSpace(0); + PARAM_CHECK(ret == 0, return, "Init parameter workspace fail"); + ret = InitPersistParamWorkSpace(); + PARAM_CHECK(ret == 0, return, "Init persist parameter workspace fail"); + // param server + if (g_paramService.serverTask == NULL) { + ParamStreamInfo info = {}; + info.server = PIPE_NAME; + info.close = NULL; + info.recvMessage = NULL; + info.incomingConnect = OnIncomingConnect; + ret = ParamServerCreate(&g_paramService.serverTask, &info); + PARAM_CHECK(ret == 0, return, "Failed to create server"); + } + // init trigger space + ret = InitTriggerWorkSpace(); + PARAM_CHECK(ret == 0, return, "Failed to init trigger"); + RegisterTriggerExec(TRIGGER_PARAM_WAIT, ExecuteWatchTrigger_); + RegisterTriggerExec(TRIGGER_PARAM_WATCH, ExecuteWatchTrigger_); + // read selinux label + LoadSelinuxLabel(); + // from cmdline + LoadParamFromCmdLine(); +} + +int StartParamService(void) +{ + return ParamServiceStart(); +} + +void StopParamService(void) +{ + PARAM_LOGI("StopParamService."); + ClosePersistParamWorkSpace(); + CloseParamWorkSpace(); + CloseTriggerWorkSpace(); + ParamTaskClose(g_paramService.serverTask); + g_paramService.serverTask = NULL; + ParamServiceStop(); +} + +int SystemWriteParam(const char *name, const char *value) +{ + return SystemSetParam(name, value, GetParamSecurityLabel()); +} + +#ifdef STARTUP_INIT_TEST +ParamService *GetParamService() +{ + return &g_paramService; +} +#endif \ No newline at end of file diff --git a/services/param/liteos/param_client.c b/services/param/liteos/param_client.c new file mode 100755 index 0000000000000000000000000000000000000000..00067c4a74b9f4186dfbd196265632a04fb2420d --- /dev/null +++ b/services/param/liteos/param_client.c @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2021 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 "init_param.h" +#include "param_manager.h" +#ifdef PARAM_LOAD_CFG_FROM_CODE +#include "param_cfg.h" +#endif + +#define MIN_SLEEP (100 * 1000) +static ClientWorkSpace g_clientSpace = {}; +__attribute__((constructor)) static void ClientInit(void); +__attribute__((destructor)) static void ClientDeinit(void); + +static int InitParamClient(void) +{ + if (getpid() == 1) { + PARAM_LOGI("Init process, do not init client"); + return 0; + } + if (PARAM_TEST_FLAG(g_clientSpace.flags, WORKSPACE_FLAGS_INIT)) { + return 0; + } + PARAM_LOGV("InitParamClient"); + int ret = InitParamWorkSpace(1); + PARAM_CHECK(ret == 0, return -1, "Failed to init param workspace"); + PARAM_SET_FLAG(g_clientSpace.flags, WORKSPACE_FLAGS_INIT); + // init persist to save + InitPersistParamWorkSpace(); +#ifdef PARAM_LOAD_CFG_FROM_CODE + for (size_t i = 0; i < ARRAY_LENGTH(g_paramDefCfgNodes); i++) { + PARAM_LOGI("InitParamClient name %s = %s", g_paramDefCfgNodes[i].name, g_paramDefCfgNodes[i].value); + uint32_t dataIndex = 0; + ret = WriteParam(g_paramDefCfgNodes[i].name, g_paramDefCfgNodes[i].value, &dataIndex, 0); + PARAM_CHECK(ret == 0, continue, "Failed to set param %d name %s %s", + ret, g_paramDefCfgNodes[i].name, g_paramDefCfgNodes[i].value); + } +#endif +#ifdef __LITEOS_M__ + // get persist param + LoadPersistParams(); +#endif + return 0; +} + +void ClientInit(void) +{ + PARAM_LOGV("ClientInit"); +#ifndef STARTUP_INIT_TEST + (void)InitParamClient(); +#endif +} + +void ClientDeinit(void) +{ + if (PARAM_TEST_FLAG(g_clientSpace.flags, WORKSPACE_FLAGS_INIT)) { + CloseParamWorkSpace(); + } + PARAM_SET_FLAG(g_clientSpace.flags, 0); +} + +int SystemSetParameter(const char *name, const char *value) +{ + PARAM_CHECK(name != NULL && value != NULL, return -1, "Invalid name or value %s", name); + InitParamClient(); + int ctrlService = 0; + int ret = CheckParameterSet(name, value, GetParamSecurityLabel(), &ctrlService); + PARAM_CHECK(ret == 0, return ret, "Forbit to set parameter %s", name); + PARAM_LOGV("SystemSetParameter name %s value: %s ctrlService %d", name, value, ctrlService); + if ((ctrlService & PARAM_CTRL_SERVICE) != PARAM_CTRL_SERVICE) { // ctrl param + uint32_t dataIndex = 0; + ret = WriteParam(name, value, &dataIndex, 0); + PARAM_CHECK(ret == 0, return ret, "Failed to set param %d name %s %s", ret, name, value); + ret = WritePersistParam(name, value); + PARAM_CHECK(ret == 0, return ret, "Failed to set persist param name %s", name); + } else { + PARAM_LOGE("SystemSetParameter can not support service ctrl parameter name %s", name); + } + return ret; +} + +int SystemWaitParameter(const char *name, const char *value, int32_t timeout) +{ + PARAM_CHECK(name != NULL && value != NULL, return -1, "Invalid name or value %s", name); + long long globalCommit = 0; + // first check permission + ParamHandle handle = 0; + int ret = ReadParamWithCheck(name, DAC_READ, &handle); + if (ret != PARAM_CODE_NOT_FOUND && ret != 0 && ret != PARAM_CODE_NODE_EXIST) { + PARAM_CHECK(ret == 0, return ret, "Forbid to wait parameters %s", name); + } + uint32_t diff = 0; + time_t startTime; + if (timeout <= 0) { + timeout = DEFAULT_PARAM_WAIT_TIMEOUT; + } + (void)time(&startTime); + do { + long long commit = GetSystemCommitId(); + if (commit != globalCommit) { + ParamNode *param = SystemCheckMatchParamWait(name, value); + if (param != NULL) { + ret = 0; + break; + } + } + globalCommit = commit; + + usleep(MIN_SLEEP); + time_t finishTime; + (void)time(&finishTime); + diff = (uint32_t)difftime(finishTime, startTime); + if (diff >= timeout) { + ret = PARAM_CODE_TIMEOUT; + break; + } + } while (1); + PARAM_LOGI("SystemWaitParameter name %s value: %s diff %d timeout %d", name, value, diff, diff); + return ret; +} + +int WatchParamCheck(const char *keyprefix) +{ + return PARAM_CODE_NOT_SUPPORT; +} \ No newline at end of file diff --git a/services/param/liteos/param_osadp.c b/services/param/liteos/param_osadp.c new file mode 100755 index 0000000000000000000000000000000000000000..f00dc12f9fbd2be4a144a82460745e64415c6f2e --- /dev/null +++ b/services/param/liteos/param_osadp.c @@ -0,0 +1,295 @@ +/* + * Copyright (c) 2021 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 "param_osadp.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define NSEC_PER_MSEC 1000000LL +#define MSEC_PER_SEC 1000LL + +static void TimerHandle(union sigval v) +{ + ParamTimer *timer = (ParamTimer *)v.sival_ptr; + PARAM_CHECK(timer != NULL, return, "Invalid timer"); + if (timer->timeProcessor != NULL) { + timer->timeProcessor(timer, timer->context); + } +} + +static void SetTimeSpec(struct timespec *ts, int64_t msec) +{ + ts->tv_sec = msec / MSEC_PER_SEC; // 1000LL ms --> m + ts->tv_nsec = (msec - ts->tv_sec * MSEC_PER_SEC) * NSEC_PER_MSEC; +} + +static int StartTimer(const ParamTimer *paramTimer, int64_t whenMsec, int64_t repeat) +{ + UNUSED(repeat); + struct itimerspec ts; + SetTimeSpec(&ts.it_value, whenMsec); + SetTimeSpec(&ts.it_interval, whenMsec); + int32_t ret = timer_settime(paramTimer->timerId, 0, &ts, NULL); + if (ret < 0) { + PARAM_LOGE("Failed to start timer"); + return -1; + } + return 0; +} + +int ParamTimerCreate(ParamTaskPtr *timer, ProcessTimer process, void *context) +{ + PARAM_CHECK(timer != NULL && process != NULL, return -1, "Invalid timer"); + ParamTimer *paramTimer = malloc(sizeof(ParamTimer)); + PARAM_CHECK(paramTimer != NULL, return -1, "Failed to create timer"); + paramTimer->timeProcessor = process; + paramTimer->context = context; + + struct sigevent evp; + (void)memset_s(&evp, sizeof(evp), 0, sizeof(evp)); + evp.sigev_value.sival_ptr = paramTimer; + evp.sigev_notify = SIGEV_THREAD; + evp.sigev_notify_function = TimerHandle; + int32_t ret = timer_create(CLOCK_REALTIME, &evp, ¶mTimer->timerId); + if (ret < 0) { + PARAM_LOGE("Failed to create timer"); + free(paramTimer); + return -1; + } + *timer = paramTimer; + return 0; +} + +int ParamTimerStart(const ParamTaskPtr timer, uint64_t timeout, uint64_t repeat) +{ + PARAM_CHECK(timer != NULL, return -1, "Invalid timer"); + ParamTimer *paramTimer = (ParamTimer *)timer; + PARAM_LOGE("ParamTimerStart timeout %llu ", timeout); + int32_t ret = StartTimer(paramTimer, timeout, repeat); + if (ret < 0) { + PARAM_LOGE("Failed to start timer"); + return -1; + } + return 0; +} + +void ParamTimerClose(ParamTaskPtr timer) +{ + PARAM_CHECK(timer != NULL, return, "Invalid timer"); + ParamTimer *paramTimer = (ParamTimer *)timer; + timer_delete(paramTimer->timerId); + free(paramTimer); +} + +#ifdef __LITEOS_A__ +void *GetSharedMem(const char *fileName, MemHandle *handle, uint32_t spaceSize, int readOnly) +{ + PARAM_CHECK(fileName != NULL && handle != NULL, return NULL, "Invalid filename or handle"); + int mode = readOnly ? O_RDONLY : O_CREAT | O_RDWR; + void *areaAddr = NULL; + if (!readOnly) { + int fd = open(fileName, mode, S_IRWXU | S_IRWXG | S_IROTH); + PARAM_CHECK(fd >= 0, return NULL, "Open file %s mode %x fail error %d", fileName, mode, errno); + close(fd); + } + key_t key = ftok(fileName, 0x03); // 0x03 flags for shmget + PARAM_CHECK(key != -1, return NULL, "Invalid errno %d key for %s", errno, fileName); + handle->shmid = shmget(key, spaceSize, IPC_CREAT | IPC_EXCL | 0666); // 0666 + if (handle->shmid == -1) { + handle->shmid = shmget(key, spaceSize, 0); // 0666 + } + PARAM_CHECK(handle->shmid != -1, return NULL, "Invalid shmId errno %d for %s", errno, fileName); + areaAddr = (void *)shmat(handle->shmid, NULL, 0); + return areaAddr; +} + +void FreeSharedMem(const MemHandle *handle, void *mem, uint32_t dataSize) +{ + PARAM_CHECK(mem != NULL && handle != NULL, return, "Invalid mem or handle"); + shmdt(mem); + shmctl(handle->shmid, IPC_RMID, NULL); +} + +int ParamRWMutexCreate(ParamRWMutex *lock) +{ + PARAM_CHECK(lock != NULL, return -1, "Invalid lock"); + pthread_rwlockattr_t rwlockatt; + pthread_rwlockattr_init(&rwlockatt); + pthread_rwlockattr_setpshared(&rwlockatt, PTHREAD_PROCESS_SHARED); + pthread_rwlock_init(&lock->rwlock, &rwlockatt); + return 0; +} + +int ParamRWMutexWRLock(ParamRWMutex *lock) +{ + PARAM_CHECK(lock != NULL, return -1, "Invalid lock"); + pthread_rwlock_wrlock(&lock->rwlock); + return 0; +} +int ParamRWMutexRDLock(ParamRWMutex *lock) +{ + PARAM_CHECK(lock != NULL, return -1, "Invalid lock"); + pthread_rwlock_rdlock(&lock->rwlock); + return 0; +} +int ParamRWMutexUnlock(ParamRWMutex *lock) +{ + PARAM_CHECK(lock != NULL, return -1, "Invalid lock"); + pthread_rwlock_unlock(&lock->rwlock); + return 0; +} + +int ParamRWMutexDelete(ParamRWMutex *lock) +{ + PARAM_CHECK(lock != NULL, return -1, "Invalid lock"); + uint32_t ret = pthread_rwlock_destroy(&lock->rwlock); + PARAM_CHECK(ret == 0, return -1, "Failed to mutex lock ret %d", ret); + return 0; +} + +int ParamMutexCeate(ParamMutex *mutex) +{ + PARAM_CHECK(mutex != NULL, return -1, "Invalid mutex"); + pthread_mutexattr_t mutexattr; + pthread_mutexattr_init(&mutexattr); + pthread_mutexattr_setpshared(&mutexattr, PTHREAD_PROCESS_SHARED); + pthread_mutex_init(&mutex->mutex, &mutexattr); + return 0; +} +int ParamMutexPend(ParamMutex *mutex) +{ + PARAM_CHECK(mutex != NULL, return -1, "Invalid mutex"); + if (pthread_mutex_lock(&mutex->mutex) != 0) { + PARAM_LOGE("Failed to batch begin to save param errno %d", errno); + return errno; + } + return 0; +} +int ParamMutexPost(ParamMutex *mutex) +{ + PARAM_CHECK(mutex != NULL, return -1, "Invalid mutex"); + pthread_mutex_unlock(&mutex->mutex); + return 0; +} + +int ParamMutexDelete(ParamMutex *mutex) +{ + PARAM_CHECK(mutex != NULL, return -1, "Invalid lock"); + uint32_t ret = pthread_mutex_destroy(&mutex->mutex); + PARAM_CHECK(ret == 0, return -1, "Failed to mutex lock ret %d", ret); + return 0; +} +#endif + +#ifdef __LITEOS_M__ +void *GetSharedMem(const char *fileName, MemHandle *handle, uint32_t spaceSize, int readOnly) +{ + PARAM_CHECK(spaceSize <= PARAM_WORKSPACE_MAX, return, "Invalid spaceSize %u", spaceSize); + UNUSED(fileName); + UNUSED(handle); + UNUSED(readOnly); + return (void *)malloc(spaceSize); +} + +void FreeSharedMem(const MemHandle *handle, void *mem, uint32_t dataSize) +{ + PARAM_CHECK(mem != NULL && handle != NULL, return, "Invalid mem or handle"); + UNUSED(handle); + UNUSED(dataSize); + free(mem); +} + +int ParamRWMutexCreate(ParamRWMutex *lock) +{ + PARAM_CHECK(lock != NULL, return -1, "Invalid lock"); + uint32_t ret = LOS_MuxCreate(&lock->mutex); + PARAM_CHECK(ret == LOS_OK, return -1, "Failed to init mutex ret %d", ret); + return 0; +} + +int ParamRWMutexWRLock(ParamRWMutex *lock) +{ + PARAM_CHECK(lock != NULL, return -1, "Invalid lock"); + uint32_t ret = LOS_MuxPend(&lock->mutex, LOS_WAIT_FOREVER); + PARAM_CHECK(ret == LOS_OK, return -1, "Failed to mutex lock ret %d", ret); + return 0; +} + +int ParamRWMutexRDLock(ParamRWMutex *lock) +{ + PARAM_CHECK(lock != NULL, return -1, "Invalid lock"); + uint32_t ret = LOS_MuxPend(&lock->mutex, LOS_WAIT_FOREVER); + PARAM_CHECK(ret == LOS_OK, return -1, "Failed to mutex lock ret %d", ret); + return 0; +} + +int ParamRWMutexUnlock(ParamRWMutex *lock) +{ + PARAM_CHECK(lock != NULL, return -1, "Invalid lock"); + uint32_t ret = LOS_MuxPost(&lock->mutex); + PARAM_CHECK(ret == LOS_OK, return -1, "Failed to mutex lock ret %d", ret); + return 0; +} + +int ParamRWMutexDelete(ParamRWMutex *lock) +{ + PARAM_CHECK(lock != NULL, return -1, "Invalid lock"); + uint32_t ret = LOS_MuxDelete(&lock->mutex); + PARAM_CHECK(ret == LOS_OK, return -1, "Failed to mutex lock ret %d", ret); + return 0; +} + +int ParamMutexCeate(ParamMutex *mutex) +{ + PARAM_CHECK(mutex != NULL, return -1, "Invalid lock"); + uint32_t ret = LOS_MuxCreate(&mutex->mutex); + PARAM_CHECK(ret == LOS_OK, return -1, "Failed to init mutex ret %d", ret); + return 0; +} + +int ParamMutexPend(ParamMutex *mutex) +{ + PARAM_CHECK(mutex != NULL, return -1, "Invalid lock"); + uint32_t ret = LOS_MuxPend(&mutex->mutex, LOS_WAIT_FOREVER); + PARAM_CHECK(ret == LOS_OK, return -1, "Failed to mutex lock ret %d", ret); + return 0; +} + +int ParamMutexPost(ParamMutex *mutex) +{ + PARAM_CHECK(mutex != NULL, return -1, "Invalid lock"); + uint32_t ret = LOS_MuxPost(&mutex->mutex); + PARAM_CHECK(ret == LOS_OK, return -1, "Failed to mutex lock ret %d", ret); + return 0; +} + +int ParamMutexDelete(ParamMutex *mutex) +{ + PARAM_CHECK(mutex != NULL, return -1, "Invalid mutex"); + uint32_t ret = LOS_MuxDelete(&mutex->mutex); + PARAM_CHECK(ret == LOS_OK, return -1, "Failed to delete mutex lock ret %d", ret); + return 0; +} +#endif diff --git a/services/param/liteos/param_service.c b/services/param/liteos/param_service.c new file mode 100755 index 0000000000000000000000000000000000000000..0025ee61693f12f1d6ac4aac81ba1a2b26fc1005 --- /dev/null +++ b/services/param/liteos/param_service.c @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2021 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 "init_param.h" +#include "init_utils.h" +#include "param_manager.h" + +void InitParamService(void) +{ + PARAM_LOGI("InitParamService"); + // param space + int ret = InitParamWorkSpace(0); + PARAM_CHECK(ret == 0, return, "Init parameter workspace fail"); + ret = InitPersistParamWorkSpace(); + PARAM_CHECK(ret == 0, return, "Init persist parameter workspace fail"); + // read cmd to param + LoadParamFromCmdLine(); +} + +int StartParamService(void) +{ + return 0; +} + +void StopParamService(void) +{ + PARAM_LOGI("StopParamService."); + ClosePersistParamWorkSpace(); + CloseParamWorkSpace(); +} + +int SystemWriteParam(const char *name, const char *value) +{ + int ctrlService = 0; + int ret = CheckParameterSet(name, value, GetParamSecurityLabel(), &ctrlService); + PARAM_CHECK(ret == 0, return ret, "Forbit to set parameter %s", name); + PARAM_LOGV("SystemWriteParam name %s value: %s ctrlService %d", name, value, ctrlService); + if ((ctrlService & PARAM_CTRL_SERVICE) != PARAM_CTRL_SERVICE) { // ctrl param + uint32_t dataIndex = 0; + ret = WriteParam(name, value, &dataIndex, 0); + PARAM_CHECK(ret == 0, return ret, "Failed to set param %d name %s %s", ret, name, value); + ret = WritePersistParam(name, value); + PARAM_CHECK(ret == 0, return ret, "Failed to set persist param name %s", name); + } else { + PARAM_LOGE("SystemWriteParam can not support service ctrl parameter name %s", name); + } + return ret; +} diff --git a/services/param/manager/param_manager.c b/services/param/manager/param_manager.c index 0a7238a5bb2f5fdae1b0bf229478ed986807d091..684fcf90cf7eb79fab6e60a67f5325a2b9508cad 100644 --- a/services/param/manager/param_manager.c +++ b/services/param/manager/param_manager.c @@ -16,76 +16,172 @@ #include "param_manager.h" #include -#include -#ifdef WITH_SELINUX -#include "selinux_parameter.h" -#endif +#include -#if !defined PARAM_SUPPORT_SELINUX && !defined PARAM_SUPPORT_DAC -static ParamSecurityLabel g_defaultSecurityLabel; -#endif +#include "param_trie.h" -static int GetParamSecurityOps(ParamWorkSpace *workSpace, int isInit) +static ParamWorkSpace g_paramWorkSpace = {}; + +static int WorkSpaceNodeCompare(const HashNode *node1, const HashNode *node2) { - UNUSED(isInit); -#if (defined PARAM_SUPPORT_SELINUX || defined PARAM_SUPPORT_DAC) - int ret = RegisterSecurityOps(&workSpace->paramSecurityOps, isInit); - PARAM_CHECK(workSpace->paramSecurityOps.securityInitLabel != NULL, return -1, "Invalid securityInitLabel"); - ret = workSpace->paramSecurityOps.securityInitLabel(&workSpace->securityLabel, isInit); - PARAM_CHECK(ret == 0, return PARAM_CODE_INVALID_NAME, "Failed to init security"); -#else - workSpace->securityLabel = &g_defaultSecurityLabel; - workSpace->securityLabel->flags |= LABEL_ALL_PERMISSION; -#endif - return 0; + WorkSpace *workSpace1 = HASHMAP_ENTRY(node1, WorkSpace, hashNode); + WorkSpace *workSpace2 = HASHMAP_ENTRY(node2, WorkSpace, hashNode); + return strcmp(workSpace1->fileName, workSpace2->fileName); } -int InitParamWorkSpace(ParamWorkSpace *workSpace, int onlyRead) +static int WorkSpaceKeyCompare(const HashNode *node1, const void *key) { - PARAM_CHECK(workSpace != NULL, return PARAM_CODE_INVALID_NAME, "Invalid param"); - if (PARAM_TEST_FLAG(workSpace->flags, WORKSPACE_FLAGS_INIT)) { - return 0; + WorkSpace *workSpace1 = HASHMAP_ENTRY(node1, WorkSpace, hashNode); + return strcmp(workSpace1->fileName, (char *)key); +} + +static int GenerateKeyHasCode(const char *buff, uint32_t len) +{ + int code = 0; + for (size_t i = 0; i < len; i++) { + code += buff[i] - 'A'; + } + return code; +} + +static int WorkSpaceGetNodeHasCode(const HashNode *node) +{ + WorkSpace *workSpace = HASHMAP_ENTRY(node, WorkSpace, hashNode); + size_t nameLen = strlen(workSpace->fileName); + return GenerateKeyHasCode(workSpace->fileName, nameLen); +} + +static int WorkSpaceGetKeyHasCode(const void *key) +{ + const char *buff = (char *)key; + return GenerateKeyHasCode(buff, strlen(buff)); +} + +static void WorkSpaceFree(const HashNode *node) +{ + WorkSpace *workSpace = HASHMAP_ENTRY(node, WorkSpace, hashNode); + CloseWorkSpace(workSpace); +} + +static ParamHandle GetParamHandle(const WorkSpace *workSpace, uint32_t index, const char *name) +{ + PARAM_CHECK(workSpace != NULL && workSpace->area != NULL, return -1, "Invalid param"); + uint32_t hashCode = (uint32_t)GenerateKeyHasCode(workSpace->fileName, strlen(workSpace->fileName)); + uint32_t handle = (hashCode % HASH_BUTT) << 24; // 24 left shift + handle = handle | (index + workSpace->area->startIndex); + PARAM_LOGV("GetParamHandle handle 0x%x index %u, name %s space %p", handle, index, name, workSpace); + return handle; +} + +static int InitParamSecurity(ParamWorkSpace *workSpace, + RegisterSecurityOpsPtr registerOps, ParamSecurityType type, int isInit, int op) +{ + PARAM_CHECK(workSpace != NULL && type < PARAM_SECURITY_MAX, return -1, "Invalid param"); + int ret = 0; + if (registerOps != NULL) { + ret = registerOps(&workSpace->paramSecurityOps[type], isInit); + PARAM_CHECK(workSpace->paramSecurityOps[type].securityInitLabel != NULL, + return -1, "Invalid securityInitLabel"); + ret = workSpace->paramSecurityOps[type].securityInitLabel(&workSpace->securityLabel, isInit); + PARAM_CHECK(ret == 0, return PARAM_CODE_INVALID_NAME, "Failed to init security"); } + + ParamSecurityOps *paramSecurityOps = &workSpace->paramSecurityOps[type]; + PARAM_CHECK(paramSecurityOps->securityFreeLabel != NULL, return -1, "Invalid securityFreeLabel"); + PARAM_CHECK(paramSecurityOps->securityCheckFilePermission != NULL, return -1, "Invalid securityCheck"); + PARAM_CHECK(paramSecurityOps->securityCheckParamPermission != NULL, return -1, "Invalid securityCheck"); + if (isInit == LABEL_INIT_FOR_INIT) { + PARAM_CHECK(paramSecurityOps->securityGetLabel != NULL, return -1, "Invalid securityGetLabel"); + } + ret = paramSecurityOps->securityCheckFilePermission(&workSpace->securityLabel, PARAM_STORAGE_PATH, op); + PARAM_CHECK(ret == 0, return PARAM_CODE_INVALID_NAME, "No permission to read file %s", PARAM_STORAGE_PATH); + PARAM_LOGI("InitParamSecurity %s success", paramSecurityOps->name); + return 0; +} + +PARAM_STATIC int RegisterSecurityOps(int onlyRead) +{ int isInit = 0; int op = DAC_READ; if (onlyRead == 0) { isInit = LABEL_INIT_FOR_INIT; op = DAC_WRITE; } - int ret = GetParamSecurityOps(workSpace, isInit); + int ret = InitParamSecurity(&g_paramWorkSpace, RegisterSecurityDacOps, PARAM_SECURITY_DAC, isInit, op); PARAM_CHECK(ret == 0, return -1, "Failed to get security operations"); - ParamSecurityOps *paramSecurityOps = &workSpace->paramSecurityOps; - if (!LABEL_IS_ALL_PERMITTED(workSpace->securityLabel)) { - PARAM_CHECK(paramSecurityOps->securityFreeLabel != NULL, return -1, "Invalid securityFreeLabel"); - PARAM_CHECK(paramSecurityOps->securityCheckFilePermission != NULL, return -1, "Invalid securityCheck"); - PARAM_CHECK(paramSecurityOps->securityCheckParamPermission != NULL, return -1, "Invalid securityCheck"); - if (isInit == LABEL_INIT_FOR_INIT) { - PARAM_CHECK(paramSecurityOps->securityGetLabel != NULL, return -1, "Invalid securityGetLabel"); - PARAM_CHECK(paramSecurityOps->securityDecodeLabel != NULL, return -1, "Invalid securityDecodeLabel"); - } else { - PARAM_CHECK(paramSecurityOps->securityEncodeLabel != NULL, return -1, "Invalid securityEncodeLabel"); - } - ret = paramSecurityOps->securityCheckFilePermission(workSpace->securityLabel, PARAM_STORAGE_PATH, op); - PARAM_CHECK(ret == 0, return PARAM_CODE_INVALID_NAME, "No permission to read file %s", PARAM_STORAGE_PATH); +#ifdef PARAM_SUPPORT_SELINUX + ret = InitParamSecurity(&g_paramWorkSpace, RegisterSecuritySelinuxOps, PARAM_SECURITY_SELINUX, isInit, op); + PARAM_CHECK(ret == 0, return -1, "Failed to get security operations"); +#endif + return ret; +} + +int InitParamWorkSpace(int onlyRead) +{ + if (PARAM_TEST_FLAG(g_paramWorkSpace.flags, WORKSPACE_FLAGS_INIT)) { + return 0; } - if (onlyRead) { - ret = InitWorkSpace(CLIENT_PARAM_STORAGE_PATH, &workSpace->paramSpace, onlyRead); - } else { - ret = InitWorkSpace(PARAM_STORAGE_PATH, &workSpace->paramSpace, onlyRead); + g_paramWorkSpace.securityLabel.cred.pid = getpid(); + g_paramWorkSpace.securityLabel.cred.uid = geteuid(); + g_paramWorkSpace.securityLabel.cred.gid = getegid(); + + HashInfo info = { + WorkSpaceNodeCompare, + WorkSpaceKeyCompare, + WorkSpaceGetNodeHasCode, + WorkSpaceGetKeyHasCode, + WorkSpaceFree, + HASH_BUTT + }; + int ret = HashMapCreate(&g_paramWorkSpace.workSpaceHashHandle, &info); + PARAM_CHECK(ret == 0, return -1, "Failed to create hash map for workspace"); + WORKSPACE_INIT_LOCK(g_paramWorkSpace); + ListInit(&g_paramWorkSpace.workSpaceList); + + ret = RegisterSecurityOps(onlyRead); + PARAM_CHECK(ret == 0, return -1, "Failed to get security operations"); + PARAM_SET_FLAG(g_paramWorkSpace.flags, WORKSPACE_FLAGS_INIT); + +#ifndef PARAM_SUPPORT_SELINUX + ret = AddWorkSpace(WORKSPACE_NAME_NORMAL, onlyRead, PARAM_WORKSPACE_MAX); + PARAM_CHECK(ret == 0, return -1, "Failed to add dac workspace"); +#endif + // add dac workspace + ret = AddWorkSpace(WORKSPACE_NAME_DAC, onlyRead, PARAM_WORKSPACE_SMALL); + PARAM_CHECK(ret == 0, return -1, "Failed to add dac workspace"); + if (onlyRead == 0) { + // load user info for dac + LoadGroupUser(); + // add default dac policy + ParamAuditData auditData = {}; + auditData.name = "#"; + auditData.dacData.gid = 0; // for root + auditData.dacData.uid = 0; // for root + auditData.dacData.mode = DAC_DEFAULT_MODE; // 0774 default mode + ret = AddSecurityLabel(&auditData); + PARAM_CHECK(ret == 0, return ret, "Failed to add default dac label"); } - PARAM_CHECK(ret == 0, return PARAM_CODE_INVALID_NAME, "Failed to init workspace"); - PARAM_SET_FLAG(workSpace->flags, WORKSPACE_FLAGS_INIT); return ret; } -void CloseParamWorkSpace(ParamWorkSpace *workSpace) +void CloseParamWorkSpace(void) { - PARAM_CHECK(workSpace != NULL, return, "Invalid workSpace"); - CloseWorkSpace(&workSpace->paramSpace); - if (workSpace->paramSecurityOps.securityFreeLabel != NULL) { - workSpace->paramSecurityOps.securityFreeLabel(workSpace->securityLabel); + PARAM_LOGI("CloseParamWorkSpace"); + WORKSPACE_RW_LOCK(g_paramWorkSpace); + if (g_paramWorkSpace.workSpaceHashHandle != NULL) { + HashMapDestory(g_paramWorkSpace.workSpaceHashHandle); + g_paramWorkSpace.workSpaceHashHandle = NULL; + } + WORKSPACE_RW_UNLOCK(g_paramWorkSpace); + for (int i = 0; i < PARAM_SECURITY_MAX; i++) { + if (g_paramWorkSpace.paramSecurityOps[i].securityFreeLabel != NULL) { + g_paramWorkSpace.paramSecurityOps[i].securityFreeLabel(&g_paramWorkSpace.securityLabel); + } } - workSpace->flags = 0; +#ifdef PARAMWORKSPACE_NEED_MUTEX + ParamRWMutexDelete(&g_paramWorkSpace.rwlock); +#endif + g_paramWorkSpace.flags = 0; } static uint32_t ReadCommitId(ParamNode *entry) @@ -98,10 +194,10 @@ static uint32_t ReadCommitId(ParamNode *entry) return commitId & PARAM_FLAGS_COMMITID; } -int ReadParamCommitId(const ParamWorkSpace *workSpace, ParamHandle handle, uint32_t *commitId) +int ReadParamCommitId(ParamHandle handle, uint32_t *commitId) { - PARAM_CHECK(workSpace != NULL && commitId != NULL, return PARAM_CODE_INVALID_PARAM, "Invalid workSpace"); - ParamNode *entry = (ParamNode *)GetTrieNode(&workSpace->paramSpace, handle); + PARAM_WORKSPACE_CHECK(&g_paramWorkSpace, return -1, "Invalid space"); + ParamNode *entry = (ParamNode *)GetTrieNodeByHandle(handle); if (entry == NULL) { return -1; } @@ -109,18 +205,19 @@ int ReadParamCommitId(const ParamWorkSpace *workSpace, ParamHandle handle, uint3 return 0; } -int ReadParamWithCheck(const ParamWorkSpace *workSpace, const char *name, uint32_t op, ParamHandle *handle) +int ReadParamWithCheck(const char *name, uint32_t op, ParamHandle *handle) { + PARAM_WORKSPACE_CHECK(&g_paramWorkSpace, return -1, "Invalid space"); PARAM_CHECK(handle != NULL, return PARAM_CODE_INVALID_PARAM, "Invalid param handle"); - PARAM_CHECK(workSpace != NULL && name != NULL, return PARAM_CODE_INVALID_PARAM, "Invalid param name"); + PARAM_CHECK(name != NULL, return PARAM_CODE_INVALID_PARAM, "Invalid param name"); *handle = -1; -#ifdef READ_CHECK - int ret = CheckParamPermission(workSpace, workSpace->securityLabel, name, op); + int ret = CheckParamPermission(&g_paramWorkSpace.securityLabel, name, op); PARAM_CHECK(ret == 0, return ret, "Forbid to access parameter %s", name); -#endif - ParamTrieNode *node = FindTrieNode(&workSpace->paramSpace, name, strlen(name), NULL); + WorkSpace *space = GetWorkSpace(name); + ParamTrieNode *node = FindTrieNode(space, name, strlen(name), NULL); if (node != NULL && node->dataIndex != 0) { - *handle = node->dataIndex; + *handle = GetParamHandle(space, node->dataIndex, name); + PARAM_LOGV("ReadParamWithCheck %s 0x%x %d", name, *handle, node->dataIndex); return 0; } else if (node != NULL) { return PARAM_CODE_NODE_EXIST; @@ -128,10 +225,11 @@ int ReadParamWithCheck(const ParamWorkSpace *workSpace, const char *name, uint32 return PARAM_CODE_NOT_FOUND; } -int ReadParamValue(const ParamWorkSpace *workSpace, ParamHandle handle, char *value, uint32_t *length) +int ReadParamValue(ParamHandle handle, char *value, uint32_t *length) { - PARAM_CHECK(workSpace != NULL && length != NULL, return PARAM_CODE_INVALID_PARAM, "Invalid param"); - ParamNode *entry = (ParamNode *)GetTrieNode(&workSpace->paramSpace, handle); + PARAM_WORKSPACE_CHECK(&g_paramWorkSpace, return -1, "Invalid space"); + PARAM_CHECK(length != NULL, return PARAM_CODE_INVALID_PARAM, "Invalid param"); + ParamNode *entry = (ParamNode *)GetTrieNodeByHandle(handle); if (entry == NULL) { return -1; } @@ -151,10 +249,11 @@ int ReadParamValue(const ParamWorkSpace *workSpace, ParamHandle handle, char *va return 0; } -int ReadParamName(const ParamWorkSpace *workSpace, ParamHandle handle, char *name, uint32_t length) +int ReadParamName(ParamHandle handle, char *name, uint32_t length) { - PARAM_CHECK(workSpace != NULL && name != NULL, return PARAM_CODE_INVALID_PARAM, "Invalid param"); - ParamNode *entry = (ParamNode *)GetTrieNode(&workSpace->paramSpace, handle); + PARAM_WORKSPACE_CHECK(&g_paramWorkSpace, return -1, "Invalid space"); + PARAM_CHECK(name != NULL, return PARAM_CODE_INVALID_PARAM, "Invalid param"); + ParamNode *entry = (ParamNode *)GetTrieNodeByHandle(handle); if (entry == NULL) { return -1; } @@ -165,7 +264,7 @@ int ReadParamName(const ParamWorkSpace *workSpace, ParamHandle handle, char *nam return 0; } -int CheckParamValue(const WorkSpace *workSpace, const ParamTrieNode *node, const char *name, const char *value) +int CheckParamValue(const ParamTrieNode *node, const char *name, const char *value) { if (IS_READY_ONLY(name)) { PARAM_CHECK(strlen(value) < PARAM_CONST_VALUE_LEN_MAX, @@ -217,9 +316,155 @@ int CheckParamName(const char *name, int info) return 0; } -static int ProcessParamTraversal(const WorkSpace *workSpace, const ParamTrieNode *node, void *cookie) +static int AddParam(WorkSpace *workSpace, const char *name, const char *value, uint32_t *dataIndex) +{ + ParamTrieNode *node = AddTrieNode(workSpace, name, strlen(name)); + PARAM_CHECK(node != NULL, return PARAM_CODE_REACHED_MAX, "Failed to add node"); + ParamNode *entry = (ParamNode *)GetTrieNode(workSpace, node->dataIndex); + if (entry == NULL) { + uint32_t offset = AddParamNode(workSpace, name, strlen(name), value, strlen(value)); + PARAM_CHECK(offset > 0, return PARAM_CODE_REACHED_MAX, "Failed to allocate name %s", name); + SaveIndex(&node->dataIndex, offset); + long long globalCommitId = atomic_load_explicit(&workSpace->area->commitId, memory_order_relaxed); + atomic_store_explicit(&workSpace->area->commitId, ++globalCommitId, memory_order_release); +#ifdef PARAM_SUPPORT_SELINUX + WorkSpace *space = GetWorkSpace(WORKSPACE_NAME_DAC); + if (space != workSpace) { // dac commit is global commit + globalCommitId = atomic_load_explicit(&space->area->commitId, memory_order_relaxed); + atomic_store_explicit(&space->area->commitId, ++globalCommitId, memory_order_release); + } +#endif + } + if (dataIndex != NULL) { + *dataIndex = node->dataIndex; + } + PARAM_LOGV("AddParam name %s value: %s", name, value); + return 0; +} + +static int UpdateParam(const WorkSpace *workSpace, uint32_t *dataIndex, const char *name, const char *value) +{ + ParamNode *entry = (ParamNode *)GetTrieNode(workSpace, *dataIndex); + PARAM_CHECK(entry != NULL, return PARAM_CODE_REACHED_MAX, "Failed to update param value %s %u", name, *dataIndex); + PARAM_CHECK(entry->keyLength == strlen(name), return PARAM_CODE_INVALID_NAME, "Failed to check name len %s", name); + + uint32_t valueLen = strlen(value); + uint32_t commitId = atomic_load_explicit(&entry->commitId, memory_order_relaxed); + atomic_store_explicit(&entry->commitId, commitId | PARAM_FLAGS_MODIFY, memory_order_relaxed); + long long globalCommitId = atomic_load_explicit(&workSpace->area->commitId, memory_order_relaxed); + if (entry->valueLength < PARAM_VALUE_LEN_MAX && valueLen < PARAM_VALUE_LEN_MAX) { + int ret = memcpy_s(entry->data + entry->keyLength + 1, PARAM_VALUE_LEN_MAX, value, valueLen + 1); + PARAM_CHECK(ret == EOK, return PARAM_CODE_INVALID_VALUE, "Failed to copy value"); + entry->valueLength = valueLen; + } + uint32_t flags = commitId & ~PARAM_FLAGS_COMMITID; + atomic_store_explicit(&entry->commitId, (++commitId) | flags, memory_order_release); + atomic_store_explicit(&workSpace->area->commitId, ++globalCommitId, memory_order_release); +#ifdef PARAM_SUPPORT_SELINUX + WorkSpace *space = GetWorkSpace(WORKSPACE_NAME_DAC); + if (space != workSpace) { // dac commit is global commit + globalCommitId = atomic_load_explicit(&space->area->commitId, memory_order_relaxed); + atomic_store_explicit(&space->area->commitId, ++globalCommitId, memory_order_release); + } +#endif + PARAM_LOGV("UpdateParam name %s value: %s", name, value); + futex_wake(&entry->commitId, INT_MAX); + return 0; +} + +int WriteParam(const char *name, const char *value, uint32_t *dataIndex, int mode) +{ + PARAM_WORKSPACE_CHECK(&g_paramWorkSpace, return -1, "Invalid space"); + PARAM_CHECK(value != NULL && name != NULL, return PARAM_CODE_INVALID_PARAM, "Invalid name or value"); + WorkSpace *workSpace = GetWorkSpace(name); + PARAM_CHECK(workSpace != NULL, return PARAM_CODE_INVALID_PARAM, "Invalid workSpace"); + ParamTrieNode *node = FindTrieNode(workSpace, name, strlen(name), NULL); + int ret = 0; + if (node != NULL && node->dataIndex != 0) { + if (dataIndex != NULL) { + *dataIndex = node->dataIndex; + } + if ((mode & LOAD_PARAM_ONLY_ADD) == LOAD_PARAM_ONLY_ADD) { + return PARAM_CODE_READ_ONLY; + } + ret = CheckParamValue(node, name, value); + PARAM_CHECK(ret == 0, return ret, "Invalid param value param: %s=%s", name, value); + PARAMSPACE_AREA_RW_LOCK(workSpace); + ret = UpdateParam(workSpace, &node->dataIndex, name, value); + PARAMSPACE_AREA_RW_UNLOCK(workSpace); + } else { + ret = CheckParamValue(node, name, value); + PARAM_CHECK(ret == 0, return ret, "Invalid param value param: %s=%s", name, value); + PARAMSPACE_AREA_RW_LOCK(workSpace); + ret = AddParam((WorkSpace *)workSpace, name, value, dataIndex); + PARAMSPACE_AREA_RW_UNLOCK(workSpace); + } + return ret; +} + +int AddSecurityLabel(const ParamAuditData *auditData) +{ + PARAM_WORKSPACE_CHECK(&g_paramWorkSpace, return -1, "Invalid space"); + PARAM_CHECK(auditData != NULL && auditData->name != NULL, return -1, "Invalid auditData"); + WorkSpace *workSpace = GetWorkSpace(WORKSPACE_NAME_DAC); + int ret = CheckParamName(auditData->name, 1); + PARAM_CHECK(ret == 0, return ret, "Illegal param name \"%s\"", auditData->name); + + ParamTrieNode *node = FindTrieNode(workSpace, auditData->name, strlen(auditData->name), NULL); + if (node == NULL) { + node = AddTrieNode(workSpace, auditData->name, strlen(auditData->name)); + } + PARAM_CHECK(node != NULL, return PARAM_CODE_REACHED_MAX, "Failed to add node %s", auditData->name); + uint32_t offset = node->labelIndex; + if (node->labelIndex == 0) { // can not support update for label + offset = AddParamSecruityNode(workSpace, auditData); + PARAM_CHECK(offset != 0, return PARAM_CODE_REACHED_MAX, "Failed to add label"); + SaveIndex(&node->labelIndex, offset); + } else { +#ifdef STARTUP_INIT_TEST + ParamSecruityNode *label = (ParamSecruityNode *)GetTrieNode(workSpace, node->labelIndex); + label->mode = auditData->dacData.mode; + label->uid = auditData->dacData.uid; + label->gid = auditData->dacData.gid; +#endif + PARAM_LOGE("Error, repeate to add label for name %s", auditData->name); + } + PARAM_LOGV("AddSecurityLabel label %d gid %d uid %d mode %o name: %s", offset, + auditData->dacData.gid, auditData->dacData.uid, auditData->dacData.mode, auditData->name); + return 0; +} + +ParamNode *SystemCheckMatchParamWait(const char *name, const char *value) +{ + WorkSpace *worksapce = GetWorkSpace(name); + PARAM_CHECK(worksapce != NULL, return NULL, "Failed to get workspace %s", name); + PARAM_LOGV("SystemCheckMatchParamWait name %s", name); + uint32_t nameLength = strlen(name); + ParamTrieNode *node = FindTrieNode(worksapce, name, nameLength, NULL); + if (node == NULL || node->dataIndex == 0) { + return NULL; + } + ParamNode *param = (ParamNode *)GetTrieNode(worksapce, node->dataIndex); + if (param == NULL) { + return NULL; + } + if ((param->keyLength != nameLength) || (strncmp(param->data, name, nameLength) != 0)) { // compare name + return NULL; + } + atomic_store_explicit(¶m->commitId, + atomic_load_explicit(¶m->commitId, memory_order_relaxed) | PARAM_FLAGS_WAITED, memory_order_release); + if ((strncmp(value, "*", 1) == 0) || (strcmp(param->data + nameLength + 1, value) == 0)) { // compare value + return param; + } + char *tmp = strstr(value, "*"); + if (tmp != NULL && (strncmp(param->data + nameLength + 1, value, tmp - value) == 0)) { + return param; + } + return NULL; +} + +static int ProcessParamTraversal(const WorkSpace *workSpace, const ParamTrieNode *node, const void *cookie) { - UNUSED(workSpace); ParamTraversalContext *context = (ParamTraversalContext *)cookie; ParamTrieNode *current = (ParamTrieNode *)node; if (current == NULL) { @@ -232,107 +477,84 @@ static int ProcessParamTraversal(const WorkSpace *workSpace, const ParamTrieNode if (entry == NULL) { return 0; } - if ((strcmp("#", context->prefix) != 0) && - (strncmp(entry->data, context->prefix, strlen(context->prefix)) != 0)) { + if ((strcmp("#", context->prefix) != 0) && (strncmp(entry->data, context->prefix, strlen(context->prefix)) != 0)) { return 0; } - context->traversalParamPtr(current->dataIndex, context->context); + uint32_t index = GetParamHandle(workSpace, current->dataIndex, entry->data); + context->traversalParamPtr(index, context->context); return 0; } -int TraversalParam(const ParamWorkSpace *workSpace, - const char *prefix, TraversalParamPtr walkFunc, void *cookie) +int SystemTraversalParameter(const char *prefix, TraversalParamPtr traversalParameter, void *cookie) { - PARAM_CHECK(workSpace != NULL && walkFunc != NULL, return PARAM_CODE_INVALID_PARAM, "Invalid param"); - ParamTraversalContext context = { - walkFunc, cookie, prefix - }; - ParamTrieNode *root = FindTrieNode(&workSpace->paramSpace, prefix, strlen(prefix), NULL); - PARAM_LOGV("TraversalParam prefix %s", prefix); - return TraversalTrieNode(&workSpace->paramSpace, root, ProcessParamTraversal, &context); -} + PARAM_WORKSPACE_CHECK(&g_paramWorkSpace, return -1, "Invalid space"); + PARAM_CHECK(traversalParameter != NULL, return -1, "The param is null"); -#ifdef WITH_SELINUX -static void *g_selinuxHandle = NULL; -static int CheckParamPermissionWithSelinux(const ParamSecurityLabel *srcLabel, const char *name, uint32_t mode) -{ - static void (*setSelinuxLogCallback)(); - static int (*setParamCheck)(const char *paraName, struct ucred *uc); - if (g_selinuxHandle == NULL) { -#ifdef __aarch64__ - g_selinuxHandle = dlopen("/system/lib64/libparaperm_checker.z.so", RTLD_LAZY); -#else - g_selinuxHandle = dlopen("/system/lib/libparaperm_checker.z.so", RTLD_LAZY); -#endif - if (g_selinuxHandle == NULL) { - PARAM_LOGE("Failed to dlopen libparaperm_checker.z.so, %s\n", dlerror()); - return DAC_RESULT_FORBIDED; + ParamTraversalContext context = {traversalParameter, cookie, "#"}; + if (!(prefix == NULL || strlen(prefix) == 0)) { + ParamHandle handle = 0; + // only check for valid parameter + int ret = ReadParamWithCheck(prefix, DAC_READ, &handle); + if (ret != PARAM_CODE_NOT_FOUND && ret != 0 && ret != PARAM_CODE_NODE_EXIST) { + PARAM_CHECK(ret == 0, return ret, "Forbid to traversal parameters"); } - } - if (setSelinuxLogCallback == NULL) { - setSelinuxLogCallback = (void (*)())dlsym(g_selinuxHandle, "SetSelinuxLogCallback"); - if (setSelinuxLogCallback == NULL) { - PARAM_LOGE("Failed to dlsym setSelinuxLogCallback, %s\n", dlerror()); - return DAC_RESULT_FORBIDED; - } - } - (*setSelinuxLogCallback)(); - - if (setParamCheck == NULL) { - setParamCheck = (int (*)(const char *paraName, struct ucred *uc))dlsym(g_selinuxHandle, "SetParamCheck"); - if (setParamCheck == NULL) { - PARAM_LOGE("Failed to dlsym setParamCheck, %s\n", dlerror()); - return DAC_RESULT_FORBIDED; + context.prefix = (char *)prefix; + } + WorkSpace *workSpace = GetFristWorkSpace(); + if (workSpace != NULL && strcmp(workSpace->fileName, WORKSPACE_NAME_DAC) == 0) { + workSpace = GetNextWorkSpace(workSpace); + } + while (workSpace != NULL) { + PARAM_LOGV("SystemTraversalParameter prefix %s in space %s", context.prefix, workSpace->fileName); + WorkSpace *next = GetNextWorkSpace(workSpace); + ParamTrieNode *root = NULL; + if (prefix != NULL && strlen(prefix) != 0) { + root = FindTrieNode(workSpace, prefix, strlen(prefix), NULL); } + PARAMSPACE_AREA_RD_LOCK(workSpace); + TraversalTrieNode(workSpace, root, ProcessParamTraversal, (const void *)&context); + PARAMSPACE_AREA_RW_UNLOCK(workSpace); + workSpace = next; } - struct ucred uc; - uc.pid = srcLabel->cred.pid; - uc.uid = srcLabel->cred.uid; - uc.gid = srcLabel->cred.gid; - int ret = setParamCheck(name, &uc); - if (ret != 0) { - PARAM_LOGI("Selinux check name %s pid %d uid %d %d result %d", name, uc.pid, uc.uid, uc.gid, ret); - } - return ret; + return 0; } -#endif -int CheckParamPermission(const ParamWorkSpace *workSpace, - const ParamSecurityLabel *srcLabel, const char *name, uint32_t mode) +int CheckParamPermission(const ParamSecurityLabel *srcLabel, const char *name, uint32_t mode) { - PARAM_CHECK(workSpace != NULL && workSpace->securityLabel != NULL, - return PARAM_CODE_INVALID_PARAM, "Invalid param"); - if (LABEL_IS_ALL_PERMITTED(workSpace->securityLabel)) { - return 0; + PARAM_CHECK(srcLabel != NULL, return DAC_RESULT_FORBIDED, "The srcLabel is null"); + PARAM_WORKSPACE_CHECK(&g_paramWorkSpace, return DAC_RESULT_FORBIDED, "Invalid space"); + int ret = DAC_RESULT_PERMISSION; + // for root, all permission + if (srcLabel->cred.uid != 0) { + for (int i = 0; i < PARAM_SECURITY_MAX; i++) { + if (PARAM_TEST_FLAG(g_paramWorkSpace.securityLabel.flags[i], LABEL_ALL_PERMISSION)) { + continue; + } + if (g_paramWorkSpace.paramSecurityOps[i].securityCheckParamPermission == NULL) { + ret = DAC_RESULT_FORBIDED; + continue; + } + ret = g_paramWorkSpace.paramSecurityOps[i].securityCheckParamPermission(srcLabel, name, mode); + PARAM_LOGV("CheckParamPermission %s %s ret %d", g_paramWorkSpace.paramSecurityOps[i].name, name, ret); + if (ret == DAC_RESULT_PERMISSION) { + break; + } + } } - PARAM_CHECK(name != NULL && srcLabel != NULL, return -1, "Invalid param"); -#ifdef WITH_SELINUX - if (mode == DAC_WRITE) { - int ret = CheckParamPermissionWithSelinux(srcLabel, name, mode); - if (ret == DAC_RESULT_PERMISSION) { - PARAM_LOGI("CheckParamPermission %s", name); - return DAC_RESULT_PERMISSION; +#ifdef PARAM_SUPPORT_SELINUX + if (ret == DAC_RESULT_PERMISSION && mode != DAC_WRITE) { // open workspace for client read + const char *label = GetSelinuxContent(name); + if (label != NULL) { + AddWorkSpace(label, 1, PARAM_WORKSPACE_DEF); + } else { + ret = DAC_RESULT_FORBIDED; } } #endif - if (workSpace->paramSecurityOps.securityCheckParamPermission == NULL) { - return DAC_RESULT_FORBIDED; - } - uint32_t labelIndex = 0; - FindTrieNode(&workSpace->paramSpace, name, strlen(name), &labelIndex); - ParamSecruityNode *node = (ParamSecruityNode *)GetTrieNode(&workSpace->paramSpace, labelIndex); - PARAM_CHECK(node != NULL, return DAC_RESULT_FORBIDED, "Can not get security label %d", labelIndex); - - ParamAuditData auditData = {}; - auditData.name = name; - auditData.dacData.uid = node->uid; - auditData.dacData.gid = node->gid; - auditData.dacData.mode = node->mode; - auditData.label = node->data; - return workSpace->paramSecurityOps.securityCheckParamPermission(srcLabel, &auditData, mode); + return ret; } -static int DumpTrieDataNodeTraversal(const WorkSpace *workSpace, const ParamTrieNode *node, void *cookie) +static int DumpTrieDataNodeTraversal(const WorkSpace *workSpace, const ParamTrieNode *node, const void *cookie) { int verbose = *(int *)cookie; ParamTrieNode *current = (ParamTrieNode *)node; @@ -361,33 +583,348 @@ static int DumpTrieDataNodeTraversal(const WorkSpace *workSpace, const ParamTrie return 0; } -static void DumpWorkSpace(const ParamWorkSpace *workSpace, int verbose) +static void HashNodeTraverseForDump(WorkSpace *workSpace, int verbose) { - PARAM_DUMP("workSpace information \n"); - PARAM_DUMP(" map file: %s \n", workSpace->paramSpace.fileName); - if (workSpace->paramSpace.area != NULL) { - PARAM_DUMP(" total size: %d \n", workSpace->paramSpace.area->dataSize); - PARAM_DUMP(" first offset: %d \n", workSpace->paramSpace.area->firstNode); - PARAM_DUMP(" current offset: %d \n", workSpace->paramSpace.area->currOffset); - PARAM_DUMP(" total node: %d \n", workSpace->paramSpace.area->trieNodeCount); - PARAM_DUMP(" total param node: %d \n", workSpace->paramSpace.area->paramNodeCount); - PARAM_DUMP(" total security node: %d\n", workSpace->paramSpace.area->securityNodeCount); + PARAM_DUMP(" map file: %s \n", workSpace->fileName); + if (workSpace->area != NULL) { + PARAM_DUMP(" total size: %d \n", workSpace->area->dataSize); + PARAM_DUMP(" first offset: %d \n", workSpace->area->firstNode); + PARAM_DUMP(" current offset: %d \n", workSpace->area->currOffset); + PARAM_DUMP(" total node: %d \n", workSpace->area->trieNodeCount); + PARAM_DUMP(" total param node: %d \n", workSpace->area->paramNodeCount); + PARAM_DUMP(" total security node: %d\n", workSpace->area->securityNodeCount); } PARAM_DUMP(" node info: \n"); - TraversalTrieNode(&workSpace->paramSpace, NULL, DumpTrieDataNodeTraversal, (void *)&verbose); + PARAMSPACE_AREA_RD_LOCK(workSpace); + TraversalTrieNode(workSpace, NULL, DumpTrieDataNodeTraversal, (const void *)&verbose); + PARAMSPACE_AREA_RW_UNLOCK(workSpace); } -void DumpParameters(const ParamWorkSpace *workSpace, int verbose) +void SystemDumpParameters(int verbose) { - PARAM_CHECK(workSpace != NULL && workSpace->securityLabel != NULL, return, "Invalid param"); + PARAM_WORKSPACE_CHECK(&g_paramWorkSpace, return, "Invalid space"); + // check default dac + ParamHandle handle = 0; + int ret = ReadParamWithCheck("#", DAC_READ, &handle); + if (ret != PARAM_CODE_NOT_FOUND && ret != 0 && ret != PARAM_CODE_NODE_EXIST) { + PARAM_CHECK(ret == 0, return, "Forbid to dump parameters"); + } + PARAM_DUMP("Dump all paramters begin ...\n"); - DumpWorkSpace(workSpace, verbose); if (verbose) { PARAM_DUMP("Local sercurity information\n"); PARAM_DUMP("\t pid: %d uid: %d gid: %d \n", - workSpace->securityLabel->cred.pid, - workSpace->securityLabel->cred.uid, - workSpace->securityLabel->cred.gid); + g_paramWorkSpace.securityLabel.cred.pid, + g_paramWorkSpace.securityLabel.cred.uid, + g_paramWorkSpace.securityLabel.cred.gid); + } + WorkSpace *workSpace = GetFristWorkSpace(); + while (workSpace != NULL) { + WorkSpace *next = GetNextWorkSpace(workSpace); + HashNodeTraverseForDump(workSpace, verbose); + workSpace = next; } PARAM_DUMP("Dump all paramters finish\n"); } + +int AddWorkSpace(const char *name, int onlyRead, uint32_t spaceSize) +{ + int ret = 0; + // check exist +#ifdef PARAM_SUPPORT_SELINUX + const char *realName = name; +#else + const char *realName = WORKSPACE_NAME_NORMAL; +#endif + WORKSPACE_RW_LOCK(g_paramWorkSpace); + HashNode *node = HashMapGet(g_paramWorkSpace.workSpaceHashHandle, (const void *)realName); + if (node != NULL) { + WORKSPACE_RW_UNLOCK(g_paramWorkSpace); + return 0; + } + PARAM_LOGI("AddWorkSpace %s spaceSize: %u onlyRead %s", name, spaceSize, onlyRead ? "true" : "false"); + WorkSpace *workSpace = NULL; + do { + ret = -1; + const size_t size = strlen(realName) + 1; + workSpace = (WorkSpace *)malloc(sizeof(WorkSpace) + size); + PARAM_CHECK(workSpace != NULL, break, "Failed to create workspace for %s", realName); + ListInit(&workSpace->node); + ret = strcpy_s(workSpace->fileName, size, realName); + PARAM_CHECK(ret == 0, break, "Failed to copy file name %s", realName); + HASHMAPInitNode(&workSpace->hashNode); + ret = InitWorkSpace(workSpace, onlyRead, spaceSize); + PARAM_CHECK(ret == 0, break, "Failed to init workspace %s", realName); + ret = HashMapAdd(g_paramWorkSpace.workSpaceHashHandle, &workSpace->hashNode); + PARAM_CHECK(ret == 0, CloseWorkSpace(workSpace); + workSpace = NULL; + break, "Failed to add hash node"); + ListAddTail(&g_paramWorkSpace.workSpaceList, &workSpace->node); + ret = 0; + workSpace = NULL; + } while (0); + if (workSpace != NULL) { + free(workSpace); + } + WORKSPACE_RW_UNLOCK(g_paramWorkSpace); + PARAM_LOGI("AddWorkSpace %s success", name); + return ret; +} + +WorkSpace *GetWorkSpace(const char *name) +{ + PARAM_CHECK(g_paramWorkSpace.workSpaceHashHandle != NULL, return NULL, "Invalid workSpaceHashHandle"); + char *tmpName = (char *)name; +#ifndef PARAM_SUPPORT_SELINUX + tmpName = WORKSPACE_NAME_NORMAL; +#else + if (strcmp(name, WORKSPACE_NAME_DAC) != 0) { + tmpName = (char *)GetSelinuxContent(name); + } +#endif + WorkSpace *space = NULL; + WORKSPACE_RD_LOCK(g_paramWorkSpace); + HashNode *node = HashMapGet(g_paramWorkSpace.workSpaceHashHandle, (const void *)tmpName); + if (node != NULL) { + space = HASHMAP_ENTRY(node, WorkSpace, hashNode); + } + WORKSPACE_RW_UNLOCK(g_paramWorkSpace); + PARAM_LOGV("GetWorkSpace %s space-name %s, space %p", name, tmpName, space); + return (space != NULL && space->area != NULL) ? space : NULL; +} + +static int CompareIndex(const HashNode *node, const void *key) +{ + WorkSpace *workSpace = HASHMAP_ENTRY(node, WorkSpace, hashNode); + if (workSpace == NULL || workSpace->area == NULL) { + return 1; + } + uint32_t index = *(uint32_t *)key; + if (workSpace->area->startIndex <= index && index < (workSpace->area->startIndex + workSpace->area->dataSize)) { + return 0; + } + return 1; +} + +ParamTrieNode *GetTrieNodeByHandle(ParamHandle handle) +{ + PARAM_ONLY_CHECK(handle != (ParamHandle)-1, return NULL); + int hashCode = ((handle >> 24) & 0x000000ff); // 24 left shift + uint32_t index = handle & 0x00ffffff; + WORKSPACE_RD_LOCK(g_paramWorkSpace); + HashNode *node = HashMapFind(g_paramWorkSpace.workSpaceHashHandle, hashCode, (const void *)&index, CompareIndex); + if (node == NULL) { + WORKSPACE_RW_UNLOCK(g_paramWorkSpace); + PARAM_LOGV("Failed to get workspace for 0x%x index %d hashCode %d", handle, index, hashCode); + return NULL; + } + WorkSpace *workSpace = HASHMAP_ENTRY(node, WorkSpace, hashNode); + WORKSPACE_RW_UNLOCK(g_paramWorkSpace); + index = index - workSpace->area->startIndex; + return (ParamTrieNode *)GetTrieNode(workSpace, index); +} + +WorkSpace *GetFristWorkSpace(void) +{ + WorkSpace *workSpace = NULL; + WORKSPACE_RD_LOCK(g_paramWorkSpace); + ListNode *node = g_paramWorkSpace.workSpaceList.next; + if (node != &g_paramWorkSpace.workSpaceList) { + workSpace = HASHMAP_ENTRY(node, WorkSpace, node); + } + WORKSPACE_RW_UNLOCK(g_paramWorkSpace); + return workSpace; +} + +WorkSpace *GetNextWorkSpace(WorkSpace *curr) +{ + PARAM_CHECK(curr != NULL, return NULL, "Invalid curr"); + WorkSpace *workSpace = NULL; + WORKSPACE_RD_LOCK(g_paramWorkSpace); + ListNode *node = curr->node.next; + if (node != &g_paramWorkSpace.workSpaceList) { + workSpace = HASHMAP_ENTRY(node, WorkSpace, node); + } + WORKSPACE_RW_UNLOCK(g_paramWorkSpace); + return workSpace; +} + +int SystemReadParam(const char *name, char *value, unsigned int *len) +{ + PARAM_WORKSPACE_CHECK(&g_paramWorkSpace, return -1, "Invalid space"); + PARAM_CHECK(name != NULL && len != NULL && strlen(name) > 0, return -1, "The name or value is null"); + ParamHandle handle = 0; + int ret = ReadParamWithCheck(name, DAC_READ, &handle); + if (ret != PARAM_CODE_NOT_FOUND && ret != 0 && ret != PARAM_CODE_NODE_EXIST) { + PARAM_CHECK(ret == 0, return ret, "Forbid to get parameter %s", name); + } + return ReadParamValue(handle, value, len); +} + +int SystemFindParameter(const char *name, ParamHandle *handle) +{ + PARAM_WORKSPACE_CHECK(&g_paramWorkSpace, return -1, "Invalid space"); + PARAM_CHECK(name != NULL && handle != NULL, return -1, "The name or handle is null"); + int ret = ReadParamWithCheck(name, DAC_READ, handle); + if (ret != PARAM_CODE_NOT_FOUND && ret != 0 && ret != PARAM_CODE_NODE_EXIST) { + PARAM_CHECK(ret == 0, return ret, "Forbid to access parameter %s", name); + } + return ret; +} + +int SysCheckParamExist(const char *name) +{ + PARAM_WORKSPACE_CHECK(&g_paramWorkSpace, return -1, "Invalid space"); + PARAM_CHECK(name != NULL, return -1, "The name or handle is null"); + ParamHandle handle; + int ret = ReadParamWithCheck(name, DAC_READ, &handle); + PARAM_LOGI("SysCheckParamExist %s result %d", name, ret); + if (ret == PARAM_CODE_NODE_EXIST) { + return 0; + } + PARAM_CHECK(ret == 0, return ret, "Forbid to access parameter %s", name); + return ret; +} + +int SystemGetParameterCommitId(ParamHandle handle, uint32_t *commitId) +{ + PARAM_WORKSPACE_CHECK(&g_paramWorkSpace, return -1, "Invalid space"); + PARAM_CHECK(handle != 0 || commitId != NULL, return -1, "The handle is null"); + return ReadParamCommitId(handle, commitId); +} + +long long GetSystemCommitId(void) +{ + PARAM_WORKSPACE_CHECK(&g_paramWorkSpace, return 0, "Invalid space"); + WorkSpace *space = GetWorkSpace(WORKSPACE_NAME_DAC); + if (space == NULL || space->area == NULL) { + return 0; + } + return atomic_load_explicit(&space->area->commitId, memory_order_acquire); +} + +int SystemGetParameterName(ParamHandle handle, char *name, unsigned int len) +{ + PARAM_WORKSPACE_CHECK(&g_paramWorkSpace, return -1, "Invalid space"); + PARAM_CHECK(name != NULL && handle != 0, return -1, "The name is null"); + return ReadParamName(handle, name, len); +} + +int SystemGetParameterValue(ParamHandle handle, char *value, unsigned int *len) +{ + PARAM_WORKSPACE_CHECK(&g_paramWorkSpace, return -1, "Invalid space"); + PARAM_CHECK(len != NULL && handle != 0, return -1, "The value is null"); + return ReadParamValue(handle, value, len); +} + +int GetParamSecurityAuditData(const char *name, int type, ParamAuditData *auditData) +{ + PARAM_WORKSPACE_CHECK(&g_paramWorkSpace, return -1, "Invalid space"); + uint32_t labelIndex = 0; + // get from dac + WorkSpace *space = GetWorkSpace(WORKSPACE_NAME_DAC); + FindTrieNode(space, name, strlen(name), &labelIndex); + ParamSecruityNode *node = (ParamSecruityNode *)GetTrieNode(space, labelIndex); + PARAM_CHECK(node != NULL, return DAC_RESULT_FORBIDED, "Can not get security label %d", labelIndex); + + auditData->name = name; + auditData->dacData.uid = node->uid; + auditData->dacData.gid = node->gid; + auditData->dacData.mode = node->mode; +#ifdef PARAM_SUPPORT_SELINUX + const char *tmpName = GetSelinuxContent(name); + if (tmpName != NULL) { + int ret = strcpy_s(auditData->label, sizeof(auditData->label), tmpName); + PARAM_CHECK(ret == 0, return 0, "Failed to copy label for %s", name); + } +#endif + return 0; +} + +int CheckParameterSet(const char *name, const char *value, const ParamSecurityLabel *srcLabel, int *ctrlService) +{ + PARAM_WORKSPACE_CHECK(&g_paramWorkSpace, return -1, "Invalid space"); + PARAM_LOGV("CheckParameterSet name %s value: %s", name, value); + PARAM_CHECK(srcLabel != NULL && ctrlService != NULL, return -1, "Invalid param "); + int ret = CheckParamName(name, 0); + PARAM_CHECK(ret == 0, return ret, "Illegal param name %s", name); + ret = CheckParamValue(NULL, name, value); + PARAM_CHECK(ret == 0, return ret, "Illegal param value %s", value); + *ctrlService = 0; + +#ifndef PARAM_SUPPORT_SELINUX + if ((getpid() != 1) && ((srcLabel->flags[0] & LABEL_CHECK_IN_ALL_PROCESS) != LABEL_CHECK_IN_ALL_PROCESS)) { + *ctrlService |= PARAM_NEED_CHECK_IN_SERVICE; +#ifndef STARTUP_INIT_TEST + return 0; +#endif + } +#endif + char *key = GetServiceCtrlName(name, value); + ret = CheckParamPermission(srcLabel, (key == NULL) ? name : key, DAC_WRITE); + if (key != NULL) { // ctrl param + free(key); + *ctrlService |= PARAM_CTRL_SERVICE; + } + return ret; +} + +int LoadSecurityLabel(const char *fileName) +{ + PARAM_WORKSPACE_CHECK(&g_paramWorkSpace, return -1, "Invalid space"); + PARAM_CHECK(fileName != NULL, return -1, "Invalid fielname for load"); +#if !(defined __LITEOS_A__ || defined __LITEOS_M__) + // load security label + ParamSecurityOps *ops = &g_paramWorkSpace.paramSecurityOps[PARAM_SECURITY_DAC]; + if (ops->securityGetLabel != NULL) { + ops->securityGetLabel(fileName); + } +#endif + return 0; +} + +void LoadSelinuxLabel(void) +{ + PARAM_WORKSPACE_CHECK(&g_paramWorkSpace, return, "Invalid space"); + // load security label +#ifdef PARAM_SUPPORT_SELINUX + ParamSecurityOps *ops = &g_paramWorkSpace.paramSecurityOps[PARAM_SECURITY_SELINUX]; + if (ops->securityGetLabel != NULL) { + ops->securityGetLabel(NULL); + } +#endif +} + +ParamSecurityLabel *GetParamSecurityLabel() +{ + return &g_paramWorkSpace.securityLabel; +} + +long long GetPersistCommitId(void) +{ + PARAM_WORKSPACE_CHECK(&g_paramWorkSpace, return -1, "Invalid space"); + WorkSpace *space = GetWorkSpace(WORKSPACE_NAME_DAC); + if (space == NULL || space->area == NULL) { + return 0; + } + return atomic_load_explicit(&space->area->commitPersistId, memory_order_acquire); +} + +void UpdatePersistCommitId(void) +{ + PARAM_WORKSPACE_CHECK(&g_paramWorkSpace, return, "Invalid space"); + WorkSpace *space = GetWorkSpace(WORKSPACE_NAME_DAC); + if (space == NULL || space->area == NULL) { + return; + } + long long globalCommitId = atomic_load_explicit(&space->area->commitPersistId, memory_order_relaxed); + atomic_store_explicit(&space->area->commitPersistId, ++globalCommitId, memory_order_release); +} + +#if defined STARTUP_INIT_TEST || defined LOCAL_TEST +ParamSecurityOps *GetParamSecurityOps(int type) +{ + PARAM_CHECK(type < PARAM_SECURITY_MAX, return NULL, "Invalid type"); + return &g_paramWorkSpace.paramSecurityOps[type]; +} +#endif diff --git a/services/param/manager/param_persist.c b/services/param/manager/param_persist.c new file mode 100755 index 0000000000000000000000000000000000000000..773c97e8a67c82cc4be8eb91f1215ee4e54cfdd6 --- /dev/null +++ b/services/param/manager/param_persist.c @@ -0,0 +1,387 @@ +/* + * Copyright (c) 2021 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 "param_persist.h" + +#include +#include +#include +#include + +#include "init_param.h" +#include "init_utils.h" +#include "param_manager.h" +#include "param_trie.h" + +static ParamPersistWorkSpace g_persistWorkSpace = {0, 0, NULL, 0, {}}; + +static int SavePersistParam(const WorkSpace *workSpace, const ParamTrieNode *node, const void *cookie) +{ + ParamTrieNode *current = (ParamTrieNode *)node; + if (current == NULL || current->dataIndex == 0) { + return 0; + } + ParamNode *entry = (ParamNode *)GetTrieNode(workSpace, current->dataIndex); + if (entry == NULL) { + return 0; + } + if (strncmp(entry->data, PARAM_PERSIST_PREFIX, strlen(PARAM_PERSIST_PREFIX)) != 0) { + return 0; + } + static char name[PARAM_NAME_LEN_MAX] = {0}; + int ret = memcpy_s(name, PARAM_NAME_LEN_MAX - 1, entry->data, entry->keyLength); + PARAM_CHECK(ret == EOK, return -1, "Failed to read param name %s", entry->data); + name[entry->keyLength] = '\0'; + ret = g_persistWorkSpace.persistParamOps.batchSave( + (PERSIST_SAVE_HANDLE)cookie, name, entry->data + entry->keyLength + 1); + PARAM_CHECK(ret == 0, return -1, "Failed to write param %s", current->key); + return ret; +} + +static int BatchSavePersistParam() +{ + PARAM_LOGV("BatchSavePersistParam"); + if (g_persistWorkSpace.persistParamOps.batchSaveBegin == NULL || + g_persistWorkSpace.persistParamOps.batchSave == NULL || + g_persistWorkSpace.persistParamOps.batchSaveEnd == NULL) { + return 0; + } + + PERSIST_SAVE_HANDLE handle; + int ret = g_persistWorkSpace.persistParamOps.batchSaveBegin(&handle); + PARAM_CHECK(ret == 0, return PARAM_CODE_INVALID_NAME, "Failed to save persist"); + // walk and save persist param + WorkSpace *workSpace = GetFristWorkSpace(); + while (workSpace != NULL) { + WorkSpace *next = GetNextWorkSpace(workSpace); + ParamTrieNode *root = FindTrieNode(workSpace, PARAM_PERSIST_PREFIX, strlen(PARAM_PERSIST_PREFIX), NULL); + PARAMSPACE_AREA_RD_LOCK(workSpace); + TraversalTrieNode(workSpace, root, SavePersistParam, (void *)handle); + PARAMSPACE_AREA_RW_UNLOCK(workSpace); + workSpace = next; + } + g_persistWorkSpace.persistParamOps.batchSaveEnd(handle); + PARAM_CHECK(ret == 0, return PARAM_CODE_INVALID_NAME, "Save persist param fail"); + + PARAM_CLEAR_FLAG(g_persistWorkSpace.flags, WORKSPACE_FLAGS_UPDATE); + (void)time(&g_persistWorkSpace.lastSaveTimer); + return ret; +} + +int InitPersistParamWorkSpace() +{ + if (PARAM_TEST_FLAG(g_persistWorkSpace.flags, WORKSPACE_FLAGS_INIT)) { + return 0; + } + (void)time(&g_persistWorkSpace.lastSaveTimer); + RegisterPersistParamOps(&g_persistWorkSpace.persistParamOps); + PARAM_SET_FLAG(g_persistWorkSpace.flags, WORKSPACE_FLAGS_INIT); + return 0; +} + +void ClosePersistParamWorkSpace(void) +{ + if (g_persistWorkSpace.saveTimer != NULL) { + ParamTimerClose(g_persistWorkSpace.saveTimer); + } + g_persistWorkSpace.flags = 0; +} + +PARAM_STATIC void TimerCallbackForSave(const ParamTaskPtr timer, void *context) +{ + UNUSED(context); + UNUSED(timer); + // for liteos,we must cycle check +#ifndef PARAM_SUPPORT_CYCLE_CHECK + ParamTimerClose(g_persistWorkSpace.saveTimer); + g_persistWorkSpace.saveTimer = NULL; + if (!PARAM_TEST_FLAG(g_persistWorkSpace.flags, WORKSPACE_FLAGS_UPDATE)) { + return; + } +#else + // check commit + long long commit = GetPersistCommitId(); + PARAM_LOGV("TimerCallbackForSave commit %lld ", commit); + if (g_persistWorkSpace.commitId == commit) { + return; + } + g_persistWorkSpace.commitId = commit; +#endif + (void)BatchSavePersistParam(); +} + +int WritePersistParam(const char *name, const char *value) +{ + PARAM_CHECK(value != NULL && name != NULL, return PARAM_CODE_INVALID_PARAM, "Invalid param"); + if (strncmp(name, PARAM_PERSIST_PREFIX, strlen(PARAM_PERSIST_PREFIX)) != 0) { + return 0; + } + PARAM_LOGV("WritePersistParam name %s ", name); + if (g_persistWorkSpace.persistParamOps.save != NULL) { + g_persistWorkSpace.persistParamOps.save(name, value); + } + // update commit for check + UpdatePersistCommitId(); + + if (!PARAM_TEST_FLAG(g_persistWorkSpace.flags, WORKSPACE_FLAGS_LOADED)) { + PARAM_LOGE("Can not save persist param before load %s ", name); + return 0; + } + if (g_persistWorkSpace.persistParamOps.batchSave == NULL) { + return 0; + } + + // check timer for save all + time_t currTimer; + (void)time(&currTimer); + uint32_t diff = (uint32_t)difftime(currTimer, g_persistWorkSpace.lastSaveTimer); + if (diff > PARAM_MUST_SAVE_PARAM_DIFF) { + if (g_persistWorkSpace.saveTimer != NULL) { + ParamTimerClose(g_persistWorkSpace.saveTimer); + g_persistWorkSpace.saveTimer = NULL; + } + return BatchSavePersistParam(); + } +#ifndef PARAM_SUPPORT_CYCLE_CHECK + PARAM_SET_FLAG(g_persistWorkSpace.flags, WORKSPACE_FLAGS_UPDATE); + if (g_persistWorkSpace.saveTimer == NULL) { + ParamTimerCreate(&g_persistWorkSpace.saveTimer, TimerCallbackForSave, NULL); + ParamTimerStart(g_persistWorkSpace.saveTimer, PARAM_MUST_SAVE_PARAM_DIFF * MS_UNIT, MS_UNIT); + } +#endif + return 0; +} + +static int GetParamValueFromBuffer(const char *name, const char *buffer, char *value, int length) +{ + size_t bootLen = strlen(OHOS_BOOT); + const char *tmpName = name + bootLen; + int ret = GetProcCmdlineValue(tmpName, buffer, value, length); + return ret; +} + +static int CommonDealFun(const char *name, const char *value, int res) +{ + int ret = 0; + if (res == 0) { + PARAM_LOGI("Add param from cmdline %s %s", name, value); + ret = CheckParamName(name, 0); + PARAM_CHECK(ret == 0, return ret, "Invalid name %s", name); + PARAM_LOGV("**** name %s, value %s", name, value); + ret = WriteParam(name, value, NULL, 0); + PARAM_CHECK(ret == 0, return ret, "Failed to write param %s %s", name, value); + } else { + PARAM_LOGE("Can not find arrt %s", name); + } + return ret; +} + +static int SnDealFun(const char *name, const char *value, int res) +{ +#ifdef USE_MTK_EMMC + static const char SN_FILE[] = {"/proc/bootdevice/cid"}; +#else + static const char SN_FILE[] = {"/sys/block/mmcblk0/device/cid"}; +#endif + int ret = CheckParamName(name, 0); + PARAM_CHECK(ret == 0, return ret, "Invalid name %s", name); + char *data = NULL; + if (res != 0) { // if cmdline not set sn or set sn value is null,read sn from default file + data = ReadFileData(SN_FILE); + if (data == NULL) { + PARAM_LOGE("Error, Read sn from default file failed!"); + return -1; + } + } else if (value[0] == '/') { + data = ReadFileData(value); + if (data == NULL) { + PARAM_LOGE("Error, Read sn from cmdline file failed!"); + return -1; + } + } else { + PARAM_LOGV("**** name %s, value %s", name, value); + ret = WriteParam(name, value, NULL, 0); + PARAM_CHECK(ret == 0, return ret, "Failed to write param %s %s", name, value); + return ret; + } + + int index = 0; + for (size_t i = 0; i < strlen(data); i++) { + // cancel \r\n + if (*(data + i) == '\r' || *(data + i) == '\n') { + break; + } + if (*(data + i) != ':') { + *(data + index) = *(data + i); + index++; + } + } + data[index] = '\0'; + PARAM_LOGV("**** name %s, value %s", name, data); + ret = WriteParam(name, data, NULL, 0); + PARAM_CHECK(ret == 0, free(data); + return ret, "Failed to write param %s %s", name, data); + free(data); + + return ret; +} + +int LoadParamFromCmdLine(void) +{ + int ret; + static const cmdLineInfo cmdLines[] = { + {OHOS_BOOT"hardware", CommonDealFun + }, + {OHOS_BOOT"bootgroup", CommonDealFun + }, + {OHOS_BOOT"reboot_reason", CommonDealFun + }, + {OHOS_BOOT"sn", SnDealFun + } + }; + char *data = ReadFileData(BOOT_CMD_LINE); + PARAM_CHECK(data != NULL, return -1, "Failed to read file %s", BOOT_CMD_LINE); + char *value = calloc(1, PARAM_CONST_VALUE_LEN_MAX + 1); + PARAM_CHECK(value != NULL, free(data); + return -1, "Failed to read file %s", BOOT_CMD_LINE); + + for (size_t i = 0; i < ARRAY_LENGTH(cmdLines); i++) { +#ifdef BOOT_EXTENDED_CMDLINE + ret = GetParamValueFromBuffer(cmdLines[i].name, BOOT_EXTENDED_CMDLINE, value, PARAM_CONST_VALUE_LEN_MAX); + if (ret != 0) { + ret = GetParamValueFromBuffer(cmdLines[i].name, data, value, PARAM_CONST_VALUE_LEN_MAX); + } +#else + ret = GetParamValueFromBuffer(cmdLines[i].name, data, value, PARAM_CONST_VALUE_LEN_MAX); +#endif + + cmdLines[i].processor(cmdLines[i].name, value, ret); + } + PARAM_LOGV("Parse cmdline finish %s", BOOT_CMD_LINE); + free(data); + free(value); + return 0; +} + +static int LoadOneParam_(const uint32_t *context, const char *name, const char *value) +{ + uint32_t mode = *(uint32_t *)context; + int ret = CheckParamName(name, 0); + if (ret != 0) { + return 0; + } + PARAM_LOGV("Add default parameter [%s] [%s]", name, value); + return WriteParam(name, value, NULL, mode & LOAD_PARAM_ONLY_ADD); +} + +static int LoadDefaultParam_(const char *fileName, uint32_t mode, const char *exclude[], uint32_t count) +{ + uint32_t paramNum = 0; + FILE *fp = fopen(fileName, "r"); + if (fp == NULL) { + return -1; + } + const int buffSize = PARAM_NAME_LEN_MAX + PARAM_CONST_VALUE_LEN_MAX + 10; // 10 max len + char *buffer = malloc(buffSize); + if (buffer == NULL) { + (void)fclose(fp); + return -1; + } + while (fgets(buffer, buffSize, fp) != NULL) { + buffer[buffSize - 1] = '\0'; + int ret = SpliteString(buffer, exclude, count, LoadOneParam_, &mode); + PARAM_CHECK(ret == 0, continue, "Failed to set param '%s' error:%d ", buffer, ret); + paramNum++; + } + (void)fclose(fp); + free(buffer); + PARAM_LOGI("Load parameters success %s total %u", fileName, paramNum); + return 0; +} + +static int ProcessParamFile(const char *fileName, void *context) +{ + static const char *exclude[] = {"ctl.", "selinux.restorecon_recursive"}; + uint32_t mode = *(int *)context; + return LoadDefaultParam_(fileName, mode, exclude, ARRAY_LENGTH(exclude)); +} + +int LoadDefaultParams(const char *fileName, uint32_t mode) +{ + PARAM_CHECK(fileName != NULL, return -1, "Invalid fielname for load"); + PARAM_LOGI("load default parameters %s.", fileName); + int ret = 0; + struct stat st; + if ((stat(fileName, &st) == 0) && !S_ISDIR(st.st_mode)) { + ret = ProcessParamFile(fileName, &mode); + } else { + ret = ReadFileInDir(fileName, ".para", ProcessParamFile, &mode); + } + + // load security label + return LoadSecurityLabel(fileName); +} + +static void LoadBuildParameter(void) +{ + // load dynamic parameter +#ifdef INCREMENTAL_VERSION + WriteParam(name, value, NULL, LOAD_PARAM_NORMAL); +#endif +#ifdef BUILD_TYPE + WriteParam(name, BUILD_TYPE, NULL, LOAD_PARAM_NORMAL); +#endif +#ifdef BUILD_USER + WriteParam(name, BUILD_USER, NULL, LOAD_PARAM_NORMAL); +#endif +#ifdef BUILD_TIME + WriteParam(name, BUILD_TIME, NULL, LOAD_PARAM_NORMAL); +#endif +#ifdef BUILD_HOST + WriteParam(name, BUILD_HOST, NULL, LOAD_PARAM_NORMAL); +#endif +#ifdef BUILD_ROOTHASH + WriteParam("const.ohos.buildroothash", BUILD_ROOTHASH, NULL, LOAD_PARAM_NORMAL); +#endif +} + +int LoadPersistParams(void) +{ + // first get build parameter + LoadBuildParameter(); + + // get persist parameter + int ret = InitPersistParamWorkSpace(); + PARAM_CHECK(ret == 0, return ret, "Failed to init persist param"); +#ifndef STARTUP_INIT_TEST + if (PARAM_TEST_FLAG(g_persistWorkSpace.flags, WORKSPACE_FLAGS_LOADED)) { + PARAM_LOGE("Persist param has been loaded"); + return 0; + } +#endif + if (g_persistWorkSpace.persistParamOps.load != NULL) { + ret = g_persistWorkSpace.persistParamOps.load(); + PARAM_SET_FLAG(g_persistWorkSpace.flags, WORKSPACE_FLAGS_LOADED); + } + // save new persist param + ret = BatchSavePersistParam(); + PARAM_CHECK(ret == 0, return ret, "Failed to load persist param"); +#ifdef PARAM_SUPPORT_CYCLE_CHECK + if (g_persistWorkSpace.saveTimer == NULL) { + ParamTimerCreate(&g_persistWorkSpace.saveTimer, TimerCallbackForSave, NULL); + ParamTimerStart(g_persistWorkSpace.saveTimer, PARAM_MUST_SAVE_PARAM_DIFF * MS_UNIT, MS_UNIT); + } +#endif + return 0; +} \ No newline at end of file diff --git a/services/param/manager/param_trie.c b/services/param/manager/param_trie.c index 03730336d12d8d82e544f251c30997605910fe28..966f142d8417e59dad900225e0b7002e7f21f166 100644 --- a/services/param/manager/param_trie.c +++ b/services/param/manager/param_trie.c @@ -16,45 +16,43 @@ #include "param_trie.h" #include -#include -#include -#include -#include -#include -#include #include +#include "init_param.h" +#include "param_osadp.h" #include "param_utils.h" -#include "sys_param.h" -static int InitWorkSpace_(WorkSpace *workSpace, int mode, int prot, uint32_t spaceSize, int readOnly) +int GetRealFileName(WorkSpace *workSpace, char *buffer, uint32_t size) { + int ret = sprintf_s(buffer, size, "%s/%s", PARAM_STORAGE_PATH, workSpace->fileName); + PARAM_CHECK(ret > 0, return -1, "Failed to copy file name %s", workSpace->fileName); + buffer[ret] = '\0'; + CheckAndCreateDir(buffer); + return 0; +} + +static int InitWorkSpace_(WorkSpace *workSpace, uint32_t spaceSize, int readOnly) +{ + static uint32_t startIndex = 0; PARAM_CHECK(workSpace != NULL, return PARAM_CODE_INVALID_PARAM, "Invalid workSpace"); - PARAM_CHECK(spaceSize <= PARAM_WORKSPACE_MAX, return PARAM_CODE_INVALID_PARAM, "Invalid workSpace"); PARAM_CHECK(workSpace->allocTrieNode != NULL, return PARAM_CODE_INVALID_PARAM, "Invalid allocTrieNode %s", workSpace->fileName); PARAM_CHECK(workSpace->compareTrieNode != NULL, return PARAM_CODE_INVALID_PARAM, "Invalid compareTrieNode %s", workSpace->fileName); - PARAM_LOGV("InitWorkSpace %s readOnly %d", workSpace->fileName, readOnly); - CheckAndCreateDir(workSpace->fileName); - - int fd = open(workSpace->fileName, mode, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH); - PARAM_CHECK(fd >= 0, return PARAM_CODE_INVALID_NAME, - "Open file %s mode %x fail error %d", workSpace->fileName, mode, errno); - - if (!readOnly) { - ftruncate(fd, spaceSize); - } - void *areaAddr = (void *)mmap(NULL, spaceSize, prot, MAP_SHARED, fd, 0); - PARAM_CHECK(areaAddr != MAP_FAILED && areaAddr != NULL, close(fd); - return PARAM_CODE_ERROR_MAP_FILE, "Failed to map memory error %d", errno); - close(fd); + char buffer[FILENAME_LEN_MAX] = {0}; + int ret = GetRealFileName(workSpace, buffer, sizeof(buffer)); + PARAM_CHECK(ret == 0, return -1, "Failed to get file name %s", workSpace->fileName); + void *areaAddr = GetSharedMem(buffer, &workSpace->memHandle, spaceSize, readOnly); + PARAM_CHECK(areaAddr != NULL, return PARAM_CODE_ERROR_MAP_FILE, + "Failed to map memory error %d areaAddr %p spaceSize %d", errno, areaAddr, spaceSize); if (!readOnly) { workSpace->area = (ParamTrieHeader *)areaAddr; workSpace->area->trieNodeCount = 0; workSpace->area->paramNodeCount = 0; workSpace->area->securityNodeCount = 0; + workSpace->area->startIndex = startIndex; + startIndex += spaceSize; workSpace->area->dataSize = spaceSize - sizeof(ParamTrieHeader); workSpace->area->currOffset = 0; uint32_t offset = workSpace->allocTrieNode(workSpace, "#", 1); @@ -73,7 +71,7 @@ static uint32_t AllocateParamTrieNode(WorkSpace *workSpace, const char *key, uin len = PARAM_ALIGN(len); PARAM_CHECK((workSpace->area->currOffset + len) < workSpace->area->dataSize, return 0, "Failed to allocate currOffset %d, dataSize %d", workSpace->area->currOffset, workSpace->area->dataSize); - ParamTrieNode *node = (ParamTrieNode*)(workSpace->area->data + workSpace->area->currOffset); + ParamTrieNode *node = (ParamTrieNode *)(workSpace->area->data + workSpace->area->currOffset); node->length = keyLen; int ret = memcpy_s(node->key, keyLen, key, keyLen); PARAM_CHECK(ret == EOK, return 0, "Failed to copy key"); @@ -99,35 +97,36 @@ static int CompareParamTrieNode(const ParamTrieNode *node, const char *key, uint return strncmp(node->key, key, keyLen); } -int InitWorkSpace(const char *fileName, WorkSpace *workSpace, int onlyRead) +int InitWorkSpace(WorkSpace *workSpace, int onlyRead, uint32_t spaceSize) { - PARAM_CHECK(fileName != NULL, return PARAM_CODE_INVALID_NAME, "Invalid fileName"); PARAM_CHECK(workSpace != NULL, return PARAM_CODE_INVALID_NAME, "Invalid workSpace"); - if (workSpace->area != NULL) { + if (PARAM_TEST_FLAG(workSpace->flags, WORKSPACE_FLAGS_INIT)) { return 0; } workSpace->compareTrieNode = CompareParamTrieNode; workSpace->allocTrieNode = AllocateParamTrieNode; - int ret = strcpy_s(workSpace->fileName, sizeof(workSpace->fileName), fileName); - PARAM_CHECK(ret == 0, return ret, "Failed to copy file name %s", fileName); - int openMode; - int prot = PROT_READ; - if (onlyRead) { - openMode = O_RDONLY; - } else { - openMode = O_CREAT | O_RDWR | O_TRUNC; - prot = PROT_READ | PROT_WRITE; - } - ret = InitWorkSpace_(workSpace, openMode, prot, PARAM_WORKSPACE_MAX, onlyRead); + int ret = InitWorkSpace_(workSpace, spaceSize, onlyRead); PARAM_CHECK(ret == 0, return ret, "Failed to init workspace %s", workSpace->fileName); + PARAMSPACE_AREA_INIT_LOCK(workSpace); + PARAM_SET_FLAG(workSpace->flags, WORKSPACE_FLAGS_INIT); return ret; } void CloseWorkSpace(WorkSpace *workSpace) { - PARAM_CHECK(workSpace != NULL && workSpace->area != NULL, return, "The workspace is null"); - munmap((char *)workSpace->area, workSpace->area->dataSize); + PARAM_CHECK(workSpace != NULL, return, "The workspace is null"); + if (!PARAM_TEST_FLAG(workSpace->flags, WORKSPACE_FLAGS_INIT)) { + free(workSpace); + return; + } + ListRemove(&workSpace->node); + PARAM_CHECK(workSpace->area != NULL, return, "The workspace area is null"); +#ifdef WORKSPACE_AREA_NEED_MUTEX + ParamRWMutexDelete(&workSpace->rwlock); +#endif + FreeSharedMem(&workSpace->memHandle, workSpace->area, workSpace->area->dataSize); workSpace->area = NULL; + free(workSpace); } static ParamTrieNode *GetTrieRoot(const WorkSpace *workSpace) @@ -160,7 +159,8 @@ static ParamTrieNode *AddToSubTrie(WorkSpace *workSpace, ParamTrieNode *current, subTrie = GetTrieNode(workSpace, current->left); if (subTrie == NULL) { uint32_t offset = workSpace->allocTrieNode(workSpace, key, keyLen); - PARAM_CHECK(offset != 0, return NULL, "Failed to allocate key %s", key); + PARAM_CHECK(offset != 0, return NULL, + "Failed to allocate key '%s' in space '%s'", key, workSpace->fileName); SaveIndex(¤t->left, offset); return GetTrieNode(workSpace, current->left); } @@ -168,7 +168,8 @@ static ParamTrieNode *AddToSubTrie(WorkSpace *workSpace, ParamTrieNode *current, subTrie = GetTrieNode(workSpace, current->right); if (subTrie == NULL) { uint32_t offset = workSpace->allocTrieNode(workSpace, key, keyLen); - PARAM_CHECK(offset != 0, return NULL, "Failed to allocate key %s", key); + PARAM_CHECK(offset != 0, return NULL, + "Failed to allocate key '%s' in space '%s'", key, workSpace->fileName); SaveIndex(¤t->right, offset); return GetTrieNode(workSpace, current->right); } @@ -192,12 +193,13 @@ ParamTrieNode *AddTrieNode(WorkSpace *workSpace, const char *key, uint32_t keyLe if (!subKeyLen) { return NULL; } - if (current->child != 0) { // 如果child存在,则检查是否匹配 + if (current->child != 0) { // 如果child存在,则检查是否匹配 ParamTrieNode *next = GetTrieNode(workSpace, current->child); current = AddToSubTrie(workSpace, next, remainingKey, subKeyLen); } else { uint32_t dataOffset = workSpace->allocTrieNode(workSpace, remainingKey, subKeyLen); - PARAM_CHECK(dataOffset != 0, return NULL, "Failed to allocate key %s", key); + PARAM_CHECK(dataOffset != 0, return NULL, + "Failed to allocate key '%s' in space '%s'", key, workSpace->fileName); SaveIndex(¤t->child, dataOffset); current = (ParamTrieNode *)GetTrieNode(workSpace, current->child); } @@ -218,11 +220,10 @@ static ParamTrieNode *FindSubTrie(const WorkSpace *workSpace, if (current == NULL) { return NULL; } - ParamTrieNode *subTrie = NULL; int ret = workSpace->compareTrieNode(current, key, keyLen); if (ret == 0) { - if (matchLabel != NULL && current->labelIndex != 0) { // 有效前缀 + if (matchLabel != NULL && current->labelIndex != 0) { *matchLabel = current->labelIndex; } return current; @@ -241,7 +242,7 @@ static ParamTrieNode *FindSubTrie(const WorkSpace *workSpace, return FindSubTrie(workSpace, subTrie, key, keyLen, matchLabel); } -ParamTrieNode *FindTrieNode(const WorkSpace *workSpace, const char *key, uint32_t keyLen, uint32_t *matchLabel) +ParamTrieNode *FindTrieNode_(const WorkSpace *workSpace, const char *key, uint32_t keyLen, uint32_t *matchLabel) { PARAM_CHECK(key != NULL && keyLen > 0, return NULL, "Invalid key "); PARAM_CHECK(workSpace != NULL && workSpace->area != NULL, return 0, "Invalid workSpace %s", key); @@ -284,7 +285,7 @@ ParamTrieNode *FindTrieNode(const WorkSpace *workSpace, const char *key, uint32_ } static int TraversalSubTrieNode(const WorkSpace *workSpace, - const ParamTrieNode *current, TraversalTrieNodePtr walkFunc, void *cookie) + const ParamTrieNode *current, TraversalTrieNodePtr walkFunc, const void *cookie) { if (current == NULL) { return 0; @@ -297,7 +298,7 @@ static int TraversalSubTrieNode(const WorkSpace *workSpace, } int TraversalTrieNode(const WorkSpace *workSpace, - const ParamTrieNode *root, TraversalTrieNodePtr walkFunc, void *cookie) + const ParamTrieNode *root, TraversalTrieNodePtr walkFunc, const void *cookie) { PARAM_CHECK(walkFunc != NULL, return PARAM_CODE_INVALID_PARAM, "Invalid param"); PARAM_CHECK(workSpace != NULL && workSpace->area != NULL, return 0, "Invalid workSpace"); @@ -321,23 +322,28 @@ uint32_t AddParamSecruityNode(WorkSpace *workSpace, const ParamAuditData *auditD { PARAM_CHECK(workSpace != NULL && workSpace->area != NULL, return 0, "Invalid param"); PARAM_CHECK(auditData != NULL && auditData->name != NULL, return 0, "Invalid auditData"); - const uint32_t labelLen = (auditData->label == NULL) ? 0 : strlen(auditData->label); +#ifdef PARAM_SUPPORT_SELINUX + const uint32_t labelLen = strlen(auditData->label); uint32_t realLen = sizeof(ParamSecruityNode) + PARAM_ALIGN(labelLen + 1); +#else + uint32_t realLen = sizeof(ParamSecruityNode); +#endif PARAM_CHECK((workSpace->area->currOffset + realLen) < workSpace->area->dataSize, return 0, "Failed to allocate currOffset %u, dataSize %u datalen %u", workSpace->area->currOffset, workSpace->area->dataSize, realLen); - ParamSecruityNode *node = (ParamSecruityNode *)(workSpace->area->data + workSpace->area->currOffset); node->uid = auditData->dacData.uid; node->gid = auditData->dacData.gid; node->mode = auditData->dacData.mode; node->length = 0; +#ifdef PARAM_SUPPORT_SELINUX if (labelLen != 0) { int ret = memcpy_s(node->data, labelLen, auditData->label, labelLen); PARAM_CHECK(ret == EOK, return 0, "Failed to copy key"); node->data[labelLen] = '\0'; node->length = labelLen; } +#endif uint32_t offset = workSpace->area->currOffset; workSpace->area->currOffset += realLen; workSpace->area->securityNodeCount++; @@ -350,7 +356,8 @@ uint32_t AddParamNode(WorkSpace *workSpace, const char *key, uint32_t keyLen, co PARAM_CHECK(key != NULL && value != NULL, return 0, "Invalid param"); uint32_t realLen = sizeof(ParamNode) + 1 + 1; - if (valueLen > PARAM_VALUE_LEN_MAX) { + // for const parameter, alloc memory on demand + if ((valueLen > PARAM_VALUE_LEN_MAX) || IS_READY_ONLY(key)) { realLen += keyLen + valueLen; } else { realLen += keyLen + PARAM_VALUE_LEN_MAX; @@ -387,3 +394,13 @@ void SaveIndex(uint32_t *index, uint32_t offset) PARAM_CHECK(index != NULL, return, "Invalid index"); *index = offset; } + +ParamTrieNode *FindTrieNode(WorkSpace *workSpace, const char *key, uint32_t keyLen, uint32_t *matchLabel) +{ + PARAM_CHECK(workSpace != NULL, return NULL, "Invalid workSpace"); + ParamTrieNode *node = NULL; + PARAMSPACE_AREA_RD_LOCK(workSpace); + node = FindTrieNode_(workSpace, key, keyLen, matchLabel); + PARAMSPACE_AREA_RW_UNLOCK(workSpace); + return node; +} \ No newline at end of file diff --git a/services/param/manager/param_utils.c b/services/param/manager/param_utils.c index d4409be08f0afc9321d57064c4effa35882d2cb0..c12bd1923fbbc6d5e5ab4b596d652bc073422aca 100644 --- a/services/param/manager/param_utils.c +++ b/services/param/manager/param_utils.c @@ -30,6 +30,7 @@ void CheckAndCreateDir(const char *fileName) { +#ifndef __LITEOS_M__ if (fileName == NULL || *fileName == '\0') { return; } @@ -43,69 +44,7 @@ void CheckAndCreateDir(const char *fileName) } MakeDirRecursive(path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); free(path); -} - -static void TrimString(char *string, uint32_t currLen) -{ - for (int i = currLen - 1; i >= 0; i--) { - if (string[i] == ' ' || string[i] == '\0') { - string[i] = '\0'; - } else { - break; - } - } -} - -int GetSubStringInfo(const char *buff, uint32_t buffLen, char delimiter, SubStringInfo *info, int subStrNumber) -{ - PARAM_CHECK(buff != NULL && info != NULL, return 0, "Invalid buff"); - size_t i = 0; - size_t buffStrLen = strlen(buff); - // 去掉开始的空格 - for (; i < buffStrLen; i++) { - if (!isspace(buff[i])) { - break; - } - } - // 过滤掉注释 - if (buff[i] == '#') { - return -1; - } - // 分割字符串 - int spaceIsValid = 0; - int curr = 0; - int valueCurr = 0; - for (; i < buffLen; i++) { - if (buff[i] == '\n' || buff[i] == '\r' || buff[i] == '\0') { - break; - } - if (buff[i] == delimiter && valueCurr != 0) { - info[curr].value[valueCurr] = '\0'; - TrimString(info[curr].value, valueCurr); - valueCurr = 0; - curr++; - spaceIsValid = 0; - } else { - if (!spaceIsValid && isspace(buff[i])) { // 过滤开始前的无效字符 - continue; - } - spaceIsValid = 1; - if ((valueCurr + 1) >= (int)sizeof(info[curr].value)) { - continue; - } - info[curr].value[valueCurr++] = buff[i]; - } - if (curr >= subStrNumber) { - break; - } - } - if (valueCurr > 0) { - info[curr].value[valueCurr] = '\0'; - TrimString(info[curr].value, valueCurr); - valueCurr = 0; - curr++; - } - return curr; +#endif } int SpliteString(char *line, const char *exclude[], uint32_t count, @@ -173,4 +112,63 @@ int SpliteString(char *line, const char *exclude[], uint32_t count, *pos = '\0'; } return result(context, name, value); +} + +static char *BuildKey(const char *format, ...) +{ + const size_t buffSize = 1024; // 1024 for format key + char *buffer = malloc(buffSize); + PARAM_CHECK(buffer != NULL, return NULL, "Failed to malloc for format"); + va_list vargs; + va_start(vargs, format); + int len = vsnprintf_s(buffer, buffSize, buffSize - 1, format, vargs); + va_end(vargs); + if (len > 0 && (size_t)len < buffSize) { + buffer[len] = '\0'; + for (int i = 0; i < len; i++) { + if (buffer[i] == '|') { + buffer[i] = '\0'; + } + } + return buffer; + } + return NULL; +} + +char *GetServiceCtrlName(const char *name, const char *value) +{ + static char *ctrlParam[] = { + "ohos.ctl.start", + "ohos.ctl.stop" + }; + static char *installParam[] = { + "ohos.servicectrl." + }; + static char *powerCtrlArg[][2] = { + {"reboot,shutdown", "reboot.shutdown"}, + {"reboot,updater", "reboot.updater"}, + {"reboot,flashd", "reboot.flashd"}, + {"reboot", "reboot"}, + }; + char *key = NULL; + if (strcmp("ohos.startup.powerctrl", name) == 0) { + for (size_t i = 0; i < ARRAY_LENGTH(powerCtrlArg); i++) { + if (strncmp(value, powerCtrlArg[i][0], strlen(powerCtrlArg[i][0])) == 0) { + return BuildKey("%s%s", OHOS_SERVICE_CTRL_PREFIX, powerCtrlArg[i][1]); + } + } + return key; + } + for (size_t i = 0; i < ARRAY_LENGTH(ctrlParam); i++) { + if (strcmp(name, ctrlParam[i]) == 0) { + return BuildKey("%s%s", OHOS_SERVICE_CTRL_PREFIX, value); + } + } + + for (size_t i = 0; i < ARRAY_LENGTH(installParam); i++) { + if (strncmp(name, installParam[i], strlen(installParam[i])) == 0) { + return BuildKey("%s.%s", name, value); + } + } + return key; } \ No newline at end of file diff --git a/services/param/service/param_persist.c b/services/param/service/param_persist.c deleted file mode 100644 index d2e5bf48a9d3f3a1888be7042e46b3dbda72a29a..0000000000000000000000000000000000000000 --- a/services/param/service/param_persist.c +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright (c) 2021 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 "param_persist.h" - -#include -#include -#include -#include - -#include "param_manager.h" -#include "param_service.h" -#include "param_trie.h" -#include "sys_param.h" - -static ParamPersistWorkSpace g_persistWorkSpace = { 0, NULL, 0, { NULL, NULL, NULL, NULL, NULL } }; - -static int AddPersistParam(const char *name, const char *value, void *context) -{ - PARAM_CHECK(value != NULL && name != NULL && context != NULL, - return PARAM_CODE_INVALID_PARAM, "Invalid name or context"); - WorkSpace *workSpace = (WorkSpace *)context; - uint32_t dataIndex = 0; - int ret = WriteParam(workSpace, name, value, &dataIndex, 0); - PARAM_CHECK(ret == 0, return ret, "Failed to write param %d name:%s %s", ret, name, value); - return 0; -} - -static int SavePersistParam(const WorkSpace *workSpace, const ParamTrieNode *node, void *cookie) -{ - ParamTrieNode *current = (ParamTrieNode *)node; - if (current == NULL || current->dataIndex == 0) { - return 0; - } - ParamNode *entry = (ParamNode *)GetTrieNode(workSpace, current->dataIndex); - if (entry == NULL) { - return 0; - } - if (strncmp(entry->data, PARAM_PERSIST_PREFIX, strlen(PARAM_PERSIST_PREFIX)) != 0) { - return 0; - } - static char name[PARAM_NAME_LEN_MAX] = { 0 }; - int ret = memcpy_s(name, PARAM_NAME_LEN_MAX - 1, entry->data, entry->keyLength); - PARAM_CHECK(ret == EOK, return -1, "Failed to read param name %s", entry->data); - name[entry->keyLength] = '\0'; - ret = g_persistWorkSpace.persistParamOps.batchSave(cookie, name, entry->data + entry->keyLength + 1); - PARAM_CHECK(ret == 0, return -1, "Failed to write param %s", current->key); - return ret; -} - -static int BatchSavePersistParam(const WorkSpace *workSpace) -{ - PARAM_LOGV("BatchSavePersistParam"); - if (g_persistWorkSpace.persistParamOps.batchSaveBegin == NULL || - g_persistWorkSpace.persistParamOps.batchSave == NULL || - g_persistWorkSpace.persistParamOps.batchSaveEnd == NULL) { - return 0; - } - - PERSIST_SAVE_HANDLE handle; - int ret = g_persistWorkSpace.persistParamOps.batchSaveBegin(&handle); - PARAM_CHECK(ret == 0, return PARAM_CODE_INVALID_NAME, "Failed to save persist"); - ParamTrieNode *root = FindTrieNode(workSpace, PARAM_PERSIST_PREFIX, strlen(PARAM_PERSIST_PREFIX), NULL); - ret = TraversalTrieNode(workSpace, root, SavePersistParam, handle); - g_persistWorkSpace.persistParamOps.batchSaveEnd(handle); - PARAM_CHECK(ret == 0, return PARAM_CODE_INVALID_NAME, "Save persist param fail"); - - PARAM_CLEAR_FLAG(g_persistWorkSpace.flags, WORKSPACE_FLAGS_UPDATE); - (void)time(&g_persistWorkSpace.lastSaveTimer); - return ret; -} - -int InitPersistParamWorkSpace(const ParamWorkSpace *workSpace) -{ - UNUSED(workSpace); - if (PARAM_TEST_FLAG(g_persistWorkSpace.flags, WORKSPACE_FLAGS_INIT)) { - return 0; - } - (void)time(&g_persistWorkSpace.lastSaveTimer); -#ifdef PARAM_SUPPORT_SAVE_PERSIST - RegisterPersistParamOps(&g_persistWorkSpace.persistParamOps); -#endif - PARAM_SET_FLAG(g_persistWorkSpace.flags, WORKSPACE_FLAGS_INIT); - return 0; -} - -void ClosePersistParamWorkSpace(void) -{ - if (g_persistWorkSpace.saveTimer != NULL) { - ParamTaskClose(g_persistWorkSpace.saveTimer); - } - g_persistWorkSpace.flags = 0; -} - -int LoadPersistParam(ParamWorkSpace *workSpace) -{ - PARAM_CHECK(workSpace != NULL, return PARAM_CODE_INVALID_PARAM, "Invalid workSpace"); - int ret = InitPersistParamWorkSpace(workSpace); - PARAM_CHECK(ret == 0, return ret, "Failed to init persist param"); -#ifndef STARTUP_INIT_TEST - if (PARAM_TEST_FLAG(g_persistWorkSpace.flags, WORKSPACE_FLAGS_LOADED)) { - PARAM_LOGE("Persist param has been loaded"); - return 0; - } -#endif - if (g_persistWorkSpace.persistParamOps.load != NULL) { - ret = g_persistWorkSpace.persistParamOps.load(AddPersistParam, &workSpace->paramSpace); - PARAM_SET_FLAG(g_persistWorkSpace.flags, WORKSPACE_FLAGS_LOADED); - } - // save new persist param - ret = BatchSavePersistParam(&workSpace->paramSpace); - PARAM_CHECK(ret == 0, return ret, "Failed to load persist param"); - return 0; -} - -PARAM_STATIC void TimerCallbackForSave(const ParamTaskPtr timer, void *context) -{ - UNUSED(context); - UNUSED(timer); - ParamTaskClose(g_persistWorkSpace.saveTimer); - g_persistWorkSpace.saveTimer = NULL; - if (!PARAM_TEST_FLAG(g_persistWorkSpace.flags, WORKSPACE_FLAGS_UPDATE)) { - return; - } - (void)BatchSavePersistParam((WorkSpace *)context); -} - -int WritePersistParam(ParamWorkSpace *workSpace, const char *name, const char *value) -{ - PARAM_CHECK(workSpace != NULL, return PARAM_CODE_INVALID_PARAM, "Invalid workSpace"); - PARAM_CHECK(value != NULL && name != NULL, return PARAM_CODE_INVALID_PARAM, "Invalid param"); - if (strncmp(name, PARAM_PERSIST_PREFIX, strlen(PARAM_PERSIST_PREFIX)) != 0) { - return 0; - } - if (!PARAM_TEST_FLAG(g_persistWorkSpace.flags, WORKSPACE_FLAGS_LOADED)) { - PARAM_LOGE("Can not save persist param before load %s ", name); - return 0; - } - PARAM_LOGV("WritePersistParam name %s ", name); - if (g_persistWorkSpace.persistParamOps.save != NULL) { - g_persistWorkSpace.persistParamOps.save(name, value); - } - - // 不需要批量保存 - if (g_persistWorkSpace.persistParamOps.batchSave == NULL) { - return 0; - } - - // check timer for save all - time_t currTimer; - (void)time(&currTimer); - uint32_t diff = (uint32_t)difftime(currTimer, g_persistWorkSpace.lastSaveTimer); - PARAM_LOGV("WritePersistParam name %s %d ", name, diff); - if (diff > PARAM_MUST_SAVE_PARAM_DIFF) { - if (g_persistWorkSpace.saveTimer != NULL) { - ParamTaskClose(g_persistWorkSpace.saveTimer); - g_persistWorkSpace.saveTimer = NULL; - } - return BatchSavePersistParam(&workSpace->paramSpace); - } - PARAM_SET_FLAG(g_persistWorkSpace.flags, WORKSPACE_FLAGS_UPDATE); - if (g_persistWorkSpace.saveTimer == NULL) { - ParamTimerCreate(&g_persistWorkSpace.saveTimer, - TimerCallbackForSave, &workSpace->paramSpace); - ParamTimerStart(g_persistWorkSpace.saveTimer, PARAM_MUST_SAVE_PARAM_DIFF * MS_UNIT, MS_UNIT); - } - return 0; -} diff --git a/services/param/service/param_service.c b/services/param/service/param_service.c deleted file mode 100755 index a963374d5e289e3b3087d805abc8e4efcccf9606..0000000000000000000000000000000000000000 --- a/services/param/service/param_service.c +++ /dev/null @@ -1,829 +0,0 @@ -/* - * Copyright (c) 2021 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 "param_service.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "init_param.h" -#include "init_utils.h" -#include "loop_event.h" -#include "param_message.h" -#include "param_manager.h" -#include "param_request.h" -#include "trigger_manager.h" - -static ParamWorkSpace g_paramWorkSpace = { 0, {}, NULL, {}, NULL, NULL }; - -#ifdef USE_MTK_EMMC -static const char SN_FILE[] = {"/proc/bootdevice/cid"}; -#else -static const char SN_FILE[] = {"/sys/block/mmcblk0/device/cid"}; -#endif - -static void OnClose(ParamTaskPtr client) -{ - PARAM_LOGV("OnClose %p", client); - ParamWatcher *watcher = (ParamWatcher *)ParamGetTaskUserData(client); - if (client == g_paramWorkSpace.watcherTask) { - ClearWatchTrigger(watcher, TRIGGER_PARAM_WATCH); - g_paramWorkSpace.watcherTask = NULL; - } else { - ClearWatchTrigger(watcher, TRIGGER_PARAM_WAIT); - } -} - -static void TimerCallback(const ParamTaskPtr timer, void *context) -{ - UNUSED(context); - UNUSED(timer); - int ret = CheckWatchTriggerTimeout(); - // no wait node - if (ret == 0 && g_paramWorkSpace.timer != NULL) { - ParamTaskClose(g_paramWorkSpace.timer); - g_paramWorkSpace.timer = NULL; - } -} - -static int AddParam(WorkSpace *workSpace, const char *name, const char *value, uint32_t *dataIndex) -{ - ParamTrieNode *node = AddTrieNode(workSpace, name, strlen(name)); - PARAM_CHECK(node != NULL, return PARAM_CODE_REACHED_MAX, "Failed to add node"); - ParamNode *entry = (ParamNode *)GetTrieNode(workSpace, node->dataIndex); - if (entry == NULL) { - uint32_t offset = AddParamNode(workSpace, name, strlen(name), value, strlen(value)); - PARAM_CHECK(offset > 0, return PARAM_CODE_REACHED_MAX, "Failed to allocate name %s", name); - SaveIndex(&node->dataIndex, offset); - long long globalCommitId = atomic_load_explicit(&workSpace->area->commitId, memory_order_relaxed); - atomic_store_explicit(&workSpace->area->commitId, ++globalCommitId, memory_order_release); - } - if (dataIndex != NULL) { - *dataIndex = node->dataIndex; - } - return 0; -} - -static int UpdateParam(const WorkSpace *workSpace, uint32_t *dataIndex, const char *name, const char *value) -{ - ParamNode *entry = (ParamNode *)GetTrieNode(workSpace, *dataIndex); - PARAM_CHECK(entry != NULL, return PARAM_CODE_REACHED_MAX, "Failed to update param value %s %u", name, *dataIndex); - PARAM_CHECK(entry->keyLength == strlen(name), return PARAM_CODE_INVALID_NAME, "Failed to check name len %s", name); - - uint32_t valueLen = strlen(value); - uint32_t commitId = atomic_load_explicit(&entry->commitId, memory_order_relaxed); - atomic_store_explicit(&entry->commitId, commitId | PARAM_FLAGS_MODIFY, memory_order_relaxed); - long long globalCommitId = atomic_load_explicit(&workSpace->area->commitId, memory_order_relaxed); - - if (entry->valueLength < PARAM_VALUE_LEN_MAX && valueLen < PARAM_VALUE_LEN_MAX) { - int ret = memcpy_s(entry->data + entry->keyLength + 1, PARAM_VALUE_LEN_MAX, value, valueLen + 1); - PARAM_CHECK(ret == EOK, return PARAM_CODE_INVALID_VALUE, "Failed to copy value"); - entry->valueLength = valueLen; - } - uint32_t flags = commitId & ~PARAM_FLAGS_COMMITID; - atomic_store_explicit(&entry->commitId, (++commitId) | flags, memory_order_release); - atomic_store_explicit(&workSpace->area->commitId, ++globalCommitId, memory_order_release); - futex_wake(&entry->commitId, INT_MAX); - return 0; -} - -int WriteParam(const WorkSpace *workSpace, const char *name, const char *value, uint32_t *dataIndex, int onlyAdd) -{ - PARAM_CHECK(workSpace != NULL, return PARAM_CODE_INVALID_PARAM, "Invalid workSpace"); - PARAM_CHECK(value != NULL && name != NULL, return PARAM_CODE_INVALID_PARAM, "Invalid name or value"); - ParamTrieNode *node = FindTrieNode(workSpace, name, strlen(name), NULL); - int ret = 0; - if (node != NULL && node->dataIndex != 0) { - if (dataIndex != NULL) { - *dataIndex = node->dataIndex; - } - if (onlyAdd) { - return PARAM_CODE_READ_ONLY; - } - ret = CheckParamValue(workSpace, node, name, value); - PARAM_CHECK(ret == 0, return ret, "Invalid param value param: %s=%s", name, value); - return UpdateParam(workSpace, &node->dataIndex, name, value); - } - ret = CheckParamValue(workSpace, node, name, value); - PARAM_CHECK(ret == 0, return ret, "Invalid param value param: %s=%s", name, value); - return AddParam((WorkSpace *)workSpace, name, value, dataIndex); -} - -PARAM_STATIC int AddSecurityLabel(const ParamAuditData *auditData, void *context) -{ - PARAM_CHECK(auditData != NULL && auditData->name != NULL, return -1, "Invalid auditData"); - PARAM_CHECK(context != NULL, return -1, "Invalid context"); - ParamWorkSpace *workSpace = (ParamWorkSpace *)context; - int ret = CheckParamName(auditData->name, 1); - PARAM_CHECK(ret == 0, return ret, "Illegal param name \"%s\"", auditData->name); - - ParamTrieNode *node = FindTrieNode(&workSpace->paramSpace, auditData->name, strlen(auditData->name), NULL); - if (node == NULL) { - node = AddTrieNode(&workSpace->paramSpace, auditData->name, strlen(auditData->name)); - } - PARAM_CHECK(node != NULL, return PARAM_CODE_REACHED_MAX, "Failed to add node %s", auditData->name); - if (node->labelIndex == 0) { // can not support update for label - uint32_t offset = AddParamSecruityNode(&workSpace->paramSpace, auditData); - PARAM_CHECK(offset != 0, return PARAM_CODE_REACHED_MAX, "Failed to add label"); - SaveIndex(&node->labelIndex, offset); - } else { -#ifdef STARTUP_INIT_TEST - ParamSecruityNode *label = (ParamSecruityNode *)GetTrieNode(&workSpace->paramSpace, node->labelIndex); - label->mode = auditData->dacData.mode; - label->uid = auditData->dacData.uid; - label->gid = auditData->dacData.gid; -#endif - PARAM_LOGE("Error, repeate to add label for name %s", auditData->name); - } - PARAM_LOGV("AddSecurityLabel label gid %d uid %d mode %o name: %s", auditData->dacData.gid, auditData->dacData.uid, - auditData->dacData.mode, auditData->name); - return 0; -} - -static char *BuildKey(ParamWorkSpace *workSpace, const char *format, ...) -{ - va_list vargs; - va_start(vargs, format); - size_t buffSize = sizeof(workSpace->buffer); - int len = vsnprintf_s(workSpace->buffer, buffSize, buffSize - 1, format, vargs); - va_end(vargs); - if (len > 0 && (size_t)len < buffSize) { - workSpace->buffer[len] = '\0'; - for (int i = 0; i < len; i++) { - if (workSpace->buffer[i] == '|') { - workSpace->buffer[i] = '\0'; - } - } - return workSpace->buffer; - } - return NULL; -} - -static char *GetServiceCtrlName(ParamWorkSpace *workSpace, const char *name, const char *value) -{ - static char *ctrlParam[] = { - "ohos.ctl.start", - "ohos.ctl.stop" - }; - static char *installParam[] = { - "ohos.servicectrl." - }; - static char *powerCtrlArg[][2] = { - {"reboot,shutdown", "reboot.shutdown"}, - {"reboot,updater", "reboot.updater"}, - {"reboot,flashd", "reboot.flashd"}, - {"reboot", "reboot"}, - }; - char *key = NULL; - if (strcmp("ohos.startup.powerctrl", name) == 0) { - for (size_t i = 0; i < ARRAY_LENGTH(powerCtrlArg); i++) { - if (strncmp(value, powerCtrlArg[i][0], strlen(powerCtrlArg[i][0])) == 0) { - return BuildKey(workSpace, "%s%s", OHOS_SERVICE_CTRL_PREFIX, powerCtrlArg[i][1]); - } - } - return key; - } - for (size_t i = 0; i < ARRAY_LENGTH(ctrlParam); i++) { - if (strcmp(name, ctrlParam[i]) == 0) { - return BuildKey(workSpace, "%s%s", OHOS_SERVICE_CTRL_PREFIX, value); - } - } - - for (size_t i = 0; i < ARRAY_LENGTH(installParam); i++) { - if (strncmp(name, installParam[i], strlen(installParam[i])) == 0) { - return BuildKey(workSpace, "%s.%s", name, value); - } - } - return key; -} - -static void CheckAndSendTrigger(ParamWorkSpace *workSpace, uint32_t dataIndex, const char *name, const char *value) -{ - ParamNode *entry = (ParamNode *)GetTrieNode(&workSpace->paramSpace, dataIndex); - PARAM_CHECK(entry != NULL, return, "Failed to get data %s ", name); - uint32_t trigger = 1; - if ((atomic_load_explicit(&entry->commitId, memory_order_relaxed) & PARAM_FLAGS_TRIGGED) != PARAM_FLAGS_TRIGGED) { - trigger = (CheckAndMarkTrigger(TRIGGER_PARAM, name) != 0) ? 1 : 0; - } - if (trigger) { - atomic_store_explicit(&entry->commitId, - atomic_load_explicit(&entry->commitId, memory_order_relaxed) | PARAM_FLAGS_TRIGGED, memory_order_release); - // notify event to process trigger - PostParamTrigger(EVENT_TRIGGER_PARAM, name, value); - } - - int wait = 1; - if ((atomic_load_explicit(&entry->commitId, memory_order_relaxed) & PARAM_FLAGS_WAITED) != PARAM_FLAGS_WAITED) { - wait = (CheckAndMarkTrigger(TRIGGER_PARAM_WAIT, name) != 0) ? 1 : 0; - } - if (wait) { - atomic_store_explicit(&entry->commitId, - atomic_load_explicit(&entry->commitId, memory_order_relaxed) | PARAM_FLAGS_WAITED, memory_order_release); - PostParamTrigger(EVENT_TRIGGER_PARAM_WAIT, name, value); - } - PostParamTrigger(EVENT_TRIGGER_PARAM_WATCH, name, value); -} - -static int SystemSetParam(const char *name, const char *value, const ParamSecurityLabel *srcLabel) -{ - PARAM_LOGV("SystemSetParam name %s value: %s", name, value); - int ret = CheckParamName(name, 0); - PARAM_CHECK(ret == 0, return ret, "Illegal param name %s", name); - char *key = GetServiceCtrlName(&g_paramWorkSpace, name, value); - if (srcLabel != NULL) { - ret = CheckParamPermission(&g_paramWorkSpace, srcLabel, (key == NULL) ? name : key, DAC_WRITE); - } - PARAM_CHECK(ret == 0, return ret, "Forbit to set parameter %s", name); - - if (key != NULL) { // ctrl param - ret = CheckParamValue(&g_paramWorkSpace.paramSpace, NULL, name, value); - PARAM_CHECK(ret == 0, return ret, "Invalid param value param: %s=%s", name, value); - PostParamTrigger(EVENT_TRIGGER_PARAM, name, value); - } else { - uint32_t dataIndex = 0; - ret = WriteParam(&g_paramWorkSpace.paramSpace, name, value, &dataIndex, 0); - PARAM_CHECK(ret == 0, return ret, "Failed to set param %d name %s %s", ret, name, value); - ret = WritePersistParam(&g_paramWorkSpace, name, value); - PARAM_CHECK(ret == 0, return ret, "Failed to set persist param name %s", name); - CheckAndSendTrigger(&g_paramWorkSpace, dataIndex, name, value); - } - return ret; -} - -static int SendResponseMsg(ParamTaskPtr worker, const ParamMessage *msg, int result) -{ - ParamResponseMessage *response = NULL; - response = (ParamResponseMessage *)CreateParamMessage(msg->type, msg->key, sizeof(ParamResponseMessage)); - PARAM_CHECK(response != NULL, return PARAM_CODE_ERROR, "Failed to alloc memory for response"); - response->msg.id.msgId = msg->id.msgId; - response->result = result; - response->msg.msgSize = sizeof(ParamResponseMessage); - ParamTaskSendMsg(worker, (ParamMessage *)response); - return 0; -} - -static int SendWatcherNotifyMessage(const TriggerExtInfo *extData, const char *content, uint32_t size) -{ - PARAM_CHECK(content != NULL, return -1, "Invalid content"); - PARAM_CHECK(extData != NULL && extData->stream != NULL, return -1, "Invalid extData"); - uint32_t msgSize = sizeof(ParamMessage) + PARAM_ALIGN(strlen(content) + 1); - ParamMessage *msg = (ParamMessage *)CreateParamMessage(MSG_NOTIFY_PARAM, "*", msgSize); - PARAM_CHECK(msg != NULL, return -1, "Failed to create msg "); - - uint32_t offset = 0; - int ret; - char *tmp = strstr(content, "="); - if (tmp != NULL) { - ret = strncpy_s(msg->key, sizeof(msg->key) - 1, content, tmp - content); - PARAM_CHECK(ret == 0, free(msg); - return -1, "Failed to fill value"); - tmp++; - ret = FillParamMsgContent(msg, &offset, PARAM_VALUE, tmp, strlen(tmp)); - PARAM_CHECK(ret == 0, free(msg); - return -1, "Failed to fill value"); - } else if (content != NULL && strlen(content) > 0) { - ret = FillParamMsgContent(msg, &offset, PARAM_VALUE, content, strlen(content)); - PARAM_CHECK(ret == 0, free(msg); - return -1, "Failed to fill value"); - } - - msg->id.msgId = 0; - if (extData->type == TRIGGER_PARAM_WAIT) { - msg->id.msgId = extData->info.waitInfo.waitId; - } else { - msg->id.msgId = extData->info.watchInfo.watchId; - } - msg->msgSize = sizeof(ParamMessage) + offset; - PARAM_LOGV("SendWatcherNotifyMessage cmd %s, id %d msgSize %d para: %s", - (extData->type == TRIGGER_PARAM_WAIT) ? "wait" : "watcher", - msg->id.msgId, msg->msgSize, content); - ParamTaskSendMsg(extData->stream, msg); - return 0; -} - -static int HandleParamSet(const ParamTaskPtr worker, const ParamMessage *msg) -{ - uint32_t offset = 0; - ParamMsgContent *valueContent = GetNextContent(msg, &offset); - PARAM_CHECK(valueContent != NULL, return -1, "Invalid msg for %s", msg->key); - int ret; - ParamMsgContent *lableContent = GetNextContent(msg, &offset); - ParamSecurityLabel *srcLabel = NULL; - if (lableContent != NULL && lableContent->contentSize != 0) { - PARAM_CHECK(g_paramWorkSpace.paramSecurityOps.securityDecodeLabel != NULL, - return -1, "Can not get decode function"); - ret = g_paramWorkSpace.paramSecurityOps.securityDecodeLabel(&srcLabel, - lableContent->content, lableContent->contentSize); - PARAM_CHECK(ret == 0, return ret, - "Failed to decode param %d name %s %s", ret, msg->key, valueContent->content); - } - if (srcLabel != NULL) { - struct ucred cr = {-1, -1, -1}; - socklen_t crSize = sizeof(cr); - if (getsockopt(LE_GetSocketFd(worker), SOL_SOCKET, SO_PEERCRED, &cr, &crSize) < 0) { - PARAM_LOGE("Failed to get opt %d", errno); - return SendResponseMsg(worker, msg, -1); - } - srcLabel->cred.uid = cr.uid; - srcLabel->cred.pid = cr.pid; - srcLabel->cred.gid = cr.gid; - } - ret = SystemSetParam(msg->key, valueContent->content, srcLabel); - if (srcLabel != NULL && g_paramWorkSpace.paramSecurityOps.securityFreeLabel != NULL) { - g_paramWorkSpace.paramSecurityOps.securityFreeLabel(srcLabel); - } - return SendResponseMsg(worker, msg, ret); -} - -static ParamNode *CheckMatchParamWait(const ParamWorkSpace *worksapce, const char *name, const char *value) -{ - uint32_t nameLength = strlen(name); - ParamTrieNode *node = FindTrieNode(&worksapce->paramSpace, name, nameLength, NULL); - if (node == NULL || node->dataIndex == 0) { - return NULL; - } - ParamNode *param = (ParamNode *)GetTrieNode(&worksapce->paramSpace, node->dataIndex); - if (param == NULL) { - return NULL; - } - if ((param->keyLength != nameLength) || (strncmp(param->data, name, nameLength) != 0)) { // compare name - return NULL; - } - atomic_store_explicit(¶m->commitId, - atomic_load_explicit(¶m->commitId, memory_order_relaxed) | PARAM_FLAGS_WAITED, memory_order_release); - if ((strncmp(value, "*", 1) == 0) || (strcmp(param->data + nameLength + 1, value) == 0)) { // compare value - return param; - } - char *tmp = strstr(value, "*"); - if (tmp != NULL && (strncmp(param->data + nameLength + 1, value, tmp - value) == 0)) { - return param; - } - return NULL; -} - -static int32_t AddWatchNode(struct tagTriggerNode_ *trigger, const struct TriggerExtInfo_ *extInfo) -{ - ParamWatcher *watcher = NULL; - if (extInfo != NULL && extInfo->stream != NULL) { - watcher = (ParamWatcher *)ParamGetTaskUserData(extInfo->stream); - } - PARAM_CHECK(watcher != NULL, return -1, "Failed to get param watcher data"); - if (extInfo->type == TRIGGER_PARAM_WAIT) { - WaitNode *node = (WaitNode *)trigger; - ListInit(&node->item); - node->timeout = extInfo->info.waitInfo.timeout; - node->stream = extInfo->stream; - node->waitId = extInfo->info.waitInfo.waitId; - ListAddTail(&watcher->triggerHead, &node->item); - } else { - WatchNode *node = (WatchNode *)trigger; - ListInit(&node->item); - node->watchId = extInfo->info.watchInfo.watchId; - ListAddTail(&watcher->triggerHead, &node->item); - } - return 0; -} - -static TriggerNode *AddWatcherTrigger(int triggerType, const char *condition, const TriggerExtInfo *extData) -{ - TriggerWorkSpace *workSpace = GetTriggerWorkSpace(); - TriggerHeader *header = (TriggerHeader *)&workSpace->triggerHead[extData->type]; - return header->addTrigger(workSpace, condition, extData); -} - -static int32_t ExecuteWatchTrigger_(const struct tagTriggerNode_ *trigger, const char *content, uint32_t size) -{ - TriggerExtInfo extData = {}; - extData.type = trigger->type; - if (trigger->type == TRIGGER_PARAM_WAIT) { - WaitNode *node = (WaitNode *)trigger; - extData.stream = node->stream; - extData.info.waitInfo.waitId = node->waitId; - extData.info.waitInfo.timeout = node->timeout; - } else { - WatchNode *node = (WatchNode *)trigger; - extData.stream = g_paramWorkSpace.watcherTask; - extData.info.watchInfo.watchId = node->watchId; - } - if (content == NULL) { - return SendWatcherNotifyMessage(&extData, "", 0); - } - return SendWatcherNotifyMessage(&extData, content, size); -} - -static int HandleParamWaitAdd(const ParamWorkSpace *worksapce, const ParamTaskPtr worker, const ParamMessage *msg) -{ - PARAM_CHECK(msg != NULL, return -1, "Invalid message"); - uint32_t offset = 0; - uint32_t timeout = DEFAULT_PARAM_WAIT_TIMEOUT; - ParamMsgContent *valueContent = GetNextContent(msg, &offset); - PARAM_CHECK(valueContent != NULL, return -1, "Invalid msg"); - PARAM_CHECK(valueContent->contentSize <= PARAM_CONST_VALUE_LEN_MAX, return -1, "Invalid msg"); - ParamMsgContent *timeoutContent = GetNextContent(msg, &offset); - if (timeoutContent != NULL) { - timeout = *((uint32_t *)(timeoutContent->content)); - } - - PARAM_LOGV("HandleParamWaitAdd name %s timeout %d", msg->key, timeout); - TriggerExtInfo extData = {}; - extData.addNode = AddWatchNode; - extData.type = TRIGGER_PARAM_WAIT; - extData.stream = worker; - extData.info.waitInfo.waitId = msg->id.watcherId; - extData.info.waitInfo.timeout = timeout; - // first check match, if match send response to client - ParamNode *param = CheckMatchParamWait(worksapce, msg->key, valueContent->content); - if (param != NULL) { - SendWatcherNotifyMessage(&extData, param->data, param->valueLength); - return 0; - } - - uint32_t buffSize = strlen(msg->key) + valueContent->contentSize + 1 + 1; - char *condition = calloc(1, buffSize); - PARAM_CHECK(condition != NULL, return -1, "Failed to create condition for %s", msg->key); - int ret = sprintf_s(condition, buffSize - 1, "%s=%s", msg->key, valueContent->content); - PARAM_CHECK(ret > EOK, free(condition); - return -1, "Failed to copy name for %s", msg->key); - TriggerNode *trigger = AddWatcherTrigger(TRIGGER_PARAM_WAIT, condition, &extData); - PARAM_CHECK(trigger != NULL, free(condition); - return -1, "Failed to add trigger for %s", msg->key); - free(condition); - if (g_paramWorkSpace.timer == NULL) { - ret = ParamTimerCreate(&g_paramWorkSpace.timer, TimerCallback, &g_paramWorkSpace); - PARAM_CHECK(ret == 0, return 0, "Failed to create timer %s", msg->key); - ret = ParamTimerStart(g_paramWorkSpace.timer, MS_UNIT, (uint64_t)-1); - PARAM_CHECK(ret == 0, - ParamTaskClose(g_paramWorkSpace.timer); - g_paramWorkSpace.timer = NULL; - return 0, "Failed to set timer %s", msg->key); - PARAM_LOGI("Start timer %p", g_paramWorkSpace.timer); - } - return 0; -} - -static int HandleParamWatcherAdd(ParamWorkSpace *workSpace, const ParamTaskPtr worker, const ParamMessage *msg) -{ - PARAM_CHECK(msg != NULL, return -1, "Invalid message"); - PARAM_CHECK((g_paramWorkSpace.watcherTask == NULL) || - (g_paramWorkSpace.watcherTask == worker), return -1, "Invalid watcher worker"); - g_paramWorkSpace.watcherTask = worker; - TriggerExtInfo extData = {}; - extData.type = TRIGGER_PARAM_WATCH; - extData.addNode = AddWatchNode; - extData.stream = worker; - extData.info.watchInfo.watchId = msg->id.watcherId; - TriggerNode *trigger = AddWatcherTrigger(TRIGGER_PARAM_WATCH, msg->key, &extData); - if (trigger == NULL) { - PARAM_LOGE("Failed to add trigger for %s", msg->key); - return SendResponseMsg(worker, msg, -1); - } - PARAM_LOGV("HandleParamWatcherAdd name %s watcher: %d", msg->key, msg->id.watcherId); - return SendResponseMsg(worker, msg, 0); -} - -static int HandleParamWatcherDel(ParamWorkSpace *workSpace, const ParamTaskPtr worker, const ParamMessage *msg) -{ - PARAM_CHECK(msg != NULL, return -1, "Invalid message"); - PARAM_LOGV("HandleParamWatcherDel name %s watcher: %d", msg->key, msg->id.watcherId); - DelWatchTrigger(TRIGGER_PARAM_WATCH, (const void *)&msg->id.watcherId); - return SendResponseMsg(worker, msg, 0); -} - -PARAM_STATIC int ProcessMessage(const ParamTaskPtr worker, const ParamMessage *msg) -{ - PARAM_CHECK((msg != NULL) && (msg->msgSize >= sizeof(ParamMessage)), return -1, "Invalid msg"); - PARAM_CHECK(worker != NULL, return -1, "Invalid worker"); - int ret = PARAM_CODE_INVALID_PARAM; - switch (msg->type) { - case MSG_SET_PARAM: - ret = HandleParamSet(worker, msg); - break; - case MSG_WAIT_PARAM: - ret = HandleParamWaitAdd(&g_paramWorkSpace, worker, msg); - break; - case MSG_ADD_WATCHER: - ret = HandleParamWatcherAdd(&g_paramWorkSpace, worker, msg); - break; - case MSG_DEL_WATCHER: - ret = HandleParamWatcherDel(&g_paramWorkSpace, worker, msg); - break; - default: - break; - } - PARAM_CHECK(ret == 0, return -1, "Failed to process message ret %d", ret); - return 0; -} - -static int LoadOneParam_ (const uint32_t *context, const char *name, const char *value) -{ - uint32_t mode = *(uint32_t *)context; - int ret = CheckParamName(name, 0); - if (ret != 0) { - return 0; - } - PARAM_LOGV("Add default parameter [%s] [%s]", name, value); - return WriteParam(&g_paramWorkSpace.paramSpace, - name, value, NULL, mode & LOAD_PARAM_ONLY_ADD); -} - -static int LoadDefaultParam_ (const char *fileName, uint32_t mode, const char *exclude[], uint32_t count) -{ - uint32_t paramNum = 0; - FILE *fp = fopen(fileName, "r"); - if (fp == NULL) { - return -1; - } - - while (fgets(g_paramWorkSpace.buffer, sizeof(g_paramWorkSpace.buffer), fp) != NULL) { - g_paramWorkSpace.buffer[sizeof(g_paramWorkSpace.buffer) - 1] = '\0'; - int ret = SpliteString(g_paramWorkSpace.buffer, exclude, count, LoadOneParam_, &mode); - PARAM_CHECK(ret == 0, continue, "Failed to set param %d %s", ret, g_paramWorkSpace.buffer); - paramNum++; - } - (void)fclose(fp); - - PARAM_LOGI("Load parameters success %s total %u", fileName, paramNum); - return 0; -} - -PARAM_STATIC int OnIncomingConnect(LoopHandle loop, TaskHandle server) -{ - ParamStreamInfo info = {}; - info.server = NULL; - info.close = OnClose; - info.recvMessage = ProcessMessage; - info.incomingConnect = NULL; - ParamTaskPtr client = NULL; - int ret = ParamStreamCreate(&client, server, &info, sizeof(ParamWatcher)); - PARAM_CHECK(ret == 0, return -1, "Failed to create client"); - - ParamWatcher *watcher = (ParamWatcher *)ParamGetTaskUserData(client); - PARAM_CHECK(watcher != NULL, return -1, "Failed to get watcher"); - ListInit(&watcher->triggerHead); - watcher->stream = client; -#ifdef STARTUP_INIT_TEST - GetParamWorkSpace()->watcherTask = client; -#endif - return 0; -} - -static int GetParamValueFromBuffer(const char *name, const char *buffer, char *value, int length) -{ - size_t bootLen = strlen(OHOS_BOOT); - const char *tmpName = name + bootLen; - int ret = GetProcCmdlineValue(tmpName, buffer, value, length); - return ret; -} - -static int CommonDealFun(const char* name, const char* value, int res) -{ - PARAM_LOGI("Add param from cmdline %s %s", name, value); - int ret = 0; - if (res == 0) { - ret = CheckParamName(name, 0); - PARAM_CHECK(ret == 0, return ret, "Invalid name %s", name); - PARAM_LOGV("**** name %s, value %s", name, value); - ret = WriteParam(&g_paramWorkSpace.paramSpace, name, value, NULL, 0); - PARAM_CHECK(ret == 0, return ret, "Failed to write param %s %s", name, value); - } else { - PARAM_LOGE("Can not find arrt %s", name); - } - return ret; -} - -static int SnDealFun(const char* name, const char* value, int res) -{ - PARAM_LOGI("Add SN param from cmdline %s %s", name, value); - int ret = CheckParamName(name, 0); - PARAM_CHECK(ret == 0, return ret, "Invalid name %s", name); - - char *data = NULL; - if (res != 0) { // if cmdline not set sn or set sn value is null,read sn from default file - data = ReadFileData(SN_FILE); - if (data == NULL) { - PARAM_LOGE("Error, Read sn from default file failed!"); - return -1; - } - } else if (value[0] == '/') { - data = ReadFileData(value); - if (data == NULL) { - PARAM_LOGE("Error, Read sn from cmdline file failed!"); - return -1; - } - } else { - PARAM_LOGV("**** name %s, value %s", name, value); - ret = WriteParam(&g_paramWorkSpace.paramSpace, name, value, NULL, 0); - PARAM_CHECK(ret == 0, return ret, "Failed to write param %s %s", name, value); - return ret; - } - - int index = 0; - for (size_t i = 0; i < strlen(data); i++) { - if (*(data + i) != ':') { - *(data + index) = *(data + i); - index++; - } - } - data[index] = '\0'; - PARAM_LOGV("**** name %s, value %s", name, data); - ret = WriteParam(&g_paramWorkSpace.paramSpace, name, data, NULL, 0); - PARAM_CHECK(ret == 0, free(data); - return ret, "Failed to write param %s %s", name, data); - free(data); - - return ret; -} - -static int LoadParamFromCmdLine(void) -{ - int ret; - static const cmdLineInfo cmdLines[] = { - {OHOS_BOOT"hardware", CommonDealFun - }, - {OHOS_BOOT"bootgroup", CommonDealFun - }, - {OHOS_BOOT"reboot_reason", CommonDealFun - }, - {OHOS_BOOT"sn", SnDealFun - }, -#ifdef STARTUP_INIT_TEST - {OHOS_BOOT"mem", CommonDealFun - }, - {OHOS_BOOT"console", CommonDealFun - }, - {OHOS_BOOT"mmz", CommonDealFun - }, - {OHOS_BOOT"androidboot.selinux", CommonDealFun - }, - {OHOS_BOOT"init", CommonDealFun - }, - {OHOS_BOOT"root", CommonDealFun - }, - {OHOS_BOOT"uuid", CommonDealFun - }, - {OHOS_BOOT"rootfstype", CommonDealFun - }, - {OHOS_BOOT"blkdevparts", CommonDealFun - }, -#endif - }; - char *data = ReadFileData(PARAM_CMD_LINE); - PARAM_CHECK(data != NULL, return -1, "Failed to read file %s", PARAM_CMD_LINE); - char *value = calloc(1, PARAM_CONST_VALUE_LEN_MAX + 1); - PARAM_CHECK(value != NULL, free(data); - return -1, "Failed to read file %s", PARAM_CMD_LINE); - - for (size_t i = 0; i < ARRAY_LENGTH(cmdLines); i++) { -#ifdef BOOT_EXTENDED_CMDLINE - ret = GetParamValueFromBuffer(cmdLines[i].name, BOOT_EXTENDED_CMDLINE, value, PARAM_CONST_VALUE_LEN_MAX); - if (ret != 0) { - ret = GetParamValueFromBuffer(cmdLines[i].name, data, value, PARAM_CONST_VALUE_LEN_MAX); - } -#else - ret = GetParamValueFromBuffer(cmdLines[i].name, data, value, PARAM_CONST_VALUE_LEN_MAX); -#endif - - cmdLines[i].processor(cmdLines[i].name, value, ret); - } - PARAM_LOGV("Parse cmdline finish %s", PARAM_CMD_LINE); - free(data); - free(value); - return 0; -} - -int SystemWriteParam(const char *name, const char *value) -{ - PARAM_CHECK(name != NULL && value != NULL, return -1, "The name is null"); - return SystemSetParam(name, value, g_paramWorkSpace.securityLabel); -} - -int SystemReadParam(const char *name, char *value, unsigned int *len) -{ - PARAM_CHECK(name != NULL && len != NULL, return -1, "The name is null"); - ParamHandle handle = 0; - int ret = ReadParamWithCheck(&g_paramWorkSpace, name, DAC_READ, &handle); - if (ret == 0) { - ret = ReadParamValue(&g_paramWorkSpace, handle, value, len); - } - return ret; -} - -int LoadPersistParams(void) -{ - return LoadPersistParam(&g_paramWorkSpace); -} - -static int ProcessParamFile(const char *fileName, void *context) -{ - static const char *exclude[] = {"ctl.", "selinux.restorecon_recursive"}; - uint32_t mode = *(int *)context; - return LoadDefaultParam_(fileName, mode, exclude, ARRAY_LENGTH(exclude)); -} - -int LoadDefaultParams(const char *fileName, uint32_t mode) -{ - PARAM_CHECK(fileName != NULL, return -1, "Invalid fielname for load"); - if (!PARAM_TEST_FLAG(g_paramWorkSpace.flags, WORKSPACE_FLAGS_INIT)) { - return PARAM_CODE_NOT_INIT; - } - PARAM_LOGI("load default parameters %s.", fileName); - int ret = 0; - struct stat st; - if ((stat(fileName, &st) == 0) && !S_ISDIR(st.st_mode)) { - ret = ProcessParamFile(fileName, &mode); - } else { - ret = ReadFileInDir(fileName, ".para", ProcessParamFile, &mode); - } - - // load security label - ParamSecurityOps *ops = &g_paramWorkSpace.paramSecurityOps; - if (ops->securityGetLabel != NULL) { - ret = ops->securityGetLabel(AddSecurityLabel, fileName, (void *)&g_paramWorkSpace); - } - return ret; -} - -void InitParamService(void) -{ - PARAM_LOGI("InitParamService pipe: %s.", PIPE_NAME); - CheckAndCreateDir(PIPE_NAME); - int ret = InitParamWorkSpace(&g_paramWorkSpace, 0); - PARAM_CHECK(ret == 0, return, "Init parameter workspace fail"); - ret = InitPersistParamWorkSpace(&g_paramWorkSpace); - PARAM_CHECK(ret == 0, return, "Init persist parameter workspace fail"); - if (g_paramWorkSpace.serverTask == NULL) { - ParamStreamInfo info = {}; - info.server = PIPE_NAME; - info.close = NULL; - info.recvMessage = NULL; - info.incomingConnect = OnIncomingConnect; - ret = ParamServerCreate(&g_paramWorkSpace.serverTask, &info); - PARAM_CHECK(ret == 0, return, "Failed to create server"); - } - ret = InitTriggerWorkSpace(); - PARAM_CHECK(ret == 0, return, "Failed to init trigger"); - - RegisterTriggerExec(TRIGGER_PARAM_WAIT, ExecuteWatchTrigger_); - RegisterTriggerExec(TRIGGER_PARAM_WATCH, ExecuteWatchTrigger_); - ParamAuditData auditData = {}; - auditData.name = "#"; - auditData.label = NULL; - auditData.dacData.gid = getegid(); - auditData.dacData.uid = geteuid(); - auditData.dacData.mode = DAC_ALL_PERMISSION; - ret = AddSecurityLabel(&auditData, (void *)&g_paramWorkSpace); - PARAM_CHECK(ret == 0, return, "Failed to add default dac label"); - - // 读取cmdline的参数 - LoadParamFromCmdLine(); -} - -int StartParamService(void) -{ - return ParamServiceStart(); -} - -void StopParamService(void) -{ - PARAM_LOGI("StopParamService."); - ClosePersistParamWorkSpace(); - CloseParamWorkSpace(&g_paramWorkSpace); - CloseTriggerWorkSpace(); - ParamTaskClose(g_paramWorkSpace.serverTask); - g_paramWorkSpace.serverTask = NULL; - ParamServiceStop(); -} - -ParamWorkSpace *GetParamWorkSpace(void) -{ - return &g_paramWorkSpace; -} - -void DumpParametersAndTriggers(void) -{ - DumpParameters(&g_paramWorkSpace, 1); - if (GetTriggerWorkSpace() != NULL) { - DumpTrigger(GetTriggerWorkSpace()); - } -} diff --git a/services/param/trigger/trigger_manager.c b/services/param/trigger/trigger_manager.c index 9efcf1b154e1da1ff027d997661658c4540a6e3c..ba6f8bcf98f42047ae48025ed8b8a69bf14467b9 100644 --- a/services/param/trigger/trigger_manager.c +++ b/services/param/trigger/trigger_manager.c @@ -522,8 +522,9 @@ static void DumpTrigger_(const TriggerWorkSpace *workSpace, int type) } } -void DumpTrigger(const TriggerWorkSpace *workSpace) +void SystemDumpTriggers(int verbose) { + TriggerWorkSpace *workSpace = GetTriggerWorkSpace(); PARAM_CHECK(workSpace != NULL, return, "Invalid workSpace "); PARAM_DUMP("Ready to dump all trigger memory \n"); PARAM_DUMP("workspace queue BOOT info:\n"); diff --git a/services/param/trigger/trigger_processor.c b/services/param/trigger/trigger_processor.c index 7368922b4d571646bae54688ea815ed864f4e1cb..e62c044e7597bf774eabf65cb797777eae800f84 100644 --- a/services/param/trigger/trigger_processor.c +++ b/services/param/trigger/trigger_processor.c @@ -20,6 +20,7 @@ #include "init_service_manager.h" #include "init_utils.h" #include "param_manager.h" +#include "param_message.h" #include "param_utils.h" #include "trigger_checker.h" #include "trigger_manager.h" @@ -274,7 +275,9 @@ static int ParseTrigger_(const TriggerWorkSpace *workSpace, PARAM_CHECK(trigger != NULL, return -1, "Failed to create trigger %s", name); PARAM_LOGV("ParseTrigger %s type %d count %d", name, type, header->triggerCount); cJSON *cmdItems = cJSON_GetObjectItem(triggerItem, CMDS_ARR_NAME_IN_JSON); - PARAM_CHECK(cJSON_IsArray(cmdItems), return -1, "Command item must be array"); + if (cmdItems == NULL || !cJSON_IsArray(cmdItems)) { + return 0; + } int cmdLinesCnt = cJSON_GetArraySize(cmdItems); PARAM_CHECK(cmdLinesCnt > 0, return -1, "Command array size must positive %s", name); @@ -298,11 +301,9 @@ int ParseTriggerConfig(const cJSON *fileRoot, int (*checkJobValid)(const char *j { PARAM_CHECK(fileRoot != NULL, return -1, "Invalid file"); cJSON *triggers = cJSON_GetObjectItemCaseSensitive(fileRoot, TRIGGER_ARR_NAME_IN_JSON); - if (triggers == NULL) { + if (triggers == NULL || !cJSON_IsArray(triggers)) { return 0; } - PARAM_CHECK(cJSON_IsArray(triggers), return -1, "Trigger item must array"); - int size = cJSON_GetArraySize(triggers); PARAM_CHECK(size > 0, return -1, "Trigger array size must positive"); diff --git a/services/param/watcher/BUILD.gn b/services/param/watcher/BUILD.gn index 251a7c0f12b7f872d2b68741cfc2c15f91fc0ad9..5dccf1374cdbfe3bddd58a47bce73f4264396b6b 100644 --- a/services/param/watcher/BUILD.gn +++ b/services/param/watcher/BUILD.gn @@ -18,41 +18,6 @@ ohos_prebuilt_etc("param_watcher.rc") { part_name = "init" } -ohos_shared_library("param_watcheragent") { - sources = [ - "agent/watcher.cpp", - "agent/watcher_manager_kits.cpp", - "agent/watcher_manager_proxy.cpp", - "agent/watcher_stub.cpp", - ] - - include_dirs = [ - "//base/startup/init_lite/services/param/include", - "//base/startup/init_lite/services/include/param", - "//base/startup/init_lite/services/param/watcher/include", - "//base/startup/init_lite/services/param/watcher/agent", - "//base/startup/init_lite/services/include", - "//base/startup/init_lite/services/log", - "//base/startup/init_lite/interfaces/innerkits/include", - "//base/startup/init_lite/services/loopevent/include", - ] - - deps = [ - "//base/startup/init_lite/services/log:agent_log", - "//base/startup/init_lite/services/param:param_client", - "//third_party/bounds_checking_function:libsec_static", - ] - - external_deps = [ - "ipc:ipc_core", - "safwk:system_ability_fwk", - "samgr_standard:samgr_proxy", - "utils_base:utils", - ] - - part_name = "init" -} - ohos_shared_library("param_watcher") { sources = [ "//base/startup/init_lite/services/utils/list.c", @@ -64,6 +29,7 @@ ohos_shared_library("param_watcher") { include_dirs = [ "//base/startup/init_lite/services/param/include", "//base/startup/init_lite/services/include/param", + "//base/startup/init_lite/services/param/linux", "//base/startup/init_lite/services/param/watcher/proxy", "//base/startup/init_lite/services/param/watcher/include", "//base/startup/init_lite/services/include", @@ -74,9 +40,8 @@ ohos_shared_library("param_watcher") { ] deps = [ - "//base/startup/init_lite/services/log:agent_log", - "//base/startup/init_lite/services/param:param_client", - "//third_party/bounds_checking_function:libsec_static", + "//base/startup/init_lite/interfaces/innerkits:libbegetutil", + "//third_party/bounds_checking_function:libsec_shared", ] external_deps = [ diff --git a/services/param/watcher/agent/watcher_manager_kits.cpp b/services/param/watcher/agent/watcher_manager_kits.cpp index 2e28b1d8495218c222df5c2ba6cf60cc788e306f..0c3cc1b21249783f0f6b2c7ee9e8e922ffbdf3cd 100644 --- a/services/param/watcher/agent/watcher_manager_kits.cpp +++ b/services/param/watcher/agent/watcher_manager_kits.cpp @@ -15,10 +15,10 @@ #include "watcher_manager_kits.h" #include "if_system_ability_manager.h" +#include "init_param.h" #include "iservice_registry.h" #include "iwatcher.h" #include "iwatcher_manager.h" -#include "param_request.h" #include "system_ability_definition.h" #include "watcher_utils.h" diff --git a/services/param/watcher/agent/watcher_manager_kits.h b/services/param/watcher/agent/watcher_manager_kits.h index c11078db39dc5a297e49fdec21b6bfaa618264d7..1e1fe4217d531240aa94aec67c9f6cf111d027fe 100644 --- a/services/param/watcher/agent/watcher_manager_kits.h +++ b/services/param/watcher/agent/watcher_manager_kits.h @@ -22,7 +22,7 @@ #include "iwatcher.h" #include "iwatcher_manager.h" #include "singleton.h" -#include "sys_param.h" +#include "init_param.h" #include "watcher.h" #include "watcher_utils.h" diff --git a/services/param/watcher/proxy/watcher_manager.cpp b/services/param/watcher/proxy/watcher_manager.cpp index 8662cbf16fc03b5b6ff150a3b9cbbf853fdcf48a..af4c5419e08241a7c48ee4bd80e405394453536e 100644 --- a/services/param/watcher/proxy/watcher_manager.cpp +++ b/services/param/watcher/proxy/watcher_manager.cpp @@ -21,7 +21,8 @@ #include #include "param_message.h" -#include "sys_param.h" +#include "param_message.h" +#include "init_param.h" #include "system_ability_definition.h" #include "watcher_utils.h" diff --git a/services/utils/BUILD.gn b/services/utils/BUILD.gn index 86acca7fca9e18d2ac7679724bfe9e90a067c5f3..ec3a50570fff674d38539bf7dd3c171b5c09ad18 100755 --- a/services/utils/BUILD.gn +++ b/services/utils/BUILD.gn @@ -10,25 +10,12 @@ # 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("//build/ohos.gni") - -ohos_static_library("libinit_utils") { - sources = [ "init_utils.c" ] - include_dirs = [ - "//third_party/bounds_checking_function/include", - "//base/startup/init_lite/services/log", - "//base/startup/init_lite/interfaces/innerkits/include", - "//base/startup/init_lite/services/include", - ] - deps = [ "//third_party/bounds_checking_function:libsec_static" ] - defines = [ "_GNU_SOURCE" ] - part_name = "init" -} if (defined(ohos_lite)) { static_library("libinit_tools") { sources = [ "//base/startup/init_lite/services/utils/init_hashmap.c", + "//base/startup/init_lite/services/utils/init_utils.c", "//base/startup/init_lite/services/utils/list.c", ] @@ -38,11 +25,11 @@ if (defined(ohos_lite)) { "//base/startup/init_lite/interfaces/innerkits/include", "//base/startup/init_lite/services/include", ] - - deps = [ "//third_party/bounds_checking_function:libsec_static" ] defines = [ "_GNU_SOURCE" ] } } else { + import("//build/ohos.gni") + ohos_static_library("libinit_tools") { sources = [ "//base/startup/init_lite/services/utils/init_hashmap.c", @@ -55,8 +42,19 @@ if (defined(ohos_lite)) { "//base/startup/init_lite/interfaces/innerkits/include", "//base/startup/init_lite/services/include", ] + defines = [ "_GNU_SOURCE" ] + part_name = "init" + } - deps = [ "//third_party/bounds_checking_function:libsec_static" ] + ohos_static_library("libinit_utils") { + sources = [ "init_utils.c" ] + + include_dirs = [ + "//third_party/bounds_checking_function/include", + "//base/startup/init_lite/services/log", + "//base/startup/init_lite/interfaces/innerkits/include", + "//base/startup/init_lite/services/include", + ] defines = [ "_GNU_SOURCE" ] part_name = "init" } diff --git a/services/utils/init_hashmap.c b/services/utils/init_hashmap.c index 4abb31003ee3cb28c950e40126bfcd117a0c0fe2..7041d9e731f1e0c52ef01428e90140089bc42c27 100644 --- a/services/utils/init_hashmap.c +++ b/services/utils/init_hashmap.c @@ -28,18 +28,12 @@ typedef struct { static uint32_t g_tableId = 0; int32_t HashMapCreate(HashMapHandle *handle, const HashInfo *info) { - INIT_ERROR_CHECK(handle != NULL && info != NULL, return -1, "Invalid param"); + INIT_ERROR_CHECK(handle != NULL && info != NULL && info->maxBucket > 0, return -1, "Invalid param"); INIT_ERROR_CHECK(info->keyHash != NULL && info->nodeHash != NULL, return -1, "Invalid param"); INIT_ERROR_CHECK(info->nodeCompare != NULL && info->keyCompare != NULL, return -1, "Invalid param"); - uint32_t maxBucket = info->maxBucket; - if (info->maxBucket > HASH_TAB_BUCKET_MAX) { - maxBucket = HASH_TAB_BUCKET_MAX; - } else if (info->maxBucket < HASH_TAB_BUCKET_MIN) { - maxBucket = HASH_TAB_BUCKET_MIN; - } - HashTab *tab = (HashTab *)calloc(1, sizeof(HashTab) + sizeof(HashNode*) * maxBucket); + HashTab *tab = (HashTab *)calloc(1, sizeof(HashTab) + sizeof(HashNode*) * info->maxBucket); INIT_ERROR_CHECK(tab != NULL, return -1, "Failed to create hash tab"); - tab->maxBucket = maxBucket; + tab->maxBucket = info->maxBucket; tab->keyHash = info->keyHash; tab->nodeCompare = info->nodeCompare; tab->keyCompare = info->keyCompare; @@ -127,7 +121,7 @@ void HashMapRemove(HashMapHandle handle, const void *key) HashNode *HashMapGet(HashMapHandle handle, const void *key) { - INIT_ERROR_CHECK(handle != NULL && key != NULL, return NULL, "Invalid param"); + INIT_ERROR_CHECK(handle != NULL && key != NULL, return NULL, "Invalid param %s", key); HashTab *tab = (HashTab *)handle; int hashCode = tab->keyHash(key); hashCode = (hashCode < 0) ? -hashCode : hashCode; @@ -170,7 +164,6 @@ HashNode *HashMapFind(HashMapHandle handle, HashTab *tab = (HashTab *)handle; INIT_ERROR_CHECK(hashCode < tab->maxBucket, return NULL, "Invalid hashcode %d %d", tab->maxBucket, hashCode); - INIT_LOGV("HashMapGet tableId %d hashCode %d", tab->tableId, hashCode); return GetHashNodeByKey(tab, tab->buckets[hashCode], key, keyCompare); } diff --git a/services/utils/init_utils.c b/services/utils/init_utils.c index 9231ee5442294060037c41049543985482f4db32..b726706726e28594c9bfdd0147258cd457cf7b14 100644 --- a/services/utils/init_utils.c +++ b/services/utils/init_utils.c @@ -32,13 +32,7 @@ #include "service_control.h" #define MAX_BUF_SIZE 1024 -#define MAX_DATA_BUFFER 2048 - -#ifdef STARTUP_UT -#define LOG_FILE_NAME "/media/sf_ubuntu/test/log.txt" -#else -#define LOG_FILE_NAME "/data/startup_log.txt" -#endif +#define MAX_SMALL_BUFFER 3096 #define MAX_JSON_FILE_LEN 102400 // max init.cfg size 100KB #define CONVERT_MICROSEC_TO_SEC(x) ((x) / 1000 / 1000.0) @@ -124,16 +118,16 @@ char *ReadFileData(const char *fileName) } char *buffer = NULL; int fd = -1; - do { - fd = open(fileName, O_RDONLY); - INIT_ERROR_CHECK(fd >= 0, break, "Failed to read file %s", fileName); - - buffer = (char *)malloc(MAX_DATA_BUFFER); // fsmanager not create, can not get fileStat st_size - INIT_ERROR_CHECK(buffer != NULL, break, "Failed to allocate memory for %s", fileName); - ssize_t readLen = read(fd, buffer, MAX_DATA_BUFFER - 1); - INIT_ERROR_CHECK(readLen > 0, break, "Failed to read data for %s", fileName); - buffer[readLen] = '\0'; - } while (0); + fd = open(fileName, O_RDONLY); + INIT_ERROR_CHECK(fd >= 0, return NULL, "Failed to read file %s", fileName); + buffer = (char *)malloc(MAX_SMALL_BUFFER); // fsmanager not create, can not get fileStat st_size + INIT_ERROR_CHECK(buffer != NULL, close(fd); + return NULL, "Failed to allocate memory for %s", fileName); + ssize_t readLen = read(fd, buffer, MAX_SMALL_BUFFER - 1); + INIT_ERROR_CHECK((readLen > 0) && (readLen < (MAX_SMALL_BUFFER - 1)), close(fd); + free(buffer); + return NULL, "Failed to read data for %s", fileName); + buffer[readLen] = '\0'; if (fd != -1) { close(fd); } @@ -372,11 +366,11 @@ int ReadFileInDir(const char *dirPath, const char *includeExt, return -1, "Failed to malloc for %s", dirPath); struct dirent *dp; + uint32_t count = 0; while ((dp = readdir(pDir)) != NULL) { if (dp->d_type == DT_DIR) { continue; } - INIT_LOGV("ReadFileInDir %s", dp->d_name); if (includeExt != NULL) { char *tmp = strstr(dp->d_name, includeExt); if (tmp == NULL) { @@ -393,9 +387,11 @@ int ReadFileInDir(const char *dirPath, const char *includeExt, } struct stat st; if (stat(fileName, &st) == 0) { + count++; processFile(fileName, context); } } + INIT_LOGI("ReadFileInDir dirPath %s %d", dirPath, count); free(fileName); closedir(pDir); return 0; @@ -414,7 +410,7 @@ int InUpdaterMode(void) int InChargerMode(void) { - char *data = ReadFileData(PARAM_CMD_LINE); + char *data = ReadFileData(BOOT_CMD_LINE); char value[CMDLINE_VALUE_LEN_MAX]; int ret = 0; @@ -474,3 +470,14 @@ const InitArgInfo *GetServieStatusMap(int *size) } return g_servieStatusMap; } + +uint32_t GetRandom() +{ + uint32_t ulSeed = 0; + int fd = open("/dev/urandom", O_RDONLY); + if (fd > 0) { + read(fd, &ulSeed, sizeof(ulSeed)); + } + close(fd); + return ulSeed; +} \ No newline at end of file diff --git a/test/fuzztest/BUILD.gn b/test/fuzztest/BUILD.gn index a35cd3a53b35bb3709087b1231e3918b99bcc167..0b67d94274117507ec067d75b265863929a52e5e 100644 --- a/test/fuzztest/BUILD.gn +++ b/test/fuzztest/BUILD.gn @@ -38,8 +38,6 @@ ohos_fuzztest("DoRebootFuzzTest") { deps = [ "//base/startup/init_lite/interfaces/innerkits:libbegetutil", - "//base/startup/init_lite/services/log:init_log", - "//base/startup/init_lite/services/param:param_client", "//third_party/bounds_checking_function:libsec_static", ] @@ -175,10 +173,7 @@ ohos_fuzztest("ServiceControlStartFuzzTest") { "//base/startup/init_lite/interfaces/innerkits/include", "//base/startup/init_lite/test/fuzztest/utils/include", ] - deps = [ - "//base/startup/init_lite/interfaces/innerkits:libbegetutil", - "//base/startup/init_lite/services/param:param_client", - ] + deps = [ "//base/startup/init_lite/interfaces/innerkits:libbegetutil" ] external_deps = [ "hiviewdfx_hilog_native:libhilog" ] cflags = [ @@ -201,10 +196,7 @@ ohos_fuzztest("ServiceControlStopFuzzTest") { "//base/startup/init_lite/interfaces/innerkits/include", "//base/startup/init_lite/test/fuzztest/utils/include", ] - deps = [ - "//base/startup/init_lite/interfaces/innerkits:libbegetutil", - "//base/startup/init_lite/services/param:param_client", - ] + deps = [ "//base/startup/init_lite/interfaces/innerkits:libbegetutil" ] external_deps = [ "hiviewdfx_hilog_native:libhilog" ] cflags = [ @@ -229,8 +221,7 @@ ohos_fuzztest("SystemDumpParametersFuzzTest") { ] deps = [ - "//base/startup/init_lite/services/log:agent_log", - "//base/startup/init_lite/services/param:param_client", + "//base/startup/init_lite/interfaces/innerkits:libbegetutil", "//base/startup/init_lite/test/fuzztest:libfuzz_utils", "//third_party/bounds_checking_function:libsec_static", ] @@ -258,8 +249,7 @@ ohos_fuzztest("SystemFindParameterFuzzTest") { ] deps = [ - "//base/startup/init_lite/services/log:agent_log", - "//base/startup/init_lite/services/param:param_client", + "//base/startup/init_lite/interfaces/innerkits:libbegetutil", "//third_party/bounds_checking_function:libsec_static", ] external_deps = [ "hiviewdfx_hilog_native:libhilog" ] @@ -286,8 +276,7 @@ ohos_fuzztest("SystemGetParameterFuzzTest") { ] deps = [ - "//base/startup/init_lite/services/log:agent_log", - "//base/startup/init_lite/services/param:param_client", + "//base/startup/init_lite/interfaces/innerkits:libbegetutil", "//third_party/bounds_checking_function:libsec_static", ] external_deps = [ "hiviewdfx_hilog_native:libhilog" ] @@ -314,8 +303,7 @@ ohos_fuzztest("SystemGetParameterCommitIdFuzzTest") { ] deps = [ - "//base/startup/init_lite/services/log:agent_log", - "//base/startup/init_lite/services/param:param_client", + "//base/startup/init_lite/interfaces/innerkits:libbegetutil", "//third_party/bounds_checking_function:libsec_static", ] external_deps = [ "hiviewdfx_hilog_native:libhilog" ] @@ -344,8 +332,7 @@ ohos_fuzztest("SystemGetParameterNameFuzzTest") { ] deps = [ - "//base/startup/init_lite/services/log:agent_log", - "//base/startup/init_lite/services/param:param_client", + "//base/startup/init_lite/interfaces/innerkits:libbegetutil", "//third_party/bounds_checking_function:libsec_static", ] external_deps = [ "hiviewdfx_hilog_native:libhilog" ] @@ -373,8 +360,7 @@ ohos_fuzztest("SystemGetParameterValueFuzzTest") { ] deps = [ - "//base/startup/init_lite/services/log:agent_log", - "//base/startup/init_lite/services/param:param_client", + "//base/startup/init_lite/interfaces/innerkits:libbegetutil", "//third_party/bounds_checking_function:libsec_static", ] external_deps = [ "hiviewdfx_hilog_native:libhilog" ] @@ -402,8 +388,7 @@ ohos_fuzztest("SystemSetParameterFuzztest") { ] deps = [ - "//base/startup/init_lite/services/log:agent_log", - "//base/startup/init_lite/services/param:param_client", + "//base/startup/init_lite/interfaces/innerkits:libbegetutil", "//third_party/bounds_checking_function:libsec_static", ] external_deps = [ "hiviewdfx_hilog_native:libhilog" ] @@ -432,8 +417,7 @@ ohos_fuzztest("SystemTraversalParameterFuzztest") { ] deps = [ - "//base/startup/init_lite/services/log:agent_log", - "//base/startup/init_lite/services/param:param_client", + "//base/startup/init_lite/interfaces/innerkits:libbegetutil", "//base/startup/init_lite/test/fuzztest:libfuzz_utils", "//third_party/bounds_checking_function:libsec_static", ] @@ -462,8 +446,7 @@ ohos_fuzztest("SystemWaitParameterFuzzTest") { ] deps = [ - "//base/startup/init_lite/services/log:agent_log", - "//base/startup/init_lite/services/param:param_client", + "//base/startup/init_lite/interfaces/innerkits:libbegetutil", "//third_party/bounds_checking_function:libsec_static", ] external_deps = [ "hiviewdfx_hilog_native:libhilog" ] @@ -491,9 +474,8 @@ ohos_fuzztest("SystemWatchParameterFuzzTest") { ] deps = [ - "//base/startup/init_lite/services/log:agent_log", - "//base/startup/init_lite/services/param:param_client", - "//base/startup/init_lite/services/param/watcher:param_watcheragent", + "//base/startup/init_lite/interfaces/innerkits:libbeget_proxy", + "//base/startup/init_lite/interfaces/innerkits:libbegetutil", "//third_party/bounds_checking_function:libsec_static", "//utils/native/base:utils", ] diff --git a/test/fuzztest/systemdumpparameters_fuzzer/systemdumpparameters_fuzzer.cpp b/test/fuzztest/systemdumpparameters_fuzzer/systemdumpparameters_fuzzer.cpp index c1be8fd092c270f9360df28a35f1d027c5a51852..f549f8108d7a820d08e8b4c835b73e0b88101eba 100644 --- a/test/fuzztest/systemdumpparameters_fuzzer/systemdumpparameters_fuzzer.cpp +++ b/test/fuzztest/systemdumpparameters_fuzzer/systemdumpparameters_fuzzer.cpp @@ -14,7 +14,7 @@ */ #include "systemdumpparameters_fuzzer.h" -#include "sys_param.h" +#include "init_param.h" #include "fuzz_utils.h" namespace OHOS { diff --git a/test/fuzztest/systemfindparameter_fuzzer/systemfindparameter_fuzzer.cpp b/test/fuzztest/systemfindparameter_fuzzer/systemfindparameter_fuzzer.cpp index 7809c01c7144e9e58da85a789d58905ddadc66f3..dba6dba573b1345c38a9b6e245a3c8d0871aacdc 100644 --- a/test/fuzztest/systemfindparameter_fuzzer/systemfindparameter_fuzzer.cpp +++ b/test/fuzztest/systemfindparameter_fuzzer/systemfindparameter_fuzzer.cpp @@ -14,7 +14,7 @@ */ #include "systemfindparameter_fuzzer.h" -#include "sys_param.h" +#include "init_param.h" static ParamHandle handle; diff --git a/test/fuzztest/systemgetparameter_fuzzer/systemgetparameter_fuzzer.cpp b/test/fuzztest/systemgetparameter_fuzzer/systemgetparameter_fuzzer.cpp index dff7b7c2af552f3bac2aa2439da5fbd4bcb1b98c..8c5518a2ccba92e0f7cc345c058e3dee5e56b9f6 100644 --- a/test/fuzztest/systemgetparameter_fuzzer/systemgetparameter_fuzzer.cpp +++ b/test/fuzztest/systemgetparameter_fuzzer/systemgetparameter_fuzzer.cpp @@ -15,7 +15,7 @@ #include "systemgetparameter_fuzzer.h" -#include "sys_param.h" +#include "init_param.h" namespace OHOS { bool FuzzSystemGetParameter(const uint8_t* data, size_t size) diff --git a/test/fuzztest/systemgetparametercommitid_fuzzer/systemgetparametercommitid_fuzzer.cpp b/test/fuzztest/systemgetparametercommitid_fuzzer/systemgetparametercommitid_fuzzer.cpp index 255bec652192404e41b9cbd1bfa56bab59208e02..80d99c486a3217550b2ab1b6eae83c1361dcda4d 100644 --- a/test/fuzztest/systemgetparametercommitid_fuzzer/systemgetparametercommitid_fuzzer.cpp +++ b/test/fuzztest/systemgetparametercommitid_fuzzer/systemgetparametercommitid_fuzzer.cpp @@ -14,8 +14,8 @@ */ #include "systemgetparametercommitid_fuzzer.h" +#include "init_param.h" #include "fuzz_utils.h" -#include "sys_param.h" namespace OHOS { bool FuzzSystemGetParameterCommitId(const uint8_t* data, size_t size) diff --git a/test/fuzztest/systemgetparametername_fuzzer/systemgetparametername_fuzzer.cpp b/test/fuzztest/systemgetparametername_fuzzer/systemgetparametername_fuzzer.cpp index 574f594365ec91ded1f32a532943459b44ec32c2..4072dd2af93d8ecfac927e0083d9427e790c0cf4 100644 --- a/test/fuzztest/systemgetparametername_fuzzer/systemgetparametername_fuzzer.cpp +++ b/test/fuzztest/systemgetparametername_fuzzer/systemgetparametername_fuzzer.cpp @@ -14,8 +14,8 @@ */ #include "systemgetparametername_fuzzer.h" +#include "init_param.h" #include "fuzz_utils.h" -#include "sys_param.h" namespace OHOS { bool FuzzSystemGetParameterName(const uint8_t* data, size_t size) diff --git a/test/fuzztest/systemgetparametervalue_fuzzer/systemgetparametervalue_fuzzer.cpp b/test/fuzztest/systemgetparametervalue_fuzzer/systemgetparametervalue_fuzzer.cpp index 88ce8fb4d842e490ce4311afc55e4cd3109a8db3..8b6cce943f06bd45db1bdedb023918ec577c247f 100644 --- a/test/fuzztest/systemgetparametervalue_fuzzer/systemgetparametervalue_fuzzer.cpp +++ b/test/fuzztest/systemgetparametervalue_fuzzer/systemgetparametervalue_fuzzer.cpp @@ -14,8 +14,8 @@ */ #include "systemgetparametervalue_fuzzer.h" +#include "init_param.h" #include "fuzz_utils.h" -#include "sys_param.h" namespace OHOS { bool FuzzSystemGetParameterValue(const uint8_t* data, size_t size) diff --git a/test/fuzztest/systemsetparameter_fuzzer/systemsetparameter_fuzzer.cpp b/test/fuzztest/systemsetparameter_fuzzer/systemsetparameter_fuzzer.cpp index 8370ae5994b6026b3e17d5fd88ebeeba77e7c7fe..17b87e6ee466740471b09fc051fd6cd5f9f1c337 100644 --- a/test/fuzztest/systemsetparameter_fuzzer/systemsetparameter_fuzzer.cpp +++ b/test/fuzztest/systemsetparameter_fuzzer/systemsetparameter_fuzzer.cpp @@ -14,7 +14,7 @@ */ #include "systemsetparameter_fuzzer.h" -#include "sys_param.h" +#include "init_param.h" namespace OHOS { bool FuzzSystemSetParameter(const uint8_t* data, size_t size) diff --git a/test/fuzztest/systemtraversalparameter_fuzzer/systemtraversalparameter_fuzzer.cpp b/test/fuzztest/systemtraversalparameter_fuzzer/systemtraversalparameter_fuzzer.cpp index 44319e2ee85b57039c69c834c5ae3f7802eeafec..af9b6fb9dcfbb8a61980b3559bdc9665774f8eae 100644 --- a/test/fuzztest/systemtraversalparameter_fuzzer/systemtraversalparameter_fuzzer.cpp +++ b/test/fuzztest/systemtraversalparameter_fuzzer/systemtraversalparameter_fuzzer.cpp @@ -18,7 +18,7 @@ #include "fuzz_utils.h" #include "init.h" #include "securec.h" -#include "sys_param.h" +#include "init_param.h" static void FakeShowParam(ParamHandle handle, void *cookie) { diff --git a/test/fuzztest/systemwaitparameter_fuzzer/systemwaitparameter_fuzzer.cpp b/test/fuzztest/systemwaitparameter_fuzzer/systemwaitparameter_fuzzer.cpp index b85acb13cbe319eb2eccd846143a79e53aea9f91..b496cbc2daa1808bc89ece2575f2913f2e06ab33 100644 --- a/test/fuzztest/systemwaitparameter_fuzzer/systemwaitparameter_fuzzer.cpp +++ b/test/fuzztest/systemwaitparameter_fuzzer/systemwaitparameter_fuzzer.cpp @@ -14,7 +14,7 @@ */ #include "systemwaitparameter_fuzzer.h" -#include "sys_param.h" +#include "init_param.h" namespace OHOS { bool FuzzSystemWaitParameter(const uint8_t* data, size_t size) diff --git a/test/fuzztest/systemwatchparameter_fuzzer/systemwatchparameter_fuzzer.cpp b/test/fuzztest/systemwatchparameter_fuzzer/systemwatchparameter_fuzzer.cpp index 173e03be81c0230bcab5c059db2da3b668abc13c..60b95eacb36386ad4514a52d4d786cf137ff2478 100644 --- a/test/fuzztest/systemwatchparameter_fuzzer/systemwatchparameter_fuzzer.cpp +++ b/test/fuzztest/systemwatchparameter_fuzzer/systemwatchparameter_fuzzer.cpp @@ -16,7 +16,7 @@ #include "systemwatchparameter_fuzzer.h" #include "init.h" -#include "sys_param.h" +#include "init_param.h" static void HandleParamChange(const char *key, const char *value, void *context) { diff --git a/test/plugintest/BUILD.gn b/test/plugintest/BUILD.gn index de581eb9d47ea68a49a4473a7c18fccae4322c51..64374a1194e9970b4760166c77884d050246b383 100755 --- a/test/plugintest/BUILD.gn +++ b/test/plugintest/BUILD.gn @@ -30,9 +30,10 @@ ohos_shared_library("libpluginparamtest") { ] deps = [ + "//base/startup/init_lite/interfaces/innerkits:libbegetutil", "//base/startup/init_lite/services/log:agent_log", "//base/startup/init_lite/services/utils:libinit_tools", - "//third_party/bounds_checking_function:libsec_static", + "//third_party/bounds_checking_function:libsec_shared", ] external_deps = [ "init:libinit_plugin_engine" ] diff --git a/test/plugintest/plugin_param_cmd.c b/test/plugintest/plugin_param_cmd.c index 346154efe8972cb15d62ba9d4311930bd119b7cc..80572bddd7a45007f147d526110afaf742dfe179 100755 --- a/test/plugintest/plugin_param_cmd.c +++ b/test/plugintest/plugin_param_cmd.c @@ -13,19 +13,21 @@ * limitations under the License. */ #include -#include +#include #include #include +#include +#include #include #include #include "begetctl.h" +#include "init_param.h" #include "loop_event.h" +#include "parameter.h" #include "plugin_test.h" #include "service_watcher.h" #include "shell_utils.h" -#include "sys_param.h" -#include "parameter.h" #define READ_DURATION 100000 static char *GetLocalBuffer(uint32_t *buffSize) @@ -44,7 +46,7 @@ static void *CmdReader(void *args) uint32_t buffSize = 0; char *buffer = GetLocalBuffer(&buffSize); while (g_stop == 0) { - int wait = READ_DURATION + READ_DURATION; // 100ms rand + int wait = READ_DURATION + READ_DURATION; // 100ms rand uint32_t size = buffSize; int ret = SystemGetParameter("test.randrom.read", buffer, &size); if (ret == 0) { @@ -142,9 +144,9 @@ static int32_t BShellParamCmdGroupTest(BShellHandle shell, int32_t argc, char *a { PLUGIN_CHECK(argc >= 1, return -1, "Invalid parameter"); PLUGIN_LOGI("BShellParamCmdGroupTest %s stage: %s", argv[0], argv[1]); - if (argc > 2 && strcmp(argv[1], "wait") == 0) { // 2 service name index - PLUGIN_LOGI("group-test-stage3: wait service %s", argv[2]); // 2 service name index - ServiceWatchForStatus(argv[2], ServiceStatusChangeTest); // 2 service name index + if (argc > 2 && strcmp(argv[1], "wait") == 0) { // 2 service name index + PLUGIN_LOGI("group-test-stage3: wait service %s", argv[2]); // 2 service name index + ServiceWatchForStatus(argv[2], ServiceStatusChangeTest); // 2 service name index LE_RunLoop(LE_GetDefaultLoop()); } return 0; @@ -154,8 +156,8 @@ static int32_t BShellParamCmdUdidGet(BShellHandle shell, int32_t argc, char *arg { PLUGIN_CHECK(argc >= 1, return -1, "Invalid parameter"); PLUGIN_LOGI("BShellParamCmdUdidGet "); - char localDeviceId[65] = {0}; // 65 udid len - AclGetDevUdid(localDeviceId, 65); // 65 udid len + char localDeviceId[65] = {0}; // 65 udid len + AclGetDevUdid(localDeviceId, 65); // 65 udid len BShellEnvOutput(shell, " udid: %s\r\n", localDeviceId); return 0; } diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 956bd297c743efc73e2788a9f8bfeb7f2860e387..13d61737302b5359f1fd9f71f5ba3fa54bbcd852 100755 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -40,6 +40,9 @@ ohos_unittest("init_ut") { "//base/startup/init_lite/interfaces/innerkits/sandbox/sandbox.c", "//base/startup/init_lite/interfaces/innerkits/sandbox/sandbox_namespace.c", "//base/startup/init_lite/interfaces/innerkits/socket/init_socket.c", + "//base/startup/init_lite/interfaces/innerkits/syspara/param_comm.c", + "//base/startup/init_lite/interfaces/innerkits/syspara/parameter.c", + "//base/startup/init_lite/interfaces/innerkits/syspara/sysversion.c", "//base/startup/init_lite/services/begetctl/param_cmd.c", "//base/startup/init_lite/services/begetctl/shell/shell_bas.c", "//base/startup/init_lite/services/begetctl/shell/shell_main.c", @@ -73,16 +76,16 @@ ohos_unittest("init_ut") { "//base/startup/init_lite/services/loopevent/timer/le_timer.c", "//base/startup/init_lite/services/loopevent/utils/le_utils.c", "//base/startup/init_lite/services/param/adapter/param_dac.c", - "//base/startup/init_lite/services/param/adapter/param_libuvadp.c", "//base/startup/init_lite/services/param/adapter/param_persistadp.c", - "//base/startup/init_lite/services/param/adapter/param_selinux.c", - "//base/startup/init_lite/services/param/client/param_request.c", + "//base/startup/init_lite/services/param/linux/param_message.c", + "//base/startup/init_lite/services/param/linux/param_msgadp.c", + "//base/startup/init_lite/services/param/linux/param_osadp.c", + "//base/startup/init_lite/services/param/linux/param_request.c", + "//base/startup/init_lite/services/param/linux/param_service.c", "//base/startup/init_lite/services/param/manager/param_manager.c", - "//base/startup/init_lite/services/param/manager/param_message.c", + "//base/startup/init_lite/services/param/manager/param_persist.c", "//base/startup/init_lite/services/param/manager/param_trie.c", "//base/startup/init_lite/services/param/manager/param_utils.c", - "//base/startup/init_lite/services/param/service/param_persist.c", - "//base/startup/init_lite/services/param/service/param_service.c", "//base/startup/init_lite/services/param/trigger/trigger_checker.c", "//base/startup/init_lite/services/param/trigger/trigger_manager.c", "//base/startup/init_lite/services/param/trigger/trigger_processor.c", @@ -97,6 +100,11 @@ ohos_unittest("init_ut") { "//base/startup/init_lite/ueventd/ueventd_socket.c", ] + if (defined(build_selinux) && build_selinux) { + sources += + [ "//base/startup/init_lite/services/param/adapter/param_selinux.c" ] + } + if (param_feature_watcher) { sources += [ "//base/startup/init_lite/services/param/watcher/agent/watcher.cpp", @@ -106,8 +114,6 @@ ohos_unittest("init_ut") { "//base/startup/init_lite/services/param/watcher/proxy/watcher_manager.cpp", "//base/startup/init_lite/services/param/watcher/proxy/watcher_manager_stub.cpp", "//base/startup/init_lite/services/param/watcher/proxy/watcher_proxy.cpp", - "param/watcher_agent_unittest.cpp", - "param/watcher_proxy_unittest.cpp", ] } @@ -126,9 +132,11 @@ ohos_unittest("init_ut") { "param/client_unittest.cpp", "param/dac_unittest.cpp", "param/param_shell_unittest.cpp", + "param/param_stub.cpp", "param/param_unittest.cpp", - "param/selinux_unittest.cpp", + "param/paramservice_unittest.cpp", "param/trigger_unittest.cpp", + "syspara/syspara_unittest.cpp", "ueventd/ueventd_config_unittest.cpp", ] @@ -138,7 +146,9 @@ ohos_unittest("init_ut") { "//base/customization/config_policy/interfaces/innerkits/include", "//base/startup/init_lite/services/init/standard", "//base/startup/init_lite/interfaces/innerkits/include", + "//base/startup/init_lite/interfaces/innerkits/include/syspara", "//base/startup/init_lite/interfaces/innerkits/fd_holder", + "//base/startup/init_lite/interfaces/innerkits/syspara", "//base/startup/init_lite/services/begetctl", "//base/startup/init_lite/services/begetctl/shell", "//base/startup/init_lite/services/include", @@ -153,20 +163,19 @@ ohos_unittest("init_ut") { "//base/startup/init_lite/services/loopevent/timer", "//base/startup/init_lite/services/loopevent/utils", "//base/startup/init_lite/services/param/adapter", + "//base/startup/init_lite/services/param/linux", "//base/startup/init_lite/services/param/include", "//base/startup/init_lite/services/param/watcher/agent", "//base/startup/init_lite/services/param/watcher/include", "//base/startup/init_lite/services/param/watcher/proxy", "//base/startup/init_lite/test/unittest", "//base/startup/init_lite/test/unittest/param", - "//base/startup/syspara_lite/interfaces/innerkits/native/syspara/include", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", "//foundation/distributedschedule/safwk/services/safwk/include", "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk", "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", "//base/startup/init_lite/ueventd/include", - "//utils/native/base/include", "//utils/system/safwk/native/include", "//third_party/bounds_checking_function/include", "//third_party/cJSON", @@ -179,31 +188,35 @@ ohos_unittest("init_ut") { "//base/customization/config_policy/frameworks/config_policy:configpolicy_util_for_init_static", "//base/security/access_token/interfaces/innerkits/nativetoken:libnativetoken", "//base/security/access_token/interfaces/innerkits/token_setproc:libtoken_setproc", - "//base/startup/syspara_lite/interfaces/innerkits/native/syspara:syspara", "//third_party/bounds_checking_function:libsec_static", "//third_party/cJSON:cjson_static", "//third_party/googletest:gmock", "//third_party/googletest:gtest", - "//utils/native/base:utils", + "//third_party/openssl:libcrypto_shared", ] defines = [ "READ_CHECK", - "PARAM_SUPPORT_DAC_CHECK", "INIT_AGENT", + "INIT_FILE", "STARTUP_INIT_TEST", - "PARAM_SUPPORT_SAVE_PERSIST", "PARAM_SUPPORT_DAC", "_GNU_SOURCE", + "PARAM_SUPPORT_TRIGGER", ] defines += [ "_GNU_SOURCE" ] external_deps = [ "hiviewdfx_hilog_native:libhilog", "init:libinit_plugin_engine", + "utils_base:utils", ] - if (param_feature_watcher) { + if (!defined(ohos_lite) && param_feature_watcher) { + sources += [ + "param/watcher_agent_unittest.cpp", + "param/watcher_proxy_unittest.cpp", + ] external_deps += [ "ipc:ipc_core", "safwk:system_ability_fwk", @@ -211,6 +224,23 @@ ohos_unittest("init_ut") { ] } + if (defined(build_selinux) && build_selinux) { + sources += [ "param/selinux_unittest.cpp" ] + include_dirs += [ + "//third_party/selinux/libselinux/include/", + "//base/security/selinux/interfaces/policycoreutils/include/", + ] + deps += [ + "//base/security/selinux:libload_policy", + "//base/security/selinux:librestorecon", + "//third_party/selinux:libselinux", + ] + defines += [ + "WITH_SELINUX", + "PARAM_SUPPORT_SELINUX", + ] + } + cflags_cc = [ "-fexceptions" ] } diff --git a/test/unittest/begetctl/begetctl_unittest.cpp b/test/unittest/begetctl/begetctl_unittest.cpp index 45bf7cb50d674c289d26dfe66c21ec529ef6ee24..390e98e26fa443be6db5022b0cf54036287549ae 100644 --- a/test/unittest/begetctl/begetctl_unittest.cpp +++ b/test/unittest/begetctl/begetctl_unittest.cpp @@ -13,7 +13,7 @@ * limitations under the License. */ #include "begetctl.h" -#include "init_unittest.h" +#include "param_stub.h" #include "securec.h" #include "shell.h" @@ -23,7 +23,10 @@ using namespace testing::ext; namespace init_ut { class BegetctlUnitTest : public testing::Test { public: - static void SetUpTestCase(void) {}; + static void SetUpTestCase(void) + { + PrepareInitUnitTestEnv(); + }; static void TearDownTestCase(void) {}; void SetUp(void) {}; void TearDown(void) {}; diff --git a/test/unittest/common/BUILD.gn b/test/unittest/common/BUILD.gn deleted file mode 100644 index 39acf4fa011048188c4a0316dc8350d91568f54d..0000000000000000000000000000000000000000 --- a/test/unittest/common/BUILD.gn +++ /dev/null @@ -1,94 +0,0 @@ -# Copyright (c) 2020 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. -if (defined(ohos_lite)) { - import("//build/lite/config/component/lite_component.gni") - import("//build/lite/config/test.gni") - - unittest("init_test") { - output_extension = "bin" - output_dir = "$root_out_dir/test/unittest/startup" - ldflags = [ - "-lstdc++", - "-lpthread", - "-lm", - ] - defines = [ - "OHOS_LITE", - "__MUSL__", - "_GNU_SOURCE", - ] - if (storage_type == "emmc") { - defines += [ "USE_EMMC_STORAGE" ] - } - defines += [ "_GNU_SOURCE" ] - - include_dirs = [ - "//base/startup/init_lite/services/include", - "//base/startup/init_lite/services/init/include", - "//base/startup/init_lite/services/log", - "//base/startup/init_lite/services/loopevent/include", - "//base/startup/init_lite/interfaces/innerkits/include", - "//third_party/cJSON", - "//third_party/bounds_checking_function/include", - "//base/startup/syspara_lite/interfaces/kits", - "//base/hiviewdfx/hilog_lite/interfaces/native/kits", - "//base/startup/init_lite/interfaces/innerkits/fd_holder", - ] - - sources = [ - "//base/startup/init_lite/services/init/adapter/init_adapter.c", - "//base/startup/init_lite/services/init/init_capability.c", - "//base/startup/init_lite/services/init/init_common_cmds.c", - "//base/startup/init_lite/services/init/init_common_service.c", - "//base/startup/init_lite/services/init/init_config.c", - "//base/startup/init_lite/services/init/init_group_manager.c", - "//base/startup/init_lite/services/init/init_service_file.c", - "//base/startup/init_lite/services/init/init_service_manager.c", - "//base/startup/init_lite/services/init/init_service_socket.c", - "//base/startup/init_lite/services/init/lite/init.c", - "//base/startup/init_lite/services/init/lite/init_cmds.c", - "//base/startup/init_lite/services/init/lite/init_jobs.c", - "//base/startup/init_lite/services/init/lite/init_reboot.c", - "//base/startup/init_lite/services/init/lite/init_service.c", - "//base/startup/init_lite/services/init/lite/init_signal_handler.c", - "//base/startup/init_lite/services/log/init_log.c", - "//base/startup/init_lite/services/utils/init_hashmap.c", - "//base/startup/init_lite/services/utils/init_utils.c", - "//base/startup/init_lite/services/utils/list.c", - "cmd_func_test.cpp", - ] - - deps = [ - "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", - "//base/startup/init_lite/initsync:initsync", - "//base/startup/init_lite/services/loopevent:loopevent", - "//base/startup/syspara_lite/frameworks/parameter:parameter", - "//build/lite/config/component/cJSON:cjson_shared", - "//third_party/bounds_checking_function:libsec_shared", - ] - if (ohos_kernel_type == "liteos_a") { - include_dirs += [ - "//kernel/liteos_a/syscall", - "//base/startup/init_lite/interfaces/kits", - "//base/startup/init_lite/initsync/include", - ] - } - } - - group("unittest") { - deps = [ ":init_test" ] - } -} else { - group("unittest") { - } -} diff --git a/test/unittest/init/cmds_unittest.cpp b/test/unittest/init/cmds_unittest.cpp index 0e2ca2c5d76e69254acca0bfe670b4ffe0a2e0c7..03dcc3c6836bedf18a22bf558fe04ff3a2d2afc5 100644 --- a/test/unittest/init/cmds_unittest.cpp +++ b/test/unittest/init/cmds_unittest.cpp @@ -16,7 +16,7 @@ #include #include "init_cmds.h" #include "init_param.h" -#include "init_unittest.h" +#include "param_stub.h" #include "init_utils.h" #include "trigger_manager.h" @@ -28,8 +28,7 @@ class CmdsUnitTest : public testing::Test { public: static void SetUpTestCase(void) { - InitParamService(); - mkdir("/data/init_ut", S_IRWXU | S_IRWXG | S_IRWXO); + PrepareInitUnitTestEnv(); }; static void TearDownTestCase(void) {}; void SetUp() {}; diff --git a/test/unittest/init/group_unittest.cpp b/test/unittest/init/group_unittest.cpp index 6f06331ba4a4e6cf3ff31fce22c5c76e86a21610..dd855bb70e21d76fade09b91303f723ebee0b6e9 100644 --- a/test/unittest/init/group_unittest.cpp +++ b/test/unittest/init/group_unittest.cpp @@ -17,11 +17,10 @@ #include "init_hashmap.h" #include "init_param.h" #include "init_service_manager.h" -#include "init_unittest.h" #include "init_utils.h" -#include "securec.h" -#include "init_service.h" #include "le_timer.h" +#include "param_stub.h" +#include "securec.h" using namespace testing::ext; using namespace std; diff --git a/test/unittest/init/init_reboot_unittest.cpp b/test/unittest/init/init_reboot_unittest.cpp index 8d21996252a59a8b1feef8d825565d13034063b3..d75d1a7c91d77135b13347b64f9e6a335cdfbac0 100644 --- a/test/unittest/init/init_reboot_unittest.cpp +++ b/test/unittest/init/init_reboot_unittest.cpp @@ -17,7 +17,7 @@ #include "init_cmds.h" #include "init_reboot.h" #include "init_param.h" -#include "init_unittest.h" +#include "param_stub.h" #include "init_utils.h" #include "trigger_manager.h" diff --git a/test/unittest/init/loopevent_unittest.cpp b/test/unittest/init/loopevent_unittest.cpp index 8b31f9caf169aed452ac8f12fbead534fe432641..2143b0c450a40f7c09950c1b2964e673a834cbf3 100644 --- a/test/unittest/init/loopevent_unittest.cpp +++ b/test/unittest/init/loopevent_unittest.cpp @@ -12,23 +12,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +#include #include #include -#include "init_unittest.h" -#include "init_utils.h" -#include "init_param.h" + +#include "begetctl.h" +#include "init.h" #include "init_hashmap.h" -#include "loop_event.h" +#include "init_param.h" +#include "init_utils.h" +#include "le_epoll.h" #include "le_loop.h" -#include "init.h" -#include "param_utils.h" -#include "le_task.h" #include "le_socket.h" -#include "le_epoll.h" -#include "param_message.h" +#include "le_task.h" +#include "loop_event.h" #include "param_manager.h" -#include "param_service.h" +#include "param_message.h" +#include "param_utils.h" #include "trigger_manager.h" using namespace testing::ext; @@ -99,15 +99,14 @@ public: void SetUp() {}; void TearDown() {}; void TestBody(void) {}; - void StreamTaskTest() + void StreamTaskTest () { LE_StreamInfo streamInfo = {}; streamInfo.recvMessage = OnReceiveRequest; streamInfo.baseInfo.flags = TASK_STREAM | TASK_PIPE | TASK_CONNECT | TASK_TEST; streamInfo.server = (char *)"/data/testpipea"; TaskHandle clientTaskHandle = nullptr; - LE_AcceptStreamClient(LE_GetDefaultLoop(), (TaskHandle)GetParamWorkSpace()->serverTask, - &clientTaskHandle, &streamInfo); + LE_AcceptStreamClient(LE_GetDefaultLoop(), (TaskHandle)serverTask_, &clientTaskHandle, &streamInfo); if (clientTaskHandle == nullptr) { return; } @@ -133,7 +132,7 @@ public: ((StreamClientTask *)clientTaskHandleb)->stream.base.handleEvent(LE_GetDefaultLoop(), clientTaskHandleb, Event_Write); ((StreamClientTask *)clientTaskHandleb)->stream.base.innerClose(LE_GetDefaultLoop(), clientTaskHandleb); - + TaskHandle clientTaskHandlec = nullptr; streamInfo.baseInfo.flags = TASK_STREAM | TASK_TCP | TASK_SERVER; streamInfo.server = (char *)"0.0.0.0:10110"; @@ -151,18 +150,17 @@ public: } void LeTaskTest() { - ParamTaskPtr serverTask = nullptr; LE_StreamServerInfo info = {}; info.baseInfo.flags = TASK_STREAM | TASK_PIPE | TASK_SERVER | TASK_TEST; info.server = (char *)"/data/testpipe"; info.baseInfo.close = Close; info.incommingConntect = IncomingConnect; - LE_CreateStreamServer(LE_GetDefaultLoop(), &serverTask, &info); - if (serverTask == nullptr) { + LE_CreateStreamServer(LE_GetDefaultLoop(), &serverTask_, &info); + if (serverTask_ == nullptr) { return; } - ((StreamServerTask *)serverTask)->base.handleEvent(LE_GetDefaultLoop(), serverTask, Event_Write); - ((StreamServerTask *)serverTask)->base.handleEvent(LE_GetDefaultLoop(), serverTask, Event_Read); + ((StreamServerTask *)serverTask_)->base.handleEvent(LE_GetDefaultLoop(), serverTask_, Event_Write); + ((StreamServerTask *)serverTask_)->base.handleEvent(LE_GetDefaultLoop(), serverTask_, Event_Read); uint64_t eventId = 0; ParamStreamInfo paramStreamInfo = {}; @@ -172,7 +170,7 @@ public: paramStreamInfo.recvMessage = ProcessMessage; paramStreamInfo.incomingConnect = NULL; ParamTaskPtr client = NULL; - int ret = ParamStreamCreate(&client, GetParamWorkSpace()->serverTask, ¶mStreamInfo, sizeof(ParamWatcher)); + int ret = ParamStreamCreate(&client, serverTask_, ¶mStreamInfo, sizeof(ParamWatcher)); PARAM_CHECK(ret == 0, return, "Failed to create client"); BufferHandle handle = LE_CreateBuffer(LE_GetDefaultLoop(), 1 + sizeof(eventId)); @@ -186,7 +184,7 @@ public: LE_FreeBuffer(LE_GetDefaultLoop(), (TaskHandle)&client, nextBuff); } - ret = ParamStreamCreate(&client, GetParamWorkSpace()->serverTask, ¶mStreamInfo, sizeof(ParamWatcher)); + ret = ParamStreamCreate(&client, serverTask_, ¶mStreamInfo, sizeof(ParamWatcher)); PARAM_CHECK(ret == 0, return, "Failed to create client"); ((StreamConnectTask *)(&client))->stream.base.handleEvent(LE_GetDefaultLoop(), (TaskHandle)(&client), Event_Read); @@ -237,6 +235,9 @@ public: AcceptSocket(-1, TASK_PIPE); AcceptSocket(-1, TASK_TCP); } + +private: + ParamTaskPtr serverTask_ = NULL; }; HWTEST_F(LoopEventUnittest, StreamTaskTest, TestSize.Level1) @@ -287,4 +288,4 @@ HWTEST_F(LoopEventUnittest, RunLoopThread, TestSize.Level1) epoll_ctl(epoll->epollFd, EPOLL_CTL_MOD, fd, &event); pthread_join(tid, nullptr); } -} // namespace init_ut +} // namespace init_ut diff --git a/test/unittest/init/mount_unittest.cpp b/test/unittest/init/mount_unittest.cpp index e86e78f126cab6bf3c223a23b530dc2cd5fa1fdd..cad55674a422d1213ca8c7dbd898b3a87fd6c60e 100644 --- a/test/unittest/init/mount_unittest.cpp +++ b/test/unittest/init/mount_unittest.cpp @@ -15,7 +15,7 @@ #include #include #include "fs_manager/fs_manager.h" -#include "init_unittest.h" +#include "param_stub.h" #include "init_mount.h" #include "securec.h" using namespace std; diff --git a/test/unittest/init/plugin_unittest.cpp b/test/unittest/init/plugin_unittest.cpp index 50eb2a690656861dddd46c422cce4f81e2e907c2..906d43b1f6f79a670dd18236370ac07f007e2d4e 100755 --- a/test/unittest/init/plugin_unittest.cpp +++ b/test/unittest/init/plugin_unittest.cpp @@ -18,7 +18,7 @@ #include "init_param.h" #include "init_plugin_engine.h" #include "init_plugin_manager.h" -#include "init_unittest.h" +#include "param_stub.h" #include "init_utils.h" #include "securec.h" diff --git a/test/unittest/init/service_file_unittest.cpp b/test/unittest/init/service_file_unittest.cpp index 4d062fce95f31efd02a5a6b24cea6a5588d8d868..9e640c5b78c9536284d353fe2c287d3159c62db0 100644 --- a/test/unittest/init/service_file_unittest.cpp +++ b/test/unittest/init/service_file_unittest.cpp @@ -20,7 +20,7 @@ #include "init_file.h" #include "init_service_file.h" -#include "init_unittest.h" +#include "param_stub.h" #include "securec.h" using namespace testing::ext; diff --git a/test/unittest/init/service_socket_unittest.cpp b/test/unittest/init/service_socket_unittest.cpp index 5f266ce2af274e2365da36d96265e9cc45eebe79..162037b8c8d10aa507e7ac4e610adc7391b2ba83 100644 --- a/test/unittest/init/service_socket_unittest.cpp +++ b/test/unittest/init/service_socket_unittest.cpp @@ -19,7 +19,7 @@ #include "init_service_manager.h" #include "init_service_socket.h" #include "init_socket.h" -#include "init_unittest.h" +#include "param_stub.h" #include "securec.h" #include "le_task.h" using namespace std; diff --git a/test/unittest/init/service_unittest.cpp b/test/unittest/init/service_unittest.cpp index df6d09ea2e875c287bfbfcb9e02843241b42e5c4..9ca7158760e87809b7cfde51f163e5d9f6f16de0 100644 --- a/test/unittest/init/service_unittest.cpp +++ b/test/unittest/init/service_unittest.cpp @@ -20,7 +20,7 @@ #include "init_service.h" #include "init_service_manager.h" #include "init_service_socket.h" -#include "init_unittest.h" +#include "param_stub.h" #include "init_utils.h" #include "securec.h" diff --git a/test/unittest/init/utils_unittest.cpp b/test/unittest/init/utils_unittest.cpp index 43dad7c182502601f7cc24ed85798a2b0832dbf5..c131340f80e8fc5fe78574656fe9bf63a29cedad 100644 --- a/test/unittest/init/utils_unittest.cpp +++ b/test/unittest/init/utils_unittest.cpp @@ -15,7 +15,7 @@ #include #include #include -#include "init_unittest.h" +#include "param_stub.h" #include "init_utils.h" #include "init_service_socket.h" #include "init_socket.h" diff --git a/test/unittest/innerkits/innerkits_unittest.cpp b/test/unittest/innerkits/innerkits_unittest.cpp index 451f5053a80f0ceda94e272831776c9bac3dbb9b..03d1124e216b1b5a92df9bc43901cc37c57f5948 100644 --- a/test/unittest/innerkits/innerkits_unittest.cpp +++ b/test/unittest/innerkits/innerkits_unittest.cpp @@ -17,7 +17,7 @@ #include #include "fs_manager/fs_manager.h" #include "init_log.h" -#include "init_unittest.h" +#include "param_stub.h" #include "securec.h" using namespace testing::ext; diff --git a/test/unittest/lite/BUILD.gn b/test/unittest/lite/BUILD.gn new file mode 100755 index 0000000000000000000000000000000000000000..792b3e5aa63561c180c199842ca1c74ddb218dde --- /dev/null +++ b/test/unittest/lite/BUILD.gn @@ -0,0 +1,201 @@ +# Copyright (c) 2020 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. +if (defined(ohos_lite)) { + import("//build/lite/config/component/lite_component.gni") + import("//build/lite/config/test.gni") + if (ohos_kernel_type == "linux" || ohos_kernel_type == "liteos_a") { + init_common_sources = [ + "//base/startup/init_lite/services/init/adapter/init_adapter.c", + "//base/startup/init_lite/services/init/init_capability.c", + "//base/startup/init_lite/services/init/init_common_cmds.c", + "//base/startup/init_lite/services/init/init_common_service.c", + "//base/startup/init_lite/services/init/init_config.c", + "//base/startup/init_lite/services/init/init_group_manager.c", + "//base/startup/init_lite/services/init/init_service_file.c", + "//base/startup/init_lite/services/init/init_service_manager.c", + "//base/startup/init_lite/services/init/init_service_socket.c", + "//base/startup/init_lite/services/init/lite/init.c", + "//base/startup/init_lite/services/init/lite/init_cmds.c", + "//base/startup/init_lite/services/init/lite/init_jobs.c", + "//base/startup/init_lite/services/init/lite/init_reboot.c", + "//base/startup/init_lite/services/init/lite/init_service.c", + "//base/startup/init_lite/services/init/lite/init_signal_handler.c", + "//base/startup/init_lite/services/log/init_log.c", + "//base/startup/init_lite/services/utils/init_hashmap.c", + "//base/startup/init_lite/services/utils/init_utils.c", + "//base/startup/init_lite/services/utils/list.c", + ] + } + param_common_sources = [ + "//base/startup/init_lite/services/param/adapter/param_dac.c", + "//base/startup/init_lite/services/param/adapter/param_persistadp.c", + "//base/startup/init_lite/services/param/manager/param_manager.c", + "//base/startup/init_lite/services/param/manager/param_persist.c", + "//base/startup/init_lite/services/param/manager/param_trie.c", + "//base/startup/init_lite/services/param/manager/param_utils.c", + ] + + sysparam_source = [ + "//base/startup/init_lite/interfaces/innerkits/syspara/param_comm.c", + "//base/startup/init_lite/interfaces/innerkits/syspara/parameter.c", + "//base/startup/init_lite/interfaces/innerkits/syspara/sysversion.c", + ] + + unittest("init_test") { + output_extension = "bin" + output_dir = "$root_out_dir/test/unittest/startup" + ldflags = [ + "-lstdc++", + "-lpthread", + "-lm", + ] + defines = [ + "OHOS_LITE", + "__MUSL__", + "_GNU_SOURCE", + "READ_CHECK", + "STARTUP_INIT_TEST", + "PARAM_SUPPORT_DAC", + "USE_MBEDTLS", + "STARTUP_INIT_UT_PATH =\"/userdata/init_ut\"", + ] + if (storage_type == "emmc") { + defines += [ "USE_EMMC_STORAGE" ] + } + + include_dirs = [ + "//base/startup/init_lite/services/include", + "//base/startup/init_lite/services/include/param", + "//base/startup/init_lite/services/init/include", + "//base/startup/init_lite/services/log", + "//base/startup/init_lite/services/loopevent/include", + "//base/startup/init_lite/services/param/adapter", + "//base/startup/init_lite/services/param/linux", + "//base/startup/init_lite/services/param/include", + "//base/startup/init_lite/services/param/watcher/agent", + "//base/startup/init_lite/services/param/watcher/include", + "//base/startup/init_lite/services/param/watcher/proxy", + "//base/startup/init_lite/test/unittest", + "//base/startup/init_lite/test/unittest/param", + "//base/startup/init_lite/interfaces/innerkits/include", + "//base/startup/init_lite/interfaces/innerkits/include/syspara", + "//third_party/cJSON", + "//third_party/bounds_checking_function/include", + "//base/hiviewdfx/hilog_lite/interfaces/native/kits", + "//base/startup/init_lite/interfaces/innerkits/fd_holder", + ] + + sources = sysparam_source + sources += param_common_sources + deps = [ "//third_party/bounds_checking_function:libsec_static" ] + + if (ohos_kernel_type == "liteos_a") { + defines += [ "__LITEOS_A__" ] + include_dirs += [ + "//kernel/liteos_a/syscall", + "//base/startup/init_lite/interfaces/kits/syscap", + "//base/startup/init_lite/initsync/include", + ] + sources += init_common_sources + sources += [ + "//base/startup/init_lite/services/param/liteos/param_client.c", + "//base/startup/init_lite/services/param/liteos/param_osadp.c", + "//base/startup/init_lite/services/param/liteos/param_service.c", + ] + + sources += [ + "../param/client_unittest.cpp", + "../param/param_stub.cpp", + "../param/param_unittest.cpp", + "../syspara/syspara_unittest.cpp", + "cmd_func_test.cpp", + ] + + # add cfg.h + deps += [ + "//base/startup/init_lite/services/param:lite_const_param_to", + "//base/startup/init_lite/services/param:lite_ohos_param_to", + ] + + deps += [ + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", + "//base/startup/init_lite/initsync:initsync", + "//base/startup/init_lite/services/loopevent:loopevent", + "//build/lite/config/component/cJSON:cjson_static", + "//third_party/mbedtls:mbedtls", + ] + include_dirs += [ "$root_out_dir/gen/init_lite" ] + defines += [ "PARAM_LOAD_CFG_FROM_CODE" ] + } + + if (ohos_kernel_type == "liteos_m") { + defines += [ "__LITEOS_M__" ] + sources += [ + "//base/startup/init_lite/services/param/liteos/param_client.c", + "//base/startup/init_lite/services/param/liteos/param_osadp.c", + "//base/startup/init_lite/services/param/liteos/param_service.c", + ] + sources += [ + "../param/dac_unittest.cpp", + "../param/param_stub.cpp", + "../param/param_unittest.cpp", + "../syspara/syspara_unittest.cpp", + ] + + # add cfg.h + deps += [ + "//base/startup/init_lite/services/param:lite_const_param_to", + "//base/startup/init_lite/services/param:lite_ohos_param_to", + ] + + deps += [ + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_static", + "//base/startup/init_lite/services/utils:libinit_tools", + "//third_party/mbedtls:mbedtls", + ] + include_dirs += [ "$root_out_dir/gen/init_lite" ] + defines += [ "PARAM_LOAD_CFG_FROM_CODE" ] + } + if (ohos_kernel_type == "linux") { + defines += [ "__LINUX__" ] + + sources += init_common_sources + sources += [ + "//base/startup/init_lite/services/param/linux/param_message.c", + "//base/startup/init_lite/services/param/linux/param_msgadp.c", + "//base/startup/init_lite/services/param/linux/param_osadp.c", + "//base/startup/init_lite/services/param/linux/param_request.c", + "//base/startup/init_lite/services/param/linux/param_service.c", + "//base/startup/init_lite/services/param/trigger/trigger_checker.c", + "//base/startup/init_lite/services/param/trigger/trigger_manager.c", + "//base/startup/init_lite/services/param/trigger/trigger_processor.c", + ] + sources += [ + "../param/client_unittest.cpp", + "../param/dac_unittest.cpp", + "../param/param_stub.cpp", + "../param/param_unittest.cpp", + "../param/paramservice_unittest.cpp", + "../syspara/syspara_unittest.cpp", + "cmd_func_test.cpp", + ] + + deps += [ + "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared", + "//base/startup/init_lite/services/loopevent:loopevent", + "//build/lite/config/component/cJSON:cjson_static", + "//third_party/mbedtls:mbedtls", + ] + } + } +} diff --git a/test/unittest/common/cmd_func_test.cpp b/test/unittest/lite/cmd_func_test.cpp old mode 100644 new mode 100755 similarity index 98% rename from test/unittest/common/cmd_func_test.cpp rename to test/unittest/lite/cmd_func_test.cpp index 101cfbad7b398131d2681736e0d74089f56d5791..72abd1588263a9082c8a455bd8fcbc87fb34ccb1 --- a/test/unittest/common/cmd_func_test.cpp +++ b/test/unittest/lite/cmd_func_test.cpp @@ -12,6 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include #include #include #include @@ -20,13 +21,13 @@ #include #include +#include "beget_ext.h" #include "cJSON.h" #include "init_cmds.h" #include "init_jobs_internal.h" #include "init_service_manager.h" -#include "beget_ext.h" +#include "param_stub.h" #include "securec.h" -#include "gtest/gtest.h" using namespace std; using namespace testing::ext; @@ -95,10 +96,10 @@ public: std::string writeContent = "This is a test file for startup subsystem init module."; if (fwrite(writeContent.c_str(), writeContent.length(), 1, testFile) != 1) { - fclose(testFile); + (void)fclose(testFile); return; } - fclose(testFile); + (void)fclose(testFile); #ifndef USE_EMMC_STORAGE // emmc storage does not support chmod/chown @@ -110,6 +111,7 @@ public: return; } #endif // USE_EMMC_STORAGE + PrepareInitUnitTestEnv(); } static void TearDownTestCase() @@ -706,13 +708,14 @@ static void CheckCmd(const TestCmdLine *resCmd) size_t spacePos = 0; size_t spaceCnt = 0; for (size_t i = 1; i < strlen(resCmd->cmdContent); ++i) { - if (resCmd->cmdContent[i] == ' ') { - ++spaceCnt; - if (spacePos != 0) { - EXPECT_NE(spacePos + 1, i); // consecutive spaces should not appear - } - spacePos = i; + if (resCmd->cmdContent[i] != ' ') { + continue; + } + ++spaceCnt; + if (spacePos != 0) { + EXPECT_NE(spacePos + 1, i); // consecutive spaces should not appear } + spacePos = i; } EXPECT_EQ(spaceCnt, 2); // 2 spaces allowed in cmd content } else if (strcmp("mount ", resCmd->name) == 0) { @@ -822,11 +825,11 @@ static void CreateIllegalCfg() std::string writeContent = "mount zpfs /patch/etc:/etc /etc"; if (fwrite(writeContent.c_str(), writeContent.length(), 1, testCfgFile) != 1) { - fclose(testCfgFile); + (void)fclose(testCfgFile); return; } - fclose(testCfgFile); + (void)fclose(testCfgFile); } /* diff --git a/test/unittest/param/client_unittest.cpp b/test/unittest/param/client_unittest.cpp index 01df8e5a8bce25a5746874e25e5e431ac1c40390..e3152e176ddef0c703ea215cb4d598e4fbadc941 100644 --- a/test/unittest/param/client_unittest.cpp +++ b/test/unittest/param/client_unittest.cpp @@ -12,20 +12,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include -#include "init_unittest.h" +#include "init_param.h" #include "init_utils.h" -#include "param_request.h" #include "param_stub.h" -#include "sys_param.h" using namespace std; using namespace testing::ext; -static int g_testPermissionResult = DAC_RESULT_PERMISSION; static void ClientCheckParamValue(const char *name, const char *expectValue) { - char tmp[PARAM_BUFFER_SIZE] = { 0 }; + char tmp[PARAM_BUFFER_SIZE] = {0}; u_int32_t len = sizeof(tmp); int ret = SystemGetParameter(name, tmp, &len); printf("ClientCheckParamValue name %s value: \'%s\' expectValue:\'%s\' \n", name, tmp, expectValue); @@ -47,6 +45,7 @@ static void *TestSendParamSetMsg(void *args) } std::string name = (char *)args; printf("TestSendParamSetMsg name :\'%s\' \n", name.c_str()); + SystemWriteParam(name.c_str(), name.c_str()); SystemSetParameter(name.c_str(), name.c_str()); ClientCheckParamValue(name.c_str(), name.c_str()); return nullptr; @@ -89,8 +88,10 @@ static void TestForMultiThread() static void TestParamTraversal() { - SystemTraversalParameter("", [](ParamHandle handle, void *cookie) { - char value[PARAM_BUFFER_SIZE + PARAM_BUFFER_SIZE] = { 0 }; + SystemTraversalParameter( + "", + [](ParamHandle handle, void *cookie) { + char value[PARAM_BUFFER_SIZE + PARAM_BUFFER_SIZE] = {0}; uint32_t commitId = 0; int ret = SystemGetParameterCommitId(handle, &commitId); EXPECT_EQ(ret, 0); @@ -102,57 +103,43 @@ static void TestParamTraversal() nullptr); } -static void TestPersistParam() -{ - SystemSetParameter("persist.111.ffff.bbbb.cccc.dddd.eeee", "1101"); - SystemSetParameter("persist.111.aaaa.bbbb.cccc.dddd.eeee", "1102"); - SystemSetParameter("persist.111.bbbb.cccc.dddd.eeee", "1103"); - ClientCheckParamValue("persist.111.bbbb.cccc.dddd.eeee", "1103"); - SystemSetParameter("persist.111.cccc.bbbb.cccc.dddd.eeee", "1104"); - SystemSetParameter("persist.111.eeee.bbbb.cccc.dddd.eeee", "1105"); - ClientCheckParamValue("persist.111.ffff.bbbb.cccc.dddd.eeee", "1101"); - SystemSetParameter("persist.111.ffff.bbbb.cccc.dddd.eeee", "1106"); - ClientCheckParamValue("persist.111.ffff.bbbb.cccc.dddd.eeee", "1106"); -} - static void TestPermission() { const char *testName = "persist.111.ffff.bbbb.cccc.dddd.eeee.55555"; - char tmp[PARAM_BUFFER_SIZE] = { 0 }; + char tmp[PARAM_BUFFER_SIZE] = {0}; int ret; // 允许本地校验 - ParamSecurityOps *paramSecurityOps = &GetClientParamWorkSpace()->paramSecurityOps; + ParamSecurityOps *paramSecurityOps = GetParamSecurityOps(0); paramSecurityOps->securityCheckParamPermission = TestCheckParamPermission; - g_testPermissionResult = DAC_RESULT_FORBIDED; - if ((GetClientParamWorkSpace() != nullptr) && (GetClientParamWorkSpace()->securityLabel != nullptr)) { - GetClientParamWorkSpace()->securityLabel->flags = LABEL_CHECK_FOR_ALL_PROCESS; + SetTestPermissionResult(DAC_RESULT_FORBIDED); + if ((GetParamSecurityLabel() != nullptr)) { + GetParamSecurityLabel()->flags[0] = LABEL_CHECK_IN_ALL_PROCESS; ret = SystemSetParameter(testName, "22202"); EXPECT_EQ(ret, DAC_RESULT_FORBIDED); } - paramSecurityOps->securityEncodeLabel = TestEncodeSecurityLabel; - paramSecurityOps->securityDecodeLabel = TestDecodeSecurityLabel; paramSecurityOps->securityFreeLabel = TestFreeLocalSecurityLabel; paramSecurityOps->securityCheckParamPermission = TestCheckParamPermission; - g_testPermissionResult = 0; + SetTestPermissionResult(0); + SystemWriteParam(testName, "22202"); ret = SystemSetParameter(testName, "22202"); - EXPECT_EQ(ret, 0); ClientCheckParamValue(testName, "22202"); const int testResult = 201; - g_testPermissionResult = testResult; + SetTestPermissionResult(testResult); // 禁止写/读 ret = SystemSetParameter(testName, "3333"); EXPECT_EQ(ret, testResult); u_int32_t len = sizeof(tmp); ret = SystemGetParameter(testName, tmp, &len); EXPECT_EQ(ret, testResult); - RegisterSecurityOps(paramSecurityOps, 0); + RegisterSecurityOps(0); } void TestClientApi(char testBuffer[], uint32_t size, const char *name, const char *value) { ParamHandle handle; int ret = SystemFindParameter(name, &handle); + SystemWriteParam(name, value); SystemSetParameter(name, value); ret = SystemFindParameter(name, &handle); EXPECT_EQ(ret, 0); @@ -167,49 +154,21 @@ void TestClientApi(char testBuffer[], uint32_t size, const char *name, const cha EXPECT_EQ(strcmp(testBuffer, value), 0); } -int TestEncodeSecurityLabel(const ParamSecurityLabel *srcLabel, char *buffer, uint32_t *bufferSize) -{ - PARAM_CHECK(bufferSize != nullptr, return -1, "Invalid param"); - if (buffer == nullptr) { - *bufferSize = sizeof(ParamSecurityLabel); - return 0; - } - PARAM_CHECK(*bufferSize >= sizeof(ParamSecurityLabel), return -1, "Invalid buffersize %u", *bufferSize); - *bufferSize = sizeof(ParamSecurityLabel); - return memcpy_s(buffer, *bufferSize, srcLabel, sizeof(ParamSecurityLabel)); -} - -int TestDecodeSecurityLabel(ParamSecurityLabel **srcLabel, const char *buffer, uint32_t bufferSize) -{ - PARAM_CHECK(bufferSize >= sizeof(ParamSecurityLabel), return -1, "Invalid buffersize %u", bufferSize); - PARAM_CHECK(srcLabel != nullptr && buffer != nullptr, return -1, "Invalid param"); - *srcLabel = (ParamSecurityLabel *)buffer; - return 0; -} - -int TestCheckParamPermission(const ParamSecurityLabel *srcLabel, const ParamAuditData *auditData, uint32_t mode) -{ - // DAC_RESULT_FORBIDED - return g_testPermissionResult; -} - -int TestFreeLocalSecurityLabel(ParamSecurityLabel *srcLabel) -{ - return 0; -} - namespace init_ut { class ClientUnitTest : public ::testing::Test { public: ClientUnitTest() {} virtual ~ClientUnitTest() {} + static void SetUpTestCase(void) + { + PrepareInitUnitTestEnv(); + }; void SetUp(void) { - ParamWorkSpace *space = GetClientParamWorkSpace(); - if (space != nullptr && space->securityLabel != nullptr) { - space->securityLabel->cred.uid = 1000; // 1000 test uid - space->securityLabel->cred.gid = 1000; // 1000 test gid + if (GetParamSecurityLabel() != nullptr) { + GetParamSecurityLabel()->cred.uid = 1000; // 1000 test uid + GetParamSecurityLabel()->cred.gid = 1000; // 1000 test gid } } void TearDown(void) {} @@ -220,10 +179,11 @@ HWTEST_F(ClientUnitTest, TestClient_01, TestSize.Level0) { const std::string name = "test.add.client.001.001"; const std::string value = "test.add.client.value.001.001"; + // direct write + SystemWriteParam(name.c_str(), value.c_str()); SystemSetParameter(name.c_str(), value.c_str()); ClientCheckParamValue(name.c_str(), value.c_str()); SystemWaitParameter(name.c_str(), value.c_str(), 1); - TestPersistParam(); // wait SystemWaitParameter(name.c_str(), value.c_str(), 1); SystemWaitParameter(name.c_str(), nullptr, 0); @@ -231,7 +191,7 @@ HWTEST_F(ClientUnitTest, TestClient_01, TestSize.Level0) HWTEST_F(ClientUnitTest, TestClient_02, TestSize.Level0) { - char testBuffer[PARAM_BUFFER_SIZE] = { 0 }; + char testBuffer[PARAM_BUFFER_SIZE] = {0}; const std::string value = "test.add.client.value.001"; const std::string name = "test.add.client.001.003"; TestClientApi(testBuffer, PARAM_BUFFER_SIZE, name.c_str(), value.c_str()); @@ -248,7 +208,9 @@ HWTEST_F(ClientUnitTest, TestClient_04, TestSize.Level0) { const std::string name = "test.add.client.001.004"; int ret = WatchParamCheck(name.c_str()); +#ifndef OHOS_LITE EXPECT_EQ(ret, 0); +#endif ret = WatchParamCheck("&&&&&.test.tttt"); EXPECT_NE(ret, 0); // test permission diff --git a/test/unittest/param/dac_unittest.cpp b/test/unittest/param/dac_unittest.cpp index 5906c9820ab76b15ff6f5fd9d654be5b4f90c793..bd287d69b8b171154efada6158cb52e3f2dc5553 100644 --- a/test/unittest/param/dac_unittest.cpp +++ b/test/unittest/param/dac_unittest.cpp @@ -12,28 +12,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include #include -#include -#include +#include "param_manager.h" #include "param_security.h" +#include "param_stub.h" #include "param_utils.h" #include "securec.h" -#include "init_unittest.h" - -extern "C" { -extern int RegisterSecurityDacOps(ParamSecurityOps *ops, int isInit); -} using namespace testing::ext; using namespace std; -static int SecurityLabelGet(const ParamAuditData *auditData, void *context) -{ - return 0; -} - +namespace init_ut { class DacUnitTest : public ::testing::Test { public: DacUnitTest() {} @@ -51,10 +41,10 @@ public: if (initParamSercurityOps.securityInitLabel == nullptr || initParamSercurityOps.securityFreeLabel == nullptr) { return -1; } - ParamSecurityLabel *label = nullptr; + ParamSecurityLabel label = {}; ret = initParamSercurityOps.securityInitLabel(&label, LABEL_INIT_FOR_INIT); EXPECT_EQ(ret, 0); - ret = initParamSercurityOps.securityFreeLabel(label); + ret = initParamSercurityOps.securityFreeLabel(&label); EXPECT_EQ(ret, 0); return 0; } @@ -66,12 +56,12 @@ public: if (initParamSercurityOps.securityCheckFilePermission == nullptr) { return -1; } - ParamSecurityLabel *label = nullptr; + ParamSecurityLabel label = {}; ret = initParamSercurityOps.securityInitLabel(&label, LABEL_INIT_FOR_INIT); EXPECT_EQ(ret, 0); - ret = initParamSercurityOps.securityCheckFilePermission(label, fileName, DAC_WRITE); + ret = initParamSercurityOps.securityCheckFilePermission(&label, fileName, DAC_WRITE); EXPECT_EQ(ret, 0); - ret = initParamSercurityOps.securityFreeLabel(label); + ret = initParamSercurityOps.securityFreeLabel(&label); EXPECT_EQ(ret, 0); return 0; } @@ -83,16 +73,17 @@ public: if (initParamSercurityOps.securityCheckFilePermission == nullptr) { return -1; } - ParamSecurityLabel *srclabel = nullptr; - ret = initParamSercurityOps.securityInitLabel(&srclabel, LABEL_INIT_FOR_INIT); - EXPECT_EQ(ret, 0); - ParamAuditData auditData = {}; auditData.name = name; - auditData.label = nullptr; - memcpy_s(&auditData.dacData, sizeof(ParamDacData), dacData, sizeof(ParamDacData)); - ret = initParamSercurityOps.securityCheckParamPermission(srclabel, &auditData, mode); - initParamSercurityOps.securityFreeLabel(srclabel); + ret = memcpy_s(&auditData.dacData, sizeof(auditData.dacData), dacData, sizeof(auditData.dacData)); + EXPECT_EQ(ret, 0); + ret = AddSecurityLabel(&auditData); + EXPECT_EQ(ret, 0); + ParamSecurityLabel srclabel = {}; + ret = initParamSercurityOps.securityInitLabel(&srclabel, LABEL_INIT_FOR_INIT); + EXPECT_EQ(ret, 0); + ret = initParamSercurityOps.securityCheckParamPermission(&srclabel, name, mode); + initParamSercurityOps.securityFreeLabel(&srclabel); return ret; } @@ -100,9 +91,6 @@ public: { int ret = RegisterSecurityDacOps(&clientParamSercurityOps, 0); EXPECT_EQ(ret, 0); - if (clientParamSercurityOps.securityDecodeLabel != nullptr) { - EXPECT_EQ(1, 0); - } if (clientParamSercurityOps.securityGetLabel != nullptr) { EXPECT_EQ(1, 0); } @@ -110,61 +98,16 @@ public: EXPECT_EQ(1, 0); return -1; } - ParamSecurityLabel *label = nullptr; + ParamSecurityLabel label = {}; ret = clientParamSercurityOps.securityInitLabel(&label, 0); EXPECT_EQ(ret, 0); - ret = clientParamSercurityOps.securityCheckFilePermission(label, fileName, DAC_READ); + ret = clientParamSercurityOps.securityCheckFilePermission(&label, fileName, DAC_READ); EXPECT_EQ(ret, 0); - ret = clientParamSercurityOps.securityFreeLabel(label); + ret = clientParamSercurityOps.securityFreeLabel(&label); EXPECT_EQ(ret, 0); return 0; } - int TestEncode(const ParamSecurityLabel *label, std::vector &buffer) - { - int ret = RegisterSecurityDacOps(&clientParamSercurityOps, 0); - EXPECT_EQ(ret, 0); - if (clientParamSercurityOps.securityDecodeLabel != nullptr) { - EXPECT_EQ(1, 0); - } - if (clientParamSercurityOps.securityGetLabel != nullptr) { - EXPECT_EQ(1, 0); - } - if (clientParamSercurityOps.securityEncodeLabel == nullptr) { - EXPECT_EQ(1, 0); - return -1; - } - uint32_t bufferSize = 0; - ret = clientParamSercurityOps.securityEncodeLabel(label, nullptr, &bufferSize); - EXPECT_EQ(ret, 0); - buffer.resize(bufferSize + 1); - ret = clientParamSercurityOps.securityEncodeLabel(label, buffer.data(), &bufferSize); - EXPECT_EQ(ret, 0); - return 0; - } - - int TestDecode(const ParamSecurityLabel *label, std::vector &buffer) - { - int ret = RegisterSecurityDacOps(&clientParamSercurityOps, 1); - EXPECT_EQ(ret, 0); - if (clientParamSercurityOps.securityDecodeLabel == nullptr) { - EXPECT_EQ(1, 0); - } - if (clientParamSercurityOps.securityEncodeLabel != nullptr) { - EXPECT_EQ(1, 0); - return -1; - } - ParamSecurityLabel *tmp = nullptr; - ret = clientParamSercurityOps.securityDecodeLabel(&tmp, buffer.data(), buffer.size()); - if (label == nullptr || tmp == nullptr) { - return -1; - } - EXPECT_EQ(ret, 0); - EXPECT_EQ(label->cred.gid, tmp->cred.gid); - EXPECT_EQ(label->cred.uid, tmp->cred.uid); - return 0; - } - private: ParamSecurityOps initParamSercurityOps {}; ParamSecurityOps clientParamSercurityOps {}; @@ -176,19 +119,10 @@ HWTEST_F(DacUnitTest, TestDacInitLocalLabel, TestSize.Level0) test.TestDacInitLocalLabel(); } -HWTEST_F(DacUnitTest, TestDacLabelEncode, TestSize.Level0) -{ - DacUnitTest test; - std::vector buffer; - ParamSecurityLabel label = {0, { 4444, 5555}}; - test.TestEncode(&label, buffer); - test.TestDecode(&label, buffer); -} - HWTEST_F(DacUnitTest, TestDacCheckFilePermission, TestSize.Level0) { DacUnitTest test; - test.TestDacCheckFilePermission(PARAM_DEFAULT_PATH"/trigger_test.cfg"); + test.TestDacCheckFilePermission(STARTUP_INIT_UT_PATH "/trigger_test.cfg"); } HWTEST_F(DacUnitTest, TestDacCheckUserParaPermission, TestSize.Level0) @@ -204,29 +138,29 @@ HWTEST_F(DacUnitTest, TestDacCheckUserParaPermission, TestSize.Level0) EXPECT_EQ(ret, 0); dacData.mode = 0400; ret = test.TestDacCheckParaPermission("test.permission.read.aaa", &dacData, DAC_WRITE); - EXPECT_EQ(ret, 0); + EXPECT_NE(ret, 0); dacData.mode = 0400; ret = test.TestDacCheckParaPermission("test.permission.read.aaa", &dacData, DAC_WATCH); - EXPECT_EQ(ret, 0); + EXPECT_NE(ret, 0); // write dacData.mode = 0200; ret = test.TestDacCheckParaPermission("test.permission.write.aaa", &dacData, DAC_READ); - EXPECT_EQ(ret, 0); + EXPECT_NE(ret, 0); dacData.mode = 0200; ret = test.TestDacCheckParaPermission("test.permission.write.aaa", &dacData, DAC_WRITE); EXPECT_EQ(ret, 0); dacData.mode = 0200; ret = test.TestDacCheckParaPermission("test.permission.write.aaa", &dacData, DAC_WATCH); - EXPECT_EQ(ret, 0); + EXPECT_NE(ret, 0); // watch dacData.mode = 0100; ret = test.TestDacCheckParaPermission("test.permission.watch.aaa", &dacData, DAC_READ); - EXPECT_EQ(ret, 0); + EXPECT_NE(ret, 0); dacData.mode = 0100; ret = test.TestDacCheckParaPermission("test.permission.watch.aaa", &dacData, DAC_WRITE); - EXPECT_EQ(ret, 0); + EXPECT_NE(ret, 0); dacData.mode = 0100; ret = test.TestDacCheckParaPermission("test.permission.watch.aaa", &dacData, DAC_WATCH); EXPECT_EQ(ret, 0); @@ -245,29 +179,29 @@ HWTEST_F(DacUnitTest, TestDacCheckGroupParaPermission, TestSize.Level0) EXPECT_EQ(ret, 0); dacData.mode = 0040; ret = test.TestDacCheckParaPermission("test.permission.read.aaa", &dacData, DAC_WRITE); - EXPECT_EQ(ret, 0); + EXPECT_NE(ret, 0); dacData.mode = 0040; ret = test.TestDacCheckParaPermission("test.permission.read.aaa", &dacData, DAC_WATCH); - EXPECT_EQ(ret, 0); + EXPECT_NE(ret, 0); // write dacData.mode = 0020; ret = test.TestDacCheckParaPermission("test.permission.write.aaa", &dacData, DAC_READ); - EXPECT_EQ(ret, 0); + EXPECT_NE(ret, 0); dacData.mode = 0020; ret = test.TestDacCheckParaPermission("test.permission.write.aaa", &dacData, DAC_WRITE); EXPECT_EQ(ret, 0); dacData.mode = 0020; ret = test.TestDacCheckParaPermission("test.permission.write.aaa", &dacData, DAC_WATCH); - EXPECT_EQ(ret, 0); + EXPECT_NE(ret, 0); // watch dacData.mode = 0010; ret = test.TestDacCheckParaPermission("test.permission.watch.aaa", &dacData, DAC_READ); - EXPECT_EQ(ret, 0); + EXPECT_NE(ret, 0); dacData.mode = 0010; ret = test.TestDacCheckParaPermission("test.permission.watch.aaa", &dacData, DAC_WRITE); - EXPECT_EQ(ret, 0); + EXPECT_NE(ret, 0); dacData.mode = 0010; ret = test.TestDacCheckParaPermission("test.permission.watch.aaa", &dacData, DAC_WATCH); EXPECT_EQ(ret, 0); @@ -286,29 +220,29 @@ HWTEST_F(DacUnitTest, TestDacCheckOtherParaPermission, TestSize.Level0) EXPECT_EQ(ret, 0); dacData.mode = 0004; ret = test.TestDacCheckParaPermission("test.permission.read.aaa", &dacData, DAC_WRITE); - EXPECT_EQ(ret, 0); + EXPECT_NE(ret, 0); dacData.mode = 0004; ret = test.TestDacCheckParaPermission("test.permission.read.aaa", &dacData, DAC_WATCH); - EXPECT_EQ(ret, 0); + EXPECT_NE(ret, 0); // write dacData.mode = 0002; ret = test.TestDacCheckParaPermission("test.permission.write.aaa", &dacData, DAC_READ); - EXPECT_EQ(ret, 0); + EXPECT_NE(ret, 0); dacData.mode = 0002; ret = test.TestDacCheckParaPermission("test.permission.write.aaa", &dacData, DAC_WRITE); EXPECT_EQ(ret, 0); dacData.mode = 0002; ret = test.TestDacCheckParaPermission("test.permission.write.aaa", &dacData, DAC_WATCH); - EXPECT_EQ(ret, 0); + EXPECT_NE(ret, 0); // watch dacData.mode = 0001; ret = test.TestDacCheckParaPermission("test.permission.watch.aaa", &dacData, DAC_READ); - EXPECT_EQ(ret, 0); + EXPECT_NE(ret, 0); dacData.mode = 0001; ret = test.TestDacCheckParaPermission("test.permission.watch.aaa", &dacData, DAC_WRITE); - EXPECT_EQ(ret, 0); + EXPECT_NE(ret, 0); dacData.mode = 0001; ret = test.TestDacCheckParaPermission("test.permission.watch.aaa", &dacData, DAC_WATCH); EXPECT_EQ(ret, 0); @@ -317,5 +251,6 @@ HWTEST_F(DacUnitTest, TestDacCheckOtherParaPermission, TestSize.Level0) HWTEST_F(DacUnitTest, TestClientDacCheckFilePermission, TestSize.Level0) { DacUnitTest test; - test.TestClientDacCheckFilePermission(PARAM_DEFAULT_PATH"/trigger_test.cfg"); + test.TestClientDacCheckFilePermission(STARTUP_INIT_UT_PATH "/trigger_test.cfg"); } +} \ No newline at end of file diff --git a/test/unittest/param/param_shell_unittest.cpp b/test/unittest/param/param_shell_unittest.cpp index 413e4a4147f503a5b4d667324e95b5fcfebe5a81..f3fb26cb7eff5ff8dd59115a23a4170ac28f9f9a 100644 --- a/test/unittest/param/param_shell_unittest.cpp +++ b/test/unittest/param/param_shell_unittest.cpp @@ -12,8 +12,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include + #include "begetctl.h" -#include "init_unittest.h" #include "securec.h" #include "shell.h" #include "shell_utils.h" diff --git a/test/unittest/param/param_stub.cpp b/test/unittest/param/param_stub.cpp new file mode 100755 index 0000000000000000000000000000000000000000..55c6cbe7a16d32cfc91de64e24cb549bc5e31d36 --- /dev/null +++ b/test/unittest/param/param_stub.cpp @@ -0,0 +1,287 @@ +/* + * Copyright (c) 2021 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 "param_stub.h" + +#include "beget_ext.h" +#include "init_param.h" +#include "param_manager.h" +#include "param_security.h" +#include "param_utils.h" +#ifdef PARAM_LOAD_CFG_FROM_CODE +#include "param_cfg.h" +#endif + +#ifdef __cplusplus +#if __cplusplus +extern "C" { +#endif +#endif + +static int g_testPermissionResult = DAC_RESULT_PERMISSION; +void SetTestPermissionResult(int result) +{ + g_testPermissionResult = result; +} + +static const char *selinuxLabels[][2] = { + {"test.permission.read", "test.persmission.read"}, + {"test.permission.write", "test.persmission.write"}, + {"test.permission.watch", "test.persmission.watch"} +}; + +static int TestGenHashCode(const char *buff) +{ + int code = 0; + size_t buffLen = strlen(buff); + for (size_t i = 0; i < buffLen; i++) { + code += buff[i] - 'A'; + } + return code; +} + +static void TestSetSelinuxLogCallback(void) {} + +static const char *forbitWriteParamName[] = { + "ohos.servicectrl.", + "test.permission.read", + "test.persmission.watch" +}; + +static int TestSetParamCheck(const char *paraName, struct ucred *uc) +{ + // forbit to read ohos.servicectrl. + for (size_t i = 0; i < ARRAY_LENGTH(forbitWriteParamName); i++) { + if (strncmp(paraName, forbitWriteParamName[i], strlen(forbitWriteParamName[i])) == 0) { + return 1; + } + } + return g_testPermissionResult; +} + +static const char *TestGetParamLabel(const char *paraName) +{ + BEGET_LOGI("TestGetParamLabel %s", paraName); + for (size_t i = 0; i < ARRAY_LENGTH(selinuxLabels); i++) { + if (strncmp(selinuxLabels[i][0], paraName, strlen(selinuxLabels[i][0])) == 0) { + return selinuxLabels[i][1]; + } + } + int code = TestGenHashCode(paraName); + code = code % (ARRAY_LENGTH(selinuxLabels)); + return selinuxLabels[code][1]; +} + +static const char *forbitReadParamName[] = { + "ohos.servicectrl.", + // "test.permission.write", +}; + +static int TestReadParamCheck(const char *paraName) +{ + // forbit to read ohos.servicectrl. + for (size_t i = 0; i < ARRAY_LENGTH(forbitReadParamName); i++) { + if (strncmp(paraName, forbitReadParamName[i], strlen(forbitReadParamName[i])) == 0) { + return 1; + } + } + return g_testPermissionResult; +} + +static void TestDestroyParamList(ParamContextsList **list) +{ +#ifdef PARAM_SUPPORT_SELINUX + ParamContextsList *head = *list; + while (head != nullptr) { + ParamContextsList *next = head->next; + free(head->info.paraName); + free(head->info.paraContext); + free(head); + head = next; + } +#endif +} + +static ParamContextsList *TestGetParamList(void) +{ +#ifdef PARAM_SUPPORT_SELINUX + ParamContextsList *head = (ParamContextsList *)malloc(sizeof(ParamContextsList)); + BEGET_ERROR_CHECK(head != nullptr, return nullptr, "Failed to alloc ParamContextsList"); + head->info.paraName = strdup(selinuxLabels[0][0]); + head->info.paraContext = strdup(selinuxLabels[0][1]); + head->next = nullptr; + for (size_t i = 1; i < ARRAY_LENGTH(selinuxLabels); i++) { + ParamContextsList *node = (ParamContextsList *)malloc(sizeof(ParamContextsList)); + BEGET_ERROR_CHECK(node != nullptr, TestDestroyParamList(&head); + return nullptr, "Failed to alloc ParamContextsList"); + node->info.paraName = strdup(selinuxLabels[i][0]); + node->info.paraContext = strdup(selinuxLabels[i][1]); + node->next = head->next; + head->next = node; + } + return head; +#else + return nullptr; +#endif +} + +void TestSetSelinuxOps(void) +{ + SelinuxSpace space = {}; + space.setSelinuxLogCallback = TestSetSelinuxLogCallback; + space.setParamCheck = TestSetParamCheck; + space.getParamLabel = TestGetParamLabel; + space.readParamCheck = TestReadParamCheck; + space.getParamList = TestGetParamList; + space.destroyParamList = TestDestroyParamList; +#ifdef PARAM_SUPPORT_SELINUX + SetSelinuxOps(&space); +#endif +} + +static void CreateTestFile(const char *fileName, const char *data) +{ + CheckAndCreateDir(fileName); + PARAM_LOGV("PrepareParamTestData for %s", fileName); + FILE *tmpFile = fopen(fileName, "wr"); + if (tmpFile != nullptr) { + fprintf(tmpFile, "%s", data); + (void)fflush(tmpFile); + fclose(tmpFile); + } +} + +static void LoadParamFromCfg(void) +{ +#ifdef PARAM_LOAD_CFG_FROM_CODE + for (size_t i = 0; i < ARRAY_LENGTH(g_paramDefCfgNodes); i++) { + PARAM_LOGI("InitParamClient name %s = %s", g_paramDefCfgNodes[i].name, g_paramDefCfgNodes[i].value); + uint32_t dataIndex = 0; + int ret = WriteParam(g_paramDefCfgNodes[i].name, g_paramDefCfgNodes[i].value, &dataIndex, 0); + PARAM_CHECK(ret == 0, continue, "Failed to set param %d name %s %s", + ret, g_paramDefCfgNodes[i].name, g_paramDefCfgNodes[i].value); + } +#endif +} +#if !(defined __LITEOS_A__ || defined __LITEOS_M__) +static const char *g_triggerData = "{" + "\"jobs\" : [{" + " \"name\" : \"early-init\"," + " \"cmds\" : [" + " \" write '/proc/sys/kernel/sysrq 0'\"," + " \" load_persist_params \"," + " \" load_persist_params \"," + " \" # load_persist_params \"," + " \" restorecon /postinstall\"," + " \"mkdir /acct/uid\"," + " \"chown root system /dev/memcg/memory.pressure_level\"," + " \"chmod 0040 /dev/memcg/memory.pressure_level\"," + " \"mkdir /dev/memcg/apps/ 0755 system system\"," + " \"mkdir /dev/memcg/system 0550 system system\"," + " \"start ueventd\"," + " \"exec_start apexd-bootstrap\"," + " \"setparam sys.usb.config ${persist.sys.usb.config}\"" + " ]" + " }," + " {" + " \"name\" : \"param:trigger_test_1\"," + " \"condition\" : \"test.sys.boot_from_charger_mode=5\"," + " \"cmds\" : [" + " \"class_stop charger\"," + " \"trigger late-init\"" + " ]" + " }," + " {" + " \"name\" : \"param:trigger_test_2\"," + " \"condition\" : \"test.sys.boot_from_charger_mode=1 " + " || test.sys.boot_from_charger_mode=2 || test.sys.boot_from_charger_mode=3\"," + " \"cmds\" : [" + " \"class_stop charger\"," + " \"trigger late-init\"" + " ]" + " }," + " {" + " \"name\" : \"load_persist_params_action\"," + " \"cmds\" : [" + " \"load_persist_params\"," + " \"start logd\"," + " \"start logd-reinit\"" + " ]" + " }," + " {" + " \"name\" : \"firmware_mounts_complete\"," + " \"cmds\" : [" + " \"rm /dev/.booting\"" + " ]" + " }" + "]" + "}"; +#endif + +void PrepareInitUnitTestEnv(void) +{ + static int evnOk = 0; + if (evnOk) { + return; + } + PARAM_LOGI("PrepareInitUnitTestEnv"); + mkdir(STARTUP_INIT_UT_PATH, S_IRWXU | S_IRWXG | S_IRWXO); + SetInitLogLevel(INIT_DEBUG); + +#if !(defined __LITEOS_A__ || defined __LITEOS_M__) + // for cmdline + const char *cmdLine = "bootgroup=device.charing.group earlycon=uart8250,mmio32,0xfe660000 \ + root=PARTUUID=614e0000-0000 rw rootwait rootfstype=ext4 console=ttyFIQ0 hardware=rk3568"; + CreateTestFile(BOOT_CMD_LINE, cmdLine); + + // for dac + std::string dacData = "ohos.servicectrl. = system:servicectrl:0775 \n"; + dacData += "test.permission. = root:root:0770\n"; + dacData += "test.permission.read. = root:root:0774\n"; + dacData += "test.permission.write.= root:root:0772\n"; + dacData += "test.permission.watcher. = root:root:0771\n"; + CreateTestFile(STARTUP_INIT_UT_PATH "/system/etc/param/ohos.para.dac", dacData.c_str()); + + CreateTestFile(STARTUP_INIT_UT_PATH"/trigger_test.cfg", g_triggerData); + TestSetSelinuxOps(); +#endif + InitParamService(); + + // read system parameters + LoadDefaultParams("/system/etc/param/ohos_const", LOAD_PARAM_NORMAL); + LoadDefaultParams("/vendor/etc/param", LOAD_PARAM_NORMAL); + LoadDefaultParams("/system/etc/param", LOAD_PARAM_ONLY_ADD); + // read ut parameters + LoadDefaultParams(STARTUP_INIT_UT_PATH "/system/etc/param/ohos_const", LOAD_PARAM_NORMAL); + LoadDefaultParams(STARTUP_INIT_UT_PATH "/vendor/etc/param", LOAD_PARAM_NORMAL); + LoadDefaultParams(STARTUP_INIT_UT_PATH "/system/etc/param", LOAD_PARAM_ONLY_ADD); + LoadParamFromCfg(); + evnOk = 1; +} + +int TestCheckParamPermission(const ParamSecurityLabel *srcLabel, const char *name, uint32_t mode) +{ + // DAC_RESULT_FORBIDED + return g_testPermissionResult; +} + +int TestFreeLocalSecurityLabel(ParamSecurityLabel *srcLabel) +{ + return 0; +} +#ifdef __cplusplus +#if __cplusplus +} +#endif +#endif \ No newline at end of file diff --git a/test/unittest/param/param_stub.h b/test/unittest/param/param_stub.h index 983034e951dd63f45f2ad000ee2edef11918872b..f8d06d334b4bcead67addef7e0ee5933fdb918fd 100644 --- a/test/unittest/param/param_stub.h +++ b/test/unittest/param/param_stub.h @@ -14,9 +14,13 @@ */ #ifndef PARAM_TEST_STUB_ #define PARAM_TEST_STUB_ +#include +#include +#include +#include + #include "param_manager.h" #include "param_security.h" -#include "param_service.h" #include "param_utils.h" #ifdef __cplusplus @@ -24,17 +28,19 @@ extern "C" { #endif #endif -extern int RunParamCommand(int argc, char *argv[]); + +#define TEST_PATH "/data/ueventd_ut" + +void PrepareInitUnitTestEnv(void); +void TestSetSelinuxOps(void); +void SetTestPermissionResult(int result); + +int TestCheckParamPermission(const ParamSecurityLabel *srcLabel, const char *name, uint32_t mode); +int TestFreeLocalSecurityLabel(ParamSecurityLabel *srcLabel); + #ifdef __cplusplus #if __cplusplus } #endif #endif - -void TestClient(int index); -int TestEncodeSecurityLabel(const ParamSecurityLabel *srcLabel, char *buffer, uint32_t *bufferSize); -int TestDecodeSecurityLabel(ParamSecurityLabel **srcLabel, const char *buffer, uint32_t bufferSize); -int TestCheckParamPermission(const ParamSecurityLabel *srcLabel, const ParamAuditData *auditData, uint32_t mode); -int TestFreeLocalSecurityLabel(ParamSecurityLabel *srcLabel); - -#endif // PARAM_TEST_STUB_ \ No newline at end of file +#endif // PARAM_TEST_STUB_ \ No newline at end of file diff --git a/test/unittest/param/param_unittest.cpp b/test/unittest/param/param_unittest.cpp index abe2b553e5c909e47ef1b608c9c8060487464d00..3aada23bae060b7c8752ef403d05f8e6c4426c1f 100644 --- a/test/unittest/param/param_unittest.cpp +++ b/test/unittest/param/param_unittest.cpp @@ -12,14 +12,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include +#include #include "init_param.h" -#include "init_unittest.h" +#include "param_message.h" #include "param_stub.h" #include "trigger_manager.h" -#include "param_message.h" -#include "param_utils.h" using namespace testing::ext; using namespace std; @@ -31,7 +29,7 @@ static void OnClose(ParamTaskPtr client) static int CheckServerParamValue(const char *name, const char *expectValue) { - char tmp[PARAM_BUFFER_SIZE] = { 0 }; + char tmp[PARAM_BUFFER_SIZE] = {0}; u_int32_t len = sizeof(tmp); SystemReadParam(name, tmp, &len); printf("CheckParamValue name %s value: \'%s\' expectValue:\'%s\' \n", name, tmp, expectValue); @@ -42,16 +40,16 @@ static int CheckServerParamValue(const char *name, const char *expectValue) return 0; } -extern "C" { -extern void TimerCallbackForSave(ParamTaskPtr timer, void *context); -} - -static ParamTaskPtr g_worker = nullptr; +namespace init_ut { class ParamUnitTest : public ::testing::Test { public: ParamUnitTest() {} virtual ~ParamUnitTest() {} + static void SetUpTestCase(void) + { + PrepareInitUnitTestEnv(); + }; void SetUp() {} void TearDown() {} void TestBody() {} @@ -75,40 +73,41 @@ public: int TestAddSecurityLabel1() { - GetParamWorkSpace()->securityLabel->cred.gid = 9999; // 9999 test gid + GetParamSecurityLabel()->cred.gid = 9999; // 9999 test gid const char *name = "label1.test.aaa.bbb.ccc.dddd.eee"; const char *value = "2001"; uint32_t labelIndex = 0; SystemWriteParam(name, value); // 获取到跟属性 - ParamTrieNode *paramNode = FindTrieNode(&GetParamWorkSpace()->paramSpace, name, strlen(name), &labelIndex); - ParamSecruityNode *node = (ParamSecruityNode *)GetTrieNode(&GetParamWorkSpace()->paramSpace, labelIndex); - if (paramNode == nullptr || node == nullptr) { + WorkSpace *workspace = GetWorkSpace(WORKSPACE_NAME_DAC); + (void)FindTrieNode(workspace, name, strlen(name), &labelIndex); + ParamSecruityNode *node = (ParamSecruityNode *)GetTrieNode(workspace, labelIndex); + if (node == nullptr) { EXPECT_EQ(1, 0); return 0; } - EXPECT_EQ(node->gid, getegid()); + EXPECT_EQ(node->gid, 0); return 0; } // 添加一个label,最长匹配到这个节点 int TestAddSecurityLabel2() { - GetParamWorkSpace()->securityLabel->cred.gid = 9999; // 9999 test gid + GetParamSecurityLabel()->cred.gid = 9999; // 9999 test gid const char *name = "label2.test.aaa.bbb.ccc.dddd.eee"; const char *value = "2001"; ParamAuditData auditData = {}; auditData.name = "label2.test.aaa"; - auditData.label = "label2.test.aaa"; - auditData.dacData.gid = 202; // 202 test dac gid + auditData.dacData.gid = 202; // 202 test dac gid auditData.dacData.uid = geteuid(); - auditData.dacData.mode = 0666; // 0666 test mode + auditData.dacData.mode = 0666; // 0666 test mode SystemWriteParam(name, value); uint32_t labelIndex = 0; - AddSecurityLabel(&auditData, GetParamWorkSpace()); - ParamTrieNode *paramNode = FindTrieNode(&GetParamWorkSpace()->paramSpace, name, strlen(name), &labelIndex); - ParamSecruityNode *node = (ParamSecruityNode *)GetTrieNode(&GetParamWorkSpace()->paramSpace, labelIndex); - if (paramNode == nullptr || node == nullptr) { + AddSecurityLabel(&auditData); + WorkSpace *workspace = GetWorkSpace(WORKSPACE_NAME_DAC); + (void)FindTrieNode(workspace, name, strlen(name), &labelIndex); + ParamSecruityNode *node = (ParamSecruityNode *)GetTrieNode(workspace, labelIndex); + if (node == nullptr) { EXPECT_EQ(1, 0); return 0; } @@ -119,54 +118,53 @@ public: // 添加一个label,最长匹配到最后一个相同节点 int TestAddSecurityLabel3() { - GetParamWorkSpace()->securityLabel->cred.gid = 9999; // 9999 test gid + GetParamSecurityLabel()->cred.gid = 9999; // 9999 test gid const char *name = "label3.test.aaa.bbb.ccc.dddd.eee"; const char *value = "2001"; ParamAuditData auditData = {}; auditData.name = "label3.test.aaa"; - auditData.label = "label3.test.aaa"; - auditData.dacData.gid = 203; // 203 test gid + auditData.dacData.gid = 203; // 203 test gid auditData.dacData.uid = geteuid(); - auditData.dacData.mode = 0666; // 0666 test mode + auditData.dacData.mode = 0666; // 0666 test mode SystemWriteParam(name, value); - AddSecurityLabel(&auditData, GetParamWorkSpace()); + AddSecurityLabel(&auditData); auditData.name = "label3.test.aaa.bbb.ccc.dddd.eee.dddd"; - auditData.label = "label3.test.aaa.bbb.ccc.dddd.eee.dddd"; - auditData.dacData.gid = 202; // 202 test dac gid + auditData.dacData.gid = 202; // 202 test dac gid auditData.dacData.uid = geteuid(); - auditData.dacData.mode = 0666; // 0666 test mode + auditData.dacData.mode = 0666; // 0666 test mode SystemWriteParam(name, value); - AddSecurityLabel(&auditData, GetParamWorkSpace()); + AddSecurityLabel(&auditData); uint32_t labelIndex = 0; - ParamTrieNode *paramNode = FindTrieNode(&GetParamWorkSpace()->paramSpace, name, strlen(name), &labelIndex); - ParamSecruityNode *node = (ParamSecruityNode *)GetTrieNode(&GetParamWorkSpace()->paramSpace, labelIndex); + WorkSpace *workspace = GetWorkSpace(WORKSPACE_NAME_DAC); + ParamTrieNode *paramNode = FindTrieNode(workspace, name, strlen(name), &labelIndex); + ParamSecruityNode *node = (ParamSecruityNode *)GetTrieNode(workspace, labelIndex); if (paramNode == nullptr || node == nullptr) { EXPECT_EQ(1, 0); return 0; } - EXPECT_EQ((int)node->gid, 203); // 203 test gid + EXPECT_EQ((int)node->gid, 203); // 203 test gid return 0; } // 添加一个label,完全匹配 int TestAddSecurityLabel4() { - GetParamWorkSpace()->securityLabel->cred.gid = 9999; // 9999 test gid + GetParamSecurityLabel()->cred.gid = 9999; // 9999 test gid const char *name = "label4.test.aaa.bbb.ccc.dddd.eee"; const char *value = "2001"; ParamAuditData auditData = {}; auditData.name = "label4.test.aaa.bbb.ccc.dddd.eee"; - auditData.label = "label4.test.aaa.bbb.ccc.dddd.eee"; - auditData.dacData.gid = 203; // 203 test gid + auditData.dacData.gid = 203; // 203 test gid auditData.dacData.uid = geteuid(); - auditData.dacData.mode = 0666; // 0666 test mode + auditData.dacData.mode = 0666; // 0666 test mode SystemWriteParam(name, value); uint32_t labelIndex = 0; - AddSecurityLabel(&auditData, GetParamWorkSpace()); - ParamTrieNode *paramNode = FindTrieNode(&GetParamWorkSpace()->paramSpace, name, strlen(name), &labelIndex); - ParamSecruityNode *node = (ParamSecruityNode *)GetTrieNode(&GetParamWorkSpace()->paramSpace, labelIndex); + AddSecurityLabel(&auditData); + WorkSpace *workspace = GetWorkSpace(WORKSPACE_NAME_DAC); + ParamTrieNode *paramNode = FindTrieNode(workspace, name, strlen(name), &labelIndex); + ParamSecruityNode *node = (ParamSecruityNode *)GetTrieNode(workspace, labelIndex); if (paramNode == nullptr || node == nullptr) { EXPECT_EQ(1, 0); return 0; @@ -236,12 +234,13 @@ public: int TestParamTraversal() { - char value[PARAM_BUFFER_SIZE + PARAM_BUFFER_SIZE] = { 0 }; - TraversalParam(GetParamWorkSpace(), "", + char value[PARAM_BUFFER_SIZE + PARAM_BUFFER_SIZE] = {0}; + SystemTraversalParameter( + "", [](ParamHandle handle, void *cookie) { - ReadParamName(GetParamWorkSpace(), handle, (char *)cookie, PARAM_BUFFER_SIZE); + ReadParamName(handle, (char *)cookie, PARAM_BUFFER_SIZE); u_int32_t len = PARAM_BUFFER_SIZE; - ReadParamValue(GetParamWorkSpace(), handle, ((char *)cookie) + PARAM_BUFFER_SIZE, &len); + ReadParamValue(handle, ((char *)cookie) + PARAM_BUFFER_SIZE, &len); printf("$$$$$$$$Param %s=%s \n", (char *)cookie, ((char *)cookie) + PARAM_BUFFER_SIZE); }, (void *)value); @@ -260,11 +259,19 @@ public: int TestPersistParam() { + ParamAuditData auditData = {}; + auditData.name = "persist."; + auditData.dacData.gid = 0; + auditData.dacData.uid = 0; + auditData.dacData.mode = 0777; // 0777 test mode + AddSecurityLabel(&auditData); + LoadPersistParams(); SystemWriteParam("persist.111.ffff.bbbb.cccc.dddd.eeee", "1101"); SystemWriteParam("persist.111.aaaa.bbbb.cccc.dddd.eeee", "1102"); SystemWriteParam("persist.111.bbbb.cccc.dddd.eeee", "1103"); CheckServerParamValue("persist.111.bbbb.cccc.dddd.eeee", "1103"); + SystemWriteParam("persist.111.cccc.bbbb.cccc.dddd.eeee", "1104"); SystemWriteParam("persist.111.eeee.bbbb.cccc.dddd.eeee", "1105"); CheckServerParamValue("persist.111.ffff.bbbb.cccc.dddd.eeee", "1101"); @@ -277,217 +284,16 @@ public: sleep(1); SystemWriteParam("persist.111.bbbb.cccc.dddd.1110", "1108"); SystemWriteParam("persist.111.bbbb.cccc.dddd.1111", "1108"); - if (GetParamWorkSpace() != nullptr) { - TimerCallbackForSave(nullptr, &(GetParamWorkSpace()->paramSpace)); - } + TimerCallbackForSave(nullptr, nullptr); LoadPersistParams(); return 0; } - int FillLabelContent(ParamSecurityOps *paramSecurityOps, ParamMessage *request, uint32_t *start, uint32_t length) - { - if (length == 0) { - return 0; - } - uint32_t bufferSize = request->msgSize - sizeof(ParamMessage); - uint32_t offset = *start; - PARAM_CHECK((offset + sizeof(ParamMsgContent) + length) <= bufferSize, - return -1, "Invalid msgSize %u offset %u length %u", request->msgSize, offset, bufferSize); - ParamMsgContent *content = (ParamMsgContent *)(request->data + offset); - content->type = PARAM_LABEL; - content->contentSize = 0; - if (length != 0 && paramSecurityOps->securityEncodeLabel != nullptr) { - int ret = paramSecurityOps->securityEncodeLabel( - GetParamWorkSpace()->securityLabel, content->content, &length); - PARAM_CHECK(ret == 0, return -1, "Failed to get label length"); - content->contentSize = length; - } - offset += sizeof(ParamMsgContent) + PARAM_ALIGN(content->contentSize); - *start = offset; - return 0; - } - - ParamTaskPtr CreateAndGetStreamTask() - { - ParamStreamInfo info = {}; - info.flags = PARAM_TEST_FLAGS; - info.server = NULL; - info.close = OnClose; - info.recvMessage = ProcessMessage; - info.incomingConnect = NULL; - ParamTaskPtr client = NULL; - int ret = ParamStreamCreate(&client, GetParamWorkSpace()->serverTask, &info, sizeof(ParamWatcher)); - PARAM_CHECK(ret == 0, return NULL, "Failed to create client"); - - ParamWatcher *watcher = (ParamWatcher *)ParamGetTaskUserData(client); - PARAM_CHECK(watcher != NULL, return NULL, "Failed to get watcher"); - ListInit(&watcher->triggerHead); - watcher->stream = client; - GetParamWorkSpace()->watcherTask = client; - return GetParamWorkSpace()->watcherTask; - } - - int TestServiceProcessMessage(const char *name, const char *value, int userLabel) - { - if (g_worker == nullptr) { - g_worker = CreateAndGetStreamTask(); - } - if (g_worker == nullptr) { - return 0; - } - uint32_t labelLen = 0; - ParamSecurityOps *paramSecurityOps = &GetParamWorkSpace()->paramSecurityOps; - if (userLabel) { - paramSecurityOps->securityEncodeLabel = TestEncodeSecurityLabel; - paramSecurityOps->securityDecodeLabel = TestDecodeSecurityLabel; - paramSecurityOps->securityFreeLabel = TestFreeLocalSecurityLabel; - paramSecurityOps->securityCheckParamPermission = TestCheckParamPermission; - } - uint32_t msgSize = sizeof(ParamMessage) + sizeof(ParamMsgContent) + PARAM_ALIGN(strlen(value) + 1); - if (paramSecurityOps->securityEncodeLabel != nullptr) { - int ret = paramSecurityOps->securityEncodeLabel(GetParamWorkSpace()->securityLabel, nullptr, &labelLen); - PARAM_CHECK(ret == 0, return -1, "Failed to get label length"); - msgSize += sizeof(ParamMsgContent) + PARAM_ALIGN(labelLen); - } - ParamMessage *request = (ParamMessage *)CreateParamMessage(MSG_SET_PARAM, name, msgSize); - PARAM_CHECK(request != nullptr, return -1, "Failed to malloc for connect"); - do { - request->type = MSG_SET_PARAM; - uint32_t offset = 0; - int ret = FillParamMsgContent(request, &offset, PARAM_VALUE, value, strlen(value)); - PARAM_CHECK(ret == 0, break, "Failed to fill value"); - ret = FillLabelContent(paramSecurityOps, request, &offset, labelLen); - PARAM_CHECK(ret == 0, break, "Failed to fill label"); - ProcessMessage((const ParamTaskPtr)g_worker, (const ParamMessage *)request); - } while (0); - free(request); - RegisterSecurityOps(paramSecurityOps, 1); - return 0; - } - - int AddWatch(int type, const char *name, const char *value) - { - if (g_worker == nullptr) { - g_worker = CreateAndGetStreamTask(); - } - if (g_worker == nullptr) { - return 0; - } - uint32_t msgSize = sizeof(ParamMessage) + sizeof(ParamMsgContent) + PARAM_ALIGN(strlen(value) + 1); - ParamMessage *request = (ParamMessage *)(ParamMessage *)CreateParamMessage(type, name, msgSize); - PARAM_CHECK(request != nullptr, return -1, "Failed to malloc for connect"); - do { - uint32_t offset = 0; - int ret = FillParamMsgContent(request, &offset, PARAM_VALUE, value, strlen(value)); - PARAM_CHECK(ret == 0, break, "Failed to fill value"); - ProcessMessage((const ParamTaskPtr)g_worker, (const ParamMessage *)request); - } while (0); - free(request); - return 0; - } - - // 无匹配 - int TestAddParamWait1() - { - const char *name = "wait.aaa.bbb.ccc.111"; - const char *value = "wait1"; - AddWatch(MSG_WAIT_PARAM, name, value); - SystemWriteParam(name, value); - return 0; - } - - // 模糊匹配 - int TestAddParamWait2() - { - const char *name = "wait.aaa.bbb.ccc.222"; - const char *value = "wait2"; - AddWatch(MSG_WAIT_PARAM, name, "*"); - SystemWriteParam(name, value); - return 0; - } - - // 属性存在 - int TestAddParamWait3() - { - const char *name = "wait.aaa.bbb.ccc.333"; - const char *value = "wait3"; - SystemWriteParam(name, value); - AddWatch(MSG_WAIT_PARAM, name, value); - return 0; - } - - int TestAddParamWatch1() - { - const char *name = "watch.aaa.bbb.ccc.111"; - const char *value = "watch1"; - AddWatch(MSG_ADD_WATCHER, name, value); - std::string newName = name; - newName += ".test.test.test"; - SystemWriteParam(newName.c_str(), value); - return 0; - } - - int TestAddParamWatch2() - { - const char *name = "watch.aaa.bbb.ccc.222"; - const char *value = "watch2"; - AddWatch(MSG_ADD_WATCHER, name, "*"); - SystemWriteParam(name, value); - return 0; - } - - int TestAddParamWatch3() - { - const char *name = "watch.aaa.bbb.ccc.333"; - const char *value = "watch3"; - std::string newName = name; - newName += ".test.test.test"; - SystemWriteParam(newName.c_str(), value); - AddWatch(MSG_ADD_WATCHER, name, value); - return 0; - } - - int TestCloseTriggerWatch() - { - ParamWatcher *watcher = (ParamWatcher *)ParamGetTaskUserData(g_worker); - ClearWatchTrigger(watcher, TRIGGER_PARAM_WAIT); - ParamTaskClose(g_worker); - g_worker = nullptr; - SystemWriteParam("init.svc.param_watcher", "stopped"); - return 0; - } - int TestDumpParamMemory() { - DumpParametersAndTriggers(); + SystemDumpParameters(1); return 0; } - - int TestServiceCtrl(const char *serviceName, int mode) - { - // service forbit - ParamAuditData auditData = {}; - auditData.name = "ohos.servicectrl."; - auditData.label = ""; - auditData.dacData.gid = 202; // 202 test dac gid - auditData.dacData.uid = 202; // 202 test dac uid - auditData.dacData.mode = mode; - AddSecurityLabel(&auditData, GetParamWorkSpace()); - return SystemWriteParam("ohos.ctl.start", serviceName); - } - - int TestPowerCtrl(const char *reboot, int mode) - { - // service forbit - ParamAuditData auditData = {}; - auditData.name = "ohos.servicectrl."; - auditData.label = ""; - auditData.dacData.gid = 202; // 202 test dac gid - auditData.dacData.uid = 202; // 202 test dac uid - auditData.dacData.mode = mode; - AddSecurityLabel(&auditData, GetParamWorkSpace()); - return SystemWriteParam("ohos.startup.powerctrl", reboot); - } }; HWTEST_F(ParamUnitTest, TestPersistParam, TestSize.Level0) @@ -499,36 +305,36 @@ HWTEST_F(ParamUnitTest, TestPersistParam, TestSize.Level0) HWTEST_F(ParamUnitTest, TestSetParam_1, TestSize.Level0) { ParamUnitTest test; - const char *params[][2] = { { "111.2222", "1" }, - { "111.2222.3333", "2" }, - { "111.2222.3333.4444", "3" }, - { "111.2222.3333.4444.666", "4" }, - { "111.2222.3333.4444.666.777", "5" } }; + const char *params[][2] = {{"111.2222", "1"}, + {"111.2222.3333", "2"}, + {"111.2222.3333.4444", "3"}, + {"111.2222.3333.4444.666", "4"}, + {"111.2222.3333.4444.666.777", "5"}}; test.TestSetParams(params, 5); } HWTEST_F(ParamUnitTest, TestSetParam_2, TestSize.Level0) { ParamUnitTest test; - const char *params[][2] = { { "111.2222.xxxx.xxx.xxx", "1_1" }, - { "111.2222.3333.xxx", "1_2" }, - { "111.2222.xxxx.3333.4444", "1_3" }, - { "111.2222.3333.xxxx.4444.666", "1_4" }, - { "111.2222.3333.4444.666.xxxxx.777", "1_5" } }; + const char *params[][2] = {{"111.2222.xxxx.xxx.xxx", "1_1"}, + {"111.2222.3333.xxx", "1_2"}, + {"111.2222.xxxx.3333.4444", "1_3"}, + {"111.2222.3333.xxxx.4444.666", "1_4"}, + {"111.2222.3333.4444.666.xxxxx.777", "1_5"}}; test.TestSetParams(params, 5); - const char *ctrlParams[][2] = { { "ctl.start.111.2222.xxxx.xxx.xxx", "2_1" }, - { "ctl.start.111.2222.3333.xxx", "2_2" }, - { "ctl.start.111.2222.xxxx.3333.4444", "2_3" }, - { "ctl.start.111.2222.3333.xxxx.4444.666", "2_4" }, - { "ctl.start.111.2222.3333.4444.666.xxxxx.777", "2_5" } }; + const char *ctrlParams[][2] = {{"ctl.start.111.2222.xxxx.xxx.xxx", "2_1"}, + {"ctl.start.111.2222.3333.xxx", "2_2"}, + {"ctl.start.111.2222.xxxx.3333.4444", "2_3"}, + {"ctl.start.111.2222.3333.xxxx.4444.666", "2_4"}, + {"ctl.start.111.2222.3333.4444.666.xxxxx.777", "2_5"}}; test.TestSetParams(ctrlParams, 5); - const char *sysParams[][2] = { { "ohos.startup.powerctrl.111.2222.xxxx.xxx.xxx", "3_1" }, - { "ohos.startup.powerctrl.111.2222.3333.xxx", "3_2" }, - { "ohos.startup.powerctrl.111.2222.xxxx.3333.4444", "3_3" }, - { "ohos.startup.powerctrl.111.2222.3333.xxxx.4444.666", "3_4" }, - { "ohos.startup.powerctrl.111.2222.3333.4444.666.xxxxx.777", "3_5" } }; + const char *sysParams[][2] = {{"ohos.startup.powerctrl.111.2222.xxxx.xxx.xxx", "3_1"}, + {"ohos.startup.powerctrl.111.2222.3333.xxx", "3_2"}, + {"ohos.startup.powerctrl.111.2222.xxxx.3333.4444", "3_3"}, + {"ohos.startup.powerctrl.111.2222.3333.xxxx.4444.666", "3_4"}, + {"ohos.startup.powerctrl.111.2222.3333.4444.666.xxxxx.777", "3_5"}}; test.TestSetParams(sysParams, 5); } @@ -572,55 +378,6 @@ HWTEST_F(ParamUnitTest, TestUpdateParam, TestSize.Level0) test.TestUpdateParam("net.tcp.default_init_rwnd", "60"); } -HWTEST_F(ParamUnitTest, TestServiceProcessMessage, TestSize.Level0) -{ - ParamUnitTest test; - test.TestServiceProcessMessage("wertt.qqqq.wwww.rrrr", "wwww.eeeee", 1); - test.TestServiceProcessMessage("wertt.2222.wwww.3333", "wwww.eeeee", 0); -} - -HWTEST_F(ParamUnitTest, TestAddParamWait1, TestSize.Level0) -{ - ParamUnitTest test; - test.TestAddParamWait1(); -} - -HWTEST_F(ParamUnitTest, TestAddParamWait2, TestSize.Level0) -{ - ParamUnitTest test; - test.TestAddParamWait2(); -} - -HWTEST_F(ParamUnitTest, TestAddParamWait3, TestSize.Level0) -{ - ParamUnitTest test; - test.TestAddParamWait3(); -} - -HWTEST_F(ParamUnitTest, TestAddParamWatch1, TestSize.Level0) -{ - ParamUnitTest test; - test.TestAddParamWatch1(); -} - -HWTEST_F(ParamUnitTest, TestAddParamWatch2, TestSize.Level0) -{ - ParamUnitTest test; - test.TestAddParamWatch2(); -} - -HWTEST_F(ParamUnitTest, TestAddParamWatch3, TestSize.Level0) -{ - ParamUnitTest test; - test.TestAddParamWatch3(); -} - -HWTEST_F(ParamUnitTest, TestCloseTriggerWatch, TestSize.Level0) -{ - ParamUnitTest test; - test.TestCloseTriggerWatch(); -} - HWTEST_F(ParamUnitTest, TestParamTraversal, TestSize.Level0) { ParamUnitTest test; @@ -632,33 +389,4 @@ HWTEST_F(ParamUnitTest, TestDumpParamMemory, TestSize.Level0) ParamUnitTest test; test.TestDumpParamMemory(); } - -HWTEST_F(ParamUnitTest, TestServiceCtrl, TestSize.Level0) -{ - ParamUnitTest test; - int ret = test.TestServiceCtrl("server1", 0770); - EXPECT_EQ(ret, 0); - ret = test.TestServiceCtrl("server2", 0772); - EXPECT_EQ(ret, 0); } - -HWTEST_F(ParamUnitTest, TestPowerCtrl, TestSize.Level0) -{ - ParamUnitTest test; - int ret = test.TestPowerCtrl("reboot,shutdown", 0770); - EXPECT_EQ(ret, 0); - ret = test.TestPowerCtrl("reboot,shutdown", 0772); - EXPECT_EQ(ret, 0); - ret = test.TestPowerCtrl("reboot,updater", 0770); - EXPECT_EQ(ret, 0); - ret = test.TestPowerCtrl("reboot,updater", 0772); - EXPECT_EQ(ret, 0); - ret = test.TestPowerCtrl("reboot,flash", 0770); - EXPECT_EQ(ret, 0); - ret = test.TestPowerCtrl("reboot,flash", 0772); - EXPECT_EQ(ret, 0); - ret = test.TestPowerCtrl("reboot", 0770); - EXPECT_EQ(ret, 0); - ret = test.TestPowerCtrl("reboot", 0772); - EXPECT_EQ(ret, 0); -} \ No newline at end of file diff --git a/test/unittest/param/paramservice_unittest.cpp b/test/unittest/param/paramservice_unittest.cpp new file mode 100755 index 0000000000000000000000000000000000000000..e93db79bb2ba9894ea3fea026fc05329364f1936 --- /dev/null +++ b/test/unittest/param/paramservice_unittest.cpp @@ -0,0 +1,530 @@ +/* + * Copyright (c) 2021 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 "init_param.h" +#include "param_message.h" +#include "param_stub.h" +#include "trigger_manager.h" + +using namespace testing::ext; +using namespace std; +static int CheckServerParamValue(const char *name, const char *expectValue) +{ + char tmp[PARAM_BUFFER_SIZE] = {0}; + u_int32_t len = sizeof(tmp); + SystemReadParam(name, tmp, &len); + printf("CheckParamValue name %s value: \'%s\' expectValue:\'%s\' \n", name, tmp, expectValue); + EXPECT_NE((int)strlen(tmp), 0); + if (expectValue != nullptr) { + EXPECT_EQ(strcmp(tmp, expectValue), 0); + } + return 0; +} + +namespace init_ut { +static ParamTaskPtr g_worker = nullptr; +class ParamServiceUnitTest : public ::testing::Test { +public: + ParamServiceUnitTest() {} + virtual ~ParamServiceUnitTest() {} + + static void SetUpTestCase(void) + { + PrepareInitUnitTestEnv(); + }; + void SetUp() {} + void TearDown() {} + void TestBody() {} + + int TestSetParams(const char *params[][1 + 1], int num) + { + for (int i = 0; i < num; i++) { + SystemWriteParam(params[i][0], params[i][1]); + } + + // check + for (int i = 0; i < num; i++) { + CheckServerParamValue(params[i][0], params[i][1]); + } + + for (int i = num - 1; i >= 0; i--) { + CheckServerParamValue(params[i][0], params[i][1]); + } + return 0; + } + + int TestAddSecurityLabel1() + { + GetParamSecurityLabel()->cred.gid = 9999; // 9999 test gid + const char *name = "label1.test.aaa.bbb.ccc.dddd.eee"; + const char *value = "2001"; + uint32_t labelIndex = 0; + SystemWriteParam(name, value); + // 获取到跟属性 + WorkSpace *workspace = GetWorkSpace(WORKSPACE_NAME_DAC); + (void)FindTrieNode(workspace, name, strlen(name), &labelIndex); + ParamSecruityNode *node = (ParamSecruityNode *)GetTrieNode(workspace, labelIndex); + if (node == nullptr) { + EXPECT_EQ(1, 0); + return 0; + } + EXPECT_EQ(node->gid, 0); + return 0; + } + + // 添加一个label,最长匹配到这个节点 + int TestAddSecurityLabel2() + { + GetParamSecurityLabel()->cred.gid = 9999; // 9999 test gid + const char *name = "label2.test.aaa.bbb.ccc.dddd.eee"; + const char *value = "2001"; + ParamAuditData auditData = {}; + auditData.name = "label2.test.aaa"; + auditData.dacData.gid = 202; // 202 test dac gid + auditData.dacData.uid = geteuid(); + auditData.dacData.mode = 0666; // 0666 test mode + SystemWriteParam(name, value); + uint32_t labelIndex = 0; + AddSecurityLabel(&auditData); + WorkSpace *workspace = GetWorkSpace(WORKSPACE_NAME_DAC); + (void)FindTrieNode(workspace, name, strlen(name), &labelIndex); + ParamSecruityNode *node = (ParamSecruityNode *)GetTrieNode(workspace, labelIndex); + if (node == nullptr) { + EXPECT_EQ(1, 0); + return 0; + } + EXPECT_EQ(node->gid, auditData.dacData.gid); + return 0; + } + + // 添加一个label,最长匹配到最后一个相同节点 + int TestAddSecurityLabel3() + { + GetParamSecurityLabel()->cred.gid = 9999; // 9999 test gid + const char *name = "label3.test.aaa.bbb.ccc.dddd.eee"; + const char *value = "2001"; + ParamAuditData auditData = {}; + auditData.name = "label3.test.aaa"; + auditData.dacData.gid = 203; // 203 test gid + auditData.dacData.uid = geteuid(); + auditData.dacData.mode = 0666; // 0666 test mode + SystemWriteParam(name, value); + AddSecurityLabel(&auditData); + + auditData.name = "label3.test.aaa.bbb.ccc.dddd.eee.dddd"; + auditData.dacData.gid = 202; // 202 test dac gid + auditData.dacData.uid = geteuid(); + auditData.dacData.mode = 0666; // 0666 test mode + SystemWriteParam(name, value); + AddSecurityLabel(&auditData); + + uint32_t labelIndex = 0; + WorkSpace *workspace = GetWorkSpace(WORKSPACE_NAME_DAC); + ParamTrieNode *paramNode = FindTrieNode(workspace, name, strlen(name), &labelIndex); + ParamSecruityNode *node = (ParamSecruityNode *)GetTrieNode(workspace, labelIndex); + if (paramNode == nullptr || node == nullptr) { + EXPECT_EQ(1, 0); + return 0; + } + EXPECT_EQ((int)node->gid, 203); // 203 test gid + return 0; + } + + // 添加一个label,完全匹配 + int TestAddSecurityLabel4() + { + GetParamSecurityLabel()->cred.gid = 9999; // 9999 test gid + const char *name = "label4.test.aaa.bbb.ccc.dddd.eee"; + const char *value = "2001"; + ParamAuditData auditData = {}; + auditData.name = "label4.test.aaa.bbb.ccc.dddd.eee"; + auditData.dacData.gid = 203; // 203 test gid + auditData.dacData.uid = geteuid(); + auditData.dacData.mode = 0666; // 0666 test mode + SystemWriteParam(name, value); + uint32_t labelIndex = 0; + AddSecurityLabel(&auditData); + WorkSpace *workspace = GetWorkSpace(WORKSPACE_NAME_DAC); + ParamTrieNode *paramNode = FindTrieNode(workspace, name, strlen(name), &labelIndex); + ParamSecruityNode *node = (ParamSecruityNode *)GetTrieNode(workspace, labelIndex); + if (paramNode == nullptr || node == nullptr) { + EXPECT_EQ(1, 0); + return 0; + } + EXPECT_EQ(node->gid, auditData.dacData.gid); + return 0; + } + + void TestBufferValue(char *buffer, uint32_t len) + { + const int printBase = 10; + for (uint32_t index = 0; index <= len; index++) { + buffer[index] = '0' + index % printBase; + if (index != 0 && index % printBase == 0) { + buffer[index] = '.'; + } + } + buffer[len] = '\0'; + } + + int TestNameIsValid() + { + char buffer[PARAM_BUFFER_SIZE]; + // set name length = 127 + TestBufferValue(buffer, PARAM_NAME_LEN_MAX - 1); + int ret = SystemWriteParam(buffer, "1111"); + EXPECT_EQ(ret, 0); + TestBufferValue(buffer, PARAM_NAME_LEN_MAX); + ret = SystemWriteParam(buffer, "1111"); + EXPECT_NE(ret, 0); + TestBufferValue(buffer, PARAM_NAME_LEN_MAX + 1); + ret = SystemWriteParam(buffer, "1111"); + EXPECT_NE(ret, 0); + + // 保存一个只读的属性,大于最大值 + TestBufferValue(buffer, PARAM_VALUE_LEN_MAX - 1); + ret = SystemWriteParam("const.test_readonly.dddddddddddddddddd.fffffffffffffffffff", buffer); + EXPECT_EQ(ret, 0); + + TestBufferValue(buffer, PARAM_VALUE_LEN_MAX + 1); + ret = SystemWriteParam("const.test_readonly.aaaaaaaaaaaaaaaaaa.fffffffffffffffffff", buffer); + EXPECT_EQ(ret, 0); + + // 更新只读项目 + TestBufferValue(buffer, PARAM_VALUE_LEN_MAX - 1); + ret = SystemWriteParam("const.test_readonly.dddddddddddddddddd.fffffffffffffffffff", buffer); + EXPECT_NE(ret, 0); + + // 写普通属性 + TestBufferValue(buffer, PARAM_VALUE_LEN_MAX - 1); + ret = SystemWriteParam("test.bigvalue.dddddddddddddddddd.fffffffffffffffffff", buffer); + EXPECT_EQ(ret, 0); + TestBufferValue(buffer, PARAM_VALUE_LEN_MAX + 1); + ret = SystemWriteParam("test.bigvalue.dddddddddddddddddd.fffffffffffffffffff", buffer); + EXPECT_NE(ret, 0); + + // invalid name + TestBufferValue(buffer, PARAM_VALUE_LEN_MAX - 1); + ret = SystemWriteParam("test.invalidname..fffffffffffffffffff", buffer); + EXPECT_NE(ret, 0); + ret = SystemWriteParam("test.invalidname.%fffffffffffffffffff", buffer); + EXPECT_NE(ret, 0); + ret = SystemWriteParam("test.invalidname.$fffffffffffffffffff", buffer); + EXPECT_NE(ret, 0); + return 0; + } + + int TestParamTraversal() + { + char value[PARAM_BUFFER_SIZE + PARAM_BUFFER_SIZE] = {0}; + SystemTraversalParameter( + "", + [](ParamHandle handle, void *cookie) { + ReadParamName(handle, (char *)cookie, PARAM_BUFFER_SIZE); + u_int32_t len = PARAM_BUFFER_SIZE; + ReadParamValue(handle, ((char *)cookie) + PARAM_BUFFER_SIZE, &len); + printf("$$$$$$$$Param %s=%s \n", (char *)cookie, ((char *)cookie) + PARAM_BUFFER_SIZE); + }, + (void *)value); + return 0; + } + + int TestUpdateParam(const char *name, const char *value) + { + SystemWriteParam(name, value); + SystemWriteParam(name, value); + SystemWriteParam(name, value); + SystemWriteParam(name, value); + CheckServerParamValue(name, value); + return 0; + } + + int TestPersistParam() + { + ParamAuditData auditData = {}; + auditData.name = "persist."; + auditData.dacData.gid = 0; + auditData.dacData.uid = 0; + auditData.dacData.mode = 0777; // 0777 test mode + AddSecurityLabel(&auditData); + + LoadPersistParams(); + SystemWriteParam("persist.111.ffff.bbbb.cccc.dddd.eeee", "1101"); + SystemWriteParam("persist.111.aaaa.bbbb.cccc.dddd.eeee", "1102"); + SystemWriteParam("persist.111.bbbb.cccc.dddd.eeee", "1103"); + CheckServerParamValue("persist.111.bbbb.cccc.dddd.eeee", "1103"); + SystemWriteParam("persist.111.cccc.bbbb.cccc.dddd.eeee", "1104"); + SystemWriteParam("persist.111.eeee.bbbb.cccc.dddd.eeee", "1105"); + CheckServerParamValue("persist.111.ffff.bbbb.cccc.dddd.eeee", "1101"); + SystemWriteParam("persist.111.ffff.bbbb.cccc.dddd.eeee", "1106"); + CheckServerParamValue("persist.111.ffff.bbbb.cccc.dddd.eeee", "1106"); + sleep(1); + SystemWriteParam("persist.111.bbbb.cccc.dddd.1107", "1107"); + SystemWriteParam("persist.111.bbbb.cccc.dddd.1108", "1108"); + SystemWriteParam("persist.111.bbbb.cccc.dddd.1109", "1108"); + sleep(1); + SystemWriteParam("persist.111.bbbb.cccc.dddd.1110", "1108"); + SystemWriteParam("persist.111.bbbb.cccc.dddd.1111", "1108"); + TimerCallbackForSave(nullptr, nullptr); + LoadPersistParams(); + return 0; + } + + ParamTaskPtr CreateAndGetStreamTask() + { + ParamStreamInfo info = {}; + info.flags = PARAM_TEST_FLAGS; + info.server = NULL; + info.close = NULL; + info.recvMessage = ProcessMessage; + info.incomingConnect = NULL; + ParamTaskPtr client = NULL; + int ret = ParamStreamCreate(&client, GetParamService()->serverTask, &info, sizeof(ParamWatcher)); + PARAM_CHECK(ret == 0, return NULL, "Failed to create client"); + + ParamWatcher *watcher = (ParamWatcher *)ParamGetTaskUserData(client); + PARAM_CHECK(watcher != NULL, return NULL, "Failed to get watcher"); + ListInit(&watcher->triggerHead); + watcher->stream = client; + GetParamService()->watcherTask = client; + return GetParamService()->watcherTask; + } + + int TestServiceProcessMessage(const char *name, const char *value, int userLabel) + { + if (g_worker == nullptr) { + g_worker = CreateAndGetStreamTask(); + } + if (g_worker == nullptr) { + return 0; + } + ParamSecurityOps *paramSecurityOps = GetParamSecurityOps(0); + if (userLabel && paramSecurityOps != NULL) { + paramSecurityOps->securityFreeLabel = TestFreeLocalSecurityLabel; + paramSecurityOps->securityCheckParamPermission = TestCheckParamPermission; + } + uint32_t msgSize = sizeof(ParamMessage) + sizeof(ParamMsgContent) + PARAM_ALIGN(strlen(value) + 1); + ParamMessage *request = (ParamMessage *)CreateParamMessage(MSG_SET_PARAM, name, msgSize); + PARAM_CHECK(request != nullptr, return -1, "Failed to malloc for connect"); + do { + request->type = MSG_SET_PARAM; + uint32_t offset = 0; + int ret = FillParamMsgContent(request, &offset, PARAM_VALUE, value, strlen(value)); + PARAM_CHECK(ret == 0, break, "Failed to fill value"); + ProcessMessage((const ParamTaskPtr)g_worker, (const ParamMessage *)request); + } while (0); + free(request); + CheckServerParamValue(name, value); + RegisterSecurityOps(1); + return 0; + } + + int AddWatch(int type, const char *name, const char *value) + { + if (g_worker == nullptr) { + g_worker = CreateAndGetStreamTask(); + } + if (g_worker == nullptr) { + return 0; + } + uint32_t msgSize = sizeof(ParamMessage) + sizeof(ParamMsgContent) + PARAM_ALIGN(strlen(value) + 1); + ParamMessage *request = (ParamMessage *)(ParamMessage *)CreateParamMessage(type, name, msgSize); + PARAM_CHECK(request != nullptr, return -1, "Failed to malloc for connect"); + do { + uint32_t offset = 0; + int ret = FillParamMsgContent(request, &offset, PARAM_VALUE, value, strlen(value)); + PARAM_CHECK(ret == 0, break, "Failed to fill value"); + ProcessMessage((const ParamTaskPtr)g_worker, (const ParamMessage *)request); + } while (0); + free(request); + return 0; + } + + // 无匹配 + int TestAddParamWait1() + { + const char *name = "wait.aaa.bbb.ccc.111"; + const char *value = "wait1"; + AddWatch(MSG_WAIT_PARAM, name, value); + SystemWriteParam(name, value); + return 0; + } + + // 模糊匹配 + int TestAddParamWait2() + { + const char *name = "wait.aaa.bbb.ccc.222"; + const char *value = "wait2"; + AddWatch(MSG_WAIT_PARAM, name, "*"); + SystemWriteParam(name, value); + return 0; + } + + // 属性存在 + int TestAddParamWait3() + { + const char *name = "wait.aaa.bbb.ccc.333"; + const char *value = "wait3"; + SystemWriteParam(name, value); + AddWatch(MSG_WAIT_PARAM, name, value); + return 0; + } + + int TestAddParamWatch1() + { + const char *name = "watch.aaa.bbb.ccc.111"; + const char *value = "watch1"; + AddWatch(MSG_ADD_WATCHER, name, value); + std::string newName = name; + newName += ".test.test.test"; + SystemWriteParam(newName.c_str(), value); + return 0; + } + + int TestAddParamWatch2() + { + const char *name = "watch.aaa.bbb.ccc.222"; + const char *value = "watch2"; + AddWatch(MSG_ADD_WATCHER, name, "*"); + SystemWriteParam(name, value); + return 0; + } + + int TestAddParamWatch3() + { + const char *name = "watch.aaa.bbb.ccc.333"; + const char *value = "watch3"; + std::string newName = name; + newName += ".test.test.test"; + SystemWriteParam(newName.c_str(), value); + AddWatch(MSG_ADD_WATCHER, name, value); + return 0; + } + + int TestCloseTriggerWatch() + { + ParamWatcher *watcher = (ParamWatcher *)ParamGetTaskUserData(g_worker); + ClearWatchTrigger(watcher, TRIGGER_PARAM_WAIT); + ParamTaskClose(g_worker); + g_worker = nullptr; + SystemWriteParam("init.svc.param_watcher", "stopped"); + return 0; + } + + int TestServiceCtrl(const char *serviceName, int mode) + { + // service forbit + ParamAuditData auditData = {}; + auditData.name = "ohos.servicectrl."; + auditData.dacData.gid = 202; // 202 test dac gid + auditData.dacData.uid = 202; // 202 test dac uid + auditData.dacData.mode = mode; + AddSecurityLabel(&auditData); + return SystemWriteParam("ohos.ctl.start", serviceName); + } + + int TestPowerCtrl(const char *reboot, int mode) + { + // service forbit + ParamAuditData auditData = {}; + auditData.name = "ohos.servicectrl."; + auditData.dacData.gid = 202; // 202 test dac gid + auditData.dacData.uid = 202; // 202 test dac uid + auditData.dacData.mode = mode; + AddSecurityLabel(&auditData); + return SystemWriteParam("ohos.startup.powerctrl", reboot); + } +}; + +HWTEST_F(ParamServiceUnitTest, TestServiceProcessMessage, TestSize.Level0) +{ + ParamServiceUnitTest test; + test.TestServiceProcessMessage("wertt.qqqq.wwww.rrrr", "wwww.eeeee", 1); + test.TestServiceProcessMessage("wertt.2222.wwww.3333", "wwww.eeeee", 0); +} + +HWTEST_F(ParamServiceUnitTest, TestAddParamWait1, TestSize.Level0) +{ + ParamServiceUnitTest test; + test.TestAddParamWait1(); +} + +HWTEST_F(ParamServiceUnitTest, TestAddParamWait2, TestSize.Level0) +{ + ParamServiceUnitTest test; + test.TestAddParamWait2(); +} + +HWTEST_F(ParamServiceUnitTest, TestAddParamWait3, TestSize.Level0) +{ + ParamServiceUnitTest test; + test.TestAddParamWait3(); +} + +HWTEST_F(ParamServiceUnitTest, TestAddParamWatch1, TestSize.Level0) +{ + ParamServiceUnitTest test; + test.TestAddParamWatch1(); +} + +HWTEST_F(ParamServiceUnitTest, TestAddParamWatch2, TestSize.Level0) +{ + ParamServiceUnitTest test; + test.TestAddParamWatch2(); +} + +HWTEST_F(ParamServiceUnitTest, TestAddParamWatch3, TestSize.Level0) +{ + ParamServiceUnitTest test; + test.TestAddParamWatch3(); +} + +HWTEST_F(ParamServiceUnitTest, TestCloseTriggerWatch, TestSize.Level0) +{ + ParamServiceUnitTest test; + test.TestCloseTriggerWatch(); +} + +HWTEST_F(ParamServiceUnitTest, TestServiceCtrl, TestSize.Level0) +{ + ParamServiceUnitTest test; + int ret = test.TestServiceCtrl("server1", 0770); + EXPECT_NE(ret, 0); + ret = test.TestServiceCtrl("server2", 0772); + EXPECT_EQ(ret, 0); +} + +HWTEST_F(ParamServiceUnitTest, TestPowerCtrl, TestSize.Level0) +{ + ParamServiceUnitTest test; + int ret = test.TestPowerCtrl("reboot,shutdown", 0770); + EXPECT_NE(ret, 0); + ret = test.TestPowerCtrl("reboot,shutdown", 0772); + EXPECT_EQ(ret, 0); + ret = test.TestPowerCtrl("reboot,updater", 0770); + EXPECT_NE(ret, 0); + ret = test.TestPowerCtrl("reboot,updater", 0772); + EXPECT_EQ(ret, 0); + ret = test.TestPowerCtrl("reboot,flash", 0770); + EXPECT_NE(ret, 0); + ret = test.TestPowerCtrl("reboot,flash", 0772); + EXPECT_EQ(ret, 0); + ret = test.TestPowerCtrl("reboot", 0770); + EXPECT_NE(ret, 0); + ret = test.TestPowerCtrl("reboot", 0772); + EXPECT_EQ(ret, 0); +} +} // namespace init_ut \ No newline at end of file diff --git a/test/unittest/param/selinux_unittest.cpp b/test/unittest/param/selinux_unittest.cpp index 8fb0390101c3b408bf21253188f881d9ab1eeb3a..de91300fa49cfdafa273aa7493a442e1df07d226 100644 --- a/test/unittest/param/selinux_unittest.cpp +++ b/test/unittest/param/selinux_unittest.cpp @@ -12,29 +12,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - -#include #include -#include -#include -#include "init_unittest.h" +#include "param_manager.h" #include "param_security.h" +#include "param_stub.h" #include "param_utils.h" #include "securec.h" -extern "C" { -extern int RegisterSecuritySelinuxOps(ParamSecurityOps *ops, int isInit); -} - using namespace testing::ext; using namespace std; -static int SecurityLabelGet(const ParamAuditData *auditData, void *context) -{ - return 0; -} - +namespace init_ut { class SelinuxUnitTest : public ::testing::Test { public: SelinuxUnitTest() {} @@ -52,10 +41,10 @@ public: if (initParamSercurityOps.securityInitLabel == nullptr || initParamSercurityOps.securityFreeLabel == nullptr) { return -1; } - ParamSecurityLabel *label = nullptr; + ParamSecurityLabel label = {}; ret = initParamSercurityOps.securityInitLabel(&label, LABEL_INIT_FOR_INIT); EXPECT_EQ(ret, 0); - ret = initParamSercurityOps.securityFreeLabel(label); + ret = initParamSercurityOps.securityFreeLabel(&label); EXPECT_EQ(ret, 0); return 0; } @@ -67,12 +56,12 @@ public: if (initParamSercurityOps.securityCheckFilePermission == nullptr) { return -1; } - ParamSecurityLabel *label = nullptr; + ParamSecurityLabel label = {}; ret = initParamSercurityOps.securityInitLabel(&label, LABEL_INIT_FOR_INIT); EXPECT_EQ(ret, 0); - ret = initParamSercurityOps.securityCheckFilePermission(label, fileName, DAC_WRITE); + ret = initParamSercurityOps.securityCheckFilePermission(&label, fileName, DAC_WRITE); EXPECT_EQ(ret, 0); - ret = initParamSercurityOps.securityFreeLabel(label); + ret = initParamSercurityOps.securityFreeLabel(&label); EXPECT_EQ(ret, 0); return 0; } @@ -84,17 +73,13 @@ public: if (initParamSercurityOps.securityCheckFilePermission == nullptr) { return -1; } - ParamSecurityLabel *srclabel = nullptr; + ParamSecurityLabel srclabel = {}; ret = initParamSercurityOps.securityInitLabel(&srclabel, LABEL_INIT_FOR_INIT); EXPECT_EQ(ret, 0); - ParamAuditData auditData = {}; - auditData.name = name; - auditData.label = label; - - ret = initParamSercurityOps.securityCheckParamPermission(srclabel, &auditData, DAC_WRITE); + ret = initParamSercurityOps.securityCheckParamPermission(&srclabel, name, DAC_WRITE); EXPECT_EQ(ret, 0); - ret = initParamSercurityOps.securityFreeLabel(srclabel); + ret = initParamSercurityOps.securityFreeLabel(&srclabel); EXPECT_EQ(ret, 0); return 0; } @@ -103,9 +88,6 @@ public: { int ret = RegisterSecuritySelinuxOps(&clientParamSercurityOps, 0); EXPECT_EQ(ret, 0); - if (clientParamSercurityOps.securityDecodeLabel != nullptr) { - EXPECT_EQ(1, 0); - } if (clientParamSercurityOps.securityGetLabel != nullptr) { EXPECT_EQ(1, 0); } @@ -113,12 +95,12 @@ public: EXPECT_EQ(1, 0); return -1; } - ParamSecurityLabel *label = nullptr; + ParamSecurityLabel label = {}; ret = clientParamSercurityOps.securityInitLabel(&label, 0); EXPECT_EQ(ret, 0); - ret = clientParamSercurityOps.securityCheckFilePermission(label, fileName, DAC_READ); + ret = clientParamSercurityOps.securityCheckFilePermission(&label, fileName, DAC_READ); EXPECT_EQ(ret, 0); - ret = clientParamSercurityOps.securityFreeLabel(label); + ret = clientParamSercurityOps.securityFreeLabel(&label); EXPECT_EQ(ret, 0); return 0; } @@ -131,17 +113,12 @@ public: if (clientParamSercurityOps.securityCheckFilePermission == nullptr) { return -1; } - ParamSecurityLabel *srclabel = nullptr; + ParamSecurityLabel srclabel = {}; ret = clientParamSercurityOps.securityInitLabel(&srclabel, 0); EXPECT_EQ(ret, 0); - - ParamAuditData auditData = {}; - auditData.name = name; - auditData.label = label; - - ret = clientParamSercurityOps.securityCheckParamPermission(srclabel, &auditData, DAC_WRITE); + ret = clientParamSercurityOps.securityCheckParamPermission(&srclabel, name, DAC_WRITE); EXPECT_EQ(ret, 0); - ret = clientParamSercurityOps.securityFreeLabel(srclabel); + ret = clientParamSercurityOps.securityFreeLabel(&srclabel); EXPECT_EQ(ret, 0); return 0; } @@ -153,69 +130,12 @@ public: if (clientParamSercurityOps.securityCheckFilePermission == nullptr) { return -1; } - ParamSecurityLabel *srclabel = nullptr; + ParamSecurityLabel srclabel = {}; ret = clientParamSercurityOps.securityInitLabel(&srclabel, 0); EXPECT_EQ(ret, 0); - - ParamAuditData auditData = {}; - auditData.name = name; - auditData.label = label; - - ret = clientParamSercurityOps.securityCheckParamPermission(srclabel, &auditData, DAC_READ); + ret = clientParamSercurityOps.securityCheckParamPermission(&srclabel, name, DAC_READ); EXPECT_EQ(ret, 0); - ret = clientParamSercurityOps.securityFreeLabel(srclabel); - EXPECT_EQ(ret, 0); - return 0; - } - - int TestEncode(ParamSecurityLabel *&label, std::vector &buffer) - { - int ret = RegisterSecuritySelinuxOps(&clientParamSercurityOps, 0); - EXPECT_EQ(ret, 0); - if (clientParamSercurityOps.securityDecodeLabel != nullptr) { - EXPECT_EQ(1, 0); - } - if (clientParamSercurityOps.securityGetLabel != nullptr) { - EXPECT_EQ(1, 0); - } - if (clientParamSercurityOps.securityEncodeLabel == nullptr) { - EXPECT_EQ(1, 0); - return -1; - } - ret = clientParamSercurityOps.securityInitLabel(&label, 0); - EXPECT_EQ(ret, 0); - - uint32_t bufferSize = 0; - ret = clientParamSercurityOps.securityEncodeLabel(label, nullptr, &bufferSize); - EXPECT_EQ(ret, 0); - buffer.resize(bufferSize + 1); - ret = clientParamSercurityOps.securityEncodeLabel(label, buffer.data(), &bufferSize); - EXPECT_EQ(ret, 0); - return 0; - } - - int TestDecode(ParamSecurityLabel *label, std::vector &buffer) - { - int ret = RegisterSecuritySelinuxOps(&clientParamSercurityOps, 1); - EXPECT_EQ(ret, 0); - if (clientParamSercurityOps.securityDecodeLabel == nullptr) { - EXPECT_EQ(1, 0); - } - if (clientParamSercurityOps.securityEncodeLabel != nullptr) { - EXPECT_EQ(1, 0); - return -1; - } - ParamSecurityLabel *tmp = nullptr; - ret = clientParamSercurityOps.securityDecodeLabel(&tmp, buffer.data(), buffer.size()); - if (tmp == nullptr || label == nullptr) { - return -1; - } - EXPECT_EQ(ret, 0); - EXPECT_EQ(label->cred.gid, tmp->cred.gid); - EXPECT_EQ(label->cred.uid, tmp->cred.uid); - ret = clientParamSercurityOps.securityFreeLabel(tmp); - EXPECT_EQ(ret, 0); - ret = clientParamSercurityOps.securityFreeLabel(label); + ret = clientParamSercurityOps.securityFreeLabel(&srclabel); EXPECT_EQ(ret, 0); return 0; } @@ -234,7 +154,7 @@ HWTEST_F(SelinuxUnitTest, TestSelinuxInitLocalLabel, TestSize.Level0) HWTEST_F(SelinuxUnitTest, TestSelinuxCheckFilePermission, TestSize.Level0) { SelinuxUnitTest test; - test.TestSelinuxCheckFilePermission(PARAM_DEFAULT_PATH"/trigger_test.cfg"); + test.TestSelinuxCheckFilePermission(STARTUP_INIT_UT_PATH "/trigger_test.cfg"); } HWTEST_F(SelinuxUnitTest, TestSelinuxCheckParaPermission, TestSize.Level0) @@ -246,7 +166,7 @@ HWTEST_F(SelinuxUnitTest, TestSelinuxCheckParaPermission, TestSize.Level0) HWTEST_F(SelinuxUnitTest, TestClientDacCheckFilePermission, TestSize.Level0) { SelinuxUnitTest test; - test.TestClientSelinuxCheckFilePermission(PARAM_DEFAULT_PATH"/trigger_test.cfg"); + test.TestClientSelinuxCheckFilePermission(STARTUP_INIT_UT_PATH "/trigger_test.cfg"); } HWTEST_F(SelinuxUnitTest, TestClientDacCheckParaPermission, TestSize.Level0) @@ -255,12 +175,4 @@ HWTEST_F(SelinuxUnitTest, TestClientDacCheckParaPermission, TestSize.Level0) test.TestClientSelinuxCheckParaPermissionWrite("aaa.bbb.bbb.ccc", "user:group1:r"); test.TestClientSelinuxCheckParaPermissionRead("aaa.bbb.bbb.ccc", "user:group1:r"); } - -HWTEST_F(SelinuxUnitTest, TestSeliniuxLabelEncode, TestSize.Level0) -{ - SelinuxUnitTest test; - std::vector buffer; - ParamSecurityLabel *label = nullptr; - test.TestEncode(label, buffer); - test.TestDecode(label, buffer); -} +} \ No newline at end of file diff --git a/test/unittest/param/trigger_unittest.cpp b/test/unittest/param/trigger_unittest.cpp index 0edb6a042be7adbffd4442e4cc55371d5e7a9c3a..e80912312af09e8f6c0abbd78ff91e49a5762e56 100644 --- a/test/unittest/param/trigger_unittest.cpp +++ b/test/unittest/param/trigger_unittest.cpp @@ -12,13 +12,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include #include "init_jobs_internal.h" #include "init_param.h" -#include "init_unittest.h" #include "init_utils.h" +#include "loop_event.h" #include "param_manager.h" -#include "param_service.h" #include "param_stub.h" #include "param_utils.h" #include "securec.h" @@ -31,13 +31,12 @@ using namespace std; static const int triggerBuffer = 512; static uint32_t g_execCmdId = 0; static int g_matchTrigger = 0; -static char g_matchTriggerName[triggerBuffer] = { 0 }; +static char g_matchTriggerName[triggerBuffer] = {0}; static int TestCmdExec(const TriggerNode *trigger, const char *content, uint32_t size) { PARAM_CHECK(trigger != NULL, return -1, "Invalid trigger"); PARAM_LOGI("DoTriggerExecute_ trigger type: %d %s", trigger->type, GetTriggerName(trigger)); - PARAM_CHECK(trigger->type <= TRIGGER_UNKNOW, return -1, - "Invalid trigger type %d", trigger->type); + PARAM_CHECK(trigger->type <= TRIGGER_UNKNOW, return -1, "Invalid trigger type %d", trigger->type); CommandNode *cmd = GetNextCmdNode((JobNode *)trigger, NULL); while (cmd != NULL) { g_execCmdId = cmd->cmdKeyIndex; @@ -49,8 +48,7 @@ static int TestCmdExec(const TriggerNode *trigger, const char *content, uint32_t static int TestTriggerExecute(TriggerNode *trigger, const char *content, uint32_t size) { JobNode *node = (JobNode *)trigger; - int ret = memcpy_s(g_matchTriggerName, - (int)sizeof(g_matchTriggerName) - 1, node->name, strlen(node->name)); + int ret = memcpy_s(g_matchTriggerName, (int)sizeof(g_matchTriggerName) - 1, node->name, strlen(node->name)); EXPECT_EQ(ret, 0); g_matchTriggerName[strlen(node->name)] = '\0'; g_matchTrigger++; @@ -87,7 +85,7 @@ public: EXPECT_EQ(matchCmd != 0, 1); ReadConfig(); - ParseInitCfg(PARAM_DEFAULT_PATH "/trigger_test.cfg"); + ParseInitCfg(STARTUP_INIT_UT_PATH "/trigger_test.cfg"); // trigger PostTrigger(EVENT_TRIGGER_BOOT, "pre-init", strlen("pre-init")); PostTrigger(EVENT_TRIGGER_BOOT, "init", strlen("init")); @@ -459,7 +457,7 @@ public: int TestDumpTrigger() { - DumpTrigger(GetTriggerWorkSpace()); + SystemDumpTriggers(1); return 0; } }; diff --git a/test/unittest/param/watcher_agent_unittest.cpp b/test/unittest/param/watcher_agent_unittest.cpp index b5477629c9efe2a6e5797236e4c99ed460a01186..9680d2ca5cc3df2d989937b0d410bcc2093d8014 100644 --- a/test/unittest/param/watcher_agent_unittest.cpp +++ b/test/unittest/param/watcher_agent_unittest.cpp @@ -12,19 +12,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include -#include -#include #include #include "if_system_ability_manager.h" +#include "init_param.h" #include "iservice_registry.h" #include "iwatcher.h" #include "iwatcher_manager.h" #include "message_parcel.h" +#include "param_manager.h" #include "param_utils.h" -#include "param_request.h" -#include "sys_param.h" #include "system_ability_definition.h" #include "watcher.h" #include "watcher_manager_kits.h" @@ -46,10 +43,9 @@ public: void SetUp() { - ParamWorkSpace *space = GetClientParamWorkSpace(); - if (space != nullptr && space->securityLabel != nullptr) { - space->securityLabel->cred.uid = 1000; // 1000 test uid - space->securityLabel->cred.gid = 1000; // 1000 test gid + if (GetParamSecurityLabel() != nullptr) { + GetParamSecurityLabel()->cred.uid = 1000; // 1000 test uid + GetParamSecurityLabel()->cred.gid = 1000; // 1000 test gid } } void TearDown() {} @@ -66,7 +62,7 @@ public: EXPECT_NE(ret, 0); // 被禁止 ret = SystemWatchParameter("test.permission.read.test1*", TestParameterChange, nullptr); - EXPECT_EQ(ret, 0); + EXPECT_NE(ret, 0); return 0; } @@ -84,7 +80,7 @@ public: EXPECT_NE(ret, 0); // 被禁止 ret = SystemWatchParameter("test.permission.read.test1*", nullptr, nullptr); - EXPECT_EQ(ret, 0); + EXPECT_NE(ret, 0); return 0; } diff --git a/test/unittest/param/watcher_proxy_unittest.cpp b/test/unittest/param/watcher_proxy_unittest.cpp index df7787f846c4fb5b7382bd5776317f408977f41e..1f289d5f1432a6d0bbaed6bd1b091e49785c01d5 100644 --- a/test/unittest/param/watcher_proxy_unittest.cpp +++ b/test/unittest/param/watcher_proxy_unittest.cpp @@ -12,19 +12,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include -#include -#include #include #include "if_system_ability_manager.h" -#include "init_unittest.h" +#include "param_stub.h" #include "iservice_registry.h" #include "iwatcher.h" #include "iwatcher_manager.h" #include "message_parcel.h" #include "param_message.h" -#include "param_request.h" +#include "init_param.h" #include "param_utils.h" #include "parcel.h" #include "securec.h" diff --git a/test/unittest/syspara/syspara_unittest.cpp b/test/unittest/syspara/syspara_unittest.cpp new file mode 100755 index 0000000000000000000000000000000000000000..4791d4ddb901d887748778ccb6d2c0c452ae2b24 --- /dev/null +++ b/test/unittest/syspara/syspara_unittest.cpp @@ -0,0 +1,264 @@ +/* + * Copyright (c) 2021 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 "gtest/gtest.h" + +#include "init_param.h" +#include "parameter.h" +#include "sysparam_errno.h" + +using namespace testing::ext; + +namespace OHOS { +class SysparaUnitTest : public testing::Test { +public: + static void SetUpTestCase() {} + static void TearDownTestCase() {} + void SetUp() {} + void TearDown() {} +}; + + +HWTEST_F(SysparaUnitTest, parameterTest001, TestSize.Level0) +{ + printf("Device type =%s\n", GetDeviceType()); + printf("Manufacture =%s\n", GetManufacture()); + printf("GetBrand =%s\n", GetBrand()); + printf("MarketName =%s\n", GetMarketName()); + printf("ProductSeries =%s\n", GetProductSeries()); + printf("ProductModel =%s\n", GetProductModel()); + printf("SoftwareModel =%s\n", GetSoftwareModel()); + printf("HardwareModel =%s\n", GetHardwareModel()); + printf("Software profile =%s\n", GetHardwareProfile()); + printf("Serial =%s\n", GetSerial()); + printf("OS full name =%s\n", GetOSFullName()); + printf("OS Release type =%s\n", GetOsReleaseType()); + printf("Display version =%s\n", GetDisplayVersion()); + printf("bootloader version =%s\n", GetBootloaderVersion()); + printf("secure patch level =%s\n", GetSecurityPatchTag()); +} + +HWTEST_F(SysparaUnitTest, parameterTest001_1, TestSize.Level0) +{ + printf("secure patch level =%s\n", GetSecurityPatchTag()); + printf("abi list =%s\n", GetAbiList()); + printf("first api version =%d\n", GetFirstApiVersion()); + printf("SDK api version =%d\n", GetSdkApiVersion()); + printf("Incremental version = %s\n", GetIncrementalVersion()); + printf("formal id =%s\n", GetVersionId()); + printf("build tyep =%s\n", GetBuildType()); + printf("build user =%s\n", GetBuildUser()); + printf("Build host = %s\n", GetBuildHost()); + printf("build time =%s\n", GetBuildTime()); + printf("build root later..., %s\n", GetBuildRootHash()); +} + +HWTEST_F(SysparaUnitTest, parameterTest001_2, TestSize.Level0) +{ + EXPECT_STRNE(GetDeviceType(), nullptr); + EXPECT_STRNE(GetManufacture(), nullptr); + EXPECT_STRNE(GetBrand(), nullptr); + EXPECT_STRNE(GetMarketName(), nullptr); + EXPECT_STRNE(GetProductSeries(), nullptr); + EXPECT_STRNE(GetProductModel(), nullptr); + EXPECT_STRNE(GetSoftwareModel(), nullptr); + EXPECT_STRNE(GetHardwareModel(), nullptr); + EXPECT_STRNE(GetHardwareProfile(), nullptr); + EXPECT_STRNE(GetOSFullName(), nullptr); + EXPECT_STRNE(GetOsReleaseType(), nullptr); + EXPECT_STRNE(GetDisplayVersion(), nullptr); + EXPECT_STRNE(GetBootloaderVersion(), nullptr); + EXPECT_STRNE(GetSecurityPatchTag(), nullptr); +} + +HWTEST_F(SysparaUnitTest, parameterTest001_3, TestSize.Level0) +{ + EXPECT_STRNE(GetSecurityPatchTag(), nullptr); + EXPECT_STRNE(GetAbiList(), nullptr); + EXPECT_GT(GetFirstApiVersion(), 0); + EXPECT_GT(GetSdkApiVersion(), 0); + EXPECT_STRNE(GetIncrementalVersion(), nullptr); + EXPECT_STRNE(GetVersionId(), nullptr); + EXPECT_STRNE(GetBuildType(), nullptr); + EXPECT_STRNE(GetBuildUser(), nullptr); + EXPECT_STRNE(GetBuildHost(), nullptr); + EXPECT_STRNE(GetBuildTime(), nullptr); + EXPECT_STRNE(GetBuildRootHash(), nullptr); +} + +HWTEST_F(SysparaUnitTest, parameterTest002, TestSize.Level0) +{ + char key1[] = "test.ro.sys.version"; + char value1[] = "set read only key"; + int ret = SetParameter(key1, value1); + EXPECT_EQ(ret, EC_SUCCESS); +} + +HWTEST_F(SysparaUnitTest, parameterTest003, TestSize.Level0) +{ + char key2[] = "rw.sys.version*%version"; + char value2[] = "set value with illegal key"; + int ret = SetParameter(key2, value2); + EXPECT_EQ(ret, EC_FAILURE); +} + +/* key = 32 */ +HWTEST_F(SysparaUnitTest, parameterTest004, TestSize.Level0) +{ + char key3[] = "rw.sys.version.utilskvparameter0"; + char value3[] = "set with key = 32"; + int ret = SetParameter(key3, value3); + EXPECT_EQ(ret, EC_SUCCESS); +} + +/* value > 128 */ +HWTEST_F(SysparaUnitTest, parameterTest005, TestSize.Level0) +{ + char key4[] = "rw.sys.version.version"; + char value4[] = "rw.sys.version.version.version.version flash_offset = *(hi_u32 *)DT_SetGetU32(&g_Element[0], 0)a\ + size = *(hi_u32 *)DT_SetGetU32(&g_Element[1], 0)a"; + int ret = SetParameter(key4, value4); + EXPECT_EQ(ret, EC_FAILURE); +} + +HWTEST_F(SysparaUnitTest, parameterTest006, TestSize.Level0) +{ + char key1[] = "rw.product.not.exist"; + char value1[64] = {0}; + char defValue1[] = "value of key not exist..."; + int ret = GetParameter(key1, defValue1, value1, 64); + EXPECT_EQ(ret, static_cast(strlen(defValue1))); +} + +HWTEST_F(SysparaUnitTest, parameterTest007, TestSize.Level0) +{ + char key2[] = "rw.sys.version.version.version.version"; + char value2[64] = {0}; + char defValue2[] = "value of key > 32 ..."; + int ret = GetParameter(key2, defValue2, value2, 64); + EXPECT_EQ(ret, static_cast(strlen(defValue2))); +} + +HWTEST_F(SysparaUnitTest, parameterTest008, TestSize.Level0) +{ + char key4[] = "test.rw.sys.version"; + char* value4 = nullptr; + char defValue3[] = "value of key > 32 ..."; + int ret = GetParameter(key4, defValue3, value4, 0); + EXPECT_EQ(ret, EC_INVALID); +} + +HWTEST_F(SysparaUnitTest, parameterTest009, TestSize.Level0) +{ + char key5[] = "test.rw.product.type.2222222"; + char value5[] = "rw.sys.version.version.version.version \ + flash_offset = *(hi_u32 *)DT_SetGetU32(&g_Element[0], 0)"; + int ret = SetParameter(key5, value5); + EXPECT_EQ(ret, EC_FAILURE); + char valueGet[2] = {0}; + char defValue3[] = "value of key > 32 ..."; + ret = GetParameter(key5, defValue3, valueGet, 2); + EXPECT_EQ(ret, EC_INVALID); +} + +HWTEST_F(SysparaUnitTest, parameterTest0010, TestSize.Level0) +{ + char key1[] = "test.rw.sys.version"; + char value1[] = "10.1.0"; + int ret = SetParameter(key1, value1); + EXPECT_EQ(ret, 0); + ret = SystemWriteParam(key1, value1); + EXPECT_EQ(ret, 0); + char valueGet1[32] = {0}; + ret = GetParameter(key1, "version=10.1.0", valueGet1, 32); + EXPECT_EQ(ret, static_cast(strlen(valueGet1))); + + char key2[] = "test.rw.product.type"; + char value2[] = "wifi_iot"; + ret = SetParameter(key2, value2); + EXPECT_EQ(ret, 0); + ret = SystemWriteParam(key2, value2); + EXPECT_EQ(ret, 0); + char valueGet2[32] = {0}; + ret = GetParameter(key2, "version=10.1.0", valueGet2, 32); + EXPECT_EQ(ret, static_cast(strlen(valueGet2))); + + char key3[] = "test.rw.product.manufacturer"; + char value3[] = "TEST MANUFACTURER"; + ret = SetParameter(key3, value3); + EXPECT_EQ(ret, 0); + ret = SystemWriteParam(key3, value3); + EXPECT_EQ(ret, 0); + char valueGet3[32] = {0}; + ret = GetParameter(key3, "version=10.1.0", valueGet3, 32); + EXPECT_EQ(ret, static_cast(strlen(valueGet3))); + + char key4[] = "test.rw.product.marketname"; + char value4[] = "TEST MARKETNAME"; + ret = SetParameter(key4, value4); + EXPECT_EQ(ret, 0); + ret = SystemWriteParam(key4, value4); + EXPECT_EQ(ret, 0); + char valueGet4[32] = {0}; + ret = GetParameter(key4, "version=10.1.0", valueGet4, 32); + EXPECT_EQ(ret, static_cast(strlen(valueGet4))); +} + +HWTEST_F(SysparaUnitTest, parameterTest0011, TestSize.Level0) +{ + char key1[] = "test.rw.sys.version.wait1"; + char value1[] = "10.1.0"; + int ret = SetParameter(key1, value1); + EXPECT_EQ(ret, 0); + ret = SystemWriteParam(key1, value1); + EXPECT_EQ(ret, 0); + ret = WaitParameter(key1, value1, 10); + EXPECT_EQ(ret, 0); + ret = WaitParameter(key1, "*", 10); + EXPECT_EQ(ret, 0); + char key2[] = "test.rw.sys.version.wait2"; + ret = WaitParameter(key2, "*", 1); + EXPECT_EQ(ret, 105); +} + +HWTEST_F(SysparaUnitTest, parameterTest0012, TestSize.Level0) +{ + char key1[] = "test.rw.sys.version.version1"; + char value1[] = "10.1.0"; + int ret = SetParameter(key1, value1); + EXPECT_EQ(ret, 0); + + ret = SystemWriteParam(key1, value1); + EXPECT_EQ(ret, 0); + // success + unsigned int handle = FindParameter(key1); + EXPECT_NE(handle, static_cast(-1)); + char valueGet1[32] = {0}; + ret = GetParameterValue(handle, valueGet1, 32); + EXPECT_EQ(ret, static_cast(strlen(valueGet1))); + char nameGet1[32] = {0}; + ret = GetParameterName(handle, nameGet1, 32); + EXPECT_EQ(ret, static_cast(strlen(nameGet1))); + + // fail + char key2[] = "test.rw.sys.version.version2"; + handle = FindParameter(key2); + EXPECT_EQ(handle, static_cast(-1)); + ret = GetParameterValue(handle, valueGet1, 32); + EXPECT_EQ(ret, -1); + ret = GetParameterName(handle, nameGet1, 32); + EXPECT_EQ(ret, -1); +} +} // namespace OHOS diff --git a/test/unittest/test_data/trigger_test.cfg b/test/unittest/test_data/trigger_test.cfg index fe8867e6cbc8a2a967d6347c8abd2aaff4e95628..7b754cb5c548e54433451415cbdb390bb8d6f88e 100755 --- a/test/unittest/test_data/trigger_test.cfg +++ b/test/unittest/test_data/trigger_test.cfg @@ -7,7 +7,6 @@ " load_persist_params ", " load_persist_params ", " # load_persist_params ", - "#restorecon /adb_keys", " restorecon /postinstall", "mkdir /acct/uid", "chown root system /dev/memcg/memory.pressure_level", diff --git a/test/unittest/ueventd/ueventd_config_unittest.cpp b/test/unittest/ueventd/ueventd_config_unittest.cpp index bd6f4511361077cf0fcd7b8efa3416f96a2b7cdf..e92fbd365c94fb60d393bbb55353727fc0d29edc 100644 --- a/test/unittest/ueventd/ueventd_config_unittest.cpp +++ b/test/unittest/ueventd/ueventd_config_unittest.cpp @@ -19,7 +19,7 @@ #include #include #include -#include "init_unittest.h" +#include "param_stub.h" #include "init_utils.h" #include "ueventd_read_cfg.h" #include "ueventd_parameter.h" @@ -27,7 +27,6 @@ using namespace std; using namespace testing::ext; -#define TEST_PATH "/data/ueventd_ut" namespace ueventd_ut { static bool FileExists(const std::string &file) { diff --git a/ueventd/BUILD.gn b/ueventd/BUILD.gn index c78ba1003ad48e49e71d294aa0c5b55c777538d6..b29978727c835eb06feb144806d09e6a00f47de6 100644 --- a/ueventd/BUILD.gn +++ b/ueventd/BUILD.gn @@ -120,7 +120,7 @@ if (defined(ohos_lite)) { "//base/startup/init_lite/interfaces/innerkits/include", ] deps = service_ueventd_deps - deps += [ "//base/startup/init_lite/services/param:param_client" ] + deps += [ "//base/startup/init_lite/interfaces/innerkits:libbegetutil" ] cflags = [] if (build_selinux) { diff --git a/ueventd/standard/ueventd_parameter.c b/ueventd/standard/ueventd_parameter.c index bd53fc30f4693fadf1df7cfb87b0cd0783f951c6..f296936b857d56ad02300f5f39f41795a26837f5 100644 --- a/ueventd/standard/ueventd_parameter.c +++ b/ueventd/standard/ueventd_parameter.c @@ -21,7 +21,7 @@ #define INIT_LOG_TAG "ueventd" #include "init_log.h" #include "list.h" -#include "sys_param.h" +#include "init_param.h" #include "ueventd.h" #include "ueventd_read_cfg.h" #include "ueventd_utils.h" diff --git a/watchdog/BUILD.gn b/watchdog/BUILD.gn index 27b4bc5bb51cb3660ba4322b912bf5099fd8d07b..9301c02c7061e3ef7a7016708e5dc61e4c1c4e64 100644 --- a/watchdog/BUILD.gn +++ b/watchdog/BUILD.gn @@ -22,7 +22,10 @@ if (defined(ohos_lite)) { "//base/startup/init_lite/services/log", "//base/startup/init_lite/interfaces/innerkits/include", ] - deps = [ "//base/startup/init_lite/services/log:init_log" ] + deps = [ + "//base/startup/init_lite/services/log:init_log", + "//third_party/bounds_checking_function:libsec_static", + ] defines = [ "_GNU_SOURCE", "OHOS_LITE_WATCHDOG", @@ -39,7 +42,10 @@ if (defined(ohos_lite)) { "//base/startup/init_lite/services/log", "//base/startup/init_lite/interfaces/innerkits/include", ] - deps = [ "//base/startup/init_lite/services/log:init_log" ] + deps = [ + "//base/startup/init_lite/services/log:init_log", + "//third_party/bounds_checking_function:libsec_shared", + ] defines = [ "LINUX_WATCHDOG" ] defines += [ "_GNU_SOURCE" ] install_enable = true