From c22a0dc80da0d1342d343177f5f9fd401848b2ff Mon Sep 17 00:00:00 2001 From: changzheng6 Date: Tue, 4 Apr 2023 09:22:03 +0800 Subject: [PATCH] dbms init Signed-off-by: changzheng6 --- BUILD.gn | 37 + README.en.md | 36 - README.md | 39 - bundle.json | 67 + dbms.gni | 59 + interfaces/inner_api/BUILD.gn | 43 + .../include/distributed_bms_interface.h | 137 ++ .../inner_api/include/distributed_bms_proxy.h | 132 ++ .../inner_api/src/distributed_bms_proxy.cpp | 339 ++++ .../kits/js/distributebundlemgr/BUILD.gn | 56 + .../distributed_bundle_mgr.cpp | 491 ++++++ .../distributed_bundle_mgr.h | 62 + .../js/distributebundlemgr/native_module.cpp | 66 + interfaces/kits/js/distributedBundle/BUILD.gn | 60 + .../distributedBundle/distributed_bundle.cpp | 326 ++++ .../js/distributedBundle/distributed_bundle.h | 39 + .../distributed_bundle_unsupported.cpp | 36 + .../js/distributedBundle/native_module.cpp | 65 + services/dbms/BUILD.gn | 82 + .../dbms/include/account_manager_helper.h | 29 + services/dbms/include/distributed_bms.h | 153 ++ services/dbms/include/distributed_bms_host.h | 51 + .../dbms/include/distributed_data_storage.h | 63 + services/dbms/include/distributed_monitor.h | 57 + services/dbms/include/event_report.h | 51 + services/dbms/include/image_compress.h | 46 + services/dbms/sa_profile/402.json | 28 + services/dbms/sa_profile/BUILD.gn | 35 + services/dbms/sa_profile/distributedbms.cfg | 27 + services/dbms/src/account_manager_helper.cpp | 49 + services/dbms/src/distributed_bms.cpp | 463 ++++++ services/dbms/src/distributed_bms_host.cpp | 340 ++++ .../dbms/src/distributed_data_storage.cpp | 403 +++++ services/dbms/src/event_report.cpp | 67 + services/dbms/src/image_compress.cpp | 185 +++ services/dbms/test/BUILD.gn | 20 + .../unittest/dbms_services_kit_test/BUILD.gn | 80 + .../dbms_services_kit_test.cpp | 1465 +++++++++++++++++ .../distributed_bms_host_test/BUILD.gn | 75 + .../distributed_bms_host_test.cpp | 752 +++++++++ .../mock_distributed_bms_interface.cpp | 83 + .../mock_distributed_bms_interface.h | 53 + 42 files changed, 6672 insertions(+), 75 deletions(-) create mode 100644 BUILD.gn delete mode 100644 README.en.md delete mode 100644 README.md create mode 100644 bundle.json create mode 100644 dbms.gni create mode 100644 interfaces/inner_api/BUILD.gn create mode 100644 interfaces/inner_api/include/distributed_bms_interface.h create mode 100644 interfaces/inner_api/include/distributed_bms_proxy.h create mode 100644 interfaces/inner_api/src/distributed_bms_proxy.cpp create mode 100644 interfaces/kits/js/distributebundlemgr/BUILD.gn create mode 100644 interfaces/kits/js/distributebundlemgr/distributed_bundle_mgr.cpp create mode 100644 interfaces/kits/js/distributebundlemgr/distributed_bundle_mgr.h create mode 100644 interfaces/kits/js/distributebundlemgr/native_module.cpp create mode 100644 interfaces/kits/js/distributedBundle/BUILD.gn create mode 100644 interfaces/kits/js/distributedBundle/distributed_bundle.cpp create mode 100644 interfaces/kits/js/distributedBundle/distributed_bundle.h create mode 100644 interfaces/kits/js/distributedBundle/distributed_bundle_unsupported.cpp create mode 100644 interfaces/kits/js/distributedBundle/native_module.cpp create mode 100644 services/dbms/BUILD.gn create mode 100644 services/dbms/include/account_manager_helper.h create mode 100644 services/dbms/include/distributed_bms.h create mode 100644 services/dbms/include/distributed_bms_host.h create mode 100644 services/dbms/include/distributed_data_storage.h create mode 100644 services/dbms/include/distributed_monitor.h create mode 100644 services/dbms/include/event_report.h create mode 100644 services/dbms/include/image_compress.h create mode 100644 services/dbms/sa_profile/402.json create mode 100644 services/dbms/sa_profile/BUILD.gn create mode 100644 services/dbms/sa_profile/distributedbms.cfg create mode 100644 services/dbms/src/account_manager_helper.cpp create mode 100644 services/dbms/src/distributed_bms.cpp create mode 100644 services/dbms/src/distributed_bms_host.cpp create mode 100644 services/dbms/src/distributed_data_storage.cpp create mode 100644 services/dbms/src/event_report.cpp create mode 100644 services/dbms/src/image_compress.cpp create mode 100644 services/dbms/test/BUILD.gn create mode 100644 services/dbms/test/unittest/dbms_services_kit_test/BUILD.gn create mode 100644 services/dbms/test/unittest/dbms_services_kit_test/dbms_services_kit_test.cpp create mode 100644 services/dbms/test/unittest/distributed_bms_host_test/BUILD.gn create mode 100644 services/dbms/test/unittest/distributed_bms_host_test/distributed_bms_host_test.cpp create mode 100644 services/dbms/test/unittest/distributed_bms_host_test/mock_distributed_bms_interface.cpp create mode 100644 services/dbms/test/unittest/distributed_bms_host_test/mock_distributed_bms_interface.h diff --git a/BUILD.gn b/BUILD.gn new file mode 100644 index 0000000..d9ee11f --- /dev/null +++ b/BUILD.gn @@ -0,0 +1,37 @@ +# Copyright (c) 2022-2023 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") + +group("inner_api_target") { + deps = [ "interfaces/inner_api:dbms_fwk" ] +} + +group("jsapi_target") { + deps = [ + "interfaces/kits/js/distributebundlemgr:jsapi_target", + "interfaces/kits/js/distributedBundle:jsapi_target", + ] +} + +group("dbms_target") { + deps = [ + "services/dbms:dbms_target", + "services/dbms/sa_profile:distributedbms", + ] +} + +group("test_target") { + testonly = true + deps = [ "services/dbms/test:unittest" ] +} diff --git a/README.en.md b/README.en.md deleted file mode 100644 index c66178c..0000000 --- a/README.en.md +++ /dev/null @@ -1,36 +0,0 @@ -# bundlemanager_distributed_bundle_framework - -#### Description -{**When you're done, you can delete the content in this README and update the file with details for others getting started with your repository**} - -#### Software Architecture -Software architecture description - -#### Installation - -1. xxxx -2. xxxx -3. xxxx - -#### Instructions - -1. xxxx -2. xxxx -3. xxxx - -#### Contribution - -1. Fork the repository -2. Create Feat_xxx branch -3. Commit your code -4. Create Pull Request - - -#### Gitee Feature - -1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md -2. Gitee blog [blog.gitee.com](https://blog.gitee.com) -3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore) -4. The most valuable open source project [GVP](https://gitee.com/gvp) -5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help) -6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) diff --git a/README.md b/README.md deleted file mode 100644 index 24df4ee..0000000 --- a/README.md +++ /dev/null @@ -1,39 +0,0 @@ -# bundlemanager_distributed_bundle_framework - -#### 介绍 -{**以下是 Gitee 平台说明,您可以替换此简介** -Gitee 是 OSCHINA 推出的基于 Git 的代码托管平台(同时支持 SVN)。专为开发者提供稳定、高效、安全的云端软件开发协作平台 -无论是个人、团队、或是企业,都能够用 Gitee 实现代码托管、项目管理、协作开发。企业项目请看 [https://gitee.com/enterprises](https://gitee.com/enterprises)} - -#### 软件架构 -软件架构说明 - - -#### 安装教程 - -1. xxxx -2. xxxx -3. xxxx - -#### 使用说明 - -1. xxxx -2. xxxx -3. xxxx - -#### 参与贡献 - -1. Fork 本仓库 -2. 新建 Feat_xxx 分支 -3. 提交代码 -4. 新建 Pull Request - - -#### 特技 - -1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md -2. Gitee 官方博客 [blog.gitee.com](https://blog.gitee.com) -3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解 Gitee 上的优秀开源项目 -4. [GVP](https://gitee.com/gvp) 全称是 Gitee 最有价值开源项目,是综合评定出的优秀开源项目 -5. Gitee 官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help) -6. Gitee 封面人物是一档用来展示 Gitee 会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/) diff --git a/bundle.json b/bundle.json new file mode 100644 index 0000000..02e65e7 --- /dev/null +++ b/bundle.json @@ -0,0 +1,67 @@ +{ + "name": "@ohos/distributed_bundle_framework", + "description": "分布式包管理服务", + "version": "3.1", + "license": "Apache 2.0", + "segment": { + "destPath": "foundation/bundlemanager/distributed_bundle_framework" + }, + "component": { + "name": "distributed_bundle_framework", + "subsystem": "bundlemanager", + "syscap": [ + "SystemCapability.BundleManager.DistributedBundleFramework" + ], + "features": [ + "distributed_bundle_framework_graphics" + ], + "adapted_system_type": [ + "standard" + ], + "rom": "100KB", + "ram": "100KB", + "deps": { + "components": [ + "ability_base", + "access_token", + "bundle_framework", + "common", + "c_utils", + "hisysevent_native", + "hiviewdfx_hilog_native", + "i18n", + "ipc", + "multimedia_image_framework", + "napi", + "os_account", + "resource_management", + "safwk", + "samgr" + ], + "third_party": [ + ] + }, + "build": { + "sub_component": [ + "//foundation/bundlemanager/distributed_bundle_framework:inner_api_target", + "//foundation/bundlemanager/distributed_bundle_framework:jsapi_target", + "//foundation/bundlemanager/distributed_bundle_framework:dbms_target" + ], + "inner_kits": [ + { + "header": { + "header_base": "//foundation/bundlemanager/distributed_bundle_framework/interfaces/inner_api/include", + "header_files": [ + "distributed_bms_interface.h", + "distributed_bms_proxy.h" + ] + }, + "name": "//foundation/bundlemanager/distributed_bundle_framework/interfaces/inner_api:dbms_fwk" + } + ], + "test": [ + "//foundation/bundlemanager/distributed_bundle_framework:test_target" + ] + } + } +} \ No newline at end of file diff --git a/dbms.gni b/dbms.gni new file mode 100644 index 0000000..0ea9825 --- /dev/null +++ b/dbms.gni @@ -0,0 +1,59 @@ +# 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. + +bundlemanager_path = "//foundation/bundlemanager" +bundle_framework_path = "${bundlemanager_path}/bundle_framework" + +common_path = "${bundle_framework_path}/common" +dbms_inner_api_path = + "${bundlemanager_path}/distributed_bundle_framework/interfaces/inner_api" +dbms_services_path = + "${bundlemanager_path}/distributed_bundle_framework/services/dbms" +kits_path = "${bundle_framework_path}/interfaces/kits" + +declare_args() { + distributed_bundle_framework_graphics = true + + ability_runtime_enable_dbms = true + account_enable_dbms = true + distributed_bundle_framework_enable = true + hisysevent_enable_dbms = true + + if (defined(global_parts_info) && + !defined(global_parts_info.ability_ability_runtime)) { + ability_runtime_enable_dbms = false + } + + if (defined(global_parts_info) && + !defined(global_parts_info.account_os_account)) { + account_enable_dbms = false + } + + if (defined(global_parts_info) && + !defined(global_parts_info.bundlemanager_distributed_bundle_framework)) { + distributed_bundle_framework_enable = false + } + + if (defined(global_parts_info) && + !defined(global_parts_info.hiviewdfx_hisysevent_native)) { + hisysevent_enable_dbms = false + } +} + +print("distributed_bundle_framework_graphics = " + + "$distributed_bundle_framework_graphics") +print("ability_runtime_enable_dbms = " + "$ability_runtime_enable_dbms") +print("account_enable_dbms = " + "$account_enable_dbms") +print("distributed_bundle_framework_enable = " + + "$distributed_bundle_framework_enable") +print("hisysevent_enable_dbms = " + "$hisysevent_enable_dbms") diff --git a/interfaces/inner_api/BUILD.gn b/interfaces/inner_api/BUILD.gn new file mode 100644 index 0000000..56850b6 --- /dev/null +++ b/interfaces/inner_api/BUILD.gn @@ -0,0 +1,43 @@ +# 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("//build/ohos.gni") +import("../../dbms.gni") + +config("dbms_fwk_config") { + include_dirs = [ "include" ] +} + +ohos_shared_library("dbms_fwk") { + sources = [ "src/distributed_bms_proxy.cpp" ] + + defines = [ + "APP_LOG_TAG = \"DistributedBundleMgrService\"", + "LOG_DOMAIN = 0xD001120", + ] + + public_configs = [ ":dbms_fwk_config" ] + + deps = [ "${common_path}:libappexecfwk_common" ] + + external_deps = [ + "ability_base:want", + "bundle_framework:appexecfwk_base", + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + + part_name = "distributed_bundle_framework" + subsystem_name = "bundlemanager" +} diff --git a/interfaces/inner_api/include/distributed_bms_interface.h b/interfaces/inner_api/include/distributed_bms_interface.h new file mode 100644 index 0000000..0b477cd --- /dev/null +++ b/interfaces/inner_api/include/distributed_bms_interface.h @@ -0,0 +1,137 @@ +/* + * 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. + */ + +#ifndef FOUNDATION_APPEXECFWK_SERVICES_DBMS_INCLUDE_DISTRIBUTED_BMS_INTERFACE_H +#define FOUNDATION_APPEXECFWK_SERVICES_DBMS_INCLUDE_DISTRIBUTED_BMS_INTERFACE_H + +#include +#include + +#include "distributed_bundle_info.h" +#include "element_name.h" +#include "iremote_broker.h" +#include "remote_ability_info.h" + +namespace OHOS { +namespace AppExecFwk { +class IDistributedBms : public IRemoteBroker { +public: + DECLARE_INTERFACE_DESCRIPTOR(u"ohos.appexecfwk.IDistributedbms"); + + /** + * @brief get remote ability info + * @param elementName Indicates the elementName. + * @param remoteAbilityInfo Indicates the remote ability info. + * @return Returns result code when get remote ability info. + */ + virtual int32_t GetRemoteAbilityInfo( + const OHOS::AppExecFwk::ElementName &elementName, RemoteAbilityInfo &remoteAbilityInfo) = 0; + + /** + * @brief get remote ability info + * @param elementName Indicates the elementName. + * @param localeInfo Indicates the localeInfo. + * @param remoteAbilityInfo Indicates the remote ability info. + * @return Returns result code when get remote ability info. + */ + virtual int32_t GetRemoteAbilityInfo(const OHOS::AppExecFwk::ElementName &elementName, + const std::string &localeInfo, RemoteAbilityInfo &remoteAbilityInfo) = 0; + + /** + * @brief get remote ability infos + * @param elementNames Indicates the elementNames. + * @param remoteAbilityInfos Indicates the remote ability infos. + * @return Returns result code when get remote ability infos. + */ + virtual int32_t GetRemoteAbilityInfos( + const std::vector &elementNames, std::vector &remoteAbilityInfos) = 0; + + /** + * @brief get remote ability infos + * @param elementNames Indicates the elementNames. + * @param localeInfo Indicates the localeInfo. + * @param remoteAbilityInfos Indicates the remote ability infos. + * @return Returns result code when get remote ability infos. + */ + virtual int32_t GetRemoteAbilityInfos(const std::vector &elementNames, const std::string &localeInfo, + std::vector &remoteAbilityInfos) = 0; + + /** + * @brief get ability info + * @param elementName Indicates the elementName. + * @param remoteAbilityInfo Indicates the remote ability info. + * @return Returns result code when get ability info. + */ + virtual int32_t GetAbilityInfo( + const OHOS::AppExecFwk::ElementName &elementName, RemoteAbilityInfo &remoteAbilityInfo) = 0; + + /** + * @brief get ability info + * @param elementName Indicates the elementName. + * @param localeInfo Indicates the localeInfo. + * @param remoteAbilityInfo Indicates the remote ability info. + * @return Returns result code when get ability info. + */ + virtual int32_t GetAbilityInfo(const OHOS::AppExecFwk::ElementName &elementName, const std::string &localeInfo, + RemoteAbilityInfo &remoteAbilityInfo) = 0; + + /** + * @brief get ability infos + * @param elementNames Indicates the elementNames. + * @param remoteAbilityInfos Indicates the remote ability infos. + * @return Returns result code when get ability infos. + */ + virtual int32_t GetAbilityInfos( + const std::vector &elementNames, std::vector &remoteAbilityInfos) = 0; + + /** + * @brief get ability infos + * @param elementNames Indicates the elementNames. + * @param localeInfo Indicates the localeInfo. + * @param remoteAbilityInfos Indicates the remote ability infos. + * @return Returns result code when get ability infos. + */ + virtual int32_t GetAbilityInfos(const std::vector &elementNames, const std::string &localeInfo, + std::vector &remoteAbilityInfos) = 0; + + virtual bool GetDistributedBundleInfo(const std::string &networkId, const std::string &bundleName, + DistributedBundleInfo &distributedBundleInfo) = 0; + + /** + * @brief get distributedBundleName based on a given accessTokenId and networkId. + * @param networkId Indicates the networkId of remote device. + * @param accessTokenId AccessTokenId of the application + * @param bundleNames distributed bundle name. + * @return Returns ERR_OK on success, others on failure when get distributed bundle name. + */ + virtual int32_t GetDistributedBundleName(const std::string &networkId, uint32_t accessTokenId, + std::string &bundleName) = 0; + + enum class Message { + GET_REMOTE_ABILITY_INFO = 0, + GET_REMOTE_ABILITY_INFOS, + GET_ABILITY_INFO, + GET_ABILITY_INFOS, + GET_REMOTE_ABILITY_INFO_WITH_LOCALE, + GET_REMOTE_ABILITY_INFOS_WITH_LOCALE, + GET_ABILITY_INFO_WITH_LOCALE, + GET_ABILITY_INFOS_WITH_LOCALE, + GET_DISTRIBUTED_BUNDLE_INFO, + GET_DISTRIBUTED_BUNDLE_NAME, + }; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_DBMS_INCLUDE_DISTRIBUTED_BMS_INTERFACE_H \ No newline at end of file diff --git a/interfaces/inner_api/include/distributed_bms_proxy.h b/interfaces/inner_api/include/distributed_bms_proxy.h new file mode 100644 index 0000000..ee43ec0 --- /dev/null +++ b/interfaces/inner_api/include/distributed_bms_proxy.h @@ -0,0 +1,132 @@ +/* + * 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. + */ + +#ifndef FOUNDATION_APPEXECFWK_SERVICES_DBMS_INCLUDE_DISTRIBUTED_BMS_PROXY_H +#define FOUNDATION_APPEXECFWK_SERVICES_DBMS_INCLUDE_DISTRIBUTED_BMS_PROXY_H + +#include + +#include "distributed_bms_interface.h" +#include "iremote_proxy.h" + +namespace OHOS { +namespace AppExecFwk { +class DistributedBmsProxy : public IRemoteProxy { +public: + explicit DistributedBmsProxy(const sptr &object); + virtual ~DistributedBmsProxy() override; + + /** + * @brief get remote ability info + * @param elementName Indicates the elementName. + * @param remoteAbilityInfo Indicates the remote ability info. + * @return Returns result code when get ability info. + */ + int32_t GetRemoteAbilityInfo( + const OHOS::AppExecFwk::ElementName &elementName, RemoteAbilityInfo &remoteAbilityInfo) override; + + /** + * @brief get remote ability info + * @param elementName Indicates the elementName. + * @param localeInfo Indicates the localeInfo. + * @param remoteAbilityInfo Indicates the remote ability info. + * @return Returns result code when get remote ability info. + */ + int32_t GetRemoteAbilityInfo(const OHOS::AppExecFwk::ElementName &elementName, const std::string &localeInfo, + RemoteAbilityInfo &remoteAbilityInfo) override; + + /** + * @brief get remote ability infos + * @param elementNames Indicates the elementNames. + * @param remoteAbilityInfos Indicates the remote ability infos. + * @return Returns result code when get remote ability infos. + */ + int32_t GetRemoteAbilityInfos( + const std::vector &elementNames, std::vector &remoteAbilityInfos) override; + + /** + * @brief get remote ability infos + * @param elementNames Indicates the elementNames. + * @param localeInfo Indicates the localeInfo. + * @param remoteAbilityInfos Indicates the remote ability infos. + * @return Returns result code when get remote ability infos. + */ + int32_t GetRemoteAbilityInfos(const std::vector &elementNames, const std::string &localeInfo, + std::vector &remoteAbilityInfos) override; + + /** + * @brief get ability info + * @param elementName Indicates the elementName. + * @param remoteAbilityInfo Indicates the remote ability info. + * @return Returns result code when get ability info. + */ + int32_t GetAbilityInfo( + const OHOS::AppExecFwk::ElementName &elementName, RemoteAbilityInfo &remoteAbilityInfo) override; + + /** + * @brief get ability info + * @param elementName Indicates the elementName. + * @param localeInfo Indicates the localeInfo. + * @param remoteAbilityInfo Indicates the remote ability info. + * @return Returns result code when get ability info. + */ + int32_t GetAbilityInfo(const OHOS::AppExecFwk::ElementName &elementName, const std::string &localeInfo, + RemoteAbilityInfo &remoteAbilityInfo) override; + + /** + * @brief get ability infos + * @param elementNames Indicates the elementNames. + * @param remoteAbilityInfos Indicates the remote ability infos. + * @return Returns result code when get ability infos. + */ + int32_t GetAbilityInfos( + const std::vector &elementNames, std::vector &remoteAbilityInfos) override; + + /** + * @brief get ability infos + * @param elementNames Indicates the elementNames. + * @param localeInfo Indicates the localeInfo. + * @param remoteAbilityInfos Indicates the remote ability infos. + * @return Returns result code when get ability infos. + */ + int32_t GetAbilityInfos(const std::vector &elementNames, const std::string &localeInfo, + std::vector &remoteAbilityInfos) override; + + bool GetDistributedBundleInfo(const std::string &networkId, const std::string &bundleName, + DistributedBundleInfo &distributedBundleInfo) override; + + /** + * @brief get distributedBundleName based on a given accessTokenId and networkId. + * @param networkId Indicates the networkId of remote device. + * @param accessTokenId AccessTokenId of the application + * @param bundleNames distributed bundle name. + * @return Returns ERR_OK on success, others on failure when get distributed bundle name. + */ + int32_t GetDistributedBundleName(const std::string &networkId, uint32_t accessTokenId, + std::string &bundleName) override; +private: + int32_t SendRequest(IDistributedBms::Message code, MessageParcel &data, MessageParcel &reply); + template + bool WriteParcelableVector(const std::vector &parcelableVector, Parcel &data); + template + int32_t GetParcelableInfo(IDistributedBms::Message code, MessageParcel &data, T &parcelableInfo); + template + int32_t GetParcelableInfos(IDistributedBms::Message code, MessageParcel &data, std::vector &parcelableInfos); + int32_t CheckElementName(const ElementName &elementName); + static inline BrokerDelegator delegator_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_DBMS_INCLUDE_DISTRIBUTED_BMS_PROXY_H \ No newline at end of file diff --git a/interfaces/inner_api/src/distributed_bms_proxy.cpp b/interfaces/inner_api/src/distributed_bms_proxy.cpp new file mode 100644 index 0000000..8f6b9f0 --- /dev/null +++ b/interfaces/inner_api/src/distributed_bms_proxy.cpp @@ -0,0 +1,339 @@ +/* + * 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. + */ + +#include "distributed_bms_proxy.h" + +#include "app_log_wrapper.h" +#include "appexecfwk_errors.h" +#include "parcel_macro.h" + +namespace OHOS { +namespace AppExecFwk { +DistributedBmsProxy::DistributedBmsProxy(const sptr &object) : IRemoteProxy(object) +{ + APP_LOGI("DistributedBmsProxy instance is created"); +} + +DistributedBmsProxy::~DistributedBmsProxy() +{ + APP_LOGI("DistributedBmsProxy instance is destroyed"); +} + +int32_t DistributedBmsProxy::GetRemoteAbilityInfo( + const OHOS::AppExecFwk::ElementName &elementName, RemoteAbilityInfo &remoteAbilityInfo) +{ + APP_LOGD("DistributedBmsProxy GetRemoteAbilityInfo"); + return GetRemoteAbilityInfo(elementName, "", remoteAbilityInfo); +} + +int32_t DistributedBmsProxy::GetRemoteAbilityInfo(const OHOS::AppExecFwk::ElementName &elementName, + const std::string &localeInfo, + RemoteAbilityInfo &remoteAbilityInfo) +{ + APP_LOGD("DistributedBmsProxy GetRemoteAbilityInfoWithLocale"); + int32_t checkRet = CheckElementName(elementName); + if (checkRet != ERR_OK) { + APP_LOGE("DistributedBmsProxy GetRemoteAbilityInfoWithLocale check elementName failed"); + return checkRet; + } + MessageParcel data; + MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + APP_LOGE("fail to GetRemoteAbilityInfo due to write InterfaceToken fail"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(&elementName)) { + APP_LOGE("DistributedBmsProxy GetRemoteAbilityInfo write elementName error"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteString(localeInfo)) { + APP_LOGE("DistributedBmsProxy GetRemoteAbilityInfo write localeInfo error"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int32_t result = GetParcelableInfo( + IDistributedBms::Message::GET_REMOTE_ABILITY_INFO_WITH_LOCALE, data, remoteAbilityInfo); + if (result != OHOS::NO_ERROR) { + APP_LOGE("fail to query ability info mutiparam from server, result:%{public}d", result); + } + return result; +} + +int32_t DistributedBmsProxy::GetRemoteAbilityInfos( + const std::vector &elementNames, std::vector &remoteAbilityInfos) +{ + APP_LOGD("DistributedBmsProxy GetRemoteAbilityInfos"); + return GetRemoteAbilityInfos(elementNames, "", remoteAbilityInfos); +} + +int32_t DistributedBmsProxy::GetRemoteAbilityInfos(const std::vector &elementNames, + const std::string &localeInfo, + std::vector &remoteAbilityInfos) +{ + APP_LOGD("DistributedBmsProxy GetRemoteAbilityInfosWithLocale"); + for (const auto &elementName : elementNames) { + int32_t checkRet = CheckElementName(elementName); + if (checkRet != ERR_OK) { + APP_LOGE("DistributedBmsProxy GetRemoteAbilityInfosWithLocale check elementName failed"); + return checkRet; + } + } + MessageParcel data; + MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + APP_LOGE("fail to GetRemoteAbilityInfos due to write InterfaceToken fail"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!WriteParcelableVector(elementNames, data)) { + APP_LOGE("DistributedBmsProxy GetRemoteAbilityInfos write elementName error"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteString(localeInfo)) { + APP_LOGE("DistributedBmsProxy GetRemoteAbilityInfos write localeInfo error"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int32_t result = GetParcelableInfos( + IDistributedBms::Message::GET_REMOTE_ABILITY_INFOS_WITH_LOCALE, data, remoteAbilityInfos); + if (result != OHOS::NO_ERROR) { + APP_LOGE("fail to query remote ability infos mutiparam from server"); + } + return result; +} + +int32_t DistributedBmsProxy::GetAbilityInfo( + const OHOS::AppExecFwk::ElementName &elementName, RemoteAbilityInfo &remoteAbilityInfo) +{ + APP_LOGD("DistributedBmsProxy GetAbilityInfo"); + return GetAbilityInfo(elementName, "", remoteAbilityInfo); +} + +int32_t DistributedBmsProxy::GetAbilityInfo(const OHOS::AppExecFwk::ElementName &elementName, + const std::string &localeInfo, + RemoteAbilityInfo &remoteAbilityInfo) +{ + APP_LOGD("DistributedBmsProxy GetAbilityInfoWithLocale"); + MessageParcel data; + MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + APP_LOGE("fail to GetAbilityInfo due to write InterfaceToken fail"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteParcelable(&elementName)) { + APP_LOGE("DistributedBmsProxy GetAbilityInfo write elementName error"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteString(localeInfo)) { + APP_LOGE("DistributedBmsProxy GetRemoteAbilityInfos write localeInfo error"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + int32_t result = GetParcelableInfo( + IDistributedBms::Message::GET_ABILITY_INFO_WITH_LOCALE, data, remoteAbilityInfo); + if (result == OHOS::IPC_STUB_UNKNOW_TRANS_ERR) { + return GetParcelableInfo( + IDistributedBms::Message::GET_ABILITY_INFO, data, remoteAbilityInfo); + } + return result; +} + +int32_t DistributedBmsProxy::GetAbilityInfos( + const std::vector &elementNames, std::vector &remoteAbilityInfos) +{ + APP_LOGD("DistributedBmsProxy GetAbilityInfos"); + return GetAbilityInfos(elementNames, "", remoteAbilityInfos); +} + +int32_t DistributedBmsProxy::GetAbilityInfos(const std::vector &elementNames, + const std::string &localeInfo, + std::vector &remoteAbilityInfos) +{ + APP_LOGD("DistributedBmsProxy GetAbilityInfos"); + MessageParcel data; + MessageParcel reply; + if (!data.WriteInterfaceToken(GetDescriptor())) { + APP_LOGE("fail to GetAbilityInfos due to write InterfaceToken fail"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!WriteParcelableVector(elementNames, data)) { + APP_LOGE("DistributedBmsProxy GetAbilityInfos write elementName error"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteString(localeInfo)) { + APP_LOGE("DistributedBmsProxy GetRemoteAbilityInfos write localeInfo error"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + int32_t result = GetParcelableInfos( + IDistributedBms::Message::GET_ABILITY_INFOS_WITH_LOCALE, data, remoteAbilityInfos); + if (result == OHOS::IPC_STUB_UNKNOW_TRANS_ERR) { + return GetParcelableInfos( + IDistributedBms::Message::GET_ABILITY_INFOS, data, remoteAbilityInfos); + } + return result; +} + +bool DistributedBmsProxy::GetDistributedBundleInfo(const std::string &networkId, const std::string &bundleName, + DistributedBundleInfo &distributedBundleInfo) +{ + APP_LOGD("DistributedBmsProxy GetDistributedBundleInfo"); + MessageParcel data; + if (!data.WriteInterfaceToken(GetDescriptor())) { + APP_LOGE("fail to GetDistributedBundleInfo due to write InterfaceToken fail"); + return false; + } + if (!data.WriteString(networkId)) { + APP_LOGE("DistributedBmsProxy GetDistributedBundleInfo write networkId error"); + return false; + } + if (!data.WriteString(bundleName)) { + APP_LOGE("DistributedBmsProxy GetDistributedBundleInfo write bundleName error"); + return false; + } + int32_t result = GetParcelableInfo( + IDistributedBms::Message::GET_DISTRIBUTED_BUNDLE_INFO, data, distributedBundleInfo); + if (result == OHOS::NO_ERROR) { + return true; + } + return false; +} + +int32_t DistributedBmsProxy::GetDistributedBundleName(const std::string &networkId, uint32_t accessTokenId, + std::string &bundleName) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(GetDescriptor())) { + APP_LOGE("fail to get distributed bundleInfo list due to write InterfaceToken fail"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteString(networkId)) { + APP_LOGE("distributed mms proxy get distributed bundleInfo list write networkId error"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!data.WriteUint32(accessTokenId)) { + APP_LOGE("distributed mms proxy get distributed bundleInfo list write accessTokenId error"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + MessageParcel reply; + int32_t result = SendRequest(IDistributedBms::Message::GET_DISTRIBUTED_BUNDLE_NAME, data, reply); + if (result == OHOS::NO_ERROR) { + bundleName = reply.ReadString(); + } + return result; +} + +template +bool DistributedBmsProxy::WriteParcelableVector(const std::vector &parcelableVector, Parcel &data) +{ + if (!data.WriteInt32(parcelableVector.size())) { + APP_LOGE("write ParcelableVector failed"); + return false; + } + + for (auto &parcelable : parcelableVector) { + if (!data.WriteParcelable(&parcelable)) { + APP_LOGE("write ParcelableVector failed"); + return false; + } + } + return true; +} + +template +int32_t DistributedBmsProxy::GetParcelableInfo(IDistributedBms::Message code, MessageParcel &data, T &parcelableInfo) +{ + MessageParcel reply; + int32_t result = SendRequest(code, data, reply); + if (result != OHOS::NO_ERROR) { + APP_LOGE("reply result false"); + return result; + } + + if (!reply.ReadBool()) { + APP_LOGE("reply result false"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + std::unique_ptr info(reply.ReadParcelable()); + if (!info) { + APP_LOGE("readParcelableInfo failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + parcelableInfo = *info; + APP_LOGD("get parcelable info success"); + return OHOS::NO_ERROR; +} + +template +int32_t DistributedBmsProxy::GetParcelableInfos( + IDistributedBms::Message code, MessageParcel &data, std::vector &parcelableInfos) +{ + MessageParcel reply; + int32_t result = SendRequest(code, data, reply); + if (result != OHOS::NO_ERROR) { + APP_LOGE("reply result false"); + return result; + } + + if (!reply.ReadBool()) { + APP_LOGE("reply result false"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + + int32_t infoSize = reply.ReadInt32(); + for (int32_t i = 0; i < infoSize; i++) { + std::unique_ptr info(reply.ReadParcelable()); + if (!info) { + APP_LOGE("Read Parcelable infos failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + parcelableInfos.emplace_back(*info); + } + APP_LOGD("get parcelable infos success"); + return OHOS::NO_ERROR; +} + +int32_t DistributedBmsProxy::SendRequest(IDistributedBms::Message code, MessageParcel &data, MessageParcel &reply) +{ + APP_LOGD("DistributedBmsProxy SendRequest"); + sptr remote = Remote(); + MessageOption option(MessageOption::TF_SYNC); + if (remote == nullptr) { + APP_LOGE("fail to send %{public}d cmd to service due to remote object is null", code); + return ERR_APPEXECFWK_FAILED_GET_REMOTE_PROXY; + } + int32_t result = remote->SendRequest(static_cast(code), data, reply, option); + if (result != OHOS::NO_ERROR) { + APP_LOGE("fail to send %{public}d cmd to service due to transact error:%{public}d", code, result); + } + return result; +} + +int32_t DistributedBmsProxy::CheckElementName(const ElementName &elementName) +{ + if (elementName.GetBundleName().empty()) { + APP_LOGE("fail to GetRemoteAbilityInfo due to bundleName empty"); + return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST; + } + if (elementName.GetAbilityName().empty()) { + APP_LOGE("fail to GetRemoteAbilityInfo due to abilityName empty"); + return ERR_BUNDLE_MANAGER_ABILITY_NOT_EXIST; + } + if (elementName.GetDeviceID().empty()) { + APP_LOGE("fail to GetRemoteAbilityInfo due to devicedID empty"); + return ERR_BUNDLE_MANAGER_DEVICE_ID_NOT_EXIST; + } + return ERR_OK; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/distributebundlemgr/BUILD.gn b/interfaces/kits/js/distributebundlemgr/BUILD.gn new file mode 100644 index 0000000..1ed9193 --- /dev/null +++ b/interfaces/kits/js/distributebundlemgr/BUILD.gn @@ -0,0 +1,56 @@ +# Copyright (c) 2021-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("//build/ohos.gni") +import("../../../../dbms.gni") + +ohos_shared_library("distributedbundle") { + include_dirs = [] + defines = [ + "APP_LOG_TAG = \"DistributedBundleMgrService\"", + "LOG_DOMAIN = 0xD001120", + ] + sources = [ + "distributed_bundle_mgr.cpp", + "native_module.cpp", + ] + + configs = [ "${dbms_services_path}:distributed_bms_config" ] + + deps = [ + "${common_path}:libappexecfwk_common", + "${dbms_inner_api_path}:dbms_fwk", + ] + + external_deps = [ + "ability_base:want", + "bundle_framework:appexecfwk_base", + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "napi:ace_napi", + "samgr:samgr_proxy", + ] + + relative_install_dir = "module" + subsystem_name = "bundlemanager" + part_name = "distributed_bundle_framework" +} + +group("jsapi_target") { + deps = [] + + if (support_jsapi && distributed_bundle_framework_graphics) { + deps += [ ":distributedbundle" ] + } +} diff --git a/interfaces/kits/js/distributebundlemgr/distributed_bundle_mgr.cpp b/interfaces/kits/js/distributebundlemgr/distributed_bundle_mgr.cpp new file mode 100644 index 0000000..17915b0 --- /dev/null +++ b/interfaces/kits/js/distributebundlemgr/distributed_bundle_mgr.cpp @@ -0,0 +1,491 @@ +/* + * 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. + */ +#include "distributed_bundle_mgr.h" + +#include + +#include "app_log_wrapper.h" +#include "appexecfwk_errors.h" +#include "bundle_constants.h" +#include "distributed_bms_interface.h" +#include "distributed_bms_proxy.h" +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include "securec.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace AppExecFwk { +using namespace OHOS; +using namespace OHOS::AppExecFwk; + +namespace { +constexpr size_t ARGS_SIZE_ONE = 1; +constexpr size_t ARGS_SIZE_THREE = 3; +constexpr int32_t PARAM0 = 0; +constexpr int32_t PARAM1 = 1; +constexpr int32_t PARAM2 = 2; +constexpr int32_t NAPI_RETURN_ZERO = 0; +constexpr int32_t NAPI_RETURN_ONE = 1; +constexpr int32_t GET_REMOTE_ABILITY_INFO_MAX_SIZE = 10; +enum GetRemoteAbilityInfoErrorCode : int32_t { + SUCCESS = 0, + ERR_INNER_ERROR, + ERR_INVALID_PARAM, + ERR_PARAMETERS_MORE_THAN_MAX, + ERR_RPC_ERROR, +}; +} + +AsyncWorkData::AsyncWorkData(napi_env napiEnv) : env(napiEnv) {} + +AsyncWorkData::~AsyncWorkData() +{ + if (callbackRef) { + APP_LOGD("AsyncWorkData::~AsyncWorkData delete callbackRef"); + napi_delete_reference(env, callbackRef); + callbackRef = nullptr; + } + if (asyncWork) { + APP_LOGD("AsyncWorkData::~AsyncWorkData delete asyncWork"); + napi_delete_async_work(env, asyncWork); + asyncWork = nullptr; + } +} + +static OHOS::sptr GetDistributedBundleMgr() +{ + APP_LOGI("GetDistributedBundleMgr"); + auto samgr = OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + // OHOS::sptr remoteObject; + auto remoteObject = samgr->GetSystemAbility(OHOS::DISTRIBUTED_BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + return OHOS::iface_cast(remoteObject); +} + +static std::string GetStringFromNAPI(napi_env env, napi_value value) +{ + std::string result; + size_t size = 0; + + if (napi_get_value_string_utf8(env, value, nullptr, NAPI_RETURN_ZERO, &size) != napi_ok) { + APP_LOGE("can not get string size"); + return ""; + } + result.reserve(size + NAPI_RETURN_ONE); + result.resize(size); + if (napi_get_value_string_utf8(env, value, result.data(), (size + NAPI_RETURN_ONE), &size) != napi_ok) { + APP_LOGE("can not get string value"); + return ""; + } + return result; +} + +static napi_value ParseString(napi_env env, std::string ¶m, napi_value args) +{ + napi_status status; + napi_valuetype valuetype; + NAPI_CALL(env, napi_typeof(env, args, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + param = GetStringFromNAPI(env, args); + APP_LOGD("param=%{public}s.", param.c_str()); + napi_value result; + status = napi_create_int32(env, NAPI_RETURN_ONE, &result); + NAPI_ASSERT(env, status == napi_ok, "napi_create_int32 error!"); + return result; +} + +static int32_t ConvertResultCode(int32_t code) +{ + APP_LOGD("ConvertResultCode resultCode:%{public}d", code); + switch (code) { + case SUCCESS: + return SUCCESS; + case ERR_APPEXECFWK_FAILED_GET_REMOTE_PROXY: + return ERR_RPC_ERROR; + default: + break; + } + return ERR_INNER_ERROR; +} + +static void ConvertElementName(napi_env env, napi_value objElementName, const ElementName &elementName) +{ + napi_value nDeviceId; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, elementName.GetDeviceID().c_str(), NAPI_AUTO_LENGTH, &nDeviceId)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objElementName, "deviceId", nDeviceId)); + + napi_value nBundleName; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, elementName.GetBundleName().c_str(), NAPI_AUTO_LENGTH, &nBundleName)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objElementName, "bundleName", nBundleName)); + + napi_value nModuleName; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, elementName.GetModuleName().c_str(), NAPI_AUTO_LENGTH, &nModuleName)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objElementName, "moduleName", nModuleName)); + + napi_value nAbilityName; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, elementName.GetAbilityName().c_str(), NAPI_AUTO_LENGTH, &nAbilityName)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objElementName, "abilityName", nAbilityName)); +} + +static void ConvertRemoteAbilityInfo( + napi_env env, napi_value objRemoteAbilityInfo, const RemoteAbilityInfo &remoteAbilityInfo) +{ + napi_value objElementName; + NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &objElementName)); + ConvertElementName(env, objElementName, remoteAbilityInfo.elementName); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objRemoteAbilityInfo, "elementName", objElementName)); + + napi_value nLabel; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, remoteAbilityInfo.label.c_str(), NAPI_AUTO_LENGTH, &nLabel)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objRemoteAbilityInfo, "label", nLabel)); + + napi_value nIcon; + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, remoteAbilityInfo.icon.c_str(), NAPI_AUTO_LENGTH, &nIcon)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objRemoteAbilityInfo, "icon", nIcon)); +} + +static void ConvertRemoteAbilityInfos( + napi_env env, napi_value objRemoteAbilityInfos, const std::vector &remoteAbilityInfos) +{ + if (remoteAbilityInfos.size() == 0) { + APP_LOGE("ConvertRemoteAbilityInfos remoteAbilityInfos is empty"); + return; + } + size_t index = 0; + for (const auto &remoteAbilityInfo : remoteAbilityInfos) { + APP_LOGD("remoteAbilityInfo bundleName:%{public}s, abilityName:%{public}s, label:%{public}s", + remoteAbilityInfo.elementName.GetBundleName().c_str(), + remoteAbilityInfo.elementName.GetAbilityName().c_str(), + remoteAbilityInfo.label.c_str()); + napi_value objRemoteAbilityInfo = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &objRemoteAbilityInfo)); + ConvertRemoteAbilityInfo(env, objRemoteAbilityInfo, remoteAbilityInfo); + NAPI_CALL_RETURN_VOID(env, napi_set_element(env, objRemoteAbilityInfos, index, objRemoteAbilityInfo)); + index++; + } +} + +static bool ParseModuleName(napi_env env, std::string &moduleName, napi_value args) +{ + napi_status status; + napi_valuetype valueType; + napi_value prop = nullptr; + bool hasKey = false; + napi_has_named_property(env, args, "moduleName", &hasKey); + if (hasKey) { + status = napi_get_named_property(env, args, "moduleName", &prop); + napi_typeof(env, prop, &valueType); + if ((status == napi_ok) && (valueType == napi_string)) { + moduleName = GetStringFromNAPI(env, prop); + } else { + APP_LOGE("begin to parse ElementName moduleName failed"); + return false; + } + } + return true; +} + +static bool ParseElementName(napi_env env, OHOS::AppExecFwk::ElementName &elementName, napi_value args) +{ + APP_LOGD("begin to parse ElementName"); + napi_status status; + napi_valuetype valueType; + NAPI_CALL_BASE(env, napi_typeof(env, args, &valueType), false); + if (valueType != napi_object) { + APP_LOGE("args not object type"); + return false; + } + napi_value prop = nullptr; + status = napi_get_named_property(env, args, "deviceId", &prop); + napi_typeof(env, prop, &valueType); + if (status == napi_ok && valueType == napi_string) { + elementName.SetDeviceID(GetStringFromNAPI(env, prop)); + } else { + APP_LOGE("begin to parse ElementName deviceId failed"); + return false; + } + prop = nullptr; + status = napi_get_named_property(env, args, "bundleName", &prop); + napi_typeof(env, prop, &valueType); + if (status == napi_ok && valueType == napi_string) { + elementName.SetBundleName(GetStringFromNAPI(env, prop)); + } else { + APP_LOGE("begin to parse ElementName bundleName failed"); + return false; + } + prop = nullptr; + status = napi_get_named_property(env, args, "abilityName", &prop); + napi_typeof(env, prop, &valueType); + if (status == napi_ok && valueType == napi_string) { + elementName.SetAbilityName(GetStringFromNAPI(env, prop)); + } else { + APP_LOGE("begin to parse ElementName abilityName failed"); + return false; + } + std::string moduleName; + if (!ParseModuleName(env, moduleName, args)) { + return false; + } + elementName.SetModuleName(moduleName); + APP_LOGD("parse ElementName end"); + return true; +} + +static bool ParseElementNames(napi_env env, std::vector &elementNames, napi_value args) +{ + APP_LOGD("begin to parse ElementNames"); + bool isArray = false; + NAPI_CALL_BASE(env, napi_is_array(env, args, &isArray), false); + if (!isArray) { + APP_LOGE("parseElementNames args not array"); + return false; + } + uint32_t arrayLength = 0; + NAPI_CALL_BASE(env, napi_get_array_length(env, args, &arrayLength), false); + APP_LOGD("arrayLength:%{public}d", arrayLength); + for (uint32_t i = 0; i < arrayLength; i++) { + napi_value value = nullptr; + NAPI_CALL_BASE(env, napi_get_element(env, args, i, &value), false); + napi_valuetype valueType = napi_undefined; + NAPI_CALL_BASE(env, napi_typeof(env, value, &valueType), false); + if (valueType != napi_object) { + APP_LOGE("array inside not object type"); + elementNames.clear(); + return false; + } + ElementName elementName; + if (ParseElementName(env, elementName, value)) { + elementNames.push_back(elementName); + } else { + APP_LOGE("elementNames parse elementName failed"); + return false; + } + } + return true; +} + +static int32_t InnerGetRemoteAbilityInfo( + const OHOS::AppExecFwk::ElementName &elementName, const std::string &locale, RemoteAbilityInfo &remoteAbilityInfo) +{ + auto iDistBundleMgr = GetDistributedBundleMgr(); + if (!iDistBundleMgr) { + APP_LOGE("can not get iDistBundleMgr"); + return ERR_INNER_ERROR; + } + int32_t result = iDistBundleMgr->GetRemoteAbilityInfo(elementName, locale, remoteAbilityInfo); + if (result != 0) { + APP_LOGE("InnerGetRemoteAbilityInfo failed"); + } + return ConvertResultCode(result); +} + +static int32_t InnerGetRemoteAbilityInfos(const std::vector &elementNames, const std::string &locale, + std::vector &remoteAbilityInfos) +{ + if (elementNames.size() == 0) { + APP_LOGE("InnerGetRemoteAbilityInfos elementNames is empty"); + return ERR_INVALID_PARAM; + } + auto iDistBundleMgr = GetDistributedBundleMgr(); + if (!iDistBundleMgr) { + APP_LOGE("can not get iDistBundleMgr"); + return ERR_INNER_ERROR; + } + int32_t result = iDistBundleMgr->GetRemoteAbilityInfos(elementNames, locale, remoteAbilityInfos); + if (result != 0) { + APP_LOGE("InnerGetRemoteAbilityInfo failed"); + } + return ConvertResultCode(result); +} + +napi_value GetRemoteAbilityInfo(napi_env env, napi_callback_info info) +{ + size_t requireArgc = ARGS_SIZE_ONE; + size_t argc = ARGS_SIZE_THREE; + napi_value argv[ARGS_SIZE_THREE] = { 0 }; + napi_value thisArg = nullptr; + void *data = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisArg, &data)); + NAPI_ASSERT(env, argc >= requireArgc, "requires 1 parameter"); + + ElementNameInfo *asyncCallbackInfo = new (std::nothrow) ElementNameInfo(env); + if (asyncCallbackInfo == nullptr) { + return nullptr; + } + std::unique_ptr callbackPtr {asyncCallbackInfo}; + for (size_t i = 0; i < argc; ++i) { + napi_valuetype valueType = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[i], &valueType)); + if ((i == PARAM0) && (valueType == napi_object)) { + if (!ParseElementName(env, asyncCallbackInfo->elementName, argv[i])) { + asyncCallbackInfo->errCode = ERR_INVALID_PARAM; + } + } else if ((i == PARAM1) && (valueType == napi_string)) { + ParseString(env, asyncCallbackInfo->locale, argv[i]); + } else if ((i == PARAM1 || i == PARAM2) && (valueType == napi_function)) { + NAPI_CALL(env, napi_create_reference(env, argv[i], NAPI_RETURN_ONE, &asyncCallbackInfo->callbackRef)); + break; + } else { + asyncCallbackInfo->errCode = ERR_INVALID_PARAM; + asyncCallbackInfo->errMssage = "type misMatch"; + } + } + + napi_value promise = nullptr; + if (asyncCallbackInfo->callbackRef == nullptr) { + NAPI_CALL(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise)); + } else { + NAPI_CALL(env, napi_get_undefined(env, &promise)); + } + napi_value resource = nullptr; + NAPI_CALL(env, napi_create_string_utf8(env, "getRemoteAbilityInfo", NAPI_AUTO_LENGTH, &resource)); + NAPI_CALL(env, napi_create_async_work( + env, nullptr, resource, + [](napi_env env, void* data) { + ElementNameInfo* asyncCallbackInfo = reinterpret_cast(data); + if (!asyncCallbackInfo->errCode) { + asyncCallbackInfo->errCode = + InnerGetRemoteAbilityInfo(asyncCallbackInfo->elementName, + asyncCallbackInfo->locale, + asyncCallbackInfo->remoteAbilityInfo); + } + }, + [](napi_env env, napi_status status, void* data) { + ElementNameInfo* asyncCallbackInfo = reinterpret_cast(data); + std::unique_ptr callbackPtr {asyncCallbackInfo}; + napi_value result[2] = { 0 }; + if (asyncCallbackInfo->errCode) { + napi_create_int32(env, asyncCallbackInfo->errCode, &result[0]); + } else { + napi_create_uint32(env, 0, &result[0]); + NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &result[1])); + ConvertRemoteAbilityInfo(env, result[1], asyncCallbackInfo->remoteAbilityInfo); + } + if (asyncCallbackInfo->callbackRef) { + napi_value callback = nullptr; + napi_value placeHolder = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, asyncCallbackInfo->callbackRef, &callback)); + napi_call_function(env, nullptr, callback, sizeof(result) / sizeof(result[0]), result, &placeHolder); + } else { + if (asyncCallbackInfo->errCode) { + NAPI_CALL_RETURN_VOID(env, napi_reject_deferred(env, asyncCallbackInfo->deferred, result[0])); + } else { + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, asyncCallbackInfo->deferred, result[1])); + } + } + }, + reinterpret_cast(asyncCallbackInfo), &asyncCallbackInfo->asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + callbackPtr.release(); + return promise; +} + +napi_value GetRemoteAbilityInfos(napi_env env, napi_callback_info info) +{ + size_t requireArgc = ARGS_SIZE_ONE; + size_t argc = ARGS_SIZE_THREE; + napi_value argv[ARGS_SIZE_THREE] = { 0 }; + napi_value thisArg = nullptr; + void *data = nullptr; + + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisArg, &data)); + NAPI_ASSERT(env, argc >= requireArgc, "requires 1 parameter"); + + ElementNameInfos *asyncCallbackInfo = new (std::nothrow) ElementNameInfos(env); + if (asyncCallbackInfo == nullptr) { + return nullptr; + } + std::unique_ptr callbackPtr {asyncCallbackInfo}; + for (size_t i = 0; i < argc; ++i) { + napi_valuetype valueType = napi_undefined; + napi_typeof(env, argv[i], &valueType); + if (i == PARAM0) { + if (!ParseElementNames(env, asyncCallbackInfo->elementNames, argv[i])) { + asyncCallbackInfo->errCode = ERR_INVALID_PARAM; + } + if (static_cast(asyncCallbackInfo->elementNames.size()) > GET_REMOTE_ABILITY_INFO_MAX_SIZE) { + APP_LOGE("InnerGetRemoteAbilityInfos elementNames more than max"); + asyncCallbackInfo->errCode = ERR_PARAMETERS_MORE_THAN_MAX; + } + } else if ((i == PARAM1) && (valueType == napi_string)) { + ParseString(env, asyncCallbackInfo->locale, argv[i]); + } else if ((i == PARAM1 || i == PARAM2) && (valueType == napi_function)) { + NAPI_CALL(env, napi_create_reference(env, argv[i], NAPI_RETURN_ONE, &asyncCallbackInfo->callbackRef)); + break; + } else { + asyncCallbackInfo->errCode = ERR_INVALID_PARAM; + asyncCallbackInfo->errMssage = "type misMatch"; + } + } + + napi_value promise = nullptr; + if (asyncCallbackInfo->callbackRef == nullptr) { + NAPI_CALL(env, napi_create_promise(env, &asyncCallbackInfo->deferred, &promise)); + } else { + NAPI_CALL(env, napi_get_undefined(env, &promise)); + } + napi_value resource = nullptr; + NAPI_CALL(env, napi_create_string_utf8(env, "getRemoteAbilityInfos", NAPI_AUTO_LENGTH, &resource)); + NAPI_CALL(env, napi_create_async_work( + env, nullptr, resource, + [](napi_env env, void* data) { + ElementNameInfos* asyncCallbackInfo = reinterpret_cast(data); + if (!asyncCallbackInfo->errCode) { + asyncCallbackInfo->errCode = + InnerGetRemoteAbilityInfos(asyncCallbackInfo->elementNames, + asyncCallbackInfo->locale, + asyncCallbackInfo->remoteAbilityInfos); + } + }, + [](napi_env env, napi_status status, void* data) { + ElementNameInfos* asyncCallbackInfo = reinterpret_cast(data); + std::unique_ptr callbackPtr {asyncCallbackInfo}; + napi_value result[2] = { 0 }; + if (asyncCallbackInfo->errCode) { + napi_create_int32(env, asyncCallbackInfo->errCode, &result[0]); + } else { + napi_create_uint32(env, 0, &result[0]); + NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &result[1])); + ConvertRemoteAbilityInfos(env, result[1], asyncCallbackInfo->remoteAbilityInfos); + } + if (asyncCallbackInfo->callbackRef) { + napi_value callback = nullptr; + napi_value placeHolder = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, asyncCallbackInfo->callbackRef, &callback)); + napi_call_function(env, nullptr, callback, sizeof(result) / sizeof(result[0]), result, &placeHolder); + } else { + if (asyncCallbackInfo->errCode) { + napi_reject_deferred(env, asyncCallbackInfo->deferred, result[0]); + } else { + napi_resolve_deferred(env, asyncCallbackInfo->deferred, result[1]); + } + } + }, + reinterpret_cast(asyncCallbackInfo), &asyncCallbackInfo->asyncWork)); + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackInfo->asyncWork)); + callbackPtr.release(); + return promise; +} +} +} \ No newline at end of file diff --git a/interfaces/kits/js/distributebundlemgr/distributed_bundle_mgr.h b/interfaces/kits/js/distributebundlemgr/distributed_bundle_mgr.h new file mode 100644 index 0000000..278f7ea --- /dev/null +++ b/interfaces/kits/js/distributebundlemgr/distributed_bundle_mgr.h @@ -0,0 +1,62 @@ + /* + * 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. + */ + +#ifndef APPEXECFWK_STANDARD_KITS_APPKIT_NAPI_DISTRIBUTEBUNDLEMGR_DISTRIBUTED_BUNDLE_MGR_H +#define APPEXECFWK_STANDARD_KITS_APPKIT_NAPI_DISTRIBUTEBUNDLEMGR_DISTRIBUTED_BUNDLE_MGR_H +#include + +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" +#include "application_info.h" +#include "element_name.h" +#include "remote_ability_info.h" + +namespace OHOS { +namespace AppExecFwk { +struct AsyncWorkData { + explicit AsyncWorkData(napi_env napiEnv); + virtual ~AsyncWorkData(); + napi_env env; + napi_async_work asyncWork = nullptr; + napi_deferred deferred = nullptr; + napi_ref callbackRef = nullptr; +}; + +struct ElementNameInfo : public AsyncWorkData { + explicit ElementNameInfo(napi_env env) : AsyncWorkData(env) {} + OHOS::AppExecFwk::ElementName elementName; + std::string locale; + OHOS::AppExecFwk::RemoteAbilityInfo remoteAbilityInfo; + int32_t errCode = 0; + bool result = false; + std::string errMssage; +}; + +struct ElementNameInfos: public AsyncWorkData { + explicit ElementNameInfos(napi_env env) : AsyncWorkData(env) {} + std::vector elementNames; + std::string locale; + std::vector remoteAbilityInfos; + int32_t errCode = 0; + bool result = false; + std::string errMssage; +}; + +napi_value GetRemoteAbilityInfo(napi_env env, napi_callback_info info); +napi_value GetRemoteAbilityInfos(napi_env env, napi_callback_info info); +} // namespace AppExecFwk +} // namespace OHOS +#endif /* APPEXECFWK_STANDARD_KITS_APPKIT_NAPI_DISTRIBUTEBUNDLEMGR_DISTRIBUTED_BUNDLE_MGR_H */ \ No newline at end of file diff --git a/interfaces/kits/js/distributebundlemgr/native_module.cpp b/interfaces/kits/js/distributebundlemgr/native_module.cpp new file mode 100644 index 0000000..374687a --- /dev/null +++ b/interfaces/kits/js/distributebundlemgr/native_module.cpp @@ -0,0 +1,66 @@ +/* + * 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. + */ +#include +#include +#include +#include + +#include "app_log_wrapper.h" +#include "distributed_bundle_mgr.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace AppExecFwk { +EXTERN_C_START +/* + * function for module exports + */ +static napi_value Init(napi_env env, napi_value exports) +{ + /* + * Propertise define + */ + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("getRemoteAbilityInfo", GetRemoteAbilityInfo), + DECLARE_NAPI_FUNCTION("getRemoteAbilityInfos", GetRemoteAbilityInfos) + }; + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); + APP_LOGI("distributedBundle -----Init end------"); + return exports; +} +EXTERN_C_END + +/* + * Module define + */ +static napi_module _module = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = Init, + .nm_modname = "distributedBundle", + .nm_priv = ((void *)0), + .reserved = {0} +}; +/* + * Module register function + */ +extern "C" __attribute__((constructor)) void RegisterModule(void) +{ + napi_module_register(&_module); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/js/distributedBundle/BUILD.gn b/interfaces/kits/js/distributedBundle/BUILD.gn new file mode 100644 index 0000000..4607fa5 --- /dev/null +++ b/interfaces/kits/js/distributedBundle/BUILD.gn @@ -0,0 +1,60 @@ +# Copyright (c) 2022-2023 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") +import("../../../../dbms.gni") + +ohos_shared_library("distributedbundlemanager") { + include_dirs = [ "${kits_path}/js/common" ] + defines = [ + "APP_LOG_TAG = \"DistributedBundleMgrService\"", + "LOG_DOMAIN = 0xD001120", + ] + sources = [ "native_module.cpp" ] + if (distributed_bundle_framework_enable) { + sources += [ "distributed_bundle.cpp" ] + } else { + sources += [ "distributed_bundle_unsupported.cpp" ] + } + + configs = [ "${dbms_services_path}:distributed_bms_config" ] + + deps = [ + "${common_path}:libappexecfwk_common", + "${dbms_inner_api_path}:dbms_fwk", + "${kits_path}/js/common:bundle_napi_common", + ] + + external_deps = [ + "ability_base:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "napi:ace_napi", + "samgr:samgr_proxy", + ] + + relative_install_dir = "module/bundle" + subsystem_name = "bundlemanager" + part_name = "distributed_bundle_framework" +} + +group("jsapi_target") { + deps = [] + + if (support_jsapi && distributed_bundle_framework_graphics) { + deps += [ ":distributedbundlemanager" ] + } +} diff --git a/interfaces/kits/js/distributedBundle/distributed_bundle.cpp b/interfaces/kits/js/distributedBundle/distributed_bundle.cpp new file mode 100644 index 0000000..920cb18 --- /dev/null +++ b/interfaces/kits/js/distributedBundle/distributed_bundle.cpp @@ -0,0 +1,326 @@ + /* + * 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. + */ +#include "distributed_bundle.h" + +#include "app_log_wrapper.h" +#include "appexecfwk_errors.h" +#include "bundle_constants.h" +#include "bundle_errors.h" +#include "business_error.h" +#include "common_func.h" +#include "distributed_bms_interface.h" +#include "distributed_bms_proxy.h" +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "napi_arg.h" +#include "napi_constants.h" +#include "napi/native_api.h" +#include "napi/native_common.h" +#include "napi/native_node_api.h" +#include "securec.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +constexpr int32_t GET_REMOTE_ABILITY_INFO_MAX_SIZE = 10; +const std::string RESOURCE_NAME_GET_REMOTE_ABILITY_INFO = "GetRemoteAbilityInfo"; +const std::string PARAMETER_ELEMENT_NAME = "elementName"; +const std::string PARAMETER_LOCALE = "locale"; +} + +static OHOS::sptr GetDistributedBundleMgr() +{ + APP_LOGD("GetDistributedBundleMgr start"); + auto samgr = OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgr == nullptr) { + APP_LOGE("GetDistributedBundleMgr samgr is nullptr"); + return nullptr; + } + auto remoteObject = samgr->GetSystemAbility(OHOS::DISTRIBUTED_BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (remoteObject == nullptr) { + APP_LOGE("GetDistributedBundleMgr remoteObject is nullptr"); + return nullptr; + } + auto distributeBundleMgr = OHOS::iface_cast(remoteObject); + if (distributeBundleMgr == nullptr) { + APP_LOGE("GetDistributedBundleMgr distributeBundleMgr is nullptr"); + return nullptr; + } + return distributeBundleMgr; +} + +static void ConvertElementName(napi_env env, napi_value objElementName, const ElementName &elementName) +{ + napi_value nDeviceId; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, elementName.GetDeviceID().c_str(), NAPI_AUTO_LENGTH, &nDeviceId)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objElementName, "deviceId", nDeviceId)); + + napi_value nBundleName; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, elementName.GetBundleName().c_str(), NAPI_AUTO_LENGTH, &nBundleName)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objElementName, "bundleName", nBundleName)); + + napi_value nModuleName; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, elementName.GetModuleName().c_str(), NAPI_AUTO_LENGTH, &nModuleName)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objElementName, "moduleName", nModuleName)); + + napi_value nAbilityName; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, elementName.GetAbilityName().c_str(), NAPI_AUTO_LENGTH, &nAbilityName)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objElementName, "abilityName", nAbilityName)); +} + +static void ConvertRemoteAbilityInfo( + napi_env env, const RemoteAbilityInfo &remoteAbilityInfo, napi_value objRemoteAbilityInfo) +{ + napi_value objElementName; + NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &objElementName)); + ConvertElementName(env, objElementName, remoteAbilityInfo.elementName); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objRemoteAbilityInfo, "elementName", objElementName)); + + napi_value nLabel; + NAPI_CALL_RETURN_VOID( + env, napi_create_string_utf8(env, remoteAbilityInfo.label.c_str(), NAPI_AUTO_LENGTH, &nLabel)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objRemoteAbilityInfo, "label", nLabel)); + + napi_value nIcon; + NAPI_CALL_RETURN_VOID(env, napi_create_string_utf8(env, remoteAbilityInfo.icon.c_str(), NAPI_AUTO_LENGTH, &nIcon)); + NAPI_CALL_RETURN_VOID(env, napi_set_named_property(env, objRemoteAbilityInfo, "icon", nIcon)); +} + +static void ConvertRemoteAbilityInfos( + napi_env env, const std::vector &remoteAbilityInfos, napi_value objRemoteAbilityInfos) +{ + if (remoteAbilityInfos.size() == 0) { + APP_LOGE("ConvertRemoteAbilityInfos remoteAbilityInfos is empty"); + return; + } + size_t index = 0; + for (const auto &remoteAbilityInfo : remoteAbilityInfos) { + APP_LOGD("remoteAbilityInfo bundleName:%{public}s, abilityName:%{public}s, label:%{public}s", + remoteAbilityInfo.elementName.GetBundleName().c_str(), + remoteAbilityInfo.elementName.GetAbilityName().c_str(), + remoteAbilityInfo.label.c_str()); + napi_value objRemoteAbilityInfo = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &objRemoteAbilityInfo)); + ConvertRemoteAbilityInfo(env, remoteAbilityInfo, objRemoteAbilityInfo); + NAPI_CALL_RETURN_VOID(env, napi_set_element(env, objRemoteAbilityInfos, index, objRemoteAbilityInfo)); + index++; + } +} + +static bool ParseElementName(napi_env env, napi_value args, OHOS::AppExecFwk::ElementName &elementName) +{ + APP_LOGD("begin to parse ElementName"); + napi_valuetype valueType; + napi_status status = napi_typeof(env, args, &valueType); + if ((status != napi_ok)|| (valueType != napi_object)) { + APP_LOGE("args not object type"); + return false; + } + std::string deviceId; + if (!CommonFunc::ParseStringPropertyFromObject(env, args, "deviceId", true, deviceId)) { + APP_LOGE("begin to parse ElementName deviceId failed"); + return false; + } + elementName.SetDeviceID(deviceId); + + std::string bundleName; + if (!CommonFunc::ParseStringPropertyFromObject(env, args, "bundleName", true, bundleName)) { + APP_LOGE("begin to parse ElementName bundleName failed"); + return false; + } + elementName.SetBundleName(bundleName); + + std::string abilityName; + if (!CommonFunc::ParseStringPropertyFromObject(env, args, "abilityName", true, abilityName)) { + APP_LOGE("begin to parse ElementName abilityName failed"); + return false; + } + elementName.SetAbilityName(abilityName); + + std::string moduleName; + if (!CommonFunc::ParseStringPropertyFromObject(env, args, "moduleName", false, moduleName)) { + APP_LOGE("begin to parse ElementName moduleName failed"); + return false; + } + elementName.SetModuleName(moduleName); + APP_LOGD("parse ElementName end"); + return true; +} + +static bool ParseElementNames(napi_env env, napi_value args, bool &isArray, std::vector &elementNames) +{ + APP_LOGD("begin to parse ElementNames"); + NAPI_CALL_BASE(env, napi_is_array(env, args, &isArray), false); + if (!isArray) { + APP_LOGD("parseElementNames args not array"); + ElementName elementName; + if (ParseElementName(env, args, elementName)) { + elementNames.push_back(elementName); + return true; + } + return false; + } + uint32_t arrayLength = 0; + NAPI_CALL_BASE(env, napi_get_array_length(env, args, &arrayLength), false); + APP_LOGD("arrayLength:%{public}d", arrayLength); + if (arrayLength == 0) { + APP_LOGE("error: ElementNames is empty"); + return false; + } + for (uint32_t i = 0; i < arrayLength; i++) { + napi_value value = nullptr; + NAPI_CALL_BASE(env, napi_get_element(env, args, i, &value), false); + napi_valuetype valueType = napi_undefined; + NAPI_CALL_BASE(env, napi_typeof(env, value, &valueType), false); + if (valueType != napi_object) { + APP_LOGE("array inside not object type"); + elementNames.clear(); + return false; + } + ElementName elementName; + if (!ParseElementName(env, value, elementName)) { + APP_LOGE("elementNames parse elementName failed"); + return false; + } + elementNames.push_back(elementName); + } + return true; +} + +int32_t InnerGetRemoteAbilityInfo(const std::vector &elementNames, const std::string &locale, + bool isArray, std::vector &remoteAbilityInfos) +{ + if (elementNames.size() == 0) { + APP_LOGE("InnerGetRemoteAbilityInfos elementNames is empty"); + return ERROR_BUNDLE_SERVICE_EXCEPTION; + } + auto iDistBundleMgr = GetDistributedBundleMgr(); + if (iDistBundleMgr == nullptr) { + APP_LOGE("can not get iDistBundleMgr"); + return ERROR_DISTRIBUTED_SERVICE_NOT_RUNNING; + } + int32_t result; + if (isArray) { + result = iDistBundleMgr->GetRemoteAbilityInfos(elementNames, locale, remoteAbilityInfos); + } else { + RemoteAbilityInfo remoteAbilityInfo; + result = iDistBundleMgr->GetRemoteAbilityInfo(elementNames[0], locale, remoteAbilityInfo); + remoteAbilityInfos.push_back(remoteAbilityInfo); + } + if (result != 0) { + APP_LOGE("InnerGetRemoteAbilityInfo failed"); + } + return CommonFunc::ConvertErrCode(result); +} + +void GetRemoteAbilityInfoExec(napi_env env, void *data) +{ + GetRemoteAbilityInfoCallbackInfo *asyncCallbackInfo = reinterpret_cast(data); + if (asyncCallbackInfo == nullptr) { + APP_LOGE("asyncCallbackInfo is null"); + return; + } + asyncCallbackInfo->err = InnerGetRemoteAbilityInfo(asyncCallbackInfo->elementNames, + asyncCallbackInfo->locale, asyncCallbackInfo->isArray, asyncCallbackInfo->remoteAbilityInfos); +} + +void GetRemoteAbilityInfoComplete(napi_env env, napi_status status, void *data) +{ + GetRemoteAbilityInfoCallbackInfo *asyncCallbackInfo = reinterpret_cast(data); + if (asyncCallbackInfo == nullptr) { + APP_LOGE("asyncCallbackInfo is null in %{public}s", __func__); + return; + } + std::unique_ptr callbackPtr {asyncCallbackInfo}; + napi_value result[ARGS_SIZE_TWO] = {0}; + if ((asyncCallbackInfo->err == SUCCESS) && !asyncCallbackInfo->remoteAbilityInfos.empty()) { + NAPI_CALL_RETURN_VOID(env, napi_get_null(env, &result[0])); + if (callbackPtr->isArray) { + NAPI_CALL_RETURN_VOID(env, napi_create_array(env, &result[ARGS_SIZE_ONE])); + ConvertRemoteAbilityInfos(env, asyncCallbackInfo->remoteAbilityInfos, result[ARGS_SIZE_ONE]); + } else { + NAPI_CALL_RETURN_VOID(env, napi_create_object(env, &result[ARGS_SIZE_ONE])); + ConvertRemoteAbilityInfo(env, asyncCallbackInfo->remoteAbilityInfos[0], result[ARGS_SIZE_ONE]); + } + } else { + result[0] = BusinessError::CreateCommonError(env, asyncCallbackInfo->err, + RESOURCE_NAME_GET_REMOTE_ABILITY_INFO, Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED); + } + if (asyncCallbackInfo->deferred) { + if (asyncCallbackInfo->err == SUCCESS) { + NAPI_CALL_RETURN_VOID(env, napi_resolve_deferred(env, asyncCallbackInfo->deferred, result[ARGS_SIZE_ONE])); + } else { + NAPI_CALL_RETURN_VOID(env, napi_reject_deferred(env, asyncCallbackInfo->deferred, result[0])); + } + } else { + napi_value callback = nullptr; + napi_value placeHolder = nullptr; + NAPI_CALL_RETURN_VOID(env, napi_get_reference_value(env, asyncCallbackInfo->callback, &callback)); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, nullptr, callback, + sizeof(result) / sizeof(result[0]), result, &placeHolder)); + } +} + +napi_value GetRemoteAbilityInfo(napi_env env, napi_callback_info info) +{ + APP_LOGD("begin to GetRemoteAbilityInfo"); + NapiArg args(env, info); + GetRemoteAbilityInfoCallbackInfo *asyncCallbackInfo = + new (std::nothrow) GetRemoteAbilityInfoCallbackInfo(env); + if (asyncCallbackInfo == nullptr) { + return nullptr; + } + std::unique_ptr callbackPtr {asyncCallbackInfo}; + if (!args.Init(ARGS_SIZE_ONE, ARGS_SIZE_THREE)) { + APP_LOGE("param count invalid."); + BusinessError::ThrowTooFewParametersError(env, ERROR_PARAM_CHECK_ERROR); + return nullptr; + } + for (size_t i = 0; i < args.GetMaxArgc(); ++i) { + napi_valuetype valueType = napi_undefined; + napi_typeof(env, args[i], &valueType); + if ((i == ARGS_POS_ZERO) && (!ParseElementNames(env, args[i], asyncCallbackInfo->isArray, + asyncCallbackInfo->elementNames))) { + BusinessError::ThrowParameterTypeError(env, ERROR_PARAM_CHECK_ERROR, + PARAMETER_ELEMENT_NAME, TYPE_OBJECT); + return nullptr; + } else if (((i == ARGS_POS_ONE) && (valueType == napi_function)) || + ((i == ARGS_POS_TWO) && (valueType == napi_function))) { + NAPI_CALL(env, napi_create_reference(env, args[i], NAPI_RETURN_ONE, &asyncCallbackInfo->callback)); + break; + } else if ((i == ARGS_POS_ONE) && !CommonFunc::ParseString(env, args[i], asyncCallbackInfo->locale)) { + BusinessError::ThrowParameterTypeError(env, ERROR_PARAM_CHECK_ERROR, PARAMETER_LOCALE, TYPE_STRING); + return nullptr; + } + } + if (asyncCallbackInfo->elementNames.size() > GET_REMOTE_ABILITY_INFO_MAX_SIZE) { + BusinessError::ThrowError(env, ERROR_PARAM_CHECK_ERROR, + "BusinessError 401: The number of ElementNames is greater than 10"); + return nullptr; + } + auto promise = CommonFunc::AsyncCallNativeMethod(env, asyncCallbackInfo, + RESOURCE_NAME_GET_REMOTE_ABILITY_INFO, GetRemoteAbilityInfoExec, GetRemoteAbilityInfoComplete); + callbackPtr.release(); + APP_LOGD("GetRemoteAbilityInfo end"); + return promise; +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/interfaces/kits/js/distributedBundle/distributed_bundle.h b/interfaces/kits/js/distributedBundle/distributed_bundle.h new file mode 100644 index 0000000..82929c1 --- /dev/null +++ b/interfaces/kits/js/distributedBundle/distributed_bundle.h @@ -0,0 +1,39 @@ + /* + * 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. + */ + +#ifndef BUNDLE_MANAGER_FRAMEWORK_DISTRIBUTEBUNDLEMGR_INTERFACES_KITS_JS_DISTRIBUTE_BUNDLE_H +#define BUNDLE_MANAGER_FRAMEWORK_DISTRIBUTEBUNDLEMGR_INTERFACES_KITS_JS_DISTRIBUTE_BUNDLE_H + +#include +#include + +#include "base_cb_info.h" +#include "element_name.h" +#include "remote_ability_info.h" + +namespace OHOS { +namespace AppExecFwk { +struct GetRemoteAbilityInfoCallbackInfo : public BaseCallbackInfo { + explicit GetRemoteAbilityInfoCallbackInfo(napi_env napiEnv) : BaseCallbackInfo(napiEnv) {} + std::vector elementNames; + std::vector remoteAbilityInfos; + std::string locale = ""; + bool isArray = false; +}; + +napi_value GetRemoteAbilityInfo(napi_env env, napi_callback_info info); +} // namespace AppExecFwk +} // namespace OHOS +#endif // BUNDLE_MANAGER_FRAMEWORK_DISTRIBUTEBUNDLEMGR_INTERFACES_KITS_JS_DISTRIBUTE_BUNDLE_H \ No newline at end of file diff --git a/interfaces/kits/js/distributedBundle/distributed_bundle_unsupported.cpp b/interfaces/kits/js/distributedBundle/distributed_bundle_unsupported.cpp new file mode 100644 index 0000000..997234e --- /dev/null +++ b/interfaces/kits/js/distributedBundle/distributed_bundle_unsupported.cpp @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2021-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. + */ + +#include "distributed_bundle.h" + +#include + +#include "app_log_wrapper.h" +#include "bundle_errors.h" +#include "business_error.h" +#include "common_func.h" + +namespace OHOS { +namespace AppExecFwk { +napi_value GetRemoteAbilityInfo(napi_env env, napi_callback_info info) +{ + APP_LOGE("SystemCapability.BundleManager.DistributedBundleFramework not supported."); + napi_value error = BusinessError::CreateCommonError(env, ERROR_SYSTEM_ABILITY_NOT_FOUND, + "getRemoteAbilityInfo"); + napi_throw(env, error); + return nullptr; +} +} // AppExecFwk +} // OHOS diff --git a/interfaces/kits/js/distributedBundle/native_module.cpp b/interfaces/kits/js/distributedBundle/native_module.cpp new file mode 100644 index 0000000..bb367c8 --- /dev/null +++ b/interfaces/kits/js/distributedBundle/native_module.cpp @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2022-2023 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 "app_log_wrapper.h" +#include "distributed_bundle.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace AppExecFwk { +EXTERN_C_START +/* + * function for module exports + */ +static napi_value Init(napi_env env, napi_value exports) +{ + /* + * Propertise define + */ + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("getRemoteAbilityInfo", GetRemoteAbilityInfo), + }; + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); + APP_LOGI("distributedBundle -----Init end------"); + return exports; +} +EXTERN_C_END + +/* + * Module define + */ +static napi_module _module = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = Init, + .nm_modname = "bundle.distributedBundleManager", + .nm_priv = ((void *)0), + .reserved = {0} +}; +/* + * Module register function + */ +extern "C" __attribute__((constructor)) void RegisterDistributedBundleModule(void) +{ + napi_module_register(&_module); +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/dbms/BUILD.gn b/services/dbms/BUILD.gn new file mode 100644 index 0000000..784f32c --- /dev/null +++ b/services/dbms/BUILD.gn @@ -0,0 +1,82 @@ +# 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("//build/ohos.gni") +import("../../dbms.gni") + +group("dbms_target") { + if (distributed_bundle_framework_graphics) { + deps = [ ":libdbms" ] + } +} + +config("distributed_bms_config") { + include_dirs = [ "include" ] +} + +ohos_shared_library("libdbms") { + sources = [ + "src/account_manager_helper.cpp", + "src/distributed_bms.cpp", + "src/distributed_bms_host.cpp", + "src/distributed_data_storage.cpp", + "src/image_compress.cpp", + ] + + defines = [ + "APP_LOG_TAG = \"DistributedBundleMgrService\"", + "LOG_DOMAIN = 0xD001120", + ] + + configs = [ ":distributed_bms_config" ] + + deps = [ + "${common_path}:libappexecfwk_common", + "${dbms_inner_api_path}:dbms_fwk", + ] + + external_deps = [ + "ability_base:want", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "hicollie_native:libhicollie", + "hiviewdfx_hilog_native:libhilog", + "i18n:intl_util", + "init:libbegetutil", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "multimedia_image_framework:image_native", + "resource_management:global_resmgr", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (hisysevent_enable_dbms) { + sources += [ "src/event_report.cpp" ] + external_deps += [ "hisysevent_native:libhisysevent" ] + defines += [ "HISYSEVENT_ENABLE" ] + } + + if (account_enable_dbms) { + external_deps += [ "os_account:os_account_innerkits" ] + defines += [ "ACCOUNT_ENABLE" ] + } + + shlib_type = "sa" + part_name = "distributed_bundle_framework" + subsystem_name = "bundlemanager" +} diff --git a/services/dbms/include/account_manager_helper.h b/services/dbms/include/account_manager_helper.h new file mode 100644 index 0000000..0669560 --- /dev/null +++ b/services/dbms/include/account_manager_helper.h @@ -0,0 +1,29 @@ +/* + * 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. + */ + +#ifndef FOUNDATION_APPEXECFWK_SERVICES_DBMS_INCLUDE_ACCOUNT_MANAGER_HELPER_H +#define FOUNDATION_APPEXECFWK_SERVICES_DBMS_INCLUDE_ACCOUNT_MANAGER_HELPER_H + +#include + +namespace OHOS { +namespace AppExecFwk { +class AccountManagerHelper { +public: + static int32_t GetCurrentActiveUserId(); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_DBMS_INCLUDE_ACCOUNT_MANAGER_HELPER_H diff --git a/services/dbms/include/distributed_bms.h b/services/dbms/include/distributed_bms.h new file mode 100644 index 0000000..b7d2159 --- /dev/null +++ b/services/dbms/include/distributed_bms.h @@ -0,0 +1,153 @@ +/* + * 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. + */ + +#ifndef FOUNDATION_APPEXECFWK_SERVICES_D_BUNDLEMGR_INCLUDE_DISTRIBUTED_BMS_H +#define FOUNDATION_APPEXECFWK_SERVICES_D_BUNDLEMGR_INCLUDE_DISTRIBUTED_BMS_H + +#include + +#include "bundle_info.h" +#include "bundle_mgr_interface.h" +#include "distributed_bms_host.h" +#include "distributed_monitor.h" +#include "if_system_ability_manager.h" +#include "iremote_object.h" +#include "resource_manager.h" +#include "singleton.h" +#include "system_ability.h" +namespace OHOS { +namespace AppExecFwk { +class DistributedBms : public SystemAbility, public DistributedBmsHost { + DECLARE_DELAYED_SINGLETON(DistributedBms); + DECLARE_SYSTEM_ABILITY(DistributedBms); + +public: + OHOS::sptr GetBundleMgr(); + + /** + * @brief get remote ability info + * @param elementName Indicates the elementName. + * @param remoteAbilityInfo Indicates the remote ability info. + * @return Returns true when get remote ability info success; returns false otherwise. + */ + int32_t GetRemoteAbilityInfo( + const OHOS::AppExecFwk::ElementName &elementName, RemoteAbilityInfo &remoteAbilityInfo) override; + + /** + * @brief get remote ability info + * @param elementName Indicates the elementName. + * @param localeInfo Indicates the localeInfo. + * @param remoteAbilityInfo Indicates the remote ability info. + * @return Returns true when get remote ability info success; returns false otherwise. + */ + int32_t GetRemoteAbilityInfo(const OHOS::AppExecFwk::ElementName &elementName, const std::string &localeInfo, + RemoteAbilityInfo &remoteAbilityInfo) override; + /** + * @brief get remote ability infos + * @param elementNames Indicates the elementNames. + * @param remoteAbilityInfos Indicates the remote ability infos. + * @return Returns true when get remote ability info success; returns false otherwise. + */ + int32_t GetRemoteAbilityInfos( + const std::vector &elementNames, std::vector &remoteAbilityInfos) override; + + /** + * @brief get remote ability infos + * @param elementNames Indicates the elementNames. + * @param localeInfo Indicates the localeInfo. + * @param remoteAbilityInfos Indicates the remote ability infos. + * @return Returns true when get remote ability info success; returns false otherwise. + */ + int32_t GetRemoteAbilityInfos(const std::vector &elementNames, const std::string &localeInfo, + std::vector &remoteAbilityInfos) override; + + /** + * @brief get ability info + * @param elementName Indicates the elementName. + * @param remoteAbilityInfo Indicates the remote ability info. + * @return Returns true when get remote ability info success; returns false otherwise. + */ + int32_t GetAbilityInfo( + const OHOS::AppExecFwk::ElementName &elementName, RemoteAbilityInfo &remoteAbilityInfo) override; + + /** + * @brief get ability info + * @param elementName Indicates the elementName. + * @param localeInfo Indicates the localeInfo. + * @param remoteAbilityInfo Indicates the remote ability info. + * @return Returns true when get remote ability info success; returns false otherwise. + */ + int32_t GetAbilityInfo(const OHOS::AppExecFwk::ElementName &elementName, const std::string &localeInfo, + RemoteAbilityInfo &remoteAbilityInfo) override; + /** + * @brief get ability infos + * @param elementNames Indicates the elementNames. + * @param remoteAbilityInfos Indicates the remote ability infos. + * @return Returns true when get remote ability info success; returns false otherwise. + */ + int32_t GetAbilityInfos( + const std::vector &elementNames, std::vector &remoteAbilityInfos) override; + + /** + * @brief get ability infos + * @param elementNames Indicates the elementNames. + * @param localeInfo Indicates the localeInfo. + * @param remoteAbilityInfos Indicates the remote ability infos. + * @return Returns true when get remote ability info success; returns false otherwise. + */ + int32_t GetAbilityInfos(const std::vector &elementNames, const std::string &localeInfo, + std::vector &remoteAbilityInfos) override; + + bool GetDistributedBundleInfo(const std::string &networkId, const std::string &bundleName, + DistributedBundleInfo &distributedBundleInfo) override; + + /** + * @brief get distributedBundleName based on a given accessTokenId and networkId. + * @param networkId Indicates the networkId of remote device. + * @param accessTokenId AccessTokenId of the application + * @param bundleNames distributed bundle name. + * @return Returns ERR_OK on success, others on failure when get distributed bundle name. + */ + int32_t GetDistributedBundleName(const std::string &networkId, uint32_t accessTokenId, + std::string &bundleName) override; + + /** + * @brief Start the bundle manager service. + * @return + */ + virtual void OnStart() override; + /** + * @brief Stop the bundle manager service. + * @return + */ + virtual void OnStop() override; +private: + OHOS::sptr bundleMgr_; + std::shared_ptr distributedSub_; + std::mutex bundleMgrMutex_; + + void Init(); + bool GetMediaBase64(std::unique_ptr &data, int64_t fileLength, + std::string &imageType, std::string &value); + std::unique_ptr LoadResourceFile(std::string &path, int &len); + std::unique_ptr EncodeBase64(std::unique_ptr &data, int srcLen); + int32_t GetAbilityIconByContent( + const AbilityInfo &abilityInfo, int32_t userId, RemoteAbilityInfo &remoteAbilityInfo); + int32_t Base64WithoutCompress(std::unique_ptr &imageContent, size_t imageContentSize, + RemoteAbilityInfo &remoteAbilityInfo); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_D_BUNDLEMGR_INCLUDE_DISTRIBUTED_BMS_H \ No newline at end of file diff --git a/services/dbms/include/distributed_bms_host.h b/services/dbms/include/distributed_bms_host.h new file mode 100644 index 0000000..b729273 --- /dev/null +++ b/services/dbms/include/distributed_bms_host.h @@ -0,0 +1,51 @@ +/* + * 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. + */ + +#ifndef FOUNDATION_APPEXECFWK_SERVICES_DBMS_INCLUDE_DISTRIBUTED_BMS_HOST_H +#define FOUNDATION_APPEXECFWK_SERVICES_DBMS_INCLUDE_DISTRIBUTED_BMS_HOST_H + +#include "distributed_bms_interface.h" +#include "iremote_stub.h" +#include "parcel_macro.h" +#include "accesstoken_kit.h" + +namespace OHOS { +namespace AppExecFwk { +class DistributedBmsHost : public IRemoteStub { +public: + DistributedBmsHost(); + virtual ~DistributedBmsHost() override; + + virtual int OnRemoteRequest( + uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; +private: + int HandleGetRemoteAbilityInfo(Parcel &data, Parcel &reply); + int HandleGetRemoteAbilityInfos(Parcel &data, Parcel &reply); + int HandleGetAbilityInfo(Parcel &data, Parcel &reply); + int HandleGetAbilityInfos(Parcel &data, Parcel &reply); + int HandleGetDistributedBundleInfo(Parcel &data, Parcel &reply); + int HandleGetDistributedBundleName(Parcel &data, Parcel &reply); + bool VerifyCallingPermission(const std::string &permissionName); + template + bool GetParcelableInfos(Parcel &data, std::vector &parcelableInfos); + template + bool WriteParcelableVector(std::vector &parcelableVector, Parcel &data); + bool VerifySystemApp(); + bool VerifySystemAppForTokenNative(Security::AccessToken::AccessTokenID callerToken); + bool VerifySystemAppForTokenShell(Security::AccessToken::AccessTokenID callerToken); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_DBMS_INCLUDE_DISTRIBUTED_BMS_HOST_H \ No newline at end of file diff --git a/services/dbms/include/distributed_data_storage.h b/services/dbms/include/distributed_data_storage.h new file mode 100644 index 0000000..0f7596a --- /dev/null +++ b/services/dbms/include/distributed_data_storage.h @@ -0,0 +1,63 @@ +/* + * 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. + */ + +#ifndef FOUNDATION_APPEXECFWK_SERVICES_DBMS_INCLUDE_DISTRIBUTED_DATA_STORAGE_H +#define FOUNDATION_APPEXECFWK_SERVICES_DBMS_INCLUDE_DISTRIBUTED_DATA_STORAGE_H + +#include + +#include "distributed_bundle_info.h" +#include "bundle_constants.h" +#include "bundle_info.h" +#include "distributed_kv_data_manager.h" + +namespace OHOS { +namespace AppExecFwk { +class DistributedDataStorage { +public: + DistributedDataStorage(); + ~DistributedDataStorage(); + static std::shared_ptr GetInstance(); + + void SaveStorageDistributeInfo(const std::string &bundleName, int32_t userId); + void DeleteStorageDistributeInfo(const std::string &bundleName, int32_t userId); + bool GetStorageDistributeInfo(const std::string &networkId, const std::string &bundleName, + DistributedBundleInfo &info); + int32_t GetDistributedBundleName(const std::string &networkId, uint32_t accessTokenId, + std::string &bundleName); + void UpdateDistributedData(int32_t userId); + +private: + std::string DeviceAndNameToKey(const std::string &udid, const std::string &bundleName) const; + void TryTwice(const std::function &func) const; + bool CheckKvStore(); + DistributedKv::Status GetKvStore(); + bool GetLocalUdid(std::string &udid); + DistributedBundleInfo ConvertToDistributedBundleInfo(const BundleInfo &bundleInfo); + int32_t GetUdidByNetworkId(const std::string &networkId, std::string &udid); + bool InnerSaveStorageDistributeInfo(const DistributedBundleInfo &distributedBundleInfo); +private: + static std::recursive_mutex mutex_; + static std::shared_ptr instance_; + + const DistributedKv::AppId appId_ {Constants::APP_ID}; + const DistributedKv::StoreId storeId_ {Constants::DISTRIBUTE_DATA_STORE_ID}; + DistributedKv::DistributedKvDataManager dataManager_; + std::shared_ptr kvStorePtr_; + mutable std::mutex kvStorePtrMutex_; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_DBMS_INCLUDE_DISTRIBUTED_DATA_STORAGE_H diff --git a/services/dbms/include/distributed_monitor.h b/services/dbms/include/distributed_monitor.h new file mode 100644 index 0000000..406f6ca --- /dev/null +++ b/services/dbms/include/distributed_monitor.h @@ -0,0 +1,57 @@ +/* + * 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. + */ + +#ifndef FOUNDATION_APPEXECFWK_SERVICES_DBMS_INCLUDE_DISTRIBUTED_MONITOR_H +#define FOUNDATION_APPEXECFWK_SERVICES_DBMS_INCLUDE_DISTRIBUTED_MONITOR_H + +#include "common_event_manager.h" +#include "common_event_support.h" +#include "common_event_subscriber.h" +#include "common_event_subscribe_info.h" +#include "distributed_data_storage.h" + +namespace OHOS { +namespace AppExecFwk { +class DistributedMonitor : public EventFwk::CommonEventSubscriber { +public: + DistributedMonitor(const EventFwk::CommonEventSubscribeInfo& sp):CommonEventSubscriber(sp) {} + ~DistributedMonitor() {} + + void OnReceiveEvent(const EventFwk::CommonEventData &eventData) + { + auto want = eventData.GetWant(); + std::string action = want.GetAction(); + APP_LOGI("OnReceiveEvent action:%{public}s", action.c_str()); + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { + int32_t userId = eventData.GetCode(); + APP_LOGI("OnReceiveEvent switched userId:%{public}d", userId); + DistributedDataStorage::GetInstance()->UpdateDistributedData(userId); + return; + } + int32_t userId = want.GetIntParam(Constants::USER_ID, Constants::INVALID_USERID); + std::string bundleName = want.GetElement().GetBundleName(); + if (action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_ADDED || + action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_CHANGED) { + DistributedDataStorage::GetInstance()->SaveStorageDistributeInfo(bundleName, userId); + } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED) { + DistributedDataStorage::GetInstance()->DeleteStorageDistributeInfo(bundleName, userId); + } else { + APP_LOGW("OnReceiveEvent undefined action"); + } + } +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_DBMS_INCLUDE_DISTRIBUTED_MONITOR_H \ No newline at end of file diff --git a/services/dbms/include/event_report.h b/services/dbms/include/event_report.h new file mode 100644 index 0000000..318b3f9 --- /dev/null +++ b/services/dbms/include/event_report.h @@ -0,0 +1,51 @@ +/* + * 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. + */ + +#ifndef FOUNDATION_APPEXECFWK_SERVICES_DBMS_INCLUDE_EVENT_REPORT_H +#define FOUNDATION_APPEXECFWK_SERVICES_DBMS_INCLUDE_EVENT_REPORT_H + +#include + +#include "appexecfwk_errors.h" +#include "bundle_constants.h" + +namespace OHOS { +namespace AppExecFwk { +enum class DBMSEventType { + UNKNOW = 0, + GET_REMOTE_ABILITY_INFO, + GET_REMOTE_ABILITY_INFOS +}; + +struct DBMSEventInfo { + std::string deviceID; + std::string bundleName; + std::string localeInfo; + std::string abilityName; + int32_t resultCode = 0; +}; + +class EventReport { +public: + /** + * @brief Send dbms system events. + * @param dbmsEventType Indicates the dbms eventType. + * @param eventInfo Indicates the eventInfo. + */ + static void SendSystemEvent(DBMSEventType dbmsEventType, const DBMSEventInfo& eventInfo); +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_SERVICES_DBMS_INCLUDE_EVENT_REPORT_H diff --git a/services/dbms/include/image_compress.h b/services/dbms/include/image_compress.h new file mode 100644 index 0000000..4f91aa1 --- /dev/null +++ b/services/dbms/include/image_compress.h @@ -0,0 +1,46 @@ +/* + * 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. + */ + +#ifndef FOUNDATION_APPEXECFWK_SERVICES_DBMS_INCLUDE_IMAGE_COMPRESS_H +#define FOUNDATION_APPEXECFWK_SERVICES_DBMS_INCLUDE_IMAGE_COMPRESS_H + +#include +#include +#include +#include + +namespace OHOS { +namespace AppExecFwk { + enum class ImageType { + JPEG = 1, + PNG = 2, + WORNG_TYPE = 3, + }; +class ImageCompress { +public: + ImageCompress() = default; + bool IsPathValid(const std::string &srcPath); + bool IsImageNeedCompressBySize(size_t fileSize); + double CalculateRatio(size_t fileSize, const std::string &imageType); + ImageType GetImageType(const std::unique_ptr &fileData, size_t fileLength); + bool GetImageTypeString(const std::unique_ptr &fileData, size_t fileLength, std::string &imageType); + bool GetImageFileInfo(const std::string &srcFile, std::unique_ptr &fileContent, int64_t &fileLength); + bool CompressImageByContent(const std::unique_ptr &fileData, size_t fileSize, + std::unique_ptr &compressedData, int64_t &compressedSize, std::string &imageType); +}; +} +} + +#endif // FOUNDATION_APPEXECFWK_SERVICES_DBMS_INCLUDE_IMAGE_COMPRESS_H \ No newline at end of file diff --git a/services/dbms/sa_profile/402.json b/services/dbms/sa_profile/402.json new file mode 100644 index 0000000..08d765d --- /dev/null +++ b/services/dbms/sa_profile/402.json @@ -0,0 +1,28 @@ +{ + "process": "d-bms", + "systemability": [ + { + "name": 402, + "libpath": "libdbms.z.so", + "run-on-create": false, + "distributed": true, + "dump_level": 1, + "start-on-demand": { + "deviceonline": [ + { + "name": "deviceonline", + "value": "on" + } + ] + }, + "stop-on-demand": { + "deviceonline": [ + { + "name": "deviceonline", + "value": "off" + } + ] + } + } + ] +} \ No newline at end of file diff --git a/services/dbms/sa_profile/BUILD.gn b/services/dbms/sa_profile/BUILD.gn new file mode 100644 index 0000000..f3b234c --- /dev/null +++ b/services/dbms/sa_profile/BUILD.gn @@ -0,0 +1,35 @@ +# Copyright (c) 2022-2023 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") +import("//build/ohos/sa_profile/sa_profile.gni") + +group("distributedbms") { + deps = [ + ":distributedbms.cfg", + ":distributedbms_sa_profile", + ] +} + +ohos_sa_profile("distributedbms_sa_profile") { + sources = [ "402.json" ] + + part_name = "distributed_bundle_framework" +} + +ohos_prebuilt_etc("distributedbms.cfg") { + source = "distributedbms.cfg" + relative_install_dir = "init" + subsystem_name = "bundlemanager" + part_name = "distributed_bundle_framework" +} diff --git a/services/dbms/sa_profile/distributedbms.cfg b/services/dbms/sa_profile/distributedbms.cfg new file mode 100644 index 0000000..d63e2cd --- /dev/null +++ b/services/dbms/sa_profile/distributedbms.cfg @@ -0,0 +1,27 @@ +{ + "jobs" : [{ + "name" : "services:d-bms", + "cmds" : [ + "mkdir /data/service/el1/public/database 0711 ddms ddms", + "mkdir /data/service/el1/public/database/bundle_manager_service 02770 dbms ddms" + ] + } + ], + "services" : [{ + "name" : "d-bms", + "path" : ["/system/bin/sa_main", "/system/profile/d-bms.json"], + "ondemand": true, + "uid" : "dbms", + "gid" : ["dbms", "shell"], + "permission": [ + "ohos.permission.DISTRIBUTED_DATASYNC", + "ohos.permission.GET_BUNDLE_INFO_PRIVILEGED" + ], + "start-mode": "condition", + "jobs" : { + "on-start" : "services:d-bms" + }, + "secon" : "u:r:d-bms:s0" + } + ] +} diff --git a/services/dbms/src/account_manager_helper.cpp b/services/dbms/src/account_manager_helper.cpp new file mode 100644 index 0000000..6f3ddc1 --- /dev/null +++ b/services/dbms/src/account_manager_helper.cpp @@ -0,0 +1,49 @@ +/* + * 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. + */ + +#include "account_manager_helper.h" + +#include + +#include "app_log_wrapper.h" +#include "bundle_constants.h" + +#ifdef ACCOUNT_ENABLE +#include "os_account_manager.h" +#endif + +namespace OHOS { +namespace AppExecFwk { +int32_t AccountManagerHelper::GetCurrentActiveUserId() +{ +#ifdef ACCOUNT_ENABLE + std::vector activeIds; + int ret = AccountSA::OsAccountManager::QueryActiveOsAccountIds(activeIds); + if (ret != 0) { + APP_LOGE("QueryActiveOsAccountIds failed ret:%{public}d", ret); + return Constants::INVALID_USERID; + } + if (activeIds.empty()) { + APP_LOGE("QueryActiveOsAccountIds activeIds empty"); + return Constants::INVALID_USERID; + } + return activeIds[0]; +#else + APP_LOGI("ACCOUNT_ENABLE is false"); + return Constants::INVALID_USERID; +#endif +} +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/dbms/src/distributed_bms.cpp b/services/dbms/src/distributed_bms.cpp new file mode 100644 index 0000000..8ea53a2 --- /dev/null +++ b/services/dbms/src/distributed_bms.cpp @@ -0,0 +1,463 @@ +/* + * Copyright (c) 2022-2023 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 "distributed_bms.h" + +#include +#include + +#include "account_manager_helper.h" +#include "app_log_wrapper.h" +#include "appexecfwk_errors.h" +#include "bundle_mgr_interface.h" +#include "bundle_mgr_proxy.h" +#include "distributed_bms_proxy.h" +#include "distributed_data_storage.h" +#include "event_report.h" +#include "iservice_registry.h" +#include "if_system_ability_manager.h" +#include "locale_config.h" +#include "locale_info.h" +#include "image_compress.h" +#include "image_packer.h" +#include "image_source.h" +#include "system_ability_definition.h" +#ifdef HICOLLIE_ENABLE +#include "xcollie/xcollie.h" +#include "xcollie/xcollie_define.h" +#endif + +namespace OHOS { +namespace AppExecFwk { +namespace { +#ifdef HICOLLIE_ENABLE + const unsigned int LOCAL_TIME_OUT_SECONDS = 5; + const unsigned int REMOTE_TIME_OUT_SECONDS = 10; +#endif + const uint8_t DECODE_VALUE_ONE = 1; + const uint8_t DECODE_VALUE_TWO = 2; + const uint8_t DECODE_VALUE_THREE = 3; + const unsigned char DECODE_VALUE_CHAR_THREE = 3; + const uint8_t DECODE_VALUE_FOUR = 4; + const uint8_t DECODE_VALUE_SIX = 6; + const unsigned char DECODE_VALUE_CHAR_FIFTEEN = 15; + const unsigned char DECODE_VALUE_CHAR_SIXTY_THREE = 63; + const std::vector DECODE_TABLE = { + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', + 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', + 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', + 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' + }; + const std::string POSTFIX = "_Compress."; +#ifdef HISYSEVENT_ENABLE + DBMSEventInfo GetEventInfo( + const std::vector &elements, const std::string &localeInfo, int32_t resultCode) + { + DBMSEventInfo eventInfo; + if (elements.empty()) { + return eventInfo; + } + + eventInfo.deviceID = elements[0].GetDeviceID(); + eventInfo.localeInfo = localeInfo; + for (auto element : elements) { + if (eventInfo.bundleName.empty()) { + eventInfo.bundleName.append(element.GetBundleName()); + } else { + eventInfo.bundleName.append(";").append(element.GetBundleName()); + } + + if (eventInfo.abilityName.empty()) { + eventInfo.abilityName.append(element.GetAbilityName()); + } else { + eventInfo.abilityName.append(";").append(element.GetAbilityName()); + } + } + + eventInfo.resultCode = resultCode; + return eventInfo; + } + + DBMSEventInfo GetEventInfo( + const ElementName &element, const std::string &localeInfo, int32_t resultCode) + { + DBMSEventInfo eventInfo; + eventInfo.bundleName = element.GetBundleName(); + eventInfo.abilityName = element.GetAbilityName(); + eventInfo.deviceID = element.GetDeviceID(); + eventInfo.localeInfo = localeInfo; + eventInfo.resultCode = resultCode; + return eventInfo; + } +#endif +} +const bool REGISTER_RESULT = + SystemAbility::MakeAndRegisterAbility(DelayedSingleton::GetInstance().get()); + +DistributedBms::DistributedBms() : SystemAbility(DISTRIBUTED_BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, true) +{ + APP_LOGI("DistributedBms :%{public}s call", __func__); +} + +DistributedBms::~DistributedBms() +{ + APP_LOGI("DistributedBms: DBundleMgrService"); +} + +void DistributedBms::OnStart() +{ + APP_LOGI("DistributedBms: OnStart"); + Init(); + bool res = Publish(this); + if (!res) { + APP_LOGE("DistributedBms: OnStart failed"); + } + APP_LOGI("DistributedBms: OnStart end"); +} + +void DistributedBms::OnStop() +{ + APP_LOGI("DistributedBms: OnStop"); + if (distributedSub_ != nullptr) { + EventFwk::CommonEventManager::UnSubscribeCommonEvent(distributedSub_); + } +} + +void DistributedBms::Init() +{ + APP_LOGI("DistributedBms: Init"); + DistributedDataStorage::GetInstance(); + if (distributedSub_ == nullptr) { + EventFwk::MatchingSkills matchingSkills; + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_ADDED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_CHANGED); + EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills); + distributedSub_ = std::make_shared(subscribeInfo); + EventFwk::CommonEventManager::SubscribeCommonEvent(distributedSub_); + } + int32_t userId = AccountManagerHelper::GetCurrentActiveUserId(); + if (userId == Constants::INVALID_USERID) { + APP_LOGW("get user id failed"); + return; + } + DistributedDataStorage::GetInstance()->UpdateDistributedData(userId); +} + +OHOS::sptr DistributedBms::GetBundleMgr() +{ + if (bundleMgr_ == nullptr) { + std::lock_guard lock(bundleMgrMutex_); + if (bundleMgr_ == nullptr) { + auto systemAbilityManager = OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemAbilityManager == nullptr) { + APP_LOGE("GetBundleMgr GetSystemAbilityManager is null"); + return nullptr; + } + auto bundleMgrSa = systemAbilityManager->GetSystemAbility(OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (bundleMgrSa == nullptr) { + APP_LOGE("GetBundleMgr GetSystemAbility is null"); + return nullptr; + } + bundleMgr_ = OHOS::iface_cast(bundleMgrSa); + } + } + return bundleMgr_; +} + +static OHOS::sptr GetDistributedBundleMgr(const std::string &deviceId) +{ + auto samgr = OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + OHOS::sptr remoteObject; + if (deviceId.empty()) { + APP_LOGW("GetDistributedBundleMgr deviceId is empty"); + return nullptr; + } else { + APP_LOGI("GetDistributedBundleMgr get remote d-bms"); + remoteObject = samgr->CheckSystemAbility(OHOS::DISTRIBUTED_BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, deviceId); + } + return OHOS::iface_cast(remoteObject); +} + +int32_t DistributedBms::GetRemoteAbilityInfo( + const OHOS::AppExecFwk::ElementName &elementName, RemoteAbilityInfo &remoteAbilityInfo) +{ + return GetRemoteAbilityInfo(elementName, "", remoteAbilityInfo); +} + +int32_t DistributedBms::GetRemoteAbilityInfo(const OHOS::AppExecFwk::ElementName &elementName, + const std::string &localeInfo, RemoteAbilityInfo &remoteAbilityInfo) +{ + auto iDistBundleMgr = GetDistributedBundleMgr(elementName.GetDeviceID()); + int32_t resultCode = 0; + if (!iDistBundleMgr) { + APP_LOGE("GetDistributedBundle object failed"); + resultCode = ERR_BUNDLE_MANAGER_DEVICE_ID_NOT_EXIST; + } else { +#ifdef HICOLLIE_ENABLE + int timerId = HiviewDFX::XCollie::GetInstance().SetTimer("GetRemoteAbilityInfo", REMOTE_TIME_OUT_SECONDS, + nullptr, nullptr, HiviewDFX::XCOLLIE_FLAG_RECOVERY); + HiviewDFX::XCollie::GetInstance().CancelTimer(timerId); +#endif + APP_LOGD("GetDistributedBundleMgr get remote d-bms"); + resultCode = iDistBundleMgr->GetAbilityInfo(elementName, localeInfo, remoteAbilityInfo); + } + +#ifdef HISYSEVENT_ENABLE + EventReport::SendSystemEvent( + DBMSEventType::GET_REMOTE_ABILITY_INFO, GetEventInfo(elementName, localeInfo, resultCode)); +#endif + return resultCode; +} + +int32_t DistributedBms::GetRemoteAbilityInfos( + const std::vector &elementNames, std::vector &remoteAbilityInfos) +{ + return GetRemoteAbilityInfos(elementNames, "", remoteAbilityInfos); +} + +int32_t DistributedBms::GetRemoteAbilityInfos(const std::vector &elementNames, + const std::string &localeInfo, std::vector &remoteAbilityInfos) +{ + if (elementNames.empty()) { + APP_LOGE("GetDistributedBundle failed due to elementNames empty"); + return ERR_BUNDLE_MANAGER_PARAM_ERROR; + } + auto iDistBundleMgr = GetDistributedBundleMgr(elementNames[0].GetDeviceID()); + int32_t resultCode = 0; + if (!iDistBundleMgr) { + APP_LOGE("GetDistributedBundle object failed"); + resultCode = ERR_BUNDLE_MANAGER_DEVICE_ID_NOT_EXIST; + } else { +#ifdef HICOLLIE_ENABLE + int timerId = HiviewDFX::XCollie::GetInstance().SetTimer("GetRemoteAbilityInfos", REMOTE_TIME_OUT_SECONDS, + nullptr, nullptr, HiviewDFX::XCOLLIE_FLAG_RECOVERY); + HiviewDFX::XCollie::GetInstance().CancelTimer(timerId); +#endif + APP_LOGD("GetDistributedBundleMgr get remote d-bms"); + resultCode = iDistBundleMgr->GetAbilityInfos(elementNames, localeInfo, remoteAbilityInfos); + } +#ifdef HISYSEVENT_ENABLE + EventReport::SendSystemEvent( + DBMSEventType::GET_REMOTE_ABILITY_INFOS, GetEventInfo(elementNames, localeInfo, resultCode)); +#endif + return resultCode; +} + +int32_t DistributedBms::GetAbilityInfo( + const OHOS::AppExecFwk::ElementName &elementName, RemoteAbilityInfo &remoteAbilityInfo) +{ + return GetAbilityInfo(elementName, "", remoteAbilityInfo); +} + +int32_t DistributedBms::GetAbilityInfo(const OHOS::AppExecFwk::ElementName &elementName, + const std::string &localeInfo, RemoteAbilityInfo &remoteAbilityInfo) +{ + APP_LOGI("DistributedBms GetAbilityInfo bundleName:%{public}s , abilityName:%{public}s, localeInfo:%{public}s", + elementName.GetBundleName().c_str(), elementName.GetAbilityName().c_str(), localeInfo.c_str()); + auto iBundleMgr = GetBundleMgr(); + if (!iBundleMgr) { + APP_LOGE("DistributedBms GetBundleMgr failed"); + return ERR_APPEXECFWK_FAILED_SERVICE_DIED; + } + int userId = AccountManagerHelper::GetCurrentActiveUserId(); + if (userId == Constants::INVALID_USERID) { + APP_LOGE("GetCurrentUserId failed"); + return ERR_BUNDLE_MANAGER_INVALID_USER_ID; + } + std::vector abilityInfos; + OHOS::AAFwk::Want want; + want.SetElement(elementName); + ErrCode ret = iBundleMgr->QueryAbilityInfosV9(want, static_cast( + GetAbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION), userId, abilityInfos); + if (ret != ERR_OK) { + APP_LOGE("DistributedBms QueryAbilityInfo failed"); + return ret; + } + if (abilityInfos.empty()) { + APP_LOGE("DistributedBms QueryAbilityInfo abilityInfos empty"); + return ERR_APPEXECFWK_FAILED_GET_ABILITY_INFO; + } + std::string label = iBundleMgr->GetStringById( + abilityInfos[0].bundleName, abilityInfos[0].moduleName, abilityInfos[0].labelId, userId, localeInfo); + if (label.empty()) { + APP_LOGE("DistributedBms QueryAbilityInfo label empty"); + return ERR_APPEXECFWK_FAILED_GET_ABILITY_INFO; + } + remoteAbilityInfo.label = label; + remoteAbilityInfo.elementName = elementName; + return GetAbilityIconByContent(abilityInfos[0], userId, remoteAbilityInfo); +} + +int32_t DistributedBms::GetAbilityIconByContent( + const AbilityInfo &abilityInfo, int32_t userId, RemoteAbilityInfo &remoteAbilityInfo) +{ + auto iBundleMgr = GetBundleMgr(); + if (!iBundleMgr) { + APP_LOGE("DistributedBms GetBundleMgr failed"); + return ERR_APPEXECFWK_FAILED_SERVICE_DIED; + } + std::unique_ptr imageContent; + size_t imageContentSize = 0; + ErrCode ret = iBundleMgr->GetMediaData(abilityInfo.bundleName, abilityInfo.moduleName, abilityInfo.name, + imageContent, imageContentSize, userId); + if (ret != ERR_OK) { + APP_LOGE("DistributedBms GetMediaData failed"); + return ret; + } + APP_LOGD("imageContentSize is %{public}d", static_cast(imageContentSize)); + std::unique_ptr imageCompress = std::make_unique(); + if (imageCompress->IsImageNeedCompressBySize(imageContentSize)) { + std::unique_ptr compressData; + int64_t compressSize = 0; + std::string imageType; + if (!imageCompress->CompressImageByContent(imageContent, imageContentSize, + compressData, compressSize, imageType)) { + return Base64WithoutCompress(imageContent, imageContentSize, remoteAbilityInfo); + } + if (!GetMediaBase64(compressData, compressSize, imageType, remoteAbilityInfo.icon)) { + APP_LOGE("DistributedBms GetMediaBase64 failed"); + return ERR_APPEXECFWK_ENCODE_BASE64_FILE_FAILED; + } + } else { + return Base64WithoutCompress(imageContent, imageContentSize, remoteAbilityInfo); + } + return OHOS::NO_ERROR; +} + +int32_t DistributedBms::Base64WithoutCompress(std::unique_ptr &imageContent, size_t imageContentSize, + RemoteAbilityInfo &remoteAbilityInfo) +{ + std::string imageType; + std::unique_ptr imageCompress = std::make_unique(); + if (!imageCompress->GetImageTypeString(imageContent, imageContentSize, imageType)) { + return ERR_APPEXECFWK_INPUT_WRONG_TYPE_FILE; + } + if (!GetMediaBase64(imageContent, static_cast(imageContentSize), imageType, remoteAbilityInfo.icon)) { + APP_LOGE("DistributedBms GetMediaBase64 failed"); + return ERR_APPEXECFWK_ENCODE_BASE64_FILE_FAILED; + } + return OHOS::NO_ERROR; +} + +int32_t DistributedBms::GetAbilityInfos( + const std::vector &elementNames, std::vector &remoteAbilityInfos) +{ + APP_LOGD("DistributedBms GetAbilityInfos"); + return GetAbilityInfos(elementNames, "", remoteAbilityInfos); +} + +int32_t DistributedBms::GetAbilityInfos(const std::vector &elementNames, + const std::string &localeInfo, std::vector &remoteAbilityInfos) +{ + APP_LOGD("DistributedBms GetAbilityInfos"); + for (auto elementName : elementNames) { + RemoteAbilityInfo remoteAbilityInfo; + int32_t result = GetAbilityInfo(elementName, localeInfo, remoteAbilityInfo); + if (result) { + APP_LOGE("get AbilityInfo:%{public}s, %{public}s, %{public}s failed", elementName.GetBundleName().c_str(), + elementName.GetModuleName().c_str(), elementName.GetAbilityName().c_str()); + return result; + } + remoteAbilityInfos.push_back(remoteAbilityInfo); + } + return OHOS::NO_ERROR; +} + +bool DistributedBms::GetMediaBase64(std::unique_ptr &data, int64_t fileLength, + std::string &imageType, std::string &value) +{ + std::unique_ptr base64Data = EncodeBase64(data, fileLength); + value = "data:" + imageType + ";base64," + base64Data.get(); + return true; +} + +bool DistributedBms::GetDistributedBundleInfo(const std::string &networkId, const std::string &bundleName, + DistributedBundleInfo &distributedBundleInfo) +{ +#ifdef HICOLLIE_ENABLE + int timerId = HiviewDFX::XCollie::GetInstance().SetTimer("GetDistributedBundleInfo", LOCAL_TIME_OUT_SECONDS, + nullptr, nullptr, HiviewDFX::XCOLLIE_FLAG_RECOVERY); +#endif + bool ret = DistributedDataStorage::GetInstance()->GetStorageDistributeInfo( + networkId, bundleName, distributedBundleInfo); +#ifdef HICOLLIE_ENABLE + HiviewDFX::XCollie::GetInstance().CancelTimer(timerId); +#endif + return ret; +} + +int32_t DistributedBms::GetDistributedBundleName(const std::string &networkId, uint32_t accessTokenId, + std::string &bundleName) +{ +#ifdef HICOLLIE_ENABLE + int timerId = HiviewDFX::XCollie::GetInstance().SetTimer("GetDistributedBundleName", LOCAL_TIME_OUT_SECONDS, + nullptr, nullptr, HiviewDFX::XCOLLIE_FLAG_RECOVERY); +#endif + int32_t ret = DistributedDataStorage::GetInstance()->GetDistributedBundleName( + networkId, accessTokenId, bundleName); +#ifdef HICOLLIE_ENABLE + HiviewDFX::XCollie::GetInstance().CancelTimer(timerId); +#endif + return ret; +} + +std::unique_ptr DistributedBms::EncodeBase64(std::unique_ptr &data, int srcLen) +{ + int len = (srcLen / DECODE_VALUE_THREE) * DECODE_VALUE_FOUR; // Split 3 bytes to 4 parts, each containing 6 bits. + int outLen = ((srcLen % DECODE_VALUE_THREE) != 0) ? (len + DECODE_VALUE_FOUR) : len; + const uint8_t *srcData = data.get(); + std::unique_ptr result = std::make_unique(outLen + DECODE_VALUE_ONE); + char *dstData = result.get(); + int j = 0; + int i = 0; + for (; i < srcLen - DECODE_VALUE_THREE; i += DECODE_VALUE_THREE) { + unsigned char byte1 = srcData[i]; + unsigned char byte2 = srcData[i + DECODE_VALUE_ONE]; + unsigned char byte3 = srcData[i + DECODE_VALUE_TWO]; + dstData[j++] = DECODE_TABLE[byte1 >> DECODE_VALUE_TWO]; + dstData[j++] = + DECODE_TABLE[(static_cast(byte1 & DECODE_VALUE_CHAR_THREE) << DECODE_VALUE_FOUR) + | (byte2 >> DECODE_VALUE_FOUR)]; + dstData[j++] = + DECODE_TABLE[(static_cast(byte2 & DECODE_VALUE_CHAR_FIFTEEN) + << DECODE_VALUE_TWO) | (byte3 >> DECODE_VALUE_SIX)]; + dstData[j++] = DECODE_TABLE[byte3 & DECODE_VALUE_CHAR_SIXTY_THREE]; + } + if (srcLen % DECODE_VALUE_THREE == DECODE_VALUE_ONE) { + unsigned char byte1 = srcData[i]; + dstData[j++] = DECODE_TABLE[byte1 >> DECODE_VALUE_TWO]; + dstData[j++] = DECODE_TABLE[static_cast(byte1 & DECODE_VALUE_CHAR_THREE) << DECODE_VALUE_FOUR]; + dstData[j++] = '='; + dstData[j++] = '='; + } else { + unsigned char byte1 = srcData[i]; + unsigned char byte2 = srcData[i + DECODE_VALUE_ONE]; + dstData[j++] = DECODE_TABLE[byte1 >> DECODE_VALUE_TWO]; + dstData[j++] = + DECODE_TABLE[(static_cast(byte1 & DECODE_VALUE_CHAR_THREE) << DECODE_VALUE_FOUR) + | (byte2 >> DECODE_VALUE_FOUR)]; + dstData[j++] = DECODE_TABLE[static_cast(byte2 & DECODE_VALUE_CHAR_FIFTEEN) + << DECODE_VALUE_TWO]; + dstData[j++] = '='; + } + dstData[outLen] = '\0'; + + return result; +} +} +} \ No newline at end of file diff --git a/services/dbms/src/distributed_bms_host.cpp b/services/dbms/src/distributed_bms_host.cpp new file mode 100644 index 0000000..8b4ef3f --- /dev/null +++ b/services/dbms/src/distributed_bms_host.cpp @@ -0,0 +1,340 @@ +/* + * Copyright (c) 2022-2023 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 "distributed_bms_host.h" + +#include "accesstoken_kit.h" +#include "app_log_wrapper.h" +#include "appexecfwk_errors.h" +#include "bundle_constants.h" +#include "bundle_memory_guard.h" +#include "remote_ability_info.h" +#include "ipc_skeleton.h" +#include "tokenid_kit.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { +constexpr int32_t GET_REMOTE_ABILITY_INFO_MAX_SIZE = 10; +} + +DistributedBmsHost::DistributedBmsHost() +{ + APP_LOGI("DistributedBmsHost instance is created"); +} + +DistributedBmsHost::~DistributedBmsHost() +{ + APP_LOGI("DistributedBmsHost instance is destroyed"); +} + +int DistributedBmsHost::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) +{ + BundleMemoryGuard memoryGuard; + APP_LOGI("DistributedBmsHost receives message from client, code = %{public}u, flags = %{public}d", code, + option.GetFlags()); + std::u16string descripter = DistributedBmsHost::GetDescriptor(); + std::u16string remoteDescripter = data.ReadInterfaceToken(); + if (descripter != remoteDescripter) { + APP_LOGE("verify interface token failed"); + return ERR_INVALID_STATE; + } + switch (code) { + case static_cast(IDistributedBms::Message::GET_REMOTE_ABILITY_INFO): + case static_cast(IDistributedBms::Message::GET_REMOTE_ABILITY_INFO_WITH_LOCALE): + return HandleGetRemoteAbilityInfo(data, reply); + case static_cast(IDistributedBms::Message::GET_REMOTE_ABILITY_INFOS): + case static_cast(IDistributedBms::Message::GET_REMOTE_ABILITY_INFOS_WITH_LOCALE): + return HandleGetRemoteAbilityInfos(data, reply); + case static_cast(IDistributedBms::Message::GET_ABILITY_INFO): + case static_cast(IDistributedBms::Message::GET_ABILITY_INFO_WITH_LOCALE): + return HandleGetAbilityInfo(data, reply); + case static_cast(IDistributedBms::Message::GET_ABILITY_INFOS): + case static_cast(IDistributedBms::Message::GET_ABILITY_INFOS_WITH_LOCALE): + return HandleGetAbilityInfos(data, reply); + case static_cast(IDistributedBms::Message::GET_DISTRIBUTED_BUNDLE_INFO): + return HandleGetDistributedBundleInfo(data, reply); + case static_cast(IDistributedBms::Message::GET_DISTRIBUTED_BUNDLE_NAME): + return HandleGetDistributedBundleName(data, reply); + default: + APP_LOGW("DistributedBmsHost receives unknown code, code = %{public}d", code); + return IPCObjectStub::OnRemoteRequest(code, data, reply, option); + } + return NO_ERROR; +} + +int DistributedBmsHost::HandleGetRemoteAbilityInfo(Parcel &data, Parcel &reply) +{ + APP_LOGI("DistributedBmsHost handle get remote ability info"); + if (!VerifySystemApp()) { + APP_LOGE("verify system app failed"); + return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED; + } + if (!VerifyCallingPermission(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) { + APP_LOGE("verify GET_BUNDLE_INFO_PRIVILEGED failed"); + return ERR_BUNDLE_MANAGER_PERMISSION_DENIED; + } + std::unique_ptr elementName(data.ReadParcelable()); + if (!elementName) { + APP_LOGE("ReadParcelable failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + std::string localeInfo = data.ReadString(); + RemoteAbilityInfo remoteAbilityInfo; + int ret = GetRemoteAbilityInfo(*elementName, localeInfo, remoteAbilityInfo); + if (ret != NO_ERROR) { + APP_LOGE("GetRemoteAbilityInfo result:%{public}d", ret); + return ret; + } + if (!reply.WriteBool(true)) { + APP_LOGE("GetRemoteAbilityInfo write failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!reply.WriteParcelable(&remoteAbilityInfo)) { + APP_LOGE("GetRemoteAbilityInfo write failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + return NO_ERROR; +} + +int DistributedBmsHost::HandleGetRemoteAbilityInfos(Parcel &data, Parcel &reply) +{ + APP_LOGI("DistributedBmsHost handle get remote ability infos"); + if (!VerifySystemApp()) { + APP_LOGE("verify system app failed"); + return ERR_BUNDLE_MANAGER_SYSTEM_API_DENIED; + } + if (!VerifyCallingPermission(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED)) { + APP_LOGE("verify GET_BUNDLE_INFO_PRIVILEGED failed"); + return ERR_BUNDLE_MANAGER_PERMISSION_DENIED; + } + std::vector elementNames; + if (!GetParcelableInfos(data, elementNames)) { + APP_LOGE("GetRemoteAbilityInfos get parcelable infos failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + std::string localeInfo = data.ReadString(); + std::vector remoteAbilityInfos; + int ret = GetRemoteAbilityInfos(elementNames, localeInfo, remoteAbilityInfos); + if (ret != NO_ERROR) { + APP_LOGE("GetRemoteAbilityInfos result:%{public}d", ret); + return ret; + } + if (!reply.WriteBool(true)) { + APP_LOGE("GetRemoteAbilityInfos write failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!WriteParcelableVector(remoteAbilityInfos, reply)) { + APP_LOGE("GetRemoteAbilityInfos write failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + return NO_ERROR; +} + + +int DistributedBmsHost::HandleGetAbilityInfo(Parcel &data, Parcel &reply) +{ + APP_LOGI("DistributedBmsHost handle get ability info"); + std::unique_ptr elementName(data.ReadParcelable()); + if (!elementName) { + APP_LOGE("ReadParcelable failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + std::string localeInfo = data.ReadString(); + RemoteAbilityInfo remoteAbilityInfo; + int ret = GetAbilityInfo(*elementName, localeInfo, remoteAbilityInfo); + if (ret != NO_ERROR) { + APP_LOGE("GetAbilityInfo result:%{public}d", ret); + return ret; + } + if (!reply.WriteBool(true)) { + APP_LOGE("GetRemoteAbilityInfo write failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!reply.WriteParcelable(&remoteAbilityInfo)) { + APP_LOGE("GetRemoteAbilityInfo write failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + return NO_ERROR; +} + +int DistributedBmsHost::HandleGetAbilityInfos(Parcel &data, Parcel &reply) +{ + APP_LOGI("DistributedBmsHost handle get ability infos"); + std::vector elementNames; + if (!GetParcelableInfos(data, elementNames)) { + APP_LOGE("GetRemoteAbilityInfos get parcelable infos failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + std::string localeInfo = data.ReadString(); + std::vector remoteAbilityInfos; + int ret = GetAbilityInfos(elementNames, localeInfo, remoteAbilityInfos); + if (ret != NO_ERROR) { + APP_LOGE("GetAbilityInfos result:%{public}d", ret); + return ret; + } + if (!reply.WriteBool(true)) { + APP_LOGE("GetAbilityInfos write failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!WriteParcelableVector(remoteAbilityInfos, reply)) { + APP_LOGE("GetAbilityInfos write failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + return NO_ERROR; +} + +int DistributedBmsHost::HandleGetDistributedBundleInfo(Parcel &data, Parcel &reply) +{ + APP_LOGI("DistributedBmsHost handle get distributedBundleInfo"); + std::string networkId = data.ReadString(); + std::string bundleName = data.ReadString(); + DistributedBundleInfo distributedBundleInfo; + bool ret = GetDistributedBundleInfo(networkId, bundleName, distributedBundleInfo); + if (!ret) { + APP_LOGE("GetDistributedBundleInfo failed"); + return INVALID_OPERATION; + } + if (!reply.WriteBool(true)) { + APP_LOGE("GetDistributedBundleInfo write failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + if (!reply.WriteParcelable(&distributedBundleInfo)) { + APP_LOGE("GetDistributedBundleInfo write failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + return NO_ERROR; +} + +int32_t DistributedBmsHost::HandleGetDistributedBundleName(Parcel &data, Parcel &reply) +{ + APP_LOGD("DistributedBmsHost handle get distributedBundleName"); + Security::AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID(); + if (!VerifySystemAppForTokenNative(callerToken) && !VerifySystemAppForTokenShell(callerToken)) { + APP_LOGE("caller tokenType not native or shell, verify failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + std::string networkId = data.ReadString(); + uint32_t accessTokenId = data.ReadUint32(); + std::string bundleName; + int32_t ret = GetDistributedBundleName(networkId, accessTokenId, bundleName); + if (ret == NO_ERROR && !reply.WriteString(bundleName)) { + APP_LOGE("write failed"); + return ERR_APPEXECFWK_PARCEL_ERROR; + } + return ret; +} + +bool DistributedBmsHost::VerifyCallingPermission(const std::string &permissionName) +{ + APP_LOGD("VerifyCallingPermission permission %{public}s", permissionName.c_str()); + Security::AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID(); + if (VerifySystemAppForTokenNative(callerToken)) { + APP_LOGD("caller tokenType is native, verify success"); + return true; + } + int32_t ret = OHOS::Security::AccessToken::AccessTokenKit::VerifyAccessToken(callerToken, permissionName); + if (ret == OHOS::Security::AccessToken::PermissionState::PERMISSION_DENIED) { + APP_LOGE("permission %{public}s: PERMISSION_DENIED", permissionName.c_str()); + return false; + } + APP_LOGD("verify permission success"); + return true; +} + +bool DistributedBmsHost::VerifySystemApp() +{ + APP_LOGI("verifying systemApp"); + int32_t callingUid = IPCSkeleton::GetCallingUid(); + Security::AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID(); + if (VerifySystemAppForTokenNative(callerToken) || VerifySystemAppForTokenShell(callerToken) + || callingUid == Constants::ROOT_UID) { + APP_LOGI("caller tokenType is native or shell, verify success"); + return true; + } + uint64_t accessTokenIdEx = IPCSkeleton::GetCallingFullTokenID(); + if (!Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(accessTokenIdEx)) { + APP_LOGE("non-system app calling system api"); + return false; + } + return true; +} + +bool DistributedBmsHost::VerifySystemAppForTokenNative(Security::AccessToken::AccessTokenID callerToken) +{ + APP_LOGD("verifying system app for native token"); + Security::AccessToken::ATokenTypeEnum tokenType = + Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(callerToken); + APP_LOGD("token type is %{public}d", static_cast(tokenType)); + if (tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE) { + APP_LOGI("caller tokenType is native, verify success"); + return true; + } + APP_LOGE("caller tokenType not native, verify failed"); + return false; +} + +bool DistributedBmsHost::VerifySystemAppForTokenShell(Security::AccessToken::AccessTokenID callerToken) +{ + APP_LOGD("verifying system app for shell token"); + Security::AccessToken::ATokenTypeEnum tokenType = + Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(callerToken); + APP_LOGD("token type is %{public}d", static_cast(tokenType)); + if (tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_SHELL) { + APP_LOGI("caller tokenType is shell, verify success"); + return true; + } + APP_LOGE("caller tokenType not shell, verify failed"); + return false; +} + +template +bool DistributedBmsHost::WriteParcelableVector(std::vector &parcelableVector, Parcel &reply) +{ + if (!reply.WriteInt32(parcelableVector.size())) { + APP_LOGE("write ParcelableVector failed"); + return false; + } + + for (auto &parcelable : parcelableVector) { + if (!reply.WriteParcelable(&parcelable)) { + APP_LOGE("write ParcelableVector failed"); + return false; + } + } + return true; +} + +template +bool DistributedBmsHost::GetParcelableInfos(Parcel &data, std::vector &parcelableInfos) +{ + int32_t infoSize = data.ReadInt32(); + if (infoSize > GET_REMOTE_ABILITY_INFO_MAX_SIZE) { + APP_LOGE("GetParcelableInfos elements num exceeds the limit %{public}d", GET_REMOTE_ABILITY_INFO_MAX_SIZE); + return false; + } + for (int32_t i = 0; i < infoSize; i++) { + std::unique_ptr info(data.ReadParcelable()); + if (!info) { + APP_LOGE("Read Parcelable infos failed"); + return false; + } + parcelableInfos.emplace_back(*info); + } + APP_LOGD("get parcelable infos success"); + return true; +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/dbms/src/distributed_data_storage.cpp b/services/dbms/src/distributed_data_storage.cpp new file mode 100644 index 0000000..c82a1ab --- /dev/null +++ b/services/dbms/src/distributed_data_storage.cpp @@ -0,0 +1,403 @@ +/* + * 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. + */ + +#include "distributed_data_storage.h" + +#include + +#include "account_manager_helper.h" +#include "app_log_wrapper.h" +#include "distributed_bms.h" +#include "parameter.h" + +using namespace OHOS::DistributedKv; + +namespace OHOS { +namespace AppExecFwk { +namespace { +const std::string BMS_KV_BASE_DIR = "/data/service/el1/public/database/"; +const int32_t EL1 = 1; +const int32_t MAX_TIMES = 600; // 1min +const int32_t SLEEP_INTERVAL = 100 * 1000; // 100ms +const int32_t FLAGS = BundleFlag::GET_BUNDLE_WITH_ABILITIES | + ApplicationFlag::GET_APPLICATION_INFO_WITH_DISABLE | + AbilityInfoFlag::GET_ABILITY_INFO_WITH_DISABLE; +const uint32_t DEVICE_UDID_LENGTH = 65; +} // namespace + +std::shared_ptr DistributedDataStorage::instance_ = nullptr; +std::recursive_mutex DistributedDataStorage::mutex_; + +std::shared_ptr DistributedDataStorage::GetInstance() +{ + if (instance_ == nullptr) { + std::lock_guard lock_l(mutex_); + if (instance_ == nullptr) { + instance_ = std::make_shared(); + } + } + return instance_; +} + +DistributedDataStorage::DistributedDataStorage() +{ + APP_LOGI("instance is created"); + TryTwice([this] { return GetKvStore(); }); +} + +DistributedDataStorage::~DistributedDataStorage() +{ + APP_LOGI("instance is destroyed"); + dataManager_.CloseKvStore(appId_, storeId_); +} + +void DistributedDataStorage::SaveStorageDistributeInfo(const std::string &bundleName, int32_t userId) +{ + APP_LOGI("save DistributedBundleInfo data"); + { + std::lock_guard lock(kvStorePtrMutex_); + if (!CheckKvStore()) { + APP_LOGE("kvStore is nullptr"); + return; + } + } + int32_t currentUserId = AccountManagerHelper::GetCurrentActiveUserId(); + if (currentUserId == Constants::INVALID_USERID) { + currentUserId = Constants::START_USERID; + } + if (userId != currentUserId) { + APP_LOGW("install userid:%{public}d is not currentUserId:%{public}d", userId, currentUserId); + return; + } + auto bundleMgr = DelayedSingleton::GetInstance()->GetBundleMgr(); + if (bundleMgr == nullptr) { + APP_LOGE("Get bundleMgr shared_ptr nullptr"); + return; + } + BundleInfo bundleInfo; + bool ret = bundleMgr->GetBundleInfo(bundleName, FLAGS, bundleInfo, currentUserId); + if (!ret) { + APP_LOGW("GetBundleInfo:%{public}s userid:%{public}d failed", bundleName.c_str(), currentUserId); + DeleteStorageDistributeInfo(bundleName, currentUserId); + return; + } + ret = InnerSaveStorageDistributeInfo(ConvertToDistributedBundleInfo(bundleInfo)); + if (!ret) { + APP_LOGW("InnerSaveStorageDistributeInfo:%{public}s failed", bundleName.c_str()); + } +} + +bool DistributedDataStorage::InnerSaveStorageDistributeInfo(const DistributedBundleInfo &distributedBundleInfo) +{ + std::string udid; + bool ret = GetLocalUdid(udid); + if (!ret) { + APP_LOGE("GetLocalUdid error"); + return false; + } + std::string keyOfData = DeviceAndNameToKey(udid, distributedBundleInfo.bundleName); + Key key(keyOfData); + Value value(distributedBundleInfo.ToString()); + Status status = kvStorePtr_->Put(key, value); + if (status == Status::IPC_ERROR) { + status = kvStorePtr_->Put(key, value); + APP_LOGW("distribute database ipc error and try to call again, result = %{public}d", status); + } + if (status != Status::SUCCESS) { + APP_LOGE("put to kvStore error: %{public}d", status); + return false; + } + APP_LOGI("put value to kvStore success"); + return true; +} + +void DistributedDataStorage::DeleteStorageDistributeInfo(const std::string &bundleName, int32_t userId) +{ + APP_LOGI("delete DistributedBundleInfo"); + { + std::lock_guard lock(kvStorePtrMutex_); + if (!CheckKvStore()) { + APP_LOGE("kvStore is nullptr"); + return; + } + } + int32_t currentUserId = AccountManagerHelper::GetCurrentActiveUserId(); + if (userId != currentUserId) { + APP_LOGW("install userid:%{public}d is not currentUserId:%{public}d", userId, currentUserId); + return; + } + std::string udid; + bool ret = GetLocalUdid(udid); + if (!ret) { + APP_LOGE("GetLocalUdid error"); + return; + } + std::string keyOfData = DeviceAndNameToKey(udid, bundleName); + Key key(keyOfData); + Status status = kvStorePtr_->Delete(key); + if (status == Status::IPC_ERROR) { + status = kvStorePtr_->Delete(key); + APP_LOGW("distribute database ipc error and try to call again, result = %{public}d", status); + } + if (status != Status::SUCCESS) { + APP_LOGE("delete key error: %{public}d", status); + return; + } + APP_LOGI("delete value to kvStore success"); +} + +bool DistributedDataStorage::GetStorageDistributeInfo(const std::string &networkId, + const std::string &bundleName, DistributedBundleInfo &info) +{ + APP_LOGI("get DistributedBundleInfo"); + { + std::lock_guard lock(kvStorePtrMutex_); + if (!CheckKvStore()) { + APP_LOGE("kvStore is nullptr"); + return false; + } + } + std::string udid; + int32_t ret = GetUdidByNetworkId(networkId, udid); + if (ret != 0) { + APP_LOGI("can not get udid by networkId error:%{public}d", ret); + return false; + } + std::string keyOfData = DeviceAndNameToKey(udid, bundleName); + APP_LOGI("keyOfData: [%{public}s]", keyOfData.c_str()); + Key key(keyOfData); + Value value; + Status status = kvStorePtr_->Get(key, value); + if (status == Status::IPC_ERROR) { + status = kvStorePtr_->Get(key, value); + APP_LOGW("distribute database ipc error and try to call again, result = %{public}d", status); + } + if (status == Status::SUCCESS) { + if (!info.FromJsonString(value.ToString())) { + APP_LOGE("it's an error value"); + kvStorePtr_->Delete(key); + return false; + } + return true; + } + APP_LOGE("get value status: %{public}d", status); + return false; +} + +int32_t DistributedDataStorage::GetDistributedBundleName(const std::string &networkId, uint32_t accessTokenId, + std::string &bundleName) +{ + { + std::lock_guard lock(kvStorePtrMutex_); + if (!CheckKvStore()) { + APP_LOGE("kvStore is nullptr"); + return ERR_BUNDLE_MANAGER_INTERNAL_ERROR; + } + } + std::string udid; + int32_t ret = GetUdidByNetworkId(networkId, udid); + if (ret != 0) { + APP_LOGE("can not get udid by networkId error:%{public}d", ret); + return ret; + } + if (udid.size() == 0) { + APP_LOGE("get udid is Empty"); + return ERR_BUNDLE_MANAGER_INTERNAL_ERROR; + } + Key allEntryKeyPrefix(""); + std::vector allEntries; + Status status = kvStorePtr_->GetEntries(allEntryKeyPrefix, allEntries); + if (status != Status::SUCCESS) { + APP_LOGE("dataManager_ GetEntries error: %{public}d", status); + return ERR_BUNDLE_MANAGER_INTERNAL_ERROR; + } + for (auto entry : allEntries) { + std::string key = entry.key.ToString(); + std::string value = entry.value.ToString(); + if (key.find(udid) == std::string::npos) { + continue; + } + DistributedBundleInfo distributedBundleInfo; + if (distributedBundleInfo.FromJsonString(value) && distributedBundleInfo.accessTokenId == accessTokenId) { + bundleName = distributedBundleInfo.bundleName; + return OHOS::NO_ERROR; + } + } + return ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST; +} + +std::string DistributedDataStorage::DeviceAndNameToKey( + const std::string &udid, const std::string &bundleName) const +{ + std::string key = udid + Constants::FILE_UNDERLINE + bundleName; + return key; +} + +bool DistributedDataStorage::CheckKvStore() +{ + if (kvStorePtr_ != nullptr) { + return true; + } + int32_t tryTimes = MAX_TIMES; + while (tryTimes > 0) { + Status status = GetKvStore(); + if (status == Status::SUCCESS && kvStorePtr_ != nullptr) { + return true; + } + APP_LOGI("CheckKvStore, Times: %{public}d", tryTimes); + usleep(SLEEP_INTERVAL); + tryTimes--; + } + return kvStorePtr_ != nullptr; +} + +Status DistributedDataStorage::GetKvStore() +{ + Options options = { + .createIfMissing = true, + .encrypt = false, + .autoSync = true, + .securityLevel = SecurityLevel::S1, + .area = EL1, + .kvStoreType = KvStoreType::SINGLE_VERSION, + .baseDir = BMS_KV_BASE_DIR + appId_.appId + }; + Status status = dataManager_.GetSingleKvStore(options, appId_, storeId_, kvStorePtr_); + if (status != Status::SUCCESS) { + APP_LOGE("return error: %{public}d", status); + } else { + APP_LOGI("get kvStore success"); + } + return status; +} + +void DistributedDataStorage::TryTwice(const std::function &func) const +{ + Status status = func(); + if (status == Status::IPC_ERROR) { + status = func(); + APP_LOGW("distribute database ipc error and try to call again, result = %{public}d", status); + } +} + +bool DistributedDataStorage::GetLocalUdid(std::string &udid) +{ + char innerUdid[DEVICE_UDID_LENGTH] = {0}; + int ret = GetDevUdid(innerUdid, DEVICE_UDID_LENGTH); + if (ret != 0) { + APP_LOGI("GetDevUdid failed ,ret:%{public}d", ret); + return false; + } + udid = std::string(innerUdid); + return true; +} + +int32_t DistributedDataStorage::GetUdidByNetworkId(const std::string &networkId, std::string &udid) +{ + auto bundleMgr = DelayedSingleton::GetInstance()->GetBundleMgr(); + if (bundleMgr == nullptr) { + APP_LOGE("Get bundleMgr shared_ptr nullptr"); + return -1; + } + return bundleMgr->GetUdidByNetworkId(networkId, udid); +} + +DistributedBundleInfo DistributedDataStorage::ConvertToDistributedBundleInfo(const BundleInfo &bundleInfo) +{ + DistributedBundleInfo distributedBundleInfo; + distributedBundleInfo.bundleName = bundleInfo.name; + distributedBundleInfo.versionCode = bundleInfo.versionCode; + distributedBundleInfo.compatibleVersionCode = bundleInfo.compatibleVersion; + distributedBundleInfo.versionName = bundleInfo.versionName; + distributedBundleInfo.minCompatibleVersion = bundleInfo.minCompatibleVersionCode; + distributedBundleInfo.targetVersionCode = bundleInfo.targetVersion; + distributedBundleInfo.appId = bundleInfo.appId; + std::map> moduleAbilityInfos; + for (const auto &abilityInfo : bundleInfo.abilityInfos) { + DistributedAbilityInfo distributedAbilityInfo; + distributedAbilityInfo.abilityName = abilityInfo.name; + distributedAbilityInfo.permissions = abilityInfo.permissions; + distributedAbilityInfo.type = abilityInfo.type; + distributedAbilityInfo.enabled = abilityInfo.enabled; + auto infoItem = moduleAbilityInfos.find(abilityInfo.moduleName); + if (infoItem == moduleAbilityInfos.end()) { + std::vector distributedAbilityInfos; + distributedAbilityInfos.emplace_back(distributedAbilityInfo); + moduleAbilityInfos.emplace(abilityInfo.moduleName, distributedAbilityInfos); + } else { + moduleAbilityInfos[abilityInfo.moduleName].emplace_back(distributedAbilityInfo); + } + } + for (const auto& moduleAbilityInfo : moduleAbilityInfos) { + DistributedModuleInfo distributedModuleInfo; + distributedModuleInfo.moduleName = moduleAbilityInfo.first; + distributedModuleInfo.abilities = moduleAbilityInfo.second; + distributedBundleInfo.moduleInfos.emplace_back(distributedModuleInfo); + } + distributedBundleInfo.enabled = bundleInfo.applicationInfo.enabled; + distributedBundleInfo.accessTokenId = bundleInfo.applicationInfo.accessTokenId; + return distributedBundleInfo; +} + +void DistributedDataStorage::UpdateDistributedData(int32_t userId) +{ + APP_LOGI("UpdateDistributedData"); + if (kvStorePtr_ == nullptr) { + APP_LOGE("kvStorePtr_ is null"); + return; + } + std::string udid; + if (!GetLocalUdid(udid)) { + APP_LOGE("GetLocalUdid failed"); + return; + } + Key allEntryKeyPrefix(""); + std::vector allEntries; + Status status = kvStorePtr_->GetEntries(allEntryKeyPrefix, allEntries); + if (status != Status::SUCCESS) { + APP_LOGE("dataManager_ GetEntries error: %{public}d", status); + return; + } + for (auto entry : allEntries) { + std::string key = entry.key.ToString(); + if (key.find(udid) == std::string::npos) { + continue; + } + status = kvStorePtr_->Delete(entry.key); + if (status != Status::SUCCESS) { + APP_LOGE("Delete key:%{public}s failed", key.c_str()); + } + } + auto bundleMgr = DelayedSingleton::GetInstance()->GetBundleMgr(); + if (bundleMgr == nullptr) { + APP_LOGE("Get bundleMgr shared_ptr nullptr"); + return; + } + std::vector bundleInfos; + if (!bundleMgr->GetBundleInfos(FLAGS, bundleInfos, userId)) { + APP_LOGE("get bundleInfos failed"); + return; + } + for (auto bundleInfo : bundleInfos) { + if (bundleInfo.singleton) { + continue; + } + if (!InnerSaveStorageDistributeInfo(ConvertToDistributedBundleInfo(bundleInfo))) { + APP_LOGW("UpdateDistributedData SaveStorageDistributeInfo:%{public}s failed", bundleInfo.name.c_str()); + } + } +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/dbms/src/event_report.cpp b/services/dbms/src/event_report.cpp new file mode 100644 index 0000000..79117f1 --- /dev/null +++ b/services/dbms/src/event_report.cpp @@ -0,0 +1,67 @@ +/* + * 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. + */ + +#include "event_report.h" + +#include + +#include "app_log_wrapper.h" +#ifdef HISYSEVENT_ENABLE +#include "hisysevent.h" +#endif + +namespace OHOS { +namespace AppExecFwk { +namespace { +const std::string GET_REMOTE_ABILITY_INFO = "GET_REMOTE_ABILITY_INFO"; +const std::string GET_REMOTE_ABILITY_INFOS = "GET_REMOTE_ABILITY_INFOS"; + +const std::string DEVICE_ID = "DEVICE_ID"; +const std::string BUNDLE_NAME = "BUNDLE_NAME"; +const std::string LOCALE_INFO = "LOCALE_INFO"; +const std::string ABILITY_NAME = "ABILITY_NAME"; +const std::string RESULT_CODE = "RESULT_CODE"; + +const std::unordered_map DBMS_EVENT_STR_MAP = { + { DBMSEventType::GET_REMOTE_ABILITY_INFO, GET_REMOTE_ABILITY_INFO }, + { DBMSEventType::GET_REMOTE_ABILITY_INFOS, GET_REMOTE_ABILITY_INFOS }, +}; +} + +void EventReport::SendSystemEvent( + DBMSEventType dbmsEventType, const DBMSEventInfo& eventInfo) +{ +#ifndef HISYSEVENT_ENABLE + APP_LOGD("Hisysevent is disabled"); +#else + auto iter = DBMS_EVENT_STR_MAP.find(dbmsEventType); + if (iter == DBMS_EVENT_STR_MAP.end()) { + return; + } + + auto eventName = iter->second; + HiSysEventWrite( + OHOS::HiviewDFX::HiSysEvent::Domain::BUNDLE_MANAGER, + eventName, + OHOS::HiviewDFX::HiSysEvent::EventType::BEHAVIOR, + DEVICE_ID, eventInfo.deviceID, + BUNDLE_NAME, eventInfo.bundleName, + LOCALE_INFO, eventInfo.localeInfo, + ABILITY_NAME, eventInfo.abilityName, + RESULT_CODE, eventInfo.resultCode); +#endif +} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/dbms/src/image_compress.cpp b/services/dbms/src/image_compress.cpp new file mode 100644 index 0000000..aab452f --- /dev/null +++ b/services/dbms/src/image_compress.cpp @@ -0,0 +1,185 @@ +/* + * 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. + */ +#include +#include +#include + + +#include "image_compress.h" + +#include "app_log_wrapper.h" +#include "securec.h" +#include "image_source.h" +#include "image_packer.h" +#include "media_errors.h" + +namespace OHOS { +namespace AppExecFwk { +namespace { + constexpr size_t FORMAT_LENGTH = 8; + const std::string JPEG_FORMAT = "image/jpeg"; + const std::string PNG_FORMAT = "image/png"; + const std::string WEBP_FORMAT = "image/webp"; + const std::string BUNDLE_PATH = "/data/app/el1/bundle"; + constexpr int32_t QUALITY = 20; + constexpr int32_t MUNBER_ONE = 1; + constexpr int64_t BUFFER_SIZE = 2 * 1024 * 1024; + constexpr int32_t FILE_MAX_SIZE = 10240; + constexpr int32_t FILE_COMPRESS_SIZE = 4096; + constexpr int32_t WEBP_COMPRESS_SIZE = 128; + constexpr uint8_t JPEG_DATA_ZERO = 0xFF; + constexpr uint8_t JPEG_DATA_ONE = 0xD8; + constexpr uint8_t JPEG_DATA_TWO = 0xFF; + constexpr uint8_t PNG_DATA_ZERO = 0x89; + constexpr uint8_t PNG_DATA_ONE = 0x50; + constexpr uint8_t PNG_DATA_TWO = 0x4E; + constexpr uint8_t PNG_DATA_THREE = 0x47; + constexpr int32_t INDEX_ZERO = 0; + constexpr int32_t INDEX_ONE = 1; + constexpr int32_t INDEX_TWO = 2; + constexpr int32_t INDEX_THREE = 3; +} +bool ImageCompress::IsPathValid(const std::string &srcPath) +{ + if (srcPath.find(BUNDLE_PATH) != std::string::npos) { + return access(srcPath.c_str(), R_OK) == 0; + } else { + return false; + } +} + +bool ImageCompress::IsImageNeedCompressBySize(size_t fileSize) +{ + return fileSize > FILE_MAX_SIZE; +} + +double ImageCompress::CalculateRatio(size_t fileSize, const std::string &imageType) +{ + if (imageType == WEBP_FORMAT) { + return sqrt(static_cast(WEBP_COMPRESS_SIZE) / fileSize); + } + return sqrt(static_cast(FILE_COMPRESS_SIZE) / fileSize); +} + +ImageType ImageCompress::GetImageType(const std::unique_ptr &fileData, size_t fileLength) +{ + if (fileLength < FORMAT_LENGTH) { + return ImageType::WORNG_TYPE; + } + const uint8_t* data = fileData.get(); + if (data[INDEX_ZERO] == JPEG_DATA_ZERO && data[INDEX_ONE] == JPEG_DATA_ONE + && data[INDEX_TWO] == JPEG_DATA_TWO) { + return ImageType::JPEG; + } else if (data[INDEX_ZERO] == PNG_DATA_ZERO && data[INDEX_ONE] == PNG_DATA_ONE && + data[INDEX_TWO] == PNG_DATA_TWO && data[INDEX_THREE] == PNG_DATA_THREE) { + return ImageType::PNG; + } else { + return ImageType::WORNG_TYPE; + } +} + +bool ImageCompress::GetImageTypeString(const std::unique_ptr &fileData, + size_t fileLength, std::string &imageType) +{ + ImageType type = GetImageType(fileData, fileLength); + if (type == ImageType::WORNG_TYPE) { + APP_LOGE("input wrong type image!"); + return false; + } + imageType = type == ImageType::JPEG ? JPEG_FORMAT : PNG_FORMAT; + return true; +} + +bool ImageCompress::GetImageFileInfo(const std::string &srcFile, + std::unique_ptr &fileContent, int64_t &fileLength) +{ + if (!IsPathValid(srcFile)) { + APP_LOGE("%{public}s is unavailable", srcFile.c_str()); + return false; + } + FILE* file = fopen(srcFile.c_str(), "rb"); + if (!file) { + APP_LOGE("ImageCompress: GetImageTypeByFile %{public}s is unavailable", srcFile.c_str()); + return false; + } + if (fseek(file, 0L, SEEK_END) != 0) { + fclose(file); + return false; + } + fileLength = ftell(file); + rewind(file); + fileContent = std::make_unique(fileLength); + if (!fread(fileContent.get(), sizeof(uint8_t), fileLength, file)) { + APP_LOGE("read file failed!"); + fclose(file); + return false; + } + if (fclose(file) != 0) { + APP_LOGE("close file failed!"); + return false; + } + return true; +} + +bool ImageCompress::CompressImageByContent(const std::unique_ptr &fileData, size_t fileSize, + std::unique_ptr &compressedData, int64_t &compressedSize, std::string &imageType) +{ + ImageType type = GetImageType(fileData, fileSize); + if (type == ImageType::WORNG_TYPE) { + APP_LOGE("input wrong image!"); + return false; + } + imageType = type == ImageType::JPEG ? JPEG_FORMAT : WEBP_FORMAT; + uint32_t errorCode = 0; + Media::SourceOptions options; + std::unique_ptr imageSourcePtr = + Media::ImageSource::CreateImageSource(fileData.get(), fileSize, options, errorCode); + // do compress + Media::DecodeOptions decodeOptions; + uint32_t pixMapError = 0; + std::unique_ptr pixMap = imageSourcePtr->CreatePixelMap(decodeOptions, pixMapError); + if (pixMap == nullptr || pixMapError != Media::SUCCESS) { + APP_LOGE("CreatePixelMap failed!"); + return false; + } + double ratio = CalculateRatio(fileSize, imageType); + APP_LOGE("ratio is %{public}f", ratio); + pixMap->scale(ratio, ratio); + Media::ImagePacker imagePacker; + Media::PackOption packOption; + packOption.format = imageType; + packOption.quality = QUALITY; + packOption.numberHint = MUNBER_ONE; + uint8_t *resultBuffer = reinterpret_cast(malloc(BUFFER_SIZE)); + if (resultBuffer == nullptr) { + APP_LOGE("image packer malloc buffer failed."); + return 0; + } + imagePacker.StartPacking(resultBuffer, BUFFER_SIZE, packOption); + imagePacker.AddImage(*pixMap); + imagePacker.FinalizePacking(compressedSize); + compressedData = std::make_unique(compressedSize); + APP_LOGD("compressedSize is %{public}d", static_cast(compressedSize)); + uint8_t *result = compressedData.get(); + if (memcpy_s(result, compressedSize, resultBuffer, compressedSize) != EOK) { + free(resultBuffer); + APP_LOGE("memcpy_s to compressedData failed!"); + return false; + } + free(resultBuffer); + return true; +} +} +} \ No newline at end of file diff --git a/services/dbms/test/BUILD.gn b/services/dbms/test/BUILD.gn new file mode 100644 index 0000000..4e13732 --- /dev/null +++ b/services/dbms/test/BUILD.gn @@ -0,0 +1,20 @@ +# Copyright (c) 2022-2023 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. + +group("unittest") { + testonly = true + deps = [ + "unittest/dbms_services_kit_test:unittest", + "unittest/distributed_bms_host_test:unittest", + ] +} diff --git a/services/dbms/test/unittest/dbms_services_kit_test/BUILD.gn b/services/dbms/test/unittest/dbms_services_kit_test/BUILD.gn new file mode 100644 index 0000000..ddf72d7 --- /dev/null +++ b/services/dbms/test/unittest/dbms_services_kit_test/BUILD.gn @@ -0,0 +1,80 @@ +# 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("//build/test.gni") +import("../../../../../dbms.gni") + +module_output_path = "bundle_framework/distributedbundleservice" + +ohos_unittest("DbmsServicesKitTest") { + use_exceptions = true + module_out_path = module_output_path + include_dirs = [ + "${dbms_inner_api_path}/include", + "${dbms_services_path}/include", + ] + + sources = [ + "${dbms_inner_api_path}/src/distributed_bms_proxy.cpp", + "${dbms_services_path}/src/account_manager_helper.cpp", + "${dbms_services_path}/src/distributed_bms.cpp", + "${dbms_services_path}/src/distributed_bms_host.cpp", + "${dbms_services_path}/src/distributed_data_storage.cpp", + "${dbms_services_path}/src/image_compress.cpp", + ] + + sources += [ "dbms_services_kit_test.cpp" ] + + deps = [ + "${common_path}:libappexecfwk_common", + "${dbms_inner_api_path}:dbms_fwk", + ] + + external_deps = [ + "ability_base:want", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "hicollie_native:libhicollie", + "hiviewdfx_hilog_native:libhilog", + "i18n:intl_util", + "init:libbegetutil", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "multimedia_image_framework:image_native", + "resource_management:global_resmgr", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + defines = [] + + if (hisysevent_enable_dbms) { + sources += [ "${dbms_services_path}/src/event_report.cpp" ] + external_deps += [ "hisysevent_native:libhisysevent" ] + defines += [ "HISYSEVENT_ENABLE" ] + } + + if (account_enable_dbms) { + external_deps += [ "os_account:os_account_innerkits" ] + defines += [ "ACCOUNT_ENABLE" ] + } +} + +group("unittest") { + testonly = true + if (ability_runtime_enable_dbms) { + deps = [ ":DbmsServicesKitTest" ] + } +} diff --git a/services/dbms/test/unittest/dbms_services_kit_test/dbms_services_kit_test.cpp b/services/dbms/test/unittest/dbms_services_kit_test/dbms_services_kit_test.cpp new file mode 100644 index 0000000..e147dd4 --- /dev/null +++ b/services/dbms/test/unittest/dbms_services_kit_test/dbms_services_kit_test.cpp @@ -0,0 +1,1465 @@ +/* + * Copyright (c) 2022-2023 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. + */ + +#define private public + +#include +#include +#include +#include +#include +#include + +#include "appexecfwk_errors.h" +#include "distributed_ability_info.h" +#include "distributed_bms.h" +#include "distributed_bms_interface.h" +#include "distributed_bms_proxy.h" +#include "distributed_bundle_info.h" +#include "distributed_module_info.h" +#include "element_name.h" +#include "event_report.h" +#include "image_compress.h" +#include "json_util.h" +#include "service_control.h" + +using namespace testing::ext; +using namespace std::chrono_literals; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +namespace { +const std::string WRONG_BUNDLE_NAME = "wrong"; +const std::string WRONG_ABILITY_NAME = "wrong"; +const std::string BUNDLE_NAME = "com.ohos.launcher"; +const std::string MODULE_NAME = "launcher_settings"; +const std::string ABILITY_NAME = "com.ohos.launcher.settings.MainAbility"; +const std::string DEVICE_ID = "1111"; +const std::string INVALID_NAME = "invalid"; +const std::string HAP_FILE_PATH = + "/data/app/el1/bundle/public/com.example.test/entry.hap"; +const std::string PATH_LOCATION = "/data/app/el1/bundle/public/com.ohos.launcher"; +const std::string PATH_LOCATIONS = "/data/app/el1/bundle/new_create.txt"; +const std::string DEVICE_ID_NORMAL = "deviceId"; +const std::string LOCALE_INFO = "localeInfo"; +const std::string EMPTY_STRING = ""; +} // namespace + +class DbmsServicesKitTest : public testing::Test { +public: + DbmsServicesKitTest(); + ~DbmsServicesKitTest(); + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + std::shared_ptr GetDistributedBms(); + std::shared_ptr GetDistributedBmsProxy(); + std::shared_ptr GetDistributedDataStorage(); + std::shared_ptr GetEventReport(); + sptr GetSptrDistributedBms(); +private: + std::shared_ptr distributedBms_ = nullptr; + std::shared_ptr distributedBmsProxy_ = nullptr; + std::shared_ptr distributedDataStorage_ = nullptr; + std::shared_ptr eventReport_ = nullptr; + sptr sptrDistributedBms_ = nullptr; +}; + +DbmsServicesKitTest::DbmsServicesKitTest() +{} + +DbmsServicesKitTest::~DbmsServicesKitTest() +{} + +void DbmsServicesKitTest::SetUpTestCase() +{} + +void DbmsServicesKitTest::TearDownTestCase() +{} + +void DbmsServicesKitTest::SetUp() +{ + std::string strExtra = std::to_string(402); + auto extraArgv = strExtra.c_str(); + ServiceControlWithExtra("d-bms", START, &extraArgv, 1); +} + +void DbmsServicesKitTest::TearDown() +{ + std::string strExtra = std::to_string(402); + auto extraArgv = strExtra.c_str(); + ServiceControlWithExtra("d-bms", STOP, &extraArgv, 1); +} + +std::shared_ptr DbmsServicesKitTest::GetDistributedBms() +{ + if (distributedBms_ == nullptr) { + distributedBms_ = std::make_unique(); + } + return distributedBms_; +} + +sptr DbmsServicesKitTest::GetSptrDistributedBms() +{ + if (sptrDistributedBms_ == nullptr) { + sptrDistributedBms_ = new DistributedBms(); + } + return sptrDistributedBms_; +} + +std::shared_ptr DbmsServicesKitTest::GetDistributedBmsProxy() +{ + if (distributedBmsProxy_ == nullptr) { + distributedBmsProxy_ = std::make_shared(nullptr); + } + return distributedBmsProxy_; +} + +std::shared_ptr DbmsServicesKitTest::GetDistributedDataStorage() +{ + if (distributedDataStorage_ == nullptr) { + distributedDataStorage_ = + std::make_unique(); + } + return distributedDataStorage_; +} + +std::shared_ptr DbmsServicesKitTest::GetEventReport() +{ + if (eventReport_ == nullptr) { + eventReport_ = std::make_shared(); + } + return eventReport_; +} + +/** + * @tc.number: DbmsServicesKitTest + * @tc.name: test GetRemoteAbilityInfo + * @tc.require: issueI5MZ8V + * @tc.desc: 1. system running normally + * 2. test ElementName empty + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0001, Function | SmallTest | Level0) +{ + auto distributedBms = GetDistributedBms(); + EXPECT_NE(distributedBms, nullptr); + if (distributedBms != nullptr) { + ElementName name; + RemoteAbilityInfo info; + auto ret = distributedBms->GetRemoteAbilityInfo(name, info); + EXPECT_EQ(ret, ERR_BUNDLE_MANAGER_DEVICE_ID_NOT_EXIST); + } +} + +/** + * @tc.number: DbmsServicesKitTest + * @tc.name: test GetRemoteAbilityInfo + * @tc.require: issueI5MZ8V + * @tc.desc: 1. system running normally + * 2. test ElementName empty + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0002, Function | SmallTest | Level0) +{ + auto distributedBms = GetDistributedBms(); + EXPECT_NE(distributedBms, nullptr); + if (distributedBms != nullptr) { + ElementName name; + RemoteAbilityInfo info; + auto ret = distributedBms->GetRemoteAbilityInfo(name, "", info); + EXPECT_EQ(ret, ERR_BUNDLE_MANAGER_DEVICE_ID_NOT_EXIST); + } +} + +/** + * @tc.number: DbmsServicesKitTest + * @tc.name: test GetRemoteAbilityInfo + * @tc.require: issueI5MZ8V + * @tc.desc: 1. system running normally + * 2. test ElementName empty + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0003, Function | SmallTest | Level0) +{ + auto distributedBms = GetDistributedBms(); + EXPECT_NE(distributedBms, nullptr); + if (distributedBms != nullptr) { + ElementName name; + RemoteAbilityInfo info; + auto ret = distributedBms->GetRemoteAbilityInfo(name, "", info); + EXPECT_EQ(ret, ERR_BUNDLE_MANAGER_DEVICE_ID_NOT_EXIST); + } +} + +/** + * @tc.number: DbmsServicesKitTest + * @tc.name: test GetRemoteAbilityInfos + * @tc.require: issueI5MZ8V + * @tc.desc: 1. system running normally + * 2. test ElementName empty + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0004, Function | SmallTest | Level0) +{ + auto distributedBms = GetDistributedBms(); + EXPECT_NE(distributedBms, nullptr); + if (distributedBms != nullptr) { + std::vector name; + std::vector info; + auto ret = distributedBms->GetRemoteAbilityInfos(name, info); + EXPECT_EQ(ret, ERR_BUNDLE_MANAGER_PARAM_ERROR); + } +} + +/** + * @tc.number: DbmsServicesKitTest + * @tc.name: test GetRemoteAbilityInfos + * @tc.require: issueI5MZ8V + * @tc.desc: 1. system running normally + * 2. test ElementName empty + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0005, Function | SmallTest | Level0) +{ + auto distributedBms = GetDistributedBms(); + EXPECT_NE(distributedBms, nullptr); + if (distributedBms != nullptr) { + std::vector name; + std::vector info; + auto ret = distributedBms->GetRemoteAbilityInfos(name, "", info); + EXPECT_EQ(ret, ERR_BUNDLE_MANAGER_PARAM_ERROR); + } +} + +/** + * @tc.number: DbmsServicesKitTest + * @tc.name: test GetAbilityInfo + * @tc.require: issueI5MZ8V + * @tc.desc: 1. system running normally + * 2. test bundleName empty + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0006, Function | SmallTest | Level0) +{ + auto distributedBms = GetDistributedBms(); + EXPECT_NE(distributedBms, nullptr); + if (distributedBms != nullptr) { + ElementName name; + name.SetBundleName(WRONG_BUNDLE_NAME); + name.SetAbilityName(ABILITY_NAME); + RemoteAbilityInfo info; + auto ret = distributedBms->GetAbilityInfo(name, info); + EXPECT_EQ(ret, ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST); + } +} + +/** + * @tc.number: DbmsServicesKitTest + * @tc.name: test GetAbilityInfo + * @tc.require: issueI5MZ8V + * @tc.desc: 1. system running normally + * 2. test abilityName empty + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0007, Function | SmallTest | Level0) +{ + auto distributedBms = GetDistributedBms(); + EXPECT_NE(distributedBms, nullptr); + if (distributedBms != nullptr) { + ElementName name; + name.SetBundleName(BUNDLE_NAME); + name.SetAbilityName(WRONG_ABILITY_NAME); + RemoteAbilityInfo info; + auto ret = distributedBms->GetAbilityInfo(name, info); + EXPECT_EQ(ret, ERR_BUNDLE_MANAGER_ABILITY_NOT_EXIST); + } +} + +/** + * @tc.number: DbmsServicesKitTest + * @tc.name: test GetAbilityInfo + * @tc.require: issueI5MZ8V + * @tc.desc: 1. system running normally + * 2. test bundleName and abilityName both exist + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0008, Function | SmallTest | Level0) +{ + auto distributedBms = GetDistributedBms(); + EXPECT_NE(distributedBms, nullptr); + if (distributedBms != nullptr) { + ElementName name; + name.SetBundleName(BUNDLE_NAME); + name.SetAbilityName(ABILITY_NAME); + RemoteAbilityInfo info; + auto ret = distributedBms->GetAbilityInfo(name, info); + EXPECT_EQ(ret, ERR_OK); + } +} + +/** + * @tc.number: DbmsServicesKitTest + * @tc.name: test GetAbilityInfo + * @tc.require: issueI5MZ8V + * @tc.desc: 1. system running normally + * 2. test wrong abilityName + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0009, Function | SmallTest | Level0) +{ + auto distributedBms = GetDistributedBms(); + EXPECT_NE(distributedBms, nullptr); + if (distributedBms != nullptr) { + ElementName name; + name.SetBundleName(BUNDLE_NAME); + name.SetModuleName(MODULE_NAME); + name.SetAbilityName(WRONG_ABILITY_NAME); + RemoteAbilityInfo info; + auto ret = distributedBms->GetAbilityInfo(name, info); + EXPECT_EQ(ret, ERR_BUNDLE_MANAGER_ABILITY_NOT_EXIST); + } +} + +/** + * @tc.number: DbmsServicesKitTest + * @tc.name: test GetAbilityInfo + * @tc.require: issueI5MZ8V + * @tc.desc: 1. system running normally + * 2. test ElementName empty + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0010, Function | SmallTest | Level0) +{ + auto distributedBms = GetDistributedBms(); + EXPECT_NE(distributedBms, nullptr); + if (distributedBms != nullptr) { + std::vector name; + std::vector info; + auto ret = distributedBms->GetAbilityInfos(name, info); + EXPECT_EQ(ret, ERR_OK); + } +} + +/** + * @tc.number: DbmsServicesKitTest + * @tc.name: test GetAbilityInfo + * @tc.require: issueI5MZ8V + * @tc.desc: 1. system running normally + * 2. test abilityName is empty + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0011, Function | SmallTest | Level0) +{ + auto distributedBms = GetDistributedBms(); + EXPECT_NE(distributedBms, nullptr); + if (distributedBms != nullptr) { + std::vector names; + ElementName name; + name.SetBundleName(BUNDLE_NAME); + name.SetModuleName(MODULE_NAME); + name.SetAbilityName(WRONG_ABILITY_NAME); + names.push_back(name); + std::vector infos; + auto ret = distributedBms->GetAbilityInfos(names, infos); + EXPECT_EQ(ret, ERR_BUNDLE_MANAGER_ABILITY_NOT_EXIST); + } +} + +/** + * @tc.number: DbmsServicesKitTest + * @tc.name: test GetAbilityInfo + * @tc.require: issueI5MZ8V + * @tc.desc: 1. system running normally + * 2. test abilityName empty + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0012, Function | SmallTest | Level0) +{ + auto distributedBms = GetDistributedBms(); + EXPECT_NE(distributedBms, nullptr); + if (distributedBms != nullptr) { + std::vector names; + ElementName name; + name.SetBundleName(BUNDLE_NAME); + name.SetAbilityName(ABILITY_NAME); + names.push_back(name); + std::vector infos; + auto ret = distributedBms->GetAbilityInfos(names, infos); + EXPECT_EQ(ret, ERR_OK); + } +} + +/** + * @tc.number: DbmsServicesKitTest + * @tc.name: test GetAbilityInfo + * @tc.require: issueI5MZ8V + * @tc.desc: 1. system running normally + * 2. test bundleName empty + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0013, Function | SmallTest | Level0) +{ + auto distributedBmsProxy = GetDistributedBmsProxy(); + EXPECT_NE(distributedBmsProxy, nullptr); + if (distributedBmsProxy != nullptr) { + ElementName name; + RemoteAbilityInfo info; + auto ret = distributedBmsProxy->GetRemoteAbilityInfo(name, "", info); + EXPECT_EQ(ret, ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST); + } +} + +/** + * @tc.number: DbmsServicesKitTest + * @tc.name: test GetAbilityInfo + * @tc.require: issueI5MZ8V + * @tc.desc: 1. system running normally + * 2. test abilityName empty + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0014, Function | SmallTest | Level0) +{ + auto distributedBmsProxy = GetDistributedBmsProxy(); + EXPECT_NE(distributedBmsProxy, nullptr); + if (distributedBmsProxy != nullptr) { + ElementName name; + name.SetBundleName(BUNDLE_NAME); + RemoteAbilityInfo info; + auto ret = distributedBmsProxy->GetRemoteAbilityInfo(name, "", info); + EXPECT_EQ(ret, ERR_BUNDLE_MANAGER_ABILITY_NOT_EXIST); + } +} + +/** + * @tc.number: DbmsServicesKitTest + * @tc.name: test GetAbilityInfo + * @tc.require: issueI5MZ8V + * @tc.desc: 1. system running normally + * 2. test deviceID empty + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0015, Function | SmallTest | Level0) +{ + auto distributedBmsProxy = GetDistributedBmsProxy(); + EXPECT_NE(distributedBmsProxy, nullptr); + if (distributedBmsProxy != nullptr) { + ElementName name; + name.SetBundleName(BUNDLE_NAME); + name.SetAbilityName(ABILITY_NAME); + RemoteAbilityInfo info; + auto ret = distributedBmsProxy->GetRemoteAbilityInfo(name, "", info); + EXPECT_EQ(ret, ERR_BUNDLE_MANAGER_DEVICE_ID_NOT_EXIST); + } +} + +/** + * @tc.number: DbmsServicesKitTest + * @tc.name: test GetAbilityInfo + * @tc.require: issueI5MZ8V + * @tc.desc: 1. system running normally + * 2. test ElementName not empty + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0016, Function | SmallTest | Level0) +{ + auto distributedBmsProxy = GetDistributedBmsProxy(); + EXPECT_NE(distributedBmsProxy, nullptr); + if (distributedBmsProxy != nullptr) { + ElementName name; + name.SetBundleName(BUNDLE_NAME); + name.SetAbilityName(ABILITY_NAME); + name.SetDeviceID(DEVICE_ID); + RemoteAbilityInfo info; + auto ret = distributedBmsProxy->GetRemoteAbilityInfo(name, "", info); + EXPECT_EQ(ret, ERR_APPEXECFWK_FAILED_GET_REMOTE_PROXY); + } +} + +/** + * @tc.number: DbmsServicesKitTest + * @tc.name: test GetAbilityInfo + * @tc.require: issueI5MZ8V + * @tc.desc: 1. system running normally + * 2. test ElementNames empty + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0017, Function | SmallTest | Level0) +{ + auto distributedBmsProxy = GetDistributedBmsProxy(); + EXPECT_NE(distributedBmsProxy, nullptr); + if (distributedBmsProxy != nullptr) { + std::vector names; + std::vector infos; + auto ret = distributedBmsProxy->GetRemoteAbilityInfos(names, infos); + EXPECT_EQ(ret, ERR_APPEXECFWK_FAILED_GET_REMOTE_PROXY); + } +} + +/** + * @tc.number: DbmsServicesKitTest + * @tc.name: test GetAbilityInfo + * @tc.require: issueI5MZ8V + * @tc.desc: 1. system running normally + * 2. test ElementNames not empty + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0018, Function | SmallTest | Level0) +{ + auto distributedBmsProxy = GetDistributedBmsProxy(); + EXPECT_NE(distributedBmsProxy, nullptr); + if (distributedBmsProxy != nullptr) { + std::vector names; + ElementName name_1; + name_1.SetBundleName(BUNDLE_NAME); + name_1.SetAbilityName(ABILITY_NAME); + name_1.SetDeviceID(DEVICE_ID); + names.push_back(name_1); + + ElementName name_2; + name_2.SetBundleName(BUNDLE_NAME); + name_2.SetAbilityName(ABILITY_NAME); + names.push_back(name_2); + + std::vector infos; + auto ret = distributedBmsProxy->GetRemoteAbilityInfos(names, infos); + EXPECT_EQ(ret, ERR_BUNDLE_MANAGER_DEVICE_ID_NOT_EXIST); + } +} + +/** + * @tc.number: DbmsServicesKitTest + * @tc.name: test GetAbilityInfo + * @tc.require: issueI5MZ8V + * @tc.desc: 1. system running normally + * 2. test GetAbilityInfo + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0019, Function | SmallTest | Level0) +{ + auto distributedBmsProxy = GetDistributedBmsProxy(); + EXPECT_NE(distributedBmsProxy, nullptr); + if (distributedBmsProxy != nullptr) { + ElementName name; + name.SetBundleName(WRONG_BUNDLE_NAME); + name.SetAbilityName(ABILITY_NAME); + RemoteAbilityInfo info; + auto ret = distributedBmsProxy->GetAbilityInfo(name, info); + EXPECT_EQ(ret, ERR_APPEXECFWK_FAILED_GET_REMOTE_PROXY); + } +} + +/** + * @tc.number: DbmsServicesKitTest + * @tc.name: test GetAbilityInfo + * @tc.require: issueI5MZ8V + * @tc.desc: 1. system running normally + * 2. test GetAbilityInfo + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0020, Function | SmallTest | Level0) +{ + auto distributedBmsProxy = GetDistributedBmsProxy(); + EXPECT_NE(distributedBmsProxy, nullptr); + if (distributedBmsProxy != nullptr) { + ElementName name; + name.SetBundleName(WRONG_BUNDLE_NAME); + name.SetAbilityName(ABILITY_NAME); + RemoteAbilityInfo info; + auto ret = distributedBmsProxy->GetAbilityInfo(name, "localeInfo", info); + EXPECT_EQ(ret, ERR_APPEXECFWK_FAILED_GET_REMOTE_PROXY); + } +} + +/** + * @tc.number: DbmsServicesKitTest + * @tc.name: test GetAbilityInfo + * @tc.require: issueI5MZ8V + * @tc.desc: 1. system running normally + * 2. test GetAbilityInfos + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0021, Function | SmallTest | Level0) +{ + auto distributedBmsProxy = GetDistributedBmsProxy(); + EXPECT_NE(distributedBmsProxy, nullptr); + if (distributedBmsProxy != nullptr) { + std::vector names; + ElementName name; + name.SetBundleName(BUNDLE_NAME); + name.SetModuleName(MODULE_NAME); + name.SetAbilityName(WRONG_ABILITY_NAME); + names.push_back(name); + std::vector infos; + auto ret = distributedBmsProxy->GetAbilityInfos(names, infos); + EXPECT_EQ(ret, ERR_APPEXECFWK_FAILED_GET_REMOTE_PROXY); + } +} + +/** + * @tc.number: DbmsServicesKitTest + * @tc.name: test GetAbilityInfo + * @tc.require: issueI5MZ8V + * @tc.desc: 1. system running normally + * 2. test GetAbilityInfos + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0022, Function | SmallTest | Level0) +{ + auto distributedBmsProxy = GetDistributedBmsProxy(); + EXPECT_NE(distributedBmsProxy, nullptr); + if (distributedBmsProxy != nullptr) { + std::vector names; + ElementName name; + name.SetBundleName(BUNDLE_NAME); + name.SetModuleName(MODULE_NAME); + name.SetAbilityName(WRONG_ABILITY_NAME); + names.push_back(name); + std::vector infos; + auto ret = distributedBmsProxy->GetAbilityInfos(names, "", infos); + EXPECT_EQ(ret, ERR_APPEXECFWK_FAILED_GET_REMOTE_PROXY); + } +} + +/** + * @tc.number: DbmsServicesKitTest + * @tc.name: test GetAbilityInfo + * @tc.require: issueI5MZ8V + * @tc.desc: 1. system running normally + * 2. test GetDistributedBundleInfo + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0023, Function | SmallTest | Level0) +{ + auto distributedBmsProxy = GetDistributedBmsProxy(); + EXPECT_NE(distributedBmsProxy, nullptr); + if (distributedBmsProxy != nullptr) { + DistributedBundleInfo distributedBundleInfo; + auto ret = distributedBmsProxy->GetDistributedBundleInfo("", "", distributedBundleInfo); + EXPECT_EQ(ret, false); + } +} + +/** + * @tc.number: DbmsServicesKitTest + * @tc.name: test IsPathValid + * @tc.require: issueI5MZ8V + * @tc.desc: 1. system running normally + * 2. test path is not valid + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0031, Function | SmallTest | Level0) +{ + std::unique_ptr imageCompress = std::make_unique(); + EXPECT_NE(imageCompress, nullptr); + if (imageCompress != nullptr) { + bool res = imageCompress->IsPathValid(HAP_FILE_PATH); + EXPECT_EQ(res, false); + } +} + +/** + * @tc.number: DbmsServicesKitTest + * @tc.name: test GetImageType + * @tc.require: issueI5MZ8V + * @tc.desc: 1. system running normally + * 2. test get image type + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0032, Function | SmallTest | Level0) +{ + std::unique_ptr imageCompress = std::make_unique(); + EXPECT_NE(imageCompress, nullptr); + if (imageCompress != nullptr) { + std::unique_ptr fileData; + constexpr size_t fileLength = 7; + ImageType res = imageCompress->GetImageType(fileData, fileLength); + EXPECT_EQ(res, ImageType::WORNG_TYPE); + } +} + +/** + * @tc.number: DbmsServicesKitTest + * @tc.name: test GetImageTypeString + * @tc.require: issueI5MZ8V + * @tc.desc: 1. system running normally + * 2. get image type failed + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0033, Function | SmallTest | Level0) +{ + std::unique_ptr imageCompress = std::make_unique(); + EXPECT_NE(imageCompress, nullptr); + if (imageCompress != nullptr) { + std::unique_ptr fileData; + constexpr size_t fileLength = 7; + std::string imageType; + bool res = imageCompress->GetImageTypeString(fileData, fileLength, imageType); + EXPECT_FALSE(res); + } +} + +/** + * @tc.number: DbmsServicesKitTest + * @tc.name: test GetImageFileInfo + * @tc.require: issueI5MZ8V + * @tc.desc: 1. system running normally + * 2. test get image file info failed + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0034, Function | SmallTest | Level0) +{ + std::unique_ptr imageCompress = std::make_unique(); + EXPECT_NE(imageCompress, nullptr); + if (imageCompress != nullptr) { + std::unique_ptr fileContent; + int64_t fileLength; + bool res = imageCompress-> + GetImageFileInfo( + HAP_FILE_PATH, fileContent, fileLength); + EXPECT_EQ(res, false); + } +} + +#ifdef HISYSEVENT_ENABLE +/** + * @tc.number: DbmsServicesKitTest_0035 + * @tc.name: SendSystemEvent + * @tc.desc: Send System Event failed + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0035, Function | SmallTest | Level0) +{ + auto eventReport = GetEventReport(); + EXPECT_NE(eventReport, nullptr); + if (eventReport != nullptr) { + DBMSEventType dbmsEventType = DBMSEventType::UNKNOW; + DBMSEventInfo eventInfo; + eventReport->SendSystemEvent(dbmsEventType, eventInfo); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0036 + * @tc.name: SendSystemEvent + * @tc.desc: Send System Event sucess + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0036, Function | SmallTest | Level0) +{ + auto eventReport = GetEventReport(); + EXPECT_NE(eventReport, nullptr); + if (eventReport != nullptr) { + DBMSEventType dbmsEventType = DBMSEventType::GET_REMOTE_ABILITY_INFO; + DBMSEventInfo eventInfo; + eventInfo.deviceID = "deviceID"; + eventInfo.bundleName = "bundleName"; + eventInfo.localeInfo = "localeInfo"; + eventInfo.abilityName = "abilityName"; + eventInfo.resultCode = 0; + eventReport->SendSystemEvent(dbmsEventType, eventInfo); + } +} +#endif + +/** + * @tc.number: DbmsServicesKitTest_0037 + * @tc.name: GetKvStore + * @tc.desc: Get KvStore + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0037, Function | SmallTest | Level0) +{ + auto distributedDataStorage = GetDistributedDataStorage(); + EXPECT_NE(distributedDataStorage, nullptr); + if (distributedDataStorage != nullptr) { + auto ret = distributedDataStorage->GetKvStore(); + EXPECT_EQ(ret, DistributedKv::Status::SUCCESS); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0038 + * @tc.name: GetLocalUdid + * @tc.desc: Get Local Udid + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0038, Function | SmallTest | Level0) +{ + auto distributedDataStorage = GetDistributedDataStorage(); + EXPECT_NE(distributedDataStorage, nullptr); + if (distributedDataStorage != nullptr) { + std::string udid = "udid"; + auto ret = distributedDataStorage->GetLocalUdid(udid); + EXPECT_EQ(ret, true); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0039 + * @tc.name: GetUdidByNetworkId + * @tc.desc: Get Udid By NetworkId + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0039, Function | SmallTest | Level0) +{ + auto distributedDataStorage = GetDistributedDataStorage(); + EXPECT_NE(distributedDataStorage, nullptr); + if (distributedDataStorage != nullptr) { + std::string networkId = "networkId"; + std::string udid = "udid"; + auto ret = distributedDataStorage->GetUdidByNetworkId(networkId, udid); + EXPECT_EQ(ret, 0); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0040 + * @tc.name: ConvertToDistributedBundleInfo + * @tc.desc: Convert To Distributed BundleInfo + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0040, Function | SmallTest | Level0) +{ + auto distributedDataStorage = GetDistributedDataStorage(); + EXPECT_NE(distributedDataStorage, nullptr); + if (distributedDataStorage != nullptr) { + BundleInfo bundleInfo; + bundleInfo.name = "name"; + AbilityInfo abilityInfo; + abilityInfo.moduleName = "moduleName"; + bundleInfo.abilityInfos.push_back(abilityInfo); + auto ret = distributedDataStorage->ConvertToDistributedBundleInfo(bundleInfo); + EXPECT_EQ(ret.bundleName, "name"); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0041 + * @tc.name: ConvertToDistributedBundleInfo + * @tc.desc: Convert To Distributed BundleInfo + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0041, Function | SmallTest | Level0) +{ + auto distributedDataStorage = GetDistributedDataStorage(); + EXPECT_NE(distributedDataStorage, nullptr); + if (distributedDataStorage != nullptr) { + BundleInfo bundleInfo; + bundleInfo.name = "name"; + AbilityInfo abilityInfo1; + abilityInfo1.moduleName = "moduleName"; + bundleInfo.abilityInfos.push_back(abilityInfo1); + AbilityInfo abilityInfo2; + abilityInfo2.moduleName = "moduleName"; + bundleInfo.abilityInfos.push_back(abilityInfo2); + auto ret = distributedDataStorage->ConvertToDistributedBundleInfo(bundleInfo); + EXPECT_EQ(ret.bundleName, "name"); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0042 + * @tc.name: UpdateDistributedData + * @tc.desc: Update Distributed Data + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0042, Function | SmallTest | Level0) +{ + auto distributedDataStorage = GetDistributedDataStorage(); + EXPECT_NE(distributedDataStorage, nullptr); + if (distributedDataStorage != nullptr) { + int32_t userId = 1; + distributedDataStorage->UpdateDistributedData(userId); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0043 + * @tc.name: CheckKvStore + * @tc.desc: Check KvStore + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0043, Function | SmallTest | Level0) +{ + auto distributedDataStorage = GetDistributedDataStorage(); + EXPECT_NE(distributedDataStorage, nullptr); + if (distributedDataStorage != nullptr) { + auto ret = distributedDataStorage->CheckKvStore(); + EXPECT_EQ(ret, true); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0044 + * @tc.name: DeviceAndNameToKey + * @tc.desc: Device And Name To Key + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0044, Function | SmallTest | Level0) +{ + auto distributedDataStorage = GetDistributedDataStorage(); + EXPECT_NE(distributedDataStorage, nullptr); + if (distributedDataStorage != nullptr) { + std::string udid = "udid"; + std::string bundleName = "bundleName"; + auto ret = distributedDataStorage->DeviceAndNameToKey(udid, bundleName); + EXPECT_EQ(ret, "udid_bundleName"); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0045 + * @tc.name: GetStorageDistributeInfo + * @tc.desc: Get Storage DistributeInfo + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0045, Function | SmallTest | Level0) +{ + auto distributedDataStorage = GetDistributedDataStorage(); + EXPECT_NE(distributedDataStorage, nullptr); + if (distributedDataStorage != nullptr) { + std::string networkId = "networkId"; + std::string bundleName = "bundleName"; + DistributedBundleInfo info; + auto ret = distributedDataStorage->GetStorageDistributeInfo(networkId, bundleName, info); + EXPECT_EQ(ret, false); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0046 + * @tc.name: DeleteStorageDistributeInfo + * @tc.desc: Delete Storage DistributeInfo + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0046, Function | SmallTest | Level0) +{ + auto distributedDataStorage = GetDistributedDataStorage(); + EXPECT_NE(distributedDataStorage, nullptr); + if (distributedDataStorage != nullptr) { + std::string bundleName = "bundleName"; + int32_t userId = 1; + distributedDataStorage->DeleteStorageDistributeInfo(bundleName, userId); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0047 + * @tc.name: InnerSaveStorageDistributeInfo + * @tc.desc: Inner Save Storage DistributeInfo + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0047, Function | SmallTest | Level0) +{ + auto distributedDataStorage = GetDistributedDataStorage(); + EXPECT_NE(distributedDataStorage, nullptr); + if (distributedDataStorage != nullptr) { + DistributedBundleInfo distributedBundleInfo; + distributedBundleInfo.bundleName = "bundleName"; + auto ret = distributedDataStorage->InnerSaveStorageDistributeInfo(distributedBundleInfo); + EXPECT_EQ(ret, true); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0048 + * @tc.name: SaveStorageDistributeInfo + * @tc.desc: Save Storage DistributeInfo + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0048, Function | SmallTest | Level0) +{ + auto distributedDataStorage = GetDistributedDataStorage(); + EXPECT_NE(distributedDataStorage, nullptr); + if (distributedDataStorage != nullptr) { + std::string bundleName = "bundleName"; + int32_t userId = 1; + distributedDataStorage->SaveStorageDistributeInfo(bundleName, userId); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0049 + * @tc.name: OnStart + * @tc.desc: On Start + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0049, Function | SmallTest | Level0) +{ + auto distributedBms = GetSptrDistributedBms(); + EXPECT_NE(distributedBms, nullptr); + if (distributedBms != nullptr) { + distributedBms->OnStart(); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0050 + * @tc.name: OnStop + * @tc.desc: On Stop + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0050, Function | SmallTest | Level0) +{ + auto distributedBms = GetSptrDistributedBms(); + EXPECT_NE(distributedBms, nullptr); + if (distributedBms != nullptr) { + distributedBms->OnStop(); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0051 + * @tc.name: Init + * @tc.desc: Init + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0051, Function | SmallTest | Level0) +{ + auto distributedBms = GetSptrDistributedBms(); + EXPECT_NE(distributedBms, nullptr); + if (distributedBms != nullptr) { + distributedBms->distributedSub_ = nullptr; + distributedBms->Init(); + EXPECT_NE(distributedBms->distributedSub_, nullptr); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0052 + * @tc.name: GetRemoteAbilityInfo + * @tc.desc: Get Remote AbilityInfo + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0052, Function | SmallTest | Level0) +{ + auto distributedBms = GetDistributedBms(); + EXPECT_NE(distributedBms, nullptr); + if (distributedBms != nullptr) { + OHOS::AppExecFwk::ElementName elementName; + elementName.SetDeviceID(""); + std::string localeInfo = LOCALE_INFO; + RemoteAbilityInfo remoteAbilityInfo; + auto ret = distributedBms->GetRemoteAbilityInfo(elementName, localeInfo, remoteAbilityInfo); + EXPECT_EQ(ret, ERR_BUNDLE_MANAGER_DEVICE_ID_NOT_EXIST); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0053 + * @tc.name: test IsPathValid + * @tc.desc: 1. system running normally + * 2. The test path is valid + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0053, Function | SmallTest | Level0) +{ + std::unique_ptr imageCompress = std::make_unique(); + EXPECT_NE(imageCompress, nullptr); + if (imageCompress != nullptr) { + bool res = imageCompress->IsPathValid(PATH_LOCATION); + EXPECT_EQ(res, true); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0054 + * @tc.name: test IsPathValid + * @tc.desc: 1. system running normally + * 2. Invalid test path (parameter is "") + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0054, Function | SmallTest | Level0) +{ + std::unique_ptr imageCompress = std::make_unique(); + EXPECT_NE(imageCompress, nullptr); + if (imageCompress != nullptr) { + bool res = imageCompress->IsPathValid(""); + EXPECT_EQ(res, false); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0055 + * @tc.name: test IsPathValid + * @tc.desc: 1. system running normally + * 2. Invalid test path (parameter is "null") + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0055, Function | SmallTest | Level0) +{ + std::unique_ptr imageCompress = std::make_unique(); + EXPECT_NE(imageCompress, nullptr); + if (imageCompress != nullptr) { + bool res = imageCompress->IsPathValid("null"); + EXPECT_EQ(res, false); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0056 + * @tc.name: test IsPathValid + * @tc.desc: 1. system running normally + * 2. Invalid test path (parameter is "/data/data11") + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0056, Function | SmallTest | Level0) +{ + std::unique_ptr imageCompress = std::make_unique(); + EXPECT_NE(imageCompress, nullptr); + if (imageCompress != nullptr) { + bool res = imageCompress->IsPathValid("/data/data11"); + EXPECT_EQ(res, false); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0057 + * @tc.name: test CalculateRatio + * @tc.desc: 1. system running normally + * 2. test CalculateRatio + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0057, Function | SmallTest | Level0) +{ + std::unique_ptr imageCompress = std::make_unique(); + EXPECT_NE(imageCompress, nullptr); + if (imageCompress != nullptr) { + constexpr size_t filesize = 2; + double res = imageCompress->CalculateRatio(filesize, "image/webp"); + EXPECT_EQ(res, 8); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0058 + * @tc.name: test CalculateRatio + * @tc.desc: 1. system running normally + * 2. test CalculateRatio (Invalid imageType parameter is "image") + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0058, Function | SmallTest | Level0) +{ + std::unique_ptr imageCompress = std::make_unique(); + EXPECT_NE(imageCompress, nullptr); + if (imageCompress != nullptr) { + constexpr size_t filesize = 1; + double res = imageCompress->CalculateRatio(filesize, "image"); + EXPECT_EQ(res, 64); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0059 + * @tc.name: test CalculateRatio + * @tc.desc: 1. system running normally + * 2. test CalculateRatio (Invalid imageType parameter is "/") + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0059, Function | SmallTest | Level0) +{ + std::unique_ptr imageCompress = std::make_unique(); + EXPECT_NE(imageCompress, nullptr); + if (imageCompress != nullptr) { + constexpr size_t filesize = 4; + double res = imageCompress->CalculateRatio(filesize, "/"); + EXPECT_EQ(res, 32); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0060 + * @tc.name: test IsImageNeedCompressBySize + * @tc.desc: 1. system running normally + * 2. test IsImageNeedCompressBySize (parameters are 10241) + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0060, Function | SmallTest | Level0) +{ + std::unique_ptr imageCompress = std::make_unique(); + EXPECT_NE(imageCompress, nullptr); + if (imageCompress != nullptr) { + constexpr size_t fileSize = 10241; + bool res = imageCompress->IsImageNeedCompressBySize(fileSize); + EXPECT_EQ(res, true); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0061 + * @tc.name: test IsImageNeedCompressBySize + * @tc.desc: 1. system running normally + * 2. test IsImageNeedCompressBySize (parameters are 10239) + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0061, Function | SmallTest | Level0) +{ + std::unique_ptr imageCompress = std::make_unique(); + EXPECT_NE(imageCompress, nullptr); + if (imageCompress != nullptr) { + constexpr size_t fileSize = 10239; + bool res = imageCompress->IsImageNeedCompressBySize(fileSize); + EXPECT_EQ(res, false); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0062 + * @tc.name: test GetImageType + * @tc.desc: 1. system running normally + * 2. test Get Image Type (The fileData parameter is valid) + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0062, Function | SmallTest | Level0) +{ + std::unique_ptr imageCompress = std::make_unique(); + EXPECT_NE(imageCompress, nullptr); + if (imageCompress != nullptr) { + constexpr size_t fileLength = 64; + std::unique_ptr fileData = std::make_unique(fileLength); + uint8_t *data = fileData.get(); + data[0] = 0xFF; + data[1] = 0xD8; + data[2] = 0xFF; + ImageType res = imageCompress->GetImageType(fileData, fileLength); + EXPECT_EQ(res, ImageType::JPEG); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0063 + * @tc.name: test GetImageType + * @tc.desc: 1. system running normally + * 2. test Get Image Type (The fileData parameter is invalid) + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0063, Function | SmallTest | Level0) +{ + std::unique_ptr imageCompress = std::make_unique(); + EXPECT_NE(imageCompress, nullptr); + if (imageCompress != nullptr) { + constexpr size_t fileLength = 64; + std::unique_ptr fileData = std::make_unique(fileLength); + uint8_t *data = fileData.get(); + data[0] = 0xFF; + data[1] = 0xD8; + ImageType res = imageCompress->GetImageType(fileData, fileLength); + EXPECT_EQ(res, ImageType::WORNG_TYPE); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0064 + * @tc.name: test GetImageType + * @tc.desc: 1. system running normally + * 2. test Get Image Type (The fileData parameter is valid) + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0064, Function | SmallTest | Level0) +{ + std::unique_ptr imageCompress = std::make_unique(); + EXPECT_NE(imageCompress, nullptr); + if (imageCompress != nullptr) { + constexpr size_t fileLength = 64; + std::unique_ptr fileData = std::make_unique(fileLength); + uint8_t *data = fileData.get(); + data[0] = 0x89; + data[1] = 0x50; + data[2] = 0x4E; + data[3] = 0x47; + ImageType res = imageCompress->GetImageType(fileData, fileLength); + EXPECT_EQ(res, ImageType::PNG); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0065 + * @tc.name: test GetImageType + * @tc.desc: 1. system running normally + * 2. test Get Image Type (The fileData parameter is invalid) + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0065, Function | SmallTest | Level0) +{ + std::unique_ptr imageCompress = std::make_unique(); + EXPECT_NE(imageCompress, nullptr); + if (imageCompress != nullptr) { + constexpr size_t fileLength = 64; + std::unique_ptr fileData = std::make_unique(fileLength); + uint8_t *data = fileData.get(); + data[0] = 0x89; + data[1] = 0x50; + data[2] = 0x4E; + ImageType res = imageCompress->GetImageType(fileData, fileLength); + EXPECT_EQ(res, ImageType::WORNG_TYPE); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0066 + * @tc.name: test GetImageFileInfo + * @tc.desc: 1. system running normally + * 2. test Get Image File Info (The srcFile parameter is invalid) + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0066, Function | SmallTest | Level0) +{ + std::unique_ptr imageCompress = std::make_unique(); + EXPECT_NE(imageCompress, nullptr); + if (imageCompress != nullptr) { + std::unique_ptr fileContent; + int64_t fileLength; + bool res = imageCompress->GetImageFileInfo(PATH_LOCATION, fileContent, fileLength); + EXPECT_EQ(res, false); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0067 + * @tc.name: test GetImageFileInfo + * @tc.desc: 1. system running normally + * 2. test Get Image File Info (The srcFile parameter is valid) + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0067, Function | SmallTest | Level0) +{ + std::unique_ptr imageCompress = std::make_unique(); + EXPECT_NE(imageCompress, nullptr); + std::fstream fs; + fs.open(PATH_LOCATIONS, std::ios_base::app); + fs.close(); + std::ofstream ofs; + ofs.open(PATH_LOCATIONS, std::ios::out|std::ios::app); + ofs << "test" << " "; + ofs.close(); + if (imageCompress != nullptr) { + int64_t fileLength = 64; + std::unique_ptr fileContent = std::make_unique(fileLength); + bool res = imageCompress->GetImageFileInfo(PATH_LOCATIONS, fileContent, fileLength); + EXPECT_EQ(res, true); + } + std::string savePath = PATH_LOCATIONS; + EXPECT_EQ(remove(savePath.c_str()), 0); +} + +/** + * @tc.number: DbmsServicesKitTest_0068 + * @tc.name: test GetImageFileInfo + * @tc.desc: 1. system running normally + * 2. test CompressImageByContent (The fileData parameter is invalid) + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0068, Function | SmallTest | Level0) +{ + std::unique_ptr imageCompress = std::make_unique(); + EXPECT_NE(imageCompress, nullptr); + if (imageCompress != nullptr) { + std::unique_ptr fileData; + std::unique_ptr compressedData; + constexpr size_t fileSize = 7; + int64_t compressedSize = 2; + std::string imageType = "image/jpeg"; + bool res = imageCompress->CompressImageByContent(fileData, fileSize, compressedData, compressedSize, imageType); + EXPECT_EQ(res, false); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0069 + * @tc.name: test GetImageFileInfo + * @tc.desc: 1. system running normally + * 2. test CompressImageByContent (The fileData parameter is valid) + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0069, Function | SmallTest | Level0) +{ + std::unique_ptr imageCompress = std::make_unique(); + EXPECT_NE(imageCompress, nullptr); + if (imageCompress != nullptr) { + std::unique_ptr fileData = std::make_unique(100); + uint8_t *data = fileData.get(); + data[0] = 0xFF; + data[1] = 0xD8; + data[2] = 0xFF; + std::unique_ptr compressedData = std::make_unique(100); + constexpr size_t fileSize = 8; + int64_t compressedSize = 2; + std::string imageType = "image/jpeg"; + bool res = imageCompress->CompressImageByContent(fileData, fileSize, compressedData, compressedSize, imageType); + EXPECT_EQ(res, false); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0070 + * @tc.name: test CheckElementName + * @tc.desc: 1. system running normally + * 2. test CheckElementName + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0070, Function | SmallTest | Level0) +{ + auto distributedBmsProxy = GetDistributedBmsProxy(); + EXPECT_NE(distributedBmsProxy, nullptr); + if (distributedBmsProxy != nullptr) { + ElementName name; + name.SetBundleName(BUNDLE_NAME); + name.SetAbilityName(WRONG_ABILITY_NAME); + name.SetDeviceID(DEVICE_ID); + auto ret = distributedBmsProxy->CheckElementName(name); + EXPECT_EQ(ret, ERR_OK); + } +} + +/** + * @tc.number: DbmsServicesKitTest_0071 + * @tc.name: test GetAbilityInfo + * @tc.desc: 1. system running normally + * 2. test bundleName empty + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0071, Function | SmallTest | Level0) +{ + auto distributedBmsProxy = GetDistributedBmsProxy(); + EXPECT_NE(distributedBmsProxy, nullptr); + if (distributedBmsProxy != nullptr) { + ElementName name; + RemoteAbilityInfo info; + auto ret = distributedBmsProxy->GetRemoteAbilityInfo(name, info); + EXPECT_EQ(ret, ERR_BUNDLE_MANAGER_BUNDLE_NOT_EXIST); + } +} + +/** +* @tc.number: DbmsServicesKitTest_0072 +* @tc.name: GetRemoteAbilityInfo +* @tc.desc: Get Remote AbilityInfo +*/ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0072, Function | SmallTest | Level0) +{ + auto distributedBms = GetDistributedBms(); + EXPECT_NE(distributedBms, nullptr); + if (distributedBms != nullptr) { + OHOS::AppExecFwk::ElementName elementName; + std::string deviceId = DEVICE_ID_NORMAL; + elementName.SetDeviceID(deviceId); + std::string localeInfo = LOCALE_INFO; + RemoteAbilityInfo remoteAbilityInfo; + auto ret = distributedBms->GetRemoteAbilityInfo(elementName, localeInfo, remoteAbilityInfo); + EXPECT_EQ(ret, ERR_BUNDLE_MANAGER_DEVICE_ID_NOT_EXIST); + } +} + +/** +* @tc.number: DbmsServicesKitTest_0073 +* @tc.name: test GetRemoteAbilityInfos +* @tc.desc: Get Remote AbilityInfos +*/ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0073, Function | SmallTest | Level0) +{ + auto distributedBms = GetDistributedBms(); + EXPECT_NE(distributedBms, nullptr); + if (distributedBms != nullptr) { + std::vector names; + ElementName name; + name.SetBundleName(BUNDLE_NAME); + name.SetAbilityName(ABILITY_NAME); + name.SetDeviceID(EMPTY_STRING); + names.push_back(name); + std::vector info; + auto ret = distributedBms->GetRemoteAbilityInfos(names, EMPTY_STRING, info); + EXPECT_EQ(ret, ERR_BUNDLE_MANAGER_DEVICE_ID_NOT_EXIST); + } +} + +/** +* @tc.number: DbmsServicesKitTest_0074 +* @tc.name: test GetRemoteAbilityInfos +* @tc.desc: Get Remote AbilityInfos +*/ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0074, Function | SmallTest | Level0) +{ + auto distributedBms = GetDistributedBms(); + EXPECT_NE(distributedBms, nullptr); + if (distributedBms != nullptr) { + std::vector names; + ElementName name; + name.SetBundleName(BUNDLE_NAME); + name.SetAbilityName(ABILITY_NAME); + name.SetDeviceID(DEVICE_ID); + names.push_back(name); + std::vector info; + auto ret = distributedBms->GetRemoteAbilityInfos(names, EMPTY_STRING, info); + EXPECT_EQ(ret, ERR_BUNDLE_MANAGER_DEVICE_ID_NOT_EXIST); + } +} + + +/** + * @tc.number: DbmsServicesKitTest + * @tc.name: test GetDistributedBundleName + * @tc.desc: 1. get distributed bundle name by networkId and accessTokenId + */ +HWTEST_F(DbmsServicesKitTest, DbmsServicesKitTest_0075, Function | SmallTest | Level0) +{ + auto distributedBmsProxy = GetDistributedBmsProxy(); + std::string bundleName; + EXPECT_NE(distributedBmsProxy, nullptr); + if (distributedBmsProxy != nullptr) { + DistributedBundleInfo distributedBundleInfo; + int32_t ret = distributedBmsProxy->GetDistributedBundleName("", 0, bundleName); + EXPECT_EQ(ret, ERR_APPEXECFWK_FAILED_GET_REMOTE_PROXY); + } +} + +} // OHOS \ No newline at end of file diff --git a/services/dbms/test/unittest/distributed_bms_host_test/BUILD.gn b/services/dbms/test/unittest/distributed_bms_host_test/BUILD.gn new file mode 100644 index 0000000..76bb0cb --- /dev/null +++ b/services/dbms/test/unittest/distributed_bms_host_test/BUILD.gn @@ -0,0 +1,75 @@ +# Copyright (c) 2023 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/test.gni") +import("../../../../../dbms.gni") + +module_output_path = "bundle_framework/distributedbundleservice" + +ohos_unittest("DistributedBmsHostTest") { + use_exceptions = true + module_out_path = module_output_path + include_dirs = [ "${dbms_services_path}/include" ] + + sources = [ "${dbms_services_path}/src/distributed_bms_host.cpp" ] + + sources += [ + "distributed_bms_host_test.cpp", + "mock_distributed_bms_interface.cpp", + ] + + deps = [ + "${common_path}:libappexecfwk_common", + "${dbms_inner_api_path}:dbms_fwk", + "//third_party/googletest:gmock_main", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "ability_base:want", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "hicollie_native:libhicollie", + "hiviewdfx_hilog_native:libhilog", + "i18n:intl_util", + "init:libbegetutil", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "multimedia_image_framework:image_native", + "resource_management:global_resmgr", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + defines = [] + + if (hisysevent_enable_dbms) { + sources += [ "${dbms_services_path}/src/event_report.cpp" ] + external_deps += [ "hisysevent_native:libhisysevent" ] + defines += [ "HISYSEVENT_ENABLE" ] + } + + if (account_enable_dbms) { + external_deps += [ "os_account:os_account_innerkits" ] + defines += [ "ACCOUNT_ENABLE" ] + } +} + +group("unittest") { + testonly = true + if (ability_runtime_enable_dbms) { + deps = [ ":DistributedBmsHostTest" ] + } +} diff --git a/services/dbms/test/unittest/distributed_bms_host_test/distributed_bms_host_test.cpp b/services/dbms/test/unittest/distributed_bms_host_test/distributed_bms_host_test.cpp new file mode 100644 index 0000000..8483911 --- /dev/null +++ b/services/dbms/test/unittest/distributed_bms_host_test/distributed_bms_host_test.cpp @@ -0,0 +1,752 @@ +/* + * Copyright (c) 2023 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 +#define private public +#include "distributed_bms_host.h" + +#include "appexecfwk_errors.h" +#include "distributed_bms_proxy.h" +#undef private +#include "mock_distributed_bms_interface.h" + +using namespace testing::ext; +using namespace OHOS::AppExecFwk; + +namespace OHOS { +class DistributedBmsHostTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp() override; + void TearDown() override; +}; + +void DistributedBmsHostTest::SetUpTestCase() +{} + +void DistributedBmsHostTest::TearDownTestCase() +{} + +void DistributedBmsHostTest::SetUp() +{} + +void DistributedBmsHostTest::TearDown() +{} + +/** + * @tc.number: OnRemoteRequest_0100 + * @tc.name: Test OnRemoteRequest + * @tc.desc: Verify the OnRemoteRequest return NO_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, OnRemoteRequest_0100, Function | MediumTest | Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + MockDistributedBmsHost host; + int res = host.OnRemoteRequest(static_cast + (IDistributedBms::Message::GET_REMOTE_ABILITY_INFO), data, reply, option); + EXPECT_EQ(res, ERR_INVALID_STATE); +} + +/** + * @tc.number: OnRemoteRequest_0200 + * @tc.name: Test OnRemoteRequest + * @tc.desc: Verify the OnRemoteRequest return NO_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, OnRemoteRequest_0200, Function | MediumTest | Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + data.WriteInterfaceToken(DistributedBmsHost::GetDescriptor()); + AppExecFwk::ElementName elementName; + data.WriteParcelable(&elementName); + MockDistributedBmsHost host; + int res = host.OnRemoteRequest(static_cast(IDistributedBms::Message::GET_REMOTE_ABILITY_INFO), + data, reply, option); + EXPECT_EQ(res, NO_ERROR); +} + +/** + * @tc.number: OnRemoteRequest_0300 + * @tc.name: Test OnRemoteRequest + * @tc.desc: Verify the OnRemoteRequest return NO_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, OnRemoteRequest_0300, Function | MediumTest | Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + data.WriteInterfaceToken(DistributedBmsHost::GetDescriptor()); + AppExecFwk::ElementName elementName; + data.WriteParcelable(&elementName); + MockDistributedBmsHost host; + int res = host.OnRemoteRequest(static_cast(IDistributedBms::Message::GET_REMOTE_ABILITY_INFO_WITH_LOCALE), + data, reply, option); + EXPECT_EQ(res, NO_ERROR); +} + +/** + * @tc.number: OnRemoteRequest_0400 + * @tc.name: Test OnRemoteRequest + * @tc.desc: Verify the OnRemoteRequest return NO_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, OnRemoteRequest_0400, Function | MediumTest | Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + data.WriteInterfaceToken(DistributedBmsHost::GetDescriptor()); + std::vector elementNames; + std::string localeInfo; + DistributedBmsProxy proxy(nullptr); + proxy.WriteParcelableVector(elementNames, data); + data.WriteString(localeInfo); + MockDistributedBmsHost host; + int res = host.OnRemoteRequest(static_cast + (IDistributedBms::Message::GET_REMOTE_ABILITY_INFOS), data, reply, option); + EXPECT_EQ(res, NO_ERROR); +} + +/** + * @tc.number: OnRemoteRequest_0500 + * @tc.name: Test OnRemoteRequest + * @tc.desc: Verify the OnRemoteRequest return NO_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, OnRemoteRequest_0500, Function | MediumTest | Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + data.WriteInterfaceToken(DistributedBmsHost::GetDescriptor()); + std::vector elementNames; + std::string localeInfo; + DistributedBmsProxy proxy(nullptr); + proxy.WriteParcelableVector(elementNames, data); + data.WriteString(localeInfo); + MockDistributedBmsHost host; + int res = host.OnRemoteRequest(static_cast + (IDistributedBms::Message::GET_REMOTE_ABILITY_INFOS_WITH_LOCALE), data, reply, option); + EXPECT_EQ(res, NO_ERROR); +} + +/** + * @tc.number: OnRemoteRequest_0600 + * @tc.name: Test OnRemoteRequest + * @tc.desc: Verify the OnRemoteRequest return NO_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, OnRemoteRequest_0600, Function | MediumTest | Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + data.WriteInterfaceToken(DistributedBmsHost::GetDescriptor()); + std::vector elementNames; + std::string localeInfo; + DistributedBmsProxy proxy(nullptr); + proxy.WriteParcelableVector(elementNames, data); + data.WriteString(localeInfo); + MockDistributedBmsHost host; + int res = host.OnRemoteRequest(static_cast + (IDistributedBms::Message::GET_REMOTE_ABILITY_INFOS_WITH_LOCALE), data, reply, option); + EXPECT_EQ(res, NO_ERROR); +} + +/** + * @tc.number: OnRemoteRequest_0700 + * @tc.name: Test OnRemoteRequest + * @tc.desc: Verify the OnRemoteRequest return NO_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, OnRemoteRequest_0700, Function | MediumTest | Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + data.WriteInterfaceToken(DistributedBmsHost::GetDescriptor()); + ElementName elementName; + std::string localeInfo; + data.WriteParcelable(&elementName); + data.WriteString(localeInfo); + MockDistributedBmsHost host; + int res = host.OnRemoteRequest(static_cast + (IDistributedBms::Message::GET_ABILITY_INFO), data, reply, option); + EXPECT_EQ(res, NO_ERROR); +} + +/** + * @tc.number: OnRemoteRequest_0800 + * @tc.name: Test OnRemoteRequest + * @tc.desc: Verify the OnRemoteRequest return NO_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, OnRemoteRequest_0800, Function | MediumTest | Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + data.WriteInterfaceToken(DistributedBmsHost::GetDescriptor()); + ElementName elementName; + std::string localeInfo; + data.WriteParcelable(&elementName); + data.WriteString(localeInfo); + + MockDistributedBmsHost host; + int res = host.OnRemoteRequest(static_cast + (IDistributedBms::Message::GET_ABILITY_INFO_WITH_LOCALE), data, reply, option); + EXPECT_EQ(res, NO_ERROR); +} + +/** + * @tc.number: OnRemoteRequest_0900 + * @tc.name: Test OnRemoteRequest + * @tc.desc: Verify the OnRemoteRequest return NO_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, OnRemoteRequest_0900, Function | MediumTest | Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + data.WriteInterfaceToken(DistributedBmsHost::GetDescriptor()); + std::vector elementNames; + std::string localeInfo; + DistributedBmsProxy proxy(nullptr); + proxy.WriteParcelableVector(elementNames, data); + data.WriteString(localeInfo); + + MockDistributedBmsHost host; + int res = host.OnRemoteRequest(static_cast + (IDistributedBms::Message::GET_ABILITY_INFOS), data, reply, option); + EXPECT_EQ(res, NO_ERROR); +} + +/** + * @tc.number: OnRemoteRequest_1000 + * @tc.name: Test OnRemoteRequest + * @tc.desc: Verify the OnRemoteRequest return NO_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, OnRemoteRequest_1000, Function | MediumTest | Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + data.WriteInterfaceToken(DistributedBmsHost::GetDescriptor()); + std::vector elementNames; + std::string localeInfo; + DistributedBmsProxy proxy(nullptr); + proxy.WriteParcelableVector(elementNames, data); + data.WriteString(localeInfo); + + MockDistributedBmsHost host; + int res = host.OnRemoteRequest(static_cast + (IDistributedBms::Message::GET_ABILITY_INFOS_WITH_LOCALE), data, reply, option); + EXPECT_EQ(res, NO_ERROR); +} + +/** + * @tc.number: OnRemoteRequest_1100 + * @tc.name: Test OnRemoteRequest + * @tc.desc: Verify the OnRemoteRequest return NO_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, OnRemoteRequest_1100, Function | MediumTest | Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + data.WriteInterfaceToken(DistributedBmsHost::GetDescriptor()); + + std::string networkId; + std::string bundleName; + data.WriteString(networkId); + data.WriteString(bundleName); + + MockDistributedBmsHost host; + int res = host.OnRemoteRequest(static_cast + (IDistributedBms::Message::GET_DISTRIBUTED_BUNDLE_INFO), data, reply, option); + EXPECT_EQ(res, NO_ERROR); +} + +/** + * @tc.number: OnRemoteRequest_1200 + * @tc.name: Test OnRemoteRequest + * @tc.desc: Verify the OnRemoteRequest return IPC_STUB_UNKNOW_TRANS_ERR. + */ +HWTEST_F(DistributedBmsHostTest, OnRemoteRequest_1200, Function | MediumTest | Level1) +{ + MessageParcel data; + MessageParcel reply; + MessageOption option; + + data.WriteInterfaceToken(DistributedBmsHost::GetDescriptor()); + + std::string networkId; + std::string bundleName; + data.WriteString(networkId); + data.WriteString(bundleName); + + MockDistributedBmsHost host; + int res = host.OnRemoteRequest(static_cast(-1), data, reply, option); + EXPECT_EQ(res, IPC_STUB_UNKNOW_TRANS_ERR); +} + +/** + * @tc.number: HandleGetRemoteAbilityInfo_0100 + * @tc.name: Test HandleGetRemoteAbilityInfo + * @tc.desc: Verify the HandleGetRemoteAbilityInfo return NO_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, HandleGetRemoteAbilityInfo_0100, Function | MediumTest | Level1) +{ + Parcel data; + Parcel reply; + ElementName elementName; + elementName.SetBundleName("bundleName"); + data.WriteParcelable(&elementName); + std::string localeInfo = "localeInfo"; + data.WriteString(localeInfo); + MockDistributedBmsHost host; + int res = host.HandleGetRemoteAbilityInfo(data, reply); + EXPECT_EQ(res, NO_ERROR); +} + +/** + * @tc.number: HandleGetRemoteAbilityInfo_0200 + * @tc.name: Test HandleGetRemoteAbilityInfo + * @tc.desc: Verify the HandleGetRemoteAbilityInfo return ERR_APPEXECFWK_PARCEL_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, HandleGetRemoteAbilityInfo_0200, Function | MediumTest | Level1) +{ + Parcel data; + Parcel reply; + MockDistributedBmsHost host; + int res = host.HandleGetRemoteAbilityInfo(data, reply); + EXPECT_EQ(res, ERR_APPEXECFWK_PARCEL_ERROR); +} + +/** + * @tc.number: HandleGetRemoteAbilityInfo_0300 + * @tc.name: Test HandleGetRemoteAbilityInfo + * @tc.desc: Verify the HandleGetRemoteAbilityInfo return NO_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, HandleGetRemoteAbilityInfo_0300, Function | MediumTest | Level1) +{ + Parcel data; + Parcel reply; + MockDistributedBmsHost host; + ElementName elementName; + elementName.SetBundleName(""); + data.WriteParcelable(&elementName); + int res = host.HandleGetRemoteAbilityInfo(data, reply); + EXPECT_EQ(res, NO_ERROR); +} + +/** + * @tc.number: HandleGetRemoteAbilityInfo_0400 + * @tc.name: Test HandleGetRemoteAbilityInfo + * @tc.desc: Verify the HandleGetRemoteAbilityInfo return ERR_APPEXECFWK_PARCEL_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, HandleGetRemoteAbilityInfo_0400, Function | MediumTest | Level1) +{ + Parcel data; + Parcel reply; + MockDistributedBmsHost host; + ElementName elementName; + elementName.SetBundleName("bundleName"); + data.WriteParcelable(&elementName); + int res = host.HandleGetRemoteAbilityInfo(data, reply); + EXPECT_EQ(res, NO_ERROR); +} + +/** + * @tc.number: HandleGetRemoteAbilityInfos_0100 + * @tc.name: Test HandleGetRemoteAbilityInfos + * @tc.desc: Verify the HandleGetRemoteAbilityInfos return ERR_APPEXECFWK_PARCEL_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, HandleGetRemoteAbilityInfos_0100, Function | MediumTest | Level1) +{ + Parcel data; + Parcel reply; + MockDistributedBmsHost host; + std::vector elementNames; + std::string localeInfo; + DistributedBmsProxy proxy(nullptr); + data.WriteString(localeInfo); + proxy.WriteParcelableVector(elementNames, data); + int res = host.HandleGetRemoteAbilityInfos(data, reply); + EXPECT_EQ(res, NO_ERROR); +} + +/** + * @tc.number: HandleGetRemoteAbilityInfos_0200 + * @tc.name: Test HandleGetRemoteAbilityInfos + * @tc.desc: Verify the HandleGetRemoteAbilityInfos return NO_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, HandleGetRemoteAbilityInfos_0200, Function | MediumTest | Level1) +{ + Parcel data; + Parcel reply; + MockDistributedBmsHost host; + int res = host.HandleGetRemoteAbilityInfos(data, reply); + EXPECT_EQ(res, NO_ERROR); +} + +/** + * @tc.number: HandleGetRemoteAbilityInfos_0300 + * @tc.name: Test HandleGetRemoteAbilityInfos + * @tc.desc: Verify the HandleGetRemoteAbilityInfos return NO_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, HandleGetRemoteAbilityInfos_0300, Function | MediumTest | Level1) +{ + Parcel data; + Parcel reply; + MockDistributedBmsHost host; + std::vector elementNames; + DistributedBmsProxy proxy(nullptr); + proxy.WriteParcelableVector(elementNames, data); + int res = host.HandleGetRemoteAbilityInfos(data, reply); + EXPECT_EQ(res, NO_ERROR); +} + +/** + * @tc.number: HandleGetAbilityInfo_0100 + * @tc.name: Test HandleGetAbilityInfo + * @tc.desc: Verify the HandleGetAbilityInfo return NO_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, HandleGetAbilityInfo_0100, Function | MediumTest | Level1) +{ + Parcel data; + Parcel reply; + MockDistributedBmsHost host; + ElementName elementName; + elementName.SetBundleName("bundleName"); + data.WriteParcelable(&elementName); + int res = host.HandleGetAbilityInfo(data, reply); + EXPECT_EQ(res, NO_ERROR); +} + +/** + * @tc.number: HandleGetAbilityInfo_0200 + * @tc.name: Test HandleGetAbilityInfo + * @tc.desc: Verify the HandleGetAbilityInfo return NO_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, HandleGetAbilityInfo_0200, Function | MediumTest | Level1) +{ + Parcel data; + Parcel reply; + MockDistributedBmsHost host; + ElementName elementName; + elementName.SetBundleName("bundleName"); + data.WriteParcelable(&elementName); + std::string localeInfo = "localeInfo"; + data.WriteString(localeInfo); + int res = host.HandleGetAbilityInfo(data, reply); + EXPECT_EQ(res, NO_ERROR); +} + +/** + * @tc.number: HandleGetAbilityInfo_0300 + * @tc.name: Test HandleGetAbilityInfo + * @tc.desc: Verify the HandleGetAbilityInfo return ERR_APPEXECFWK_PARCEL_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, HandleGetAbilityInfo_0300, Function | MediumTest | Level1) +{ + Parcel data; + Parcel reply; + MockDistributedBmsHost host; + int res = host.HandleGetAbilityInfo(data, reply); + EXPECT_EQ(res, ERR_APPEXECFWK_PARCEL_ERROR); +} + +/** + * @tc.number: HandleGetAbilityInfo_0400 + * @tc.name: Test HandleGetAbilityInfo + * @tc.desc: Verify the HandleGetAbilityInfo return ERR_APPEXECFWK_PARCEL_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, HandleGetAbilityInfo_0400, Function | MediumTest | Level1) +{ + Parcel data; + Parcel reply; + MockDistributedBmsHost host; + std::string localeInfo = "localeInfo"; + data.WriteString(localeInfo); + int res = host.HandleGetAbilityInfo(data, reply); + EXPECT_EQ(res, NO_ERROR); +} + +/** + * @tc.number: HandleGetAbilityInfos_0100 + * @tc.name: Test HandleGetAbilityInfos + * @tc.desc: Verify the HandleGetAbilityInfo return NO_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, HandleGetAbilityInfos_0100, Function | MediumTest | Level1) +{ + Parcel data; + Parcel reply; + MockDistributedBmsHost host; + ElementName elementName; + elementName.SetBundleName("elementName"); + std::vector elementNames; + elementNames.emplace_back(elementName); + std::string localeInfo = "localeInfo"; + DistributedBmsProxy proxy(nullptr); + data.WriteString(localeInfo); + proxy.WriteParcelableVector(elementNames, data); + int res = host.HandleGetAbilityInfos(data, reply); + EXPECT_EQ(res, ERR_APPEXECFWK_PARCEL_ERROR); +} + +/** + * @tc.number: HandleGetAbilityInfos_0200 + * @tc.name: Test HandleGetAbilityInfos + * @tc.desc: Verify the HandleGetAbilityInfo return NO_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, HandleGetAbilityInfos_0200, Function | MediumTest | Level1) +{ + Parcel data; + Parcel reply; + MockDistributedBmsHost host; + std::string localeInfo = "localeInfo"; + DistributedBmsProxy proxy(nullptr); + data.WriteString(localeInfo); + int res = host.HandleGetAbilityInfos(data, reply); + EXPECT_EQ(res, ERR_APPEXECFWK_PARCEL_ERROR); +} + +/** + * @tc.number: HandleGetAbilityInfos_0300 + * @tc.name: Test HandleGetAbilityInfos + * @tc.desc: Verify the HandleGetAbilityInfo return NO_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, HandleGetAbilityInfos_0300, Function | MediumTest | Level1) +{ + Parcel data; + Parcel reply; + MockDistributedBmsHost host; + ElementName elementName; + elementName.SetBundleName("elementName"); + std::vector elementNames; + elementNames.emplace_back(elementName); + DistributedBmsProxy proxy(nullptr); + proxy.WriteParcelableVector(elementNames, data); + int res = host.HandleGetAbilityInfos(data, reply); + EXPECT_EQ(res, NO_ERROR); +} + +/** + * @tc.number: HandleGetAbilityInfos_0400 + * @tc.name: Test HandleGetAbilityInfos + * @tc.desc: Verify the HandleGetAbilityInfo return ERR_APPEXECFWK_PARCEL_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, HandleGetAbilityInfos_0400, Function | MediumTest | Level1) +{ + Parcel data; + Parcel reply; + MockDistributedBmsHost host; + int res = host.HandleGetAbilityInfos(data, reply); + EXPECT_EQ(res, NO_ERROR); +} + +/** + * @tc.number: HandleGetDistributedBundleInfo_0100 + * @tc.name: Test HandleGetDistributedBundleInfo + * @tc.desc: Verify the HandleGetDistributedBundleInfo return NO_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, HandleGetDistributedBundleInfo_0100, Function | MediumTest | Level1) +{ + Parcel data; + Parcel reply; + MockDistributedBmsHost host; + std::string networkId = "networkId"; + std::string bundleName = "bundleName"; + data.WriteString(networkId); + data.WriteString(bundleName); + int res = host.HandleGetDistributedBundleInfo(data, reply); + EXPECT_EQ(res, NO_ERROR); +} + +/** + * @tc.number: HandleGetDistributedBundleInfo_0200 + * @tc.name: Test HandleGetDistributedBundleInfo + * @tc.desc: Verify the HandleGetDistributedBundleInfo return NO_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, HandleGetDistributedBundleInfo_0200, Function | MediumTest | Level1) +{ + Parcel data; + Parcel reply; + MockDistributedBmsHost host; + std::string networkId = "networkId"; + data.WriteString(networkId); + int res = host.HandleGetDistributedBundleInfo(data, reply); + EXPECT_EQ(res, NO_ERROR); +} + +/** + * @tc.number: HandleGetDistributedBundleInfo_0300 + * @tc.name: Test HandleGetDistributedBundleInfo + * @tc.desc: Verify the HandleGetDistributedBundleInfo return NO_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, HandleGetDistributedBundleInfo_0300, Function | MediumTest | Level1) +{ + Parcel data; + Parcel reply; + MockDistributedBmsHost host; + std::string bundleName = "bundleName"; + data.WriteString(bundleName); + int res = host.HandleGetDistributedBundleInfo(data, reply); + EXPECT_EQ(res, NO_ERROR); +} + +/** + * @tc.number: HandleGetDistributedBundleInfo_0400 + * @tc.name: Test HandleGetDistributedBundleInfo + * @tc.desc: Verify the HandleGetDistributedBundleInfo return INVALID_OPERATION. + */ +HWTEST_F(DistributedBmsHostTest, HandleGetDistributedBundleInfo_0400, Function | MediumTest | Level1) +{ + Parcel data; + Parcel reply; + MockDistributedBmsHost host; + int res = host.HandleGetDistributedBundleInfo(data, reply); + EXPECT_EQ(res, NO_ERROR); +} + +/** + * @tc.number: HandleGetDistributedBundleName_0100 + * @tc.name: Test HandleGetDistributedBundleName + * @tc.desc: Verify the HandleGetDistributedBundleName return NO_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, HandleGetDistributedBundleName_0100, Function | MediumTest | Level1) +{ + Parcel data; + Parcel reply; + MockDistributedBmsHost host; + std::string networkId = "networkId"; + uint32_t accessTokenId = 0; + data.WriteString(networkId); + data.WriteUint32(accessTokenId); + int32_t res = host.HandleGetDistributedBundleName(data, reply); + EXPECT_EQ(res, NO_ERROR); +} + +/** + * @tc.number: HandleGetDistributedBundleName_0200 + * @tc.name: Test HandleGetDistributedBundleName + * @tc.desc: Verify the HandleGetDistributedBundleName return NO_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, HandleGetDistributedBundleName_0200, Function | MediumTest | Level1) +{ + Parcel data; + Parcel reply; + MockDistributedBmsHost host; + std::string networkId = "networkId"; + data.WriteString(networkId); + int32_t res = host.HandleGetDistributedBundleName(data, reply); + EXPECT_EQ(res, NO_ERROR); +} + +/** + * @tc.number: HandleGetDistributedBundleName_0300 + * @tc.name: Test HandleGetDistributedBundleName + * @tc.desc: Verify the HandleGetDistributedBundleName return NO_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, HandleGetDistributedBundleName_0300, Function | MediumTest | Level1) +{ + Parcel data; + Parcel reply; + MockDistributedBmsHost host; + uint32_t accessTokenId = 0; + data.WriteUint32(accessTokenId); + int32_t res = host.HandleGetDistributedBundleName(data, reply); + EXPECT_EQ(res, NO_ERROR); +} + +/** + * @tc.number: HandleGetDistributedBundleName_0400 + * @tc.name: Test HandleGetDistributedBundleName + * @tc.desc: Verify the HandleGetDistributedBundleName return NO_ERROR. + */ +HWTEST_F(DistributedBmsHostTest, HandleGetDistributedBundleName_0400, Function | MediumTest | Level1) +{ + Parcel data; + Parcel reply; + MockDistributedBmsHost host; + int32_t res = host.HandleGetDistributedBundleName(data, reply); + EXPECT_EQ(res, NO_ERROR); +} + +/** + * @tc.number: VerifyCallingPermission_0100 + * @tc.name: Test VerifyCallingPermission + * @tc.desc: Verify the VerifyCallingPermission return true. + */ +HWTEST_F(DistributedBmsHostTest, VerifyCallingPermission_0100, Function | MediumTest | Level1) +{ + MockDistributedBmsHost host; + int res = host.VerifyCallingPermission(Constants::PERMISSION_GET_BUNDLE_INFO_PRIVILEGED); + EXPECT_TRUE(res); +} + +/** + * @tc.number: VerifyCallingPermission_0200 + * @tc.name: Test VerifyCallingPermission + * @tc.desc: Verify the VerifyCallingPermission return false. + */ +HWTEST_F(DistributedBmsHostTest, VerifyCallingPermission_0200, Function | MediumTest | Level1) +{ + MockDistributedBmsHost host; + int res = host.VerifyCallingPermission(""); + EXPECT_FALSE(res); +} + +/** + * @tc.number: WriteParcelableVector_0100 + * @tc.name: Test WriteParcelableVector + * @tc.desc: Verify the WriteParcelableVector return true. + */ +HWTEST_F(DistributedBmsHostTest, WriteParcelableVector_0100, Function | MediumTest | Level1) +{ + Parcel data; + Parcel reply; + MockDistributedBmsHost host; + std::vector vector; + int res = host.WriteParcelableVector(vector, data); + EXPECT_TRUE(res); +} + +/** + * @tc.number: GetParcelableInfos_0100 + * @tc.name: Test GetParcelableInfos + * @tc.desc: Verify the GetParcelableInfos return false. + */ +HWTEST_F(DistributedBmsHostTest, GetParcelableInfos_0100, Function | MediumTest | Level1) +{ + Parcel data; + Parcel reply; + MockDistributedBmsHost host; + std::vector vector; + int res = host.GetParcelableInfos(data, vector); + EXPECT_TRUE(res); +} +} \ No newline at end of file diff --git a/services/dbms/test/unittest/distributed_bms_host_test/mock_distributed_bms_interface.cpp b/services/dbms/test/unittest/distributed_bms_host_test/mock_distributed_bms_interface.cpp new file mode 100644 index 0000000..9842231 --- /dev/null +++ b/services/dbms/test/unittest/distributed_bms_host_test/mock_distributed_bms_interface.cpp @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2023 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 "mock_distributed_bms_interface.h" + +namespace OHOS { +namespace AppExecFwk { +MockDistributedBmsHost::~MockDistributedBmsHost() +{} + +int32_t MockDistributedBmsHost::GetRemoteAbilityInfo( + const OHOS::AppExecFwk::ElementName &elementName, RemoteAbilityInfo &remoteAbilityInfo) +{ + return 0; +} + +int32_t MockDistributedBmsHost::GetRemoteAbilityInfo(const OHOS::AppExecFwk::ElementName &elementName, + const std::string &localeInfo, RemoteAbilityInfo &remoteAbilityInfo) +{ + return 0; +} + +int32_t MockDistributedBmsHost::GetRemoteAbilityInfos( + const std::vector &elementNames, std::vector &remoteAbilityInfos) +{ + return 0; +} + +int32_t MockDistributedBmsHost::GetRemoteAbilityInfos(const std::vector &elementNames, + const std::string &localeInfo, std::vector &remoteAbilityInfos) +{ + return 0; +} + +int32_t MockDistributedBmsHost::GetAbilityInfo( + const OHOS::AppExecFwk::ElementName &elementName, RemoteAbilityInfo &remoteAbilityInfo) +{ + return 0; +} + +int32_t MockDistributedBmsHost::GetAbilityInfo(const OHOS::AppExecFwk::ElementName &elementName, + const std::string &localeInfo, RemoteAbilityInfo &remoteAbilityInfo) +{ + return 0; +} + +int32_t MockDistributedBmsHost::GetAbilityInfos( + const std::vector &elementNames, std::vector &remoteAbilityInfos) +{ + return 0; +} + +int32_t MockDistributedBmsHost::GetAbilityInfos(const std::vector &elementNames, + const std::string &localeInfo, std::vector &remoteAbilityInfos) +{ + return 0; +} + +bool MockDistributedBmsHost::GetDistributedBundleInfo( + const std::string &networkId, const std::string &bundleName, DistributedBundleInfo &distributedBundleInfo) +{ + return true; +} + +int32_t MockDistributedBmsHost::GetDistributedBundleName(const std::string &networkId, uint32_t accessTokenId, + std::string &bundleName) +{ + return 0; +} + +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/dbms/test/unittest/distributed_bms_host_test/mock_distributed_bms_interface.h b/services/dbms/test/unittest/distributed_bms_host_test/mock_distributed_bms_interface.h new file mode 100644 index 0000000..6f1b245 --- /dev/null +++ b/services/dbms/test/unittest/distributed_bms_host_test/mock_distributed_bms_interface.h @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2023 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 FOUNDATION_APPEXECFWK_MOCK_DISTRIBUTED_BMS_HOST_H +#define FOUNDATION_APPEXECFWK_MOCK_DISTRIBUTED_BMS_HOST_H + +#include + +#define private public +#include "distributed_bms_host.h" +#undef private + +namespace OHOS { +namespace AppExecFwk { +class MockDistributedBmsHost : public DistributedBmsHost { +public: + MockDistributedBmsHost() = default; + ~MockDistributedBmsHost() override; + int32_t GetRemoteAbilityInfo(const OHOS::AppExecFwk::ElementName &elementName, + RemoteAbilityInfo &remoteAbilityInfo) override; + int32_t GetRemoteAbilityInfo(const OHOS::AppExecFwk::ElementName &elementName, + const std::string &localeInfo, RemoteAbilityInfo &remoteAbilityInfo) override; + int32_t GetRemoteAbilityInfos( + const std::vector &elementNames, std::vector &remoteAbilityInfos) override; + int32_t GetRemoteAbilityInfos(const std::vector &elementNames, const std::string &localeInfo, + std::vector &remoteAbilityInfos) override; + int32_t GetAbilityInfo( + const OHOS::AppExecFwk::ElementName &elementName, RemoteAbilityInfo &remoteAbilityInfo) override; + int32_t GetAbilityInfo(const OHOS::AppExecFwk::ElementName &elementName, const std::string &localeInfo, + RemoteAbilityInfo &remoteAbilityInfo) override; + int32_t GetAbilityInfos( + const std::vector &elementNames, std::vector &remoteAbilityInfos) override; + int32_t GetAbilityInfos(const std::vector &elementNames, const std::string &localeInfo, + std::vector &remoteAbilityInfos) override; + bool GetDistributedBundleInfo(const std::string &networkId, const std::string &bundleName, + DistributedBundleInfo &distributedBundleInfo) override; + int32_t GetDistributedBundleName(const std::string &networkId, uint32_t accessTokenId, + std::string &bundleName) override; +}; +} // namespace AppExecFwk +} // namespace OHOS +#endif // FOUNDATION_APPEXECFWK_MOCK_DISTRIBUTED_BMS_HOST_H \ No newline at end of file -- Gitee