From 040f071bbd9feed85d4a822b09fb993609404d72 Mon Sep 17 00:00:00 2001 From: libing23 Date: Mon, 14 Feb 2022 23:45:18 +0800 Subject: [PATCH] add tokensync service Signed-off-by: libing23 --- frameworks/accesstoken/BUILD.gn | 1 + .../include/hap_token_info_for_sync_parcel.h | 40 ++ .../include/i_accesstoken_manager.h | 33 +- .../src/hap_token_info_for_sync_parcel.cpp | 76 ++++ frameworks/common/include/accesstoken_log.h | 25 +- frameworks/common/include/data_validator.h | 2 + frameworks/common/src/data_validator.cpp | 6 + ...nsync_manager.h => i_token_sync_manager.h} | 11 +- .../accesstoken/include/accesstoken_kit.h | 8 + .../accesstoken/include/hap_token_info.h | 6 + .../accesstoken/src/accesstoken_kit.cpp | 101 ++++- .../src/accesstoken_manager_client.cpp | 150 ++++++- .../src/accesstoken_manager_client.h | 8 + .../src/accesstoken_manager_proxy.cpp | 378 ++++++++++++---- .../src/accesstoken_manager_proxy.h | 11 + interfaces/innerkits/tokensync/BUILD.gn | 9 +- .../{tokensync_kit.h => token_sync_kit.h} | 9 +- .../{tokensync_kit.cpp => token_sync_kit.cpp} | 27 +- ...ient.cpp => token_sync_manager_client.cpp} | 42 +- ...r_client.h => token_sync_manager_client.h} | 11 +- ...proxy.cpp => token_sync_manager_proxy.cpp} | 84 +++- ...ger_proxy.h => token_sync_manager_proxy.h} | 10 +- interfaces/innerkits/tokensync/test/BUILD.gn | 2 +- ...c_kit_test.cpp => token_sync_kit_test.cpp} | 4 +- ...nsync_kit_test.h => token_sync_kit_test.h} | 0 interfaces/kits/accesstoken/BUILD.gn | 3 +- services/accesstokenmanager/BUILD.gn | 4 + .../permission/permission_policy_set.h | 1 + .../service/accesstoken_manager_service.h | 9 + .../service/accesstoken_manager_stub.h | 9 + .../include/token/accesstoken_info_manager.h | 11 + .../token/accesstoken_remote_token_manager.h | 62 +++ .../cpp/include/token/hap_token_info_inner.h | 24 +- .../include/token/native_token_info_inner.h | 15 +- .../cpp/include/token/token_modify_notifier.h | 56 +++ .../main/cpp/src/database/data_translator.cpp | 12 +- .../main/cpp/src/database/sqlite_helper.cpp | 26 +- .../main/cpp/src/database/sqlite_storage.cpp | 12 +- .../permission_definition_cache.cpp | 6 +- .../cpp/src/permission/permission_manager.cpp | 56 ++- .../src/permission/permission_policy_set.cpp | 23 +- .../src/permission/permission_validator.cpp | 2 - .../service/accesstoken_manager_service.cpp | 70 ++- .../src/service/accesstoken_manager_stub.cpp | 129 +++++- .../cpp/src/token/accesstoken_id_manager.cpp | 10 +- .../src/token/accesstoken_info_manager.cpp | 412 +++++++++++++---- .../accesstoken_remote_token_manager.cpp | 154 +++++++ .../cpp/src/token/hap_token_info_inner.cpp | 162 ++++--- .../cpp/src/token/native_token_info_inner.cpp | 147 +++---- .../cpp/src/token/native_token_receptor.cpp | 14 +- .../cpp/src/token/token_modify_notifier.cpp | 119 +++++ services/tokensyncmanager/BUILD.gn | 39 +- .../include/command/base_remote_command.h | 67 +++ .../command/delete_remote_token_command.h | 52 +++ .../command/sync_remote_hap_token_command.h | 59 +++ .../sync_remote_native_token_command.h | 55 +++ .../command/update_remote_hap_token_command.h | 56 +++ .../include/common/constant.h | 97 ++++ .../include/device/device_info.h | 46 ++ .../include/device/device_info_manager.h | 104 +++++ .../include/device/device_info_repository.h | 77 ++++ .../include/protocol/remote_protocol.h | 38 ++ .../include/remote/remote_command_executor.h | 158 +++++++ .../include/remote/remote_command_factory.h | 58 +++ .../include/remote/remote_command_manager.h | 165 +++++++ .../include/remote/rpc_channel.h | 80 ++++ .../include/remote/soft_bus_channel.h | 365 +++++++++++++++ .../soft_bus_device_connection_listener.h | 76 ++++ .../include/remote/soft_bus_manager.h | 95 +++- .../remote/soft_bus_session_listener.h | 114 +++++ .../service/token_sync_event_handler.h | 43 ++ .../service/token_sync_manager_service.h} | 25 +- .../service/token_sync_manager_stub.h} | 15 +- .../src/command/base_remote_command.cpp | 260 +++++++++++ .../command/delete_remote_token_command.cpp | 104 +++++ .../command/sync_remote_hap_token_command.cpp | 109 +++++ .../sync_remote_native_token_command.cpp | 120 +++++ .../update_remote_hap_token_command.cpp | 105 +++++ .../tokensyncmanager/src/common/constant.cpp | 44 ++ .../src/device/device_info_manager.cpp | 167 +++++++ .../src/device/device_info_repository.cpp | 191 ++++++++ .../src/remote/remote_command_executor.cpp | 328 ++++++++++++++ .../src/remote/remote_command_factory.cpp | 76 ++++ .../src/remote/remote_command_manager.cpp | 292 ++++++++++++ .../src/remote/soft_bus_channel.cpp | 416 ++++++++++++++++++ .../soft_bus_device_connection_listener.cpp | 93 ++++ .../src/remote/soft_bus_manager.cpp | 346 ++++++++++----- .../src/remote/soft_bus_session_listener.cpp | 135 ++++++ .../src/service/token_sync_event_handler.cpp | 54 +++ ...ice.cpp => token_sync_manager_service.cpp} | 133 +++++- ...r_stub.cpp => token_sync_manager_stub.cpp} | 45 +- 91 files changed, 6827 insertions(+), 677 deletions(-) create mode 100644 frameworks/accesstoken/include/hap_token_info_for_sync_parcel.h create mode 100644 frameworks/accesstoken/src/hap_token_info_for_sync_parcel.cpp rename frameworks/tokensync/include/{i_tokensync_manager.h => i_token_sync_manager.h} (71%) mode change 100755 => 100644 interfaces/innerkits/accesstoken/src/accesstoken_manager_client.h rename interfaces/innerkits/tokensync/include/{tokensync_kit.h => token_sync_kit.h} (69%) rename interfaces/innerkits/tokensync/src/{tokensync_kit.cpp => token_sync_kit.cpp} (47%) rename interfaces/innerkits/tokensync/src/{tokensync_manager_client.cpp => token_sync_manager_client.cpp} (59%) rename interfaces/innerkits/tokensync/src/{tokensync_manager_client.h => token_sync_manager_client.h} (75%) rename interfaces/innerkits/tokensync/src/{tokensync_manager_proxy.cpp => token_sync_manager_proxy.cpp} (37%) rename interfaces/innerkits/tokensync/src/{tokensync_manager_proxy.h => token_sync_manager_proxy.h} (74%) rename interfaces/innerkits/tokensync/test/unittest/src/{tokensync_kit_test.cpp => token_sync_kit_test.cpp} (93%) rename interfaces/innerkits/tokensync/test/unittest/src/{tokensync_kit_test.h => token_sync_kit_test.h} (100%) create mode 100644 services/accesstokenmanager/main/cpp/include/token/accesstoken_remote_token_manager.h create mode 100644 services/accesstokenmanager/main/cpp/include/token/token_modify_notifier.h create mode 100644 services/accesstokenmanager/main/cpp/src/token/accesstoken_remote_token_manager.cpp create mode 100644 services/accesstokenmanager/main/cpp/src/token/token_modify_notifier.cpp create mode 100644 services/tokensyncmanager/include/command/base_remote_command.h create mode 100644 services/tokensyncmanager/include/command/delete_remote_token_command.h create mode 100644 services/tokensyncmanager/include/command/sync_remote_hap_token_command.h create mode 100644 services/tokensyncmanager/include/command/sync_remote_native_token_command.h create mode 100644 services/tokensyncmanager/include/command/update_remote_hap_token_command.h create mode 100644 services/tokensyncmanager/include/common/constant.h create mode 100644 services/tokensyncmanager/include/device/device_info.h create mode 100644 services/tokensyncmanager/include/device/device_info_manager.h create mode 100644 services/tokensyncmanager/include/device/device_info_repository.h create mode 100644 services/tokensyncmanager/include/protocol/remote_protocol.h create mode 100644 services/tokensyncmanager/include/remote/remote_command_executor.h create mode 100644 services/tokensyncmanager/include/remote/remote_command_factory.h create mode 100644 services/tokensyncmanager/include/remote/remote_command_manager.h create mode 100644 services/tokensyncmanager/include/remote/rpc_channel.h create mode 100644 services/tokensyncmanager/include/remote/soft_bus_channel.h create mode 100644 services/tokensyncmanager/include/remote/soft_bus_device_connection_listener.h create mode 100644 services/tokensyncmanager/include/remote/soft_bus_session_listener.h create mode 100644 services/tokensyncmanager/include/service/token_sync_event_handler.h rename services/tokensyncmanager/{src/service/tokensync_manager_service.h => include/service/token_sync_manager_service.h} (56%) rename services/tokensyncmanager/{src/service/tokensync_manager_stub.h => include/service/token_sync_manager_stub.h} (70%) create mode 100644 services/tokensyncmanager/src/command/base_remote_command.cpp create mode 100644 services/tokensyncmanager/src/command/delete_remote_token_command.cpp create mode 100644 services/tokensyncmanager/src/command/sync_remote_hap_token_command.cpp create mode 100644 services/tokensyncmanager/src/command/sync_remote_native_token_command.cpp create mode 100644 services/tokensyncmanager/src/command/update_remote_hap_token_command.cpp create mode 100644 services/tokensyncmanager/src/common/constant.cpp create mode 100644 services/tokensyncmanager/src/device/device_info_manager.cpp create mode 100644 services/tokensyncmanager/src/device/device_info_repository.cpp create mode 100644 services/tokensyncmanager/src/remote/remote_command_executor.cpp create mode 100644 services/tokensyncmanager/src/remote/remote_command_factory.cpp create mode 100644 services/tokensyncmanager/src/remote/remote_command_manager.cpp create mode 100644 services/tokensyncmanager/src/remote/soft_bus_channel.cpp create mode 100644 services/tokensyncmanager/src/remote/soft_bus_device_connection_listener.cpp create mode 100644 services/tokensyncmanager/src/remote/soft_bus_session_listener.cpp create mode 100644 services/tokensyncmanager/src/service/token_sync_event_handler.cpp rename services/tokensyncmanager/src/service/{tokensync_manager_service.cpp => token_sync_manager_service.cpp} (31%) rename services/tokensyncmanager/src/service/{tokensync_manager_stub.cpp => token_sync_manager_stub.cpp} (51%) diff --git a/frameworks/accesstoken/BUILD.gn b/frameworks/accesstoken/BUILD.gn index 1489a5df0..e7ebdac5b 100644 --- a/frameworks/accesstoken/BUILD.gn +++ b/frameworks/accesstoken/BUILD.gn @@ -39,6 +39,7 @@ ohos_shared_library("accesstoken_communication_adapter_cxx") { sources = [ "src/hap_info_parcel.cpp", "src/hap_policy_parcel.cpp", + "src/hap_token_info_for_sync_parcel.cpp", "src/hap_token_info_parcel.cpp", "src/native_token_info_parcel.cpp", "src/permission_def_parcel.cpp", diff --git a/frameworks/accesstoken/include/hap_token_info_for_sync_parcel.h b/frameworks/accesstoken/include/hap_token_info_for_sync_parcel.h new file mode 100644 index 000000000..b0c838402 --- /dev/null +++ b/frameworks/accesstoken/include/hap_token_info_for_sync_parcel.h @@ -0,0 +1,40 @@ +/* + * 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 HAP_TOKEN_INFO_FOR_SYNC_PARCEL_H +#define HAP_TOKEN_INFO_FOR_SYNC_PARCEL_H + +#include "hap_token_info.h" +#include "parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct HapTokenInfoForSyncParcel final : public Parcelable { + HapTokenInfoForSyncParcel() = default; + + ~HapTokenInfoForSyncParcel() override = default; + + bool Marshalling(Parcel &out) const override; + + static HapTokenInfoForSyncParcel *Unmarshalling(Parcel &in); + + HapTokenInfoForSync hapTokenInfoForSyncParams; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // HAP_TOKEN_INFO_FOR_SYNC_PARCEL_H + diff --git a/frameworks/accesstoken/include/i_accesstoken_manager.h b/frameworks/accesstoken/include/i_accesstoken_manager.h index aec6c78be..12b1d3165 100644 --- a/frameworks/accesstoken/include/i_accesstoken_manager.h +++ b/frameworks/accesstoken/include/i_accesstoken_manager.h @@ -18,16 +18,16 @@ #include -#include "iremote_broker.h" -#include "errors.h" - #include "access_token.h" -#include "permission_def_parcel.h" -#include "permission_state_full_parcel.h" +#include "errors.h" +#include "hap_info_parcel.h" #include "hap_policy_parcel.h" +#include "hap_token_info_for_sync_parcel.h" #include "hap_token_info_parcel.h" -#include "hap_info_parcel.h" +#include "iremote_broker.h" #include "native_token_info_parcel.h" +#include "permission_def_parcel.h" +#include "permission_state_full_parcel.h" namespace OHOS { namespace Security { @@ -58,6 +58,18 @@ public: virtual int UpdateHapToken( AccessTokenID tokenID, const std::string& appIDDesc, const HapPolicyParcel& policyParcel) = 0; + virtual int GetHapTokenInfoFromRemote(AccessTokenID tokenID, + HapTokenInfoForSyncParcel& hapSyncParcel) = 0; + virtual int GetAllNativeTokenInfo(std::vector& nativeTokenInfoRes) = 0; + virtual int SetRemoteHapTokenInfo(const std::string& deviceID, + HapTokenInfoForSyncParcel& hapSyncParcel) = 0; + virtual int SetRemoteNativeTokenInfo(const std::string& deviceID, + std::vector& nativeTokenInfoParcel) = 0; + virtual int DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID) = 0; + virtual int DeleteRemoteDeviceTokens(const std::string& deviceID) = 0; + + virtual int DumpToken(std::string& dumpInfo) = 0; + enum class InterfaceCode { VERIFY_ACCESSTOKEN = 0xff10, GET_DEF_PERMISSION = 0xff11, @@ -76,6 +88,15 @@ public: GET_NATIVE_TOKENINFO = 0xff24, GET_HAP_TOKENINFO = 0xff25, UPDATE_HAP_TOKEN = 0xff26, + + GET_HAP_TOKEN_FROM_REMOTE = 0xff27, + GET_ALL_NATIVE_TOKEN_FROM_REMOTE = 0xff28, + SET_REMOTE_HAP_TOKEN_INFO = 0xff29, + SET_REMOTE_NATIVE_TOKEN_INFO = 0xff2a, + DELETE_REMOTE_TOKEN_INFO = 0xff2b, + DELETE_REMOTE_DEVICE_TOKEN = 0xff2c, + + DUMP = 0xff30, }; }; } // namespace AccessToken diff --git a/frameworks/accesstoken/src/hap_token_info_for_sync_parcel.cpp b/frameworks/accesstoken/src/hap_token_info_for_sync_parcel.cpp new file mode 100644 index 000000000..1f3d64286 --- /dev/null +++ b/frameworks/accesstoken/src/hap_token_info_for_sync_parcel.cpp @@ -0,0 +1,76 @@ +/* + * 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 "hap_token_info_for_sync_parcel.h" +#include "hap_token_info_parcel.h" +#include "permission_state_full_parcel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +#define RETURN_IF_FALSE(expr) \ + if (!(expr)) { \ + return false; \ + } + +#define RELEASE_IF_FALSE(expr, obj) \ + if (!(expr)) { \ + delete (obj); \ + (obj) = nullptr; \ + return (obj); \ + } + +bool HapTokenInfoForSyncParcel::Marshalling(Parcel& out) const +{ + HapTokenInfoParcel baseInfoParcel; + baseInfoParcel.hapTokenInfoParams = this->hapTokenInfoForSyncParams.baseInfo; + out.WriteParcelable(&baseInfoParcel); + + const std::vector& permStateList = this->hapTokenInfoForSyncParams.permStateList; + int32_t permStateListSize = (int32_t)permStateList.size(); + RETURN_IF_FALSE(out.WriteInt32(permStateListSize)); + + for (int i = 0; i < permStateListSize; i++) { + PermissionStateFullParcel permStateParcel; + permStateParcel.permStatFull = permStateList[i]; + out.WriteParcelable(&permStateParcel); + } + + return true; +} + +HapTokenInfoForSyncParcel* HapTokenInfoForSyncParcel::Unmarshalling(Parcel& in) +{ + auto* hapTokenInfoForSyncParcel = new (std::nothrow) HapTokenInfoForSyncParcel(); + RELEASE_IF_FALSE(hapTokenInfoForSyncParcel != nullptr, hapTokenInfoForSyncParcel); + + sptr baseInfoParcel = in.ReadParcelable(); + RELEASE_IF_FALSE(baseInfoParcel != nullptr, hapTokenInfoForSyncParcel); + hapTokenInfoForSyncParcel->hapTokenInfoForSyncParams.baseInfo = baseInfoParcel->hapTokenInfoParams; + + int permStateListSize; + RELEASE_IF_FALSE(in.ReadInt32(permStateListSize), hapTokenInfoForSyncParcel); + for (int i = 0; i < permStateListSize; i++) { + sptr permissionStateParcel = in.ReadParcelable(); + RELEASE_IF_FALSE(permissionStateParcel != nullptr, hapTokenInfoForSyncParcel); + hapTokenInfoForSyncParcel->hapTokenInfoForSyncParams.permStateList.emplace_back( + permissionStateParcel->permStatFull); + } + return hapTokenInfoForSyncParcel; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + diff --git a/frameworks/common/include/accesstoken_log.h b/frameworks/common/include/accesstoken_log.h index 3fb142587..ac4aaa107 100644 --- a/frameworks/common/include/accesstoken_log.h +++ b/frameworks/common/include/accesstoken_log.h @@ -22,19 +22,24 @@ #ifndef __cplusplus -#define ACCESSTOKEN_LOG_DEBUG(fmt, ...) HILOG_DEBUG(LOG_CORE, fmt, ##__VA_ARGS__) -#define ACCESSTOKEN_LOG_INFO(fmt, ...) HILOG_INFO(LOG_CORE, fmt, ##__VA_ARGS__) -#define ACCESSTOKEN_LOG_WARN(fmt, ...) HILOG_WARN(LOG_CORE, fmt, ##__VA_ARGS__) -#define ACCESSTOKEN_LOG_ERROR(fmt, ...) HILOG_ERROR(LOG_CORE, fmt, ##__VA_ARGS__) -#define ACCESSTOKEN_LOG_FATAL(fmt, ...) HILOG_FATAL(LOG_CORE, fmt, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_DEBUG(fmt, ...) HILOG_DEBUG(LOG_CORE, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_INFO(fmt, ...) HILOG_INFO(LOG_CORE, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_WARN(fmt, ...) HILOG_WARN(LOG_CORE, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_ERROR(fmt, ...) HILOG_ERROR(LOG_CORE, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_FATAL(fmt, ...) HILOG_FATAL(LOG_CORE, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) #else -#define ACCESSTOKEN_LOG_DEBUG(label, fmt, ...) OHOS::HiviewDFX::HiLog::Debug(label, fmt, ##__VA_ARGS__) -#define ACCESSTOKEN_LOG_INFO(label, fmt, ...) OHOS::HiviewDFX::HiLog::Info(label, fmt, ##__VA_ARGS__) -#define ACCESSTOKEN_LOG_WARN(label, fmt, ...) OHOS::HiviewDFX::HiLog::Warn(label, fmt, ##__VA_ARGS__) -#define ACCESSTOKEN_LOG_ERROR(label, fmt, ...) OHOS::HiviewDFX::HiLog::Error(label, fmt, ##__VA_ARGS__) -#define ACCESSTOKEN_LOG_FATAL(label, fmt, ...) OHOS::HiviewDFX::HiLog::Fatal(label, fmt, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_DEBUG(label, fmt, ...) \ + OHOS::HiviewDFX::HiLog::Debug(label, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_INFO(label, fmt, ...) \ + OHOS::HiviewDFX::HiLog::Info(label, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_WARN(label, fmt, ...) \ + OHOS::HiviewDFX::HiLog::Warn(label, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_ERROR(label, fmt, ...) \ + OHOS::HiviewDFX::HiLog::Error(label, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) +#define ACCESSTOKEN_LOG_FATAL(label, fmt, ...) \ + OHOS::HiviewDFX::HiLog::Fatal(label, "[%{public}s]:" fmt, __func__, ##__VA_ARGS__) #endif // __cplusplus diff --git a/frameworks/common/include/data_validator.h b/frameworks/common/include/data_validator.h index f9cb353d1..8821598cf 100644 --- a/frameworks/common/include/data_validator.h +++ b/frameworks/common/include/data_validator.h @@ -14,6 +14,7 @@ */ #include +#include "access_token.h" #ifndef DATA_VALIDATOR_H #define DATA_VALIDATOR_H @@ -43,6 +44,7 @@ public: static bool IsDescValid(const std::string& desc); static bool IsPermissionFlagValid(int flag); static bool IsDcapValid(const std::string& dcap); + static bool IsTokenIDValid(AccessTokenID id); private: const static int MAX_LENGTH = 256; const static int MAX_APPIDDESC_LENGTH = 10240; diff --git a/frameworks/common/src/data_validator.cpp b/frameworks/common/src/data_validator.cpp index 3eb3e0c67..02906c1ab 100644 --- a/frameworks/common/src/data_validator.cpp +++ b/frameworks/common/src/data_validator.cpp @@ -81,6 +81,12 @@ bool DataValidator::IsPermissionFlagValid(int flag) flag == PermissionFlag::PERMISSION_USER_FIXED || flag == PermissionFlag::PERMISSION_SYSTEM_FIXED; } + +bool DataValidator::IsTokenIDValid(AccessTokenID id) +{ + return id != 0; +} + } // namespace AccessToken } // namespace Security } // namespace OHOS diff --git a/frameworks/tokensync/include/i_tokensync_manager.h b/frameworks/tokensync/include/i_token_sync_manager.h similarity index 71% rename from frameworks/tokensync/include/i_tokensync_manager.h rename to frameworks/tokensync/include/i_token_sync_manager.h index 4555102b9..8975482ce 100644 --- a/frameworks/tokensync/include/i_tokensync_manager.h +++ b/frameworks/tokensync/include/i_token_sync_manager.h @@ -21,6 +21,9 @@ #include "iremote_broker.h" #include "errors.h" +#include "access_token.h" +#include "hap_token_info_for_sync_parcel.h" + namespace OHOS { namespace Security { namespace AccessToken { @@ -30,10 +33,14 @@ public: DECLARE_INTERFACE_DESCRIPTOR(u"ohos.security.accesstoken.ITokenSyncManager"); - virtual int VerifyPermission(const std::string& bundleName, const std::string& permissionName, int userId) = 0; + virtual int GetRemoteHapTokenInfo(const std::string& deviceID, AccessTokenID tokenID) = 0; + virtual int DeleteRemoteHapTokenInfo(AccessTokenID tokenID) = 0; + virtual int UpdateRemoteHapTokenInfo(const HapTokenInfoForSync& tokenInfo) = 0; enum class InterfaceCode { - VERIFY_PERMISSION = 0xff01, + GET_REMOTE_HAP_TOKEN_INFO = 0xff01, + DELETE_REMOTE_HAP_TOKEN_INFO = 0xff02, + UPDATE_REMOTE_HAP_TOKEN_INFO = 0xff03 }; }; } // namespace AccessToken diff --git a/interfaces/innerkits/accesstoken/include/accesstoken_kit.h b/interfaces/innerkits/accesstoken/include/accesstoken_kit.h index fdc83a2b5..495f451d9 100644 --- a/interfaces/innerkits/accesstoken/include/accesstoken_kit.h +++ b/interfaces/innerkits/accesstoken/include/accesstoken_kit.h @@ -53,6 +53,14 @@ public: static int GrantPermission(AccessTokenID tokenID, const std::string& permissionName, int flag); static int RevokePermission(AccessTokenID tokenID, const std::string& permissionName, int flag); static int ClearUserGrantedPermissionState(AccessTokenID tokenID); + static int GetHapTokenInfoFromRemote(AccessTokenID tokenID, HapTokenInfoForSync& hapSync); + static int GetAllNativeTokenInfo(std::vector& nativeTokenInfosRes); + static int SetRemoteHapTokenInfo(const std::string& deviceID, const HapTokenInfoForSync& hapSync); + static int SetRemoteNativeTokenInfo(const std::string& deviceID, + std::vector& nativeTokenInfoList); + static int DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID); + static int DeleteRemoteDeviceTokens(const std::string& deviceID); + static int DumpToken(std::string& dumpInfo); }; } // namespace AccessToken } // namespace Security diff --git a/interfaces/innerkits/accesstoken/include/hap_token_info.h b/interfaces/innerkits/accesstoken/include/hap_token_info.h index 26477f893..1d38ae684 100644 --- a/interfaces/innerkits/accesstoken/include/hap_token_info.h +++ b/interfaces/innerkits/accesstoken/include/hap_token_info.h @@ -53,6 +53,12 @@ public: AccessTokenID tokenID; AccessTokenAttr tokenAttr; }; + +class HapTokenInfoForSync final { +public: + HapTokenInfo baseInfo; + std::vector permStateList; +}; } // namespace AccessToken } // namespace Security } // namespace OHOS diff --git a/interfaces/innerkits/accesstoken/src/accesstoken_kit.cpp b/interfaces/innerkits/accesstoken/src/accesstoken_kit.cpp index 3022ec14f..5585fca7a 100644 --- a/interfaces/innerkits/accesstoken/src/accesstoken_kit.cpp +++ b/interfaces/innerkits/accesstoken/src/accesstoken_kit.cpp @@ -36,7 +36,7 @@ AccessTokenIDEx AccessTokenKit::AllocHapToken(const HapInfoParams& info, const H if ((!DataValidator::IsUserIdValid(info.userID)) || !DataValidator::IsAppIDDescValid(info.appIDDesc) || !DataValidator::IsBundleNameValid(info.bundleName) || !DataValidator::IsAplNumValid(policy.apl) || !DataValidator::IsDomainValid(policy.domain)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, input param failed", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "input param failed"); return res; } @@ -45,7 +45,8 @@ AccessTokenIDEx AccessTokenKit::AllocHapToken(const HapInfoParams& info, const H AccessTokenID AccessTokenKit::AllocLocalTokenID(const std::string& remoteDeviceID, AccessTokenID remoteTokenID) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{public}s tokenID=%{public}d", + __func__, remoteDeviceID.c_str(), remoteTokenID); return AccessTokenManagerClient::GetInstance().AllocLocalTokenID(remoteDeviceID, remoteTokenID); } @@ -54,7 +55,7 @@ int AccessTokenKit::UpdateHapToken(AccessTokenID tokenID, const std::string& app ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); if ((tokenID == 0) || (!DataValidator::IsAppIDDescValid(appIDDesc)) || (!DataValidator::IsAplNumValid(policy.apl))) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, input param failed", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "input param failed"); return RET_FAILED; } return AccessTokenManagerClient::GetInstance().UpdateHapToken(tokenID, appIDDesc, policy); @@ -64,7 +65,7 @@ int AccessTokenKit::DeleteToken(AccessTokenID tokenID) { ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); if (tokenID == 0) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: tokenID is invalid", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); return RET_FAILED; } ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); @@ -75,7 +76,7 @@ ATokenTypeEnum AccessTokenKit::GetTokenType(AccessTokenID tokenID) { ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); if (tokenID == 0) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: tokenID is invalid", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); return TOKEN_INVALID; } ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); @@ -95,11 +96,11 @@ int AccessTokenKit::CheckNativeDCap(AccessTokenID tokenID, const std::string& dc { ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); if (tokenID == 0) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: tokenID is invalid", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); return RET_FAILED; } if (!DataValidator::IsDcapValid(dcap)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: dcap is invalid", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "dcap is invalid"); return RET_FAILED; } ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, dcap=%{public}s", tokenID, dcap.c_str()); @@ -110,7 +111,7 @@ AccessTokenID AccessTokenKit::GetHapTokenID(int userID, const std::string& bundl { ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); if (!DataValidator::IsUserIdValid(userID) || !DataValidator::IsBundleNameValid(bundleName)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, hap token param failed", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "hap token param failed"); return 0; } ACCESSTOKEN_LOG_INFO(LABEL, "int userID=%{public}d, bundleName=%{public}s, instIndex=%{public}d", @@ -122,7 +123,7 @@ int AccessTokenKit::GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfo& hapToke { ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); if (tokenID == 0) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: tokenID is invalid", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); return RET_FAILED; } ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d", tokenID); @@ -142,11 +143,11 @@ int AccessTokenKit::VerifyAccessToken(AccessTokenID tokenID, const std::string& { ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); if (tokenID == 0) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: tokenID is invalid", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenID is invalid"); return PERMISSION_DENIED; } if (!DataValidator::IsPermissionNameValid(permissionName)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: permissionName is invalid", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "permissionName is invalid"); return PERMISSION_DENIED; } ACCESSTOKEN_LOG_INFO(LABEL, "tokenID=%{public}d, permissionName=%{public}s", tokenID, permissionName.c_str()); @@ -170,7 +171,7 @@ int AccessTokenKit::GetDefPermission(const std::string& permissionName, Permissi { ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); if (!DataValidator::IsPermissionNameValid(permissionName)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: permissionName is invalid", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "permissionName is invalid"); return RET_FAILED; } ACCESSTOKEN_LOG_INFO(LABEL, "permissionName=%{public}s", permissionName.c_str()); @@ -185,7 +186,7 @@ int AccessTokenKit::GetDefPermissions(AccessTokenID tokenID, std::vector& nativeTokenInfosRes) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + + return AccessTokenManagerClient::GetInstance().GetAllNativeTokenInfo(nativeTokenInfosRes); +} + +int AccessTokenKit::SetRemoteHapTokenInfo(const std::string& deviceID, + const HapTokenInfoForSync& hapSync) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{public}s tokenID=%{public}d", + __func__, deviceID.c_str(), hapSync.baseInfo.tokenID); + return AccessTokenManagerClient::GetInstance().SetRemoteHapTokenInfo(deviceID, hapSync); +} + +int AccessTokenKit::SetRemoteNativeTokenInfo(const std::string& deviceID, + std::vector& nativeTokenInfoList) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{public}s", __func__, deviceID.c_str()); + return AccessTokenManagerClient::GetInstance() + .SetRemoteNativeTokenInfo(deviceID, nativeTokenInfoList); +} + +int AccessTokenKit::DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{public}s tokenID=%{public}d", + __func__, deviceID.c_str(), tokenID); + return AccessTokenManagerClient::GetInstance().DeleteRemoteToken(deviceID, tokenID); +} + +int AccessTokenKit::DeleteRemoteDeviceTokens(const std::string& deviceID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{public}s", __func__, deviceID.c_str()); + return AccessTokenManagerClient::GetInstance().DeleteRemoteDeviceTokens(deviceID); +} + +int AccessTokenKit::DumpToken(std::string& dumpInfo) +{ + return AccessTokenManagerClient::GetInstance().DumpToken(dumpInfo); +} + } // namespace AccessToken } // namespace Security } // namespace OHOS diff --git a/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.cpp b/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.cpp index dcfec1f30..f7e5d4f0d 100644 --- a/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.cpp +++ b/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.cpp @@ -18,6 +18,7 @@ #include "accesstoken_log.h" #include "accesstoken_manager_proxy.h" #include "hap_token_info.h" +#include "hap_token_info_for_sync_parcel.h" #include "iservice_registry.h" #include "native_token_info.h" @@ -47,7 +48,7 @@ int AccessTokenManagerClient::VerifyAccessToken(AccessTokenID tokenID, const std ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); return PERMISSION_DENIED; } return proxy->VerifyAccessToken(tokenID, permissionName); @@ -59,7 +60,7 @@ int AccessTokenManagerClient::GetDefPermission( ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); return RET_FAILED; } PermissionDefParcel permissionDefParcel; @@ -73,7 +74,7 @@ int AccessTokenManagerClient::GetDefPermissions(AccessTokenID tokenID, std::vect ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); return RET_FAILED; } std::vector parcelList; @@ -91,7 +92,7 @@ int AccessTokenManagerClient::GetReqPermissions( ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); return RET_FAILED; } std::vector parcelList; @@ -108,7 +109,7 @@ int AccessTokenManagerClient::GetPermissionFlag(AccessTokenID tokenID, const std ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); return DEFAULT_PERMISSION_FLAGS; } return proxy->GetPermissionFlag(tokenID, permissionName); @@ -119,7 +120,7 @@ int AccessTokenManagerClient::GrantPermission(AccessTokenID tokenID, const std:: ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); return RET_FAILED; } return proxy->GrantPermission(tokenID, permissionName, flag); @@ -130,7 +131,7 @@ int AccessTokenManagerClient::RevokePermission(AccessTokenID tokenID, const std: ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); return RET_FAILED; } return proxy->RevokePermission(tokenID, permissionName, flag); @@ -141,7 +142,7 @@ int AccessTokenManagerClient::ClearUserGrantedPermissionState(AccessTokenID toke ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); return RET_FAILED; } return proxy->ClearUserGrantedPermissionState(tokenID); @@ -153,7 +154,7 @@ AccessTokenIDEx AccessTokenManagerClient::AllocHapToken(const HapInfoParams& inf ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); return res; } HapInfoParcel hapInfoParcel; @@ -169,7 +170,7 @@ int AccessTokenManagerClient::DeleteToken(AccessTokenID tokenID) ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); return RET_FAILED; } return proxy->DeleteToken(tokenID); @@ -180,7 +181,7 @@ ATokenTypeEnum AccessTokenManagerClient::GetTokenType(AccessTokenID tokenID) ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); return TOKEN_INVALID; } return (ATokenTypeEnum)(proxy->GetTokenType(tokenID)); @@ -191,7 +192,7 @@ int AccessTokenManagerClient::CheckNativeDCap(AccessTokenID tokenID, const std:: ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); return RET_FAILED; } return proxy->CheckNativeDCap(tokenID, dcap); @@ -202,7 +203,7 @@ AccessTokenID AccessTokenManagerClient::GetHapTokenID(int userID, const std::str ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); return RET_FAILED; } return proxy->GetHapTokenID(userID, bundleName, instIndex); @@ -214,7 +215,7 @@ AccessTokenID AccessTokenManagerClient::AllocLocalTokenID( ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); return RET_FAILED; } return proxy->AllocLocalTokenID(remoteDeviceID, remoteTokenID); @@ -226,7 +227,7 @@ int AccessTokenManagerClient::UpdateHapToken( ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); return RET_FAILED; } HapPolicyParcel hapPolicyParcel; @@ -239,7 +240,7 @@ int AccessTokenManagerClient::GetHapTokenInfo(AccessTokenID tokenID, HapTokenInf ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); return RET_FAILED; } HapTokenInfoParcel hapTokenInfoParcel; @@ -254,7 +255,7 @@ int AccessTokenManagerClient::GetNativeTokenInfo(AccessTokenID tokenID, NativeTo ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); return RET_FAILED; } NativeTokenInfoParcel nativeTokenInfoParcel; @@ -263,6 +264,114 @@ int AccessTokenManagerClient::GetNativeTokenInfo(AccessTokenID tokenID, NativeTo return res; } +int AccessTokenManagerClient::GetHapTokenInfoFromRemote(AccessTokenID tokenID, HapTokenInfoForSync& hapSync) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return RET_FAILED; + } + + HapTokenInfoForSyncParcel hapSyncParcel; + int res = proxy->GetHapTokenInfoFromRemote(tokenID, hapSyncParcel); + hapSync = hapSyncParcel.hapTokenInfoForSyncParams; + return res; +} + +int AccessTokenManagerClient::GetAllNativeTokenInfo(std::vector& nativeTokenInfosRes) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return RET_FAILED; + } + + std::vector parcelList; + int result = proxy->GetAllNativeTokenInfo(parcelList); + for (auto nativeTokenParcel : parcelList) { + NativeTokenInfo native = nativeTokenParcel.nativeTokenInfoParams; + nativeTokenInfosRes.emplace_back(native); + } + + return result; +} + +int AccessTokenManagerClient::SetRemoteHapTokenInfo(const std::string& deviceID, const HapTokenInfoForSync& hapSync) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return RET_FAILED; + } + + HapTokenInfoForSyncParcel hapSyncParcel; + hapSyncParcel.hapTokenInfoForSyncParams = hapSync; + + int res = proxy->SetRemoteHapTokenInfo(deviceID, hapSyncParcel); + return res; +} + +int AccessTokenManagerClient::SetRemoteNativeTokenInfo(const std::string& deviceID, + std::vector& nativeTokenInfoList) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return RET_FAILED; + } + std::vector hapTokenInfoParcels; + for (auto native : nativeTokenInfoList) { + NativeTokenInfoParcel nativeTokenInfoParcel; + nativeTokenInfoParcel.nativeTokenInfoParams = native; + hapTokenInfoParcels.emplace_back(nativeTokenInfoParcel); + } + PermissionStateFullParcel permStateParcel; + int res = proxy->SetRemoteNativeTokenInfo(deviceID, hapTokenInfoParcels); + return res; +} + +int AccessTokenManagerClient::DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return RET_FAILED; + } + + int res = proxy->DeleteRemoteToken(deviceID, tokenID); + return res; +} + +int AccessTokenManagerClient::DeleteRemoteDeviceTokens(const std::string& deviceID) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return RET_FAILED; + } + + int res = proxy->DeleteRemoteDeviceTokens(deviceID); + return res; +} + +int AccessTokenManagerClient::DumpToken(std::string& dumpInfo) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return RET_FAILED; + } + AccessTokenID res = proxy->DumpToken(dumpInfo); + return res; +} + sptr AccessTokenManagerClient::GetProxy() { if (proxy_ == nullptr) { @@ -270,25 +379,24 @@ sptr AccessTokenManagerClient::GetProxy() if (proxy_ == nullptr) { auto sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (sam == nullptr) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: GetSystemAbilityManager is null", __func__); + ACCESSTOKEN_LOG_DEBUG(LABEL, "GetSystemAbilityManager is null"); return nullptr; } auto accesstokenSa = sam->GetSystemAbility(IAccessTokenManager::SA_ID_ACCESSTOKEN_MANAGER_SERVICE); if (accesstokenSa == nullptr) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: GetSystemAbility %{public}d is null", __func__, + ACCESSTOKEN_LOG_DEBUG(LABEL, "GetSystemAbility %{public}d is null", IAccessTokenManager::SA_ID_ACCESSTOKEN_MANAGER_SERVICE); return nullptr; } auto proxy = iface_cast(accesstokenSa); if (proxy == nullptr) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: iface_cast get null", __func__); + ACCESSTOKEN_LOG_DEBUG(LABEL, "iface_cast get null"); return nullptr; } proxy_ = proxy; } } - return proxy_; } } // namespace AccessToken diff --git a/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.h b/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.h old mode 100755 new mode 100644 index e3a9263f9..d3cc13fca --- a/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.h +++ b/interfaces/innerkits/accesstoken/src/accesstoken_manager_client.h @@ -57,6 +57,14 @@ public: int UpdateHapToken(AccessTokenID tokenID, const std::string& appIDDesc, const HapPolicyParams& policy); int GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfo& hapTokenInfoRes); int GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfo& nativeTokenInfoRes); + int GetHapTokenInfoFromRemote(AccessTokenID tokenID, HapTokenInfoForSync& hapSync); + int GetAllNativeTokenInfo(std::vector& nativeTokenInfosRes); + int SetRemoteHapTokenInfo(const std::string& deviceID, const HapTokenInfoForSync& hapSync); + int SetRemoteNativeTokenInfo(const std::string& deviceID, + std::vector& nativeTokenInfoList); + int DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID); + int DeleteRemoteDeviceTokens(const std::string& deviceID); + int DumpToken(std::string& dumpInfo); private: AccessTokenManagerClient(); diff --git a/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.cpp b/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.cpp index 0f330c8d5..ea3fc1e4d 100644 --- a/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.cpp +++ b/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.cpp @@ -39,11 +39,11 @@ int AccessTokenManagerProxy::VerifyAccessToken(AccessTokenID tokenID, const std: MessageParcel data; data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); if (!data.WriteUint32(tokenID)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write tokenID", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write tokenID"); return PERMISSION_DENIED; } if (!data.WriteString(permissionName)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write permissionName", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write permissionName"); return PERMISSION_DENIED; } @@ -51,18 +51,18 @@ int AccessTokenManagerProxy::VerifyAccessToken(AccessTokenID tokenID, const std: MessageOption option; sptr remote = Remote(); if (remote == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); return PERMISSION_DENIED; } int32_t requestResult = remote->SendRequest( static_cast(IAccessTokenManager::InterfaceCode::VERIFY_ACCESSTOKEN), data, reply, option); if (requestResult != NO_ERROR) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d", requestResult); return PERMISSION_DENIED; } int32_t result = reply.ReadInt32(); - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); return result; } @@ -72,7 +72,7 @@ int AccessTokenManagerProxy::GetDefPermission( MessageParcel data; data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); if (!data.WriteString(permissionName)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write permissionName", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write permissionName"); return RET_FAILED; } @@ -80,24 +80,24 @@ int AccessTokenManagerProxy::GetDefPermission( MessageOption option; sptr remote = Remote(); if (remote == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); return RET_FAILED; } int32_t requestResult = remote->SendRequest( static_cast(IAccessTokenManager::InterfaceCode::GET_DEF_PERMISSION), data, reply, option); if (requestResult != NO_ERROR) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d", requestResult); return RET_FAILED; } sptr resultSptr = reply.ReadParcelable(); if (resultSptr == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s ReadParcelable fail", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "read permission def parcel fail"); return RET_FAILED; } permissionDefResult = *resultSptr; int32_t result = reply.ReadInt32(); - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); return result; } @@ -107,7 +107,7 @@ int AccessTokenManagerProxy::GetDefPermissions(AccessTokenID tokenID, MessageParcel data; data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); if (!data.WriteUint32(tokenID)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write tokenID", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write tokenID"); return RET_FAILED; } @@ -115,13 +115,13 @@ int AccessTokenManagerProxy::GetDefPermissions(AccessTokenID tokenID, MessageOption option; sptr remote = Remote(); if (remote == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); return RET_FAILED; } int32_t requestResult = remote->SendRequest( static_cast(IAccessTokenManager::InterfaceCode::GET_DEF_PERMISSIONS), data, reply, option); if (requestResult != NO_ERROR) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d", requestResult); return RET_FAILED; } @@ -133,7 +133,7 @@ int AccessTokenManagerProxy::GetDefPermissions(AccessTokenID tokenID, } } int32_t result = reply.ReadInt32(); - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); return result; } @@ -143,11 +143,11 @@ int AccessTokenManagerProxy::GetReqPermissions( MessageParcel data; data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); if (!data.WriteUint32(tokenID)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write tokenID", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write tokenID"); return RET_FAILED; } if (!data.WriteInt32(isSystemGrant)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write isSystemGrant", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write isSystemGrant"); return RET_FAILED; } @@ -155,13 +155,13 @@ int AccessTokenManagerProxy::GetReqPermissions( MessageOption option; sptr remote = Remote(); if (remote == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); return RET_FAILED; } int32_t requestResult = remote->SendRequest( static_cast(IAccessTokenManager::InterfaceCode::GET_REQ_PERMISSIONS), data, reply, option); if (requestResult != NO_ERROR) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d", requestResult); return RET_FAILED; } @@ -173,7 +173,7 @@ int AccessTokenManagerProxy::GetReqPermissions( } } int32_t result = reply.ReadInt32(); - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); return result; } @@ -182,11 +182,11 @@ int AccessTokenManagerProxy::GetPermissionFlag(AccessTokenID tokenID, const std: MessageParcel data; data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); if (!data.WriteUint32(tokenID)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write tokenID", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write tokenID"); return DEFAULT_PERMISSION_FLAGS; } if (!data.WriteString(permissionName)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write permissionName", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write permissionName"); return DEFAULT_PERMISSION_FLAGS; } @@ -194,18 +194,18 @@ int AccessTokenManagerProxy::GetPermissionFlag(AccessTokenID tokenID, const std: MessageOption option; sptr remote = Remote(); if (remote == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); return DEFAULT_PERMISSION_FLAGS; } int32_t requestResult = remote->SendRequest( static_cast(IAccessTokenManager::InterfaceCode::GET_PERMISSION_FLAG), data, reply, option); if (requestResult != NO_ERROR) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d", requestResult); return DEFAULT_PERMISSION_FLAGS; } int32_t result = reply.ReadInt32(); - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); return result; } @@ -214,15 +214,15 @@ int AccessTokenManagerProxy::GrantPermission(AccessTokenID tokenID, const std::s MessageParcel data; data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); if (!data.WriteUint32(tokenID)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write tokenID", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write tokenID"); return RET_FAILED; } if (!data.WriteString(permissionName)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write permissionName", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write permissionName"); return RET_FAILED; } if (!data.WriteInt32(flag)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write flag", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write flag"); return RET_FAILED; } @@ -230,18 +230,18 @@ int AccessTokenManagerProxy::GrantPermission(AccessTokenID tokenID, const std::s MessageOption option; sptr remote = Remote(); if (remote == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); return RET_FAILED; } int32_t requestResult = remote->SendRequest( static_cast(IAccessTokenManager::InterfaceCode::GRANT_PERMISSION), data, reply, option); if (requestResult != NO_ERROR) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d", requestResult); return RET_FAILED; } int32_t result = reply.ReadInt32(); - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); return result; } @@ -250,15 +250,15 @@ int AccessTokenManagerProxy::RevokePermission(AccessTokenID tokenID, const std:: MessageParcel data; data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); if (!data.WriteUint32(tokenID)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write tokenID", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write tokenID"); return RET_FAILED; } if (!data.WriteString(permissionName)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write permissionName", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write permissionName"); return RET_FAILED; } if (!data.WriteInt32(flag)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write flag", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write flag"); return RET_FAILED; } @@ -266,18 +266,18 @@ int AccessTokenManagerProxy::RevokePermission(AccessTokenID tokenID, const std:: MessageOption option; sptr remote = Remote(); if (remote == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); return RET_FAILED; } int32_t requestResult = remote->SendRequest( static_cast(IAccessTokenManager::InterfaceCode::REVOKE_PERMISSION), data, reply, option); if (requestResult != NO_ERROR) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d", requestResult); return RET_FAILED; } int32_t result = reply.ReadInt32(); - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); return result; } @@ -286,7 +286,7 @@ int AccessTokenManagerProxy::ClearUserGrantedPermissionState(AccessTokenID token MessageParcel data; data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); if (!data.WriteUint32(tokenID)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write tokenID", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write tokenID"); return RET_FAILED; } @@ -294,18 +294,18 @@ int AccessTokenManagerProxy::ClearUserGrantedPermissionState(AccessTokenID token MessageOption option; sptr remote = Remote(); if (remote == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); return RET_FAILED; } int32_t requestResult = remote->SendRequest( static_cast(IAccessTokenManager::InterfaceCode::CLEAR_USER_GRANT_PERMISSION), data, reply, option); if (requestResult != NO_ERROR) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d", requestResult); return RET_FAILED; } int32_t result = reply.ReadInt32(); - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); return result; } @@ -329,20 +329,20 @@ AccessTokenIDEx AccessTokenManagerProxy::AllocHapToken( MessageOption option; sptr remote = Remote(); if (remote == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); res.tokenIDEx = 0; return res; } int32_t requestResult = remote->SendRequest( static_cast(IAccessTokenManager::InterfaceCode::ALLOC_TOKEN_HAP), data, reply, option); if (requestResult != NO_ERROR) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d", requestResult); res.tokenIDEx = 0; return res; } unsigned long long result = reply.ReadUint64(); - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}llu", __func__, result); + ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}llu", result); res.tokenIDEx = result; return res; } @@ -353,7 +353,7 @@ int AccessTokenManagerProxy::DeleteToken(AccessTokenID tokenID) data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); if (!data.WriteUint32(tokenID)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write tokenID", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write tokenID"); return RET_FAILED; } @@ -361,18 +361,18 @@ int AccessTokenManagerProxy::DeleteToken(AccessTokenID tokenID) MessageOption option; sptr remote = Remote(); if (remote == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); return RET_FAILED; } int32_t requestResult = remote->SendRequest( static_cast(IAccessTokenManager::InterfaceCode::TOKEN_DELETE), data, reply, option); if (requestResult != NO_ERROR) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d", requestResult); return RET_FAILED; } int result = reply.ReadInt32(); - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); return result; } @@ -382,7 +382,7 @@ int AccessTokenManagerProxy::GetTokenType(AccessTokenID tokenID) data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); if (!data.WriteUint32(tokenID)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write tokenID", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write tokenID"); return RET_FAILED; } @@ -390,18 +390,18 @@ int AccessTokenManagerProxy::GetTokenType(AccessTokenID tokenID) MessageOption option; sptr remote = Remote(); if (remote == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); return RET_FAILED; } int32_t requestResult = remote->SendRequest( static_cast(IAccessTokenManager::InterfaceCode::GET_TOKEN_TYPE), data, reply, option); if (requestResult != NO_ERROR) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d", requestResult); return RET_FAILED; } int result = reply.ReadInt32(); - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); return result; } @@ -411,29 +411,29 @@ int AccessTokenManagerProxy::CheckNativeDCap(AccessTokenID tokenID, const std::s data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); if (!data.WriteUint32(tokenID)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write tokenID", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write tokenID"); return RET_FAILED; } if (!data.WriteString(dcap)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write dcap", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write dcap"); return RET_FAILED; } MessageParcel reply; MessageOption option; sptr remote = Remote(); if (remote == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); return RET_FAILED; } int32_t requestResult = remote->SendRequest( static_cast(IAccessTokenManager::InterfaceCode::CHECK_NATIVE_DCAP), data, reply, option); if (requestResult != NO_ERROR) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d", requestResult); return RET_FAILED; } int result = reply.ReadInt32(); - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); return result; } @@ -443,33 +443,33 @@ AccessTokenID AccessTokenManagerProxy::GetHapTokenID(int userID, const std::stri data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); if (!data.WriteInt32(userID)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write tokenID", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write tokenID"); return 0; } if (!data.WriteString(bundleName)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write dcap", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write dcap"); return 0; } if (!data.WriteInt32(instIndex)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write dcap", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write dcap"); return 0; } MessageParcel reply; MessageOption option; sptr remote = Remote(); if (remote == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); return 0; } int32_t requestResult = remote->SendRequest( static_cast(IAccessTokenManager::InterfaceCode::GET_HAP_TOKEN_ID), data, reply, option); if (requestResult != NO_ERROR) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d", requestResult); return 0; } int result = reply.ReadInt32(); - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + ACCESSTOKEN_LOG_DEBUG(LABEL, "result from server data = %{public}d", result); return result; } @@ -480,29 +480,29 @@ AccessTokenID AccessTokenManagerProxy::AllocLocalTokenID( data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); if (!data.WriteString(remoteDeviceID)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write dcap", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write dcap"); return 0; } if (!data.WriteUint32(remoteTokenID)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write dcap", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write dcap"); return 0; } MessageParcel reply; MessageOption option; sptr remote = Remote(); if (remote == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); return 0; } int32_t requestResult = remote->SendRequest( static_cast(IAccessTokenManager::InterfaceCode::ALLOC_LOCAL_TOKEN_ID), data, reply, option); if (requestResult != NO_ERROR) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + ACCESSTOKEN_LOG_ERROR(LABEL, "request fail, result: %{public}d", requestResult); return 0; } AccessTokenID result = reply.ReadUint32(); - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", result); return result; } @@ -511,7 +511,7 @@ int AccessTokenManagerProxy::GetNativeTokenInfo(AccessTokenID tokenID, NativeTok MessageParcel data; data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); if (!data.WriteUint32(tokenID)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write permissionName", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write permissionName"); return RET_FAILED; } @@ -519,24 +519,24 @@ int AccessTokenManagerProxy::GetNativeTokenInfo(AccessTokenID tokenID, NativeTok MessageOption option; sptr remote = Remote(); if (remote == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); return RET_FAILED; } int32_t requestResult = remote->SendRequest( static_cast(IAccessTokenManager::InterfaceCode::GET_NATIVE_TOKENINFO), data, reply, option); if (requestResult != NO_ERROR) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); return RET_FAILED; } sptr resultSptr = reply.ReadParcelable(); if (resultSptr == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s ReadParcelable fail", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "ReadParcelable fail"); return RET_FAILED; } nativeTokenInfoRes = *resultSptr; int32_t result = reply.ReadInt32(); - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", result); return result; } @@ -545,7 +545,7 @@ int AccessTokenManagerProxy::GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfo MessageParcel data; data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); if (!data.WriteUint32(tokenID)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write permissionName", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write permissionName"); return RET_FAILED; } @@ -553,24 +553,24 @@ int AccessTokenManagerProxy::GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfo MessageOption option; sptr remote = Remote(); if (remote == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); return RET_FAILED; } int32_t requestResult = remote->SendRequest( static_cast(IAccessTokenManager::InterfaceCode::GET_HAP_TOKENINFO), data, reply, option); if (requestResult != NO_ERROR) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); return RET_FAILED; } sptr resultSptr = reply.ReadParcelable(); if (resultSptr == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s ReadParcelable fail", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "ReadParcelable fail"); return RET_FAILED; } hapTokenInfoRes = *resultSptr; int32_t result = reply.ReadInt32(); - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", result); return result; } @@ -593,18 +593,236 @@ int AccessTokenManagerProxy::UpdateHapToken(AccessTokenID tokenID, MessageOption option; sptr remote = Remote(); if (remote == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); return RET_FAILED; } int32_t requestResult = remote->SendRequest( static_cast(IAccessTokenManager::InterfaceCode::UPDATE_HAP_TOKEN), data, reply, option); if (requestResult != NO_ERROR) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); return RET_FAILED; } int32_t result = reply.ReadInt32(); - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", result); + return result; +} + +int AccessTokenManagerProxy::GetHapTokenInfoFromRemote(AccessTokenID tokenID, + HapTokenInfoForSyncParcel& hapSyncParcel) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteUint32(tokenID)) { + return RET_FAILED; + } + + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::GET_HAP_TOKEN_FROM_REMOTE), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); + return RET_FAILED; + } + + sptr hapResult = reply.ReadParcelable(); + if (hapResult == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ReadParcelable fail"); + return RET_FAILED; + } + hapSyncParcel = *hapResult; + + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", result); + return result; +} + +int AccessTokenManagerProxy::GetAllNativeTokenInfo(std::vector& nativeTokenInfoRes) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::GET_ALL_NATIVE_TOKEN_FROM_REMOTE), + data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); + return RET_FAILED; + } + + int32_t size = reply.ReadInt32(); + for (int i = 0; i < size; i++) { + sptr nativeResult = reply.ReadParcelable(); + if (nativeResult != nullptr) { + nativeTokenInfoRes.emplace_back(*nativeResult); + } + } + + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", result); + return result; +} + +int AccessTokenManagerProxy::SetRemoteHapTokenInfo(const std::string& deviceID, + HapTokenInfoForSyncParcel& hapSyncParcel) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteString(deviceID)) { + return RET_FAILED; + } + if (!data.WriteParcelable(&hapSyncParcel)) { + return RET_FAILED; + } + + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::SET_REMOTE_HAP_TOKEN_INFO), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); + return RET_FAILED; + } + + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", result); + return result; +} + +int AccessTokenManagerProxy::SetRemoteNativeTokenInfo(const std::string& deviceID, + std::vector& nativeTokenInfoParcel) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteString(deviceID)) { + return RET_FAILED; + } + if (!data.WriteUint32(nativeTokenInfoParcel.size())) { + return RET_FAILED; + } + for (NativeTokenInfoParcel& parcel : nativeTokenInfoParcel) { + if (!data.WriteParcelable(&parcel)) { + return RET_FAILED; + } + } + + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::SET_REMOTE_NATIVE_TOKEN_INFO), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); + return RET_FAILED; + } + + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", result); + return result; +} + +int AccessTokenManagerProxy::DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteString(deviceID)) { + return RET_FAILED; + } + + if (!data.WriteUint32(tokenID)) { + return RET_FAILED; + } + + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::DELETE_REMOTE_TOKEN_INFO), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); + return RET_FAILED; + } + + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", result); + return result; +} + +int AccessTokenManagerProxy::DeleteRemoteDeviceTokens(const std::string& deviceID) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + if (!data.WriteString(deviceID)) { + return RET_FAILED; + } + + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null." ); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::DELETE_REMOTE_DEVICE_TOKEN), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); + return RET_FAILED; + } + + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", result); + return result; +} + +int AccessTokenManagerProxy::DumpToken(std::string& dumpInfo) +{ + MessageParcel data; + data.WriteInterfaceToken(IAccessTokenManager::GetDescriptor()); + + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return RET_FAILED; + } + int32_t requestResult = remote->SendRequest( + static_cast(IAccessTokenManager::InterfaceCode::DUMP), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); + return RET_FAILED; + } + + dumpInfo = reply.ReadString(); + AccessTokenID result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", result); return result; } } // namespace AccessToken diff --git a/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.h b/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.h index 973714702..55655a6f4 100644 --- a/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.h +++ b/interfaces/innerkits/accesstoken/src/accesstoken_manager_proxy.h @@ -23,6 +23,7 @@ #include "hap_info_parcel.h" #include "hap_policy_parcel.h" #include "hap_token_info_parcel.h" +#include "hap_token_info_for_sync_parcel.h" #include "i_accesstoken_manager.h" #include "iremote_proxy.h" #include "native_token_info_parcel.h" @@ -56,6 +57,16 @@ public: const HapPolicyParcel& policyPar) override; int GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfoParcel& hapTokenInfoRes) override; int GetNativeTokenInfo(AccessTokenID tokenID, NativeTokenInfoParcel& nativeTokenInfoRes) override; + + int GetHapTokenInfoFromRemote(AccessTokenID tokenID, HapTokenInfoForSyncParcel& hapSyncParcel) override; + int GetAllNativeTokenInfo(std::vector& nativeTokenInfoRes) override; + int SetRemoteHapTokenInfo(const std::string& deviceID, HapTokenInfoForSyncParcel& hapSyncParcel) override; + int SetRemoteNativeTokenInfo(const std::string& deviceID, + std::vector& nativeTokenInfoParcel) override; + int DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID) override; + int DeleteRemoteDeviceTokens(const std::string& deviceID) override; + + int DumpToken(std::string& dumpInfo) override; private: static inline BrokerDelegator delegator_; }; diff --git a/interfaces/innerkits/tokensync/BUILD.gn b/interfaces/innerkits/tokensync/BUILD.gn index 1d8ba9af6..aa92f46a9 100644 --- a/interfaces/innerkits/tokensync/BUILD.gn +++ b/interfaces/innerkits/tokensync/BUILD.gn @@ -36,6 +36,8 @@ ohos_shared_library("libtokensync_sdk") { "//base/security/access_token/frameworks/tokensync/include", "//base/security/access_token/frameworks/common/include", "//base/security/access_token/interfaces/innerkits/tokensync/include", + "//base/security/access_token/interfaces/innerkits/accesstoken/include", + "//base/security/access_token/frameworks/accesstoken/include", #"//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk/main/cpp/include/permission", ] @@ -44,14 +46,15 @@ ohos_shared_library("libtokensync_sdk") { #"main/cpp/src/permission/permission_kit.cpp", #"main/cpp/src/permission/permission_manager_client.cpp", #"main/cpp/src/permission/permission_manager_proxy.cpp", - "src/tokensync_kit.cpp", - "src/tokensync_manager_client.cpp", - "src/tokensync_manager_proxy.cpp", + "src/token_sync_kit.cpp", + "src/token_sync_manager_client.cpp", + "src/token_sync_manager_proxy.cpp", ] deps = [ #"//base/security/permission/frameworks/permission_standard/permissioncommunicationadapter:permission_standard_communication_adapter_cxx", #"//base/security/permission/frameworks/permission_standard/permissioninfrastructure:permission_standard_infrastructure_cxx", + "//base/security/access_token/frameworks/accesstoken:accesstoken_communication_adapter_cxx", "//utils/native/base:utils", ] diff --git a/interfaces/innerkits/tokensync/include/tokensync_kit.h b/interfaces/innerkits/tokensync/include/token_sync_kit.h similarity index 69% rename from interfaces/innerkits/tokensync/include/tokensync_kit.h rename to interfaces/innerkits/tokensync/include/token_sync_kit.h index 3ac9d29ee..e72b00594 100644 --- a/interfaces/innerkits/tokensync/include/tokensync_kit.h +++ b/interfaces/innerkits/tokensync/include/token_sync_kit.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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 @@ -19,12 +19,17 @@ #include #include +#include "access_token.h" +#include "hap_token_info.h" + namespace OHOS { namespace Security { namespace AccessToken { class TokenSyncKit { public: - static int VerifyPermission(const std::string& bundleName, const std::string& permissionName, int userId); + static int GetRemoteHapTokenInfo(const std::string& deviceID, AccessTokenID tokenID); + static int DeleteRemoteHapTokenInfo(AccessTokenID tokenID); + static int UpdateRemoteHapTokenInfo(const HapTokenInfoForSync& tokenInfo); }; } // namespace AccessToken } // namespace Security diff --git a/interfaces/innerkits/tokensync/src/tokensync_kit.cpp b/interfaces/innerkits/tokensync/src/token_sync_kit.cpp similarity index 47% rename from interfaces/innerkits/tokensync/src/tokensync_kit.cpp rename to interfaces/innerkits/tokensync/src/token_sync_kit.cpp index 2fbaee384..090153e7b 100644 --- a/interfaces/innerkits/tokensync/src/tokensync_kit.cpp +++ b/interfaces/innerkits/tokensync/src/token_sync_kit.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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 @@ -13,13 +13,13 @@ * limitations under the License. */ -#include "tokensync_kit.h" +#include "token_sync_kit.h" #include #include #include "accesstoken_log.h" -#include "tokensync_manager_client.h" +#include "token_sync_manager_client.h" namespace OHOS { namespace Security { @@ -30,12 +30,23 @@ namespace { static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "TokenSyncKit"}; } // namespace -int TokenSyncKit::VerifyPermission(const string& bundleName, const string& permissionName, int userId) +int TokenSyncKit::GetRemoteHapTokenInfo(const std::string& deviceID, AccessTokenID tokenID) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); - ACCESSTOKEN_LOG_INFO(LABEL, "bundleName=%{public}s, permissionName=%{public}s, userId=%{public}d", - bundleName.c_str(), permissionName.c_str(), userId); - return TokenSyncManagerClient::GetInstance().VerifyPermission(bundleName, permissionName, userId); + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID=%{public}s tokenID=%{public}d", + __func__, deviceID.c_str(), tokenID); + return TokenSyncManagerClient::GetInstance().GetRemoteHapTokenInfo(deviceID, tokenID); +} + +int TokenSyncKit::DeleteRemoteHapTokenInfo(AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, tokenID=%{public}d", __func__, tokenID); + return TokenSyncManagerClient::GetInstance().DeleteRemoteHapTokenInfo(tokenID); +} + +int TokenSyncKit::UpdateRemoteHapTokenInfo(const HapTokenInfoForSync& tokenInfo) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called tokenID=%{public}d", __func__, tokenInfo.baseInfo.tokenID); + return TokenSyncManagerClient::GetInstance().UpdateRemoteHapTokenInfo(tokenInfo); } } // namespace AccessToken } // namespace Security diff --git a/interfaces/innerkits/tokensync/src/tokensync_manager_client.cpp b/interfaces/innerkits/tokensync/src/token_sync_manager_client.cpp similarity index 59% rename from interfaces/innerkits/tokensync/src/tokensync_manager_client.cpp rename to interfaces/innerkits/tokensync/src/token_sync_manager_client.cpp index b63d0ab49..87f4ccfa0 100644 --- a/interfaces/innerkits/tokensync/src/tokensync_manager_client.cpp +++ b/interfaces/innerkits/tokensync/src/token_sync_manager_client.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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 @@ -13,10 +13,10 @@ * limitations under the License. */ -#include "tokensync_manager_client.h" +#include "token_sync_manager_client.h" #include "accesstoken_log.h" - +#include "hap_token_info_for_sync_parcel.h" #include "iservice_registry.h" namespace OHOS { @@ -38,35 +38,57 @@ TokenSyncManagerClient::TokenSyncManagerClient() TokenSyncManagerClient::~TokenSyncManagerClient() {} -int TokenSyncManagerClient::VerifyPermission( - const std::string& bundleName, const std::string& permissionName, int userId) const +int TokenSyncManagerClient::GetRemoteHapTokenInfo(const std::string& deviceID, AccessTokenID tokenID) const +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return -1; + } + return proxy->GetRemoteHapTokenInfo(deviceID, tokenID); +} + +int TokenSyncManagerClient::DeleteRemoteHapTokenInfo(AccessTokenID tokenID) const { ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); auto proxy = GetProxy(); if (proxy == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); + return -1; + } + return proxy->DeleteRemoteHapTokenInfo(tokenID); +} + +int TokenSyncManagerClient::UpdateRemoteHapTokenInfo(const HapTokenInfoForSync& tokenInfo) const +{ + + ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: called!", __func__); + auto proxy = GetProxy(); + if (proxy == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "proxy is null"); return -1; } - return proxy->VerifyPermission(bundleName, permissionName, userId); + return proxy->UpdateRemoteHapTokenInfo(tokenInfo); } sptr TokenSyncManagerClient::GetProxy() const { auto sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (sam == nullptr) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: GetSystemAbilityManager is null", __func__); + ACCESSTOKEN_LOG_DEBUG(LABEL, "GetSystemAbilityManager is null"); return nullptr; } auto tokensyncSa = sam->GetSystemAbility(ITokenSyncManager::SA_ID_TOKENSYNC_MANAGER_SERVICE); if (tokensyncSa == nullptr) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: GetSystemAbility %{public}d is null", __func__, + ACCESSTOKEN_LOG_DEBUG(LABEL, "GetSystemAbility %{public}d is null", ITokenSyncManager::SA_ID_TOKENSYNC_MANAGER_SERVICE); return nullptr; } auto proxy = iface_cast(tokensyncSa); if (proxy == nullptr) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: iface_cast get null", __func__); + ACCESSTOKEN_LOG_DEBUG(LABEL, "iface_cast get null"); return nullptr; } return proxy; diff --git a/interfaces/innerkits/tokensync/src/tokensync_manager_client.h b/interfaces/innerkits/tokensync/src/token_sync_manager_client.h similarity index 75% rename from interfaces/innerkits/tokensync/src/tokensync_manager_client.h rename to interfaces/innerkits/tokensync/src/token_sync_manager_client.h index a44602772..f416cba31 100644 --- a/interfaces/innerkits/tokensync/src/tokensync_manager_client.h +++ b/interfaces/innerkits/tokensync/src/token_sync_manager_client.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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 @@ -18,8 +18,9 @@ #include -#include "i_tokensync_manager.h" - +#include "access_token.h" +#include "hap_token_info.h" +#include "i_token_sync_manager.h" #include "nocopyable.h" namespace OHOS { @@ -31,7 +32,9 @@ public: virtual ~TokenSyncManagerClient(); - int VerifyPermission(const std::string& bundleName, const std::string& permissionName, int userId) const; + int GetRemoteHapTokenInfo(const std::string& deviceID, AccessTokenID tokenID) const; + int DeleteRemoteHapTokenInfo(AccessTokenID tokenID) const; + int UpdateRemoteHapTokenInfo(const HapTokenInfoForSync& tokenInfo) const; private: TokenSyncManagerClient(); diff --git a/interfaces/innerkits/tokensync/src/tokensync_manager_proxy.cpp b/interfaces/innerkits/tokensync/src/token_sync_manager_proxy.cpp similarity index 37% rename from interfaces/innerkits/tokensync/src/tokensync_manager_proxy.cpp rename to interfaces/innerkits/tokensync/src/token_sync_manager_proxy.cpp index f1988a60e..bf603c590 100644 --- a/interfaces/innerkits/tokensync/src/tokensync_manager_proxy.cpp +++ b/interfaces/innerkits/tokensync/src/token_sync_manager_proxy.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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 @@ -13,10 +13,9 @@ * limitations under the License. */ -#include "tokensync_manager_proxy.h" +#include "token_sync_manager_proxy.h" #include "accesstoken_log.h" - #include "parcel.h" #include "string_ex.h" @@ -33,21 +32,76 @@ TokenSyncManagerProxy::TokenSyncManagerProxy(const sptr& impl) : TokenSyncManagerProxy::~TokenSyncManagerProxy() {} -int TokenSyncManagerProxy::VerifyPermission( - const std::string& bundleName, const std::string& permissionName, int userId) +int TokenSyncManagerProxy::GetRemoteHapTokenInfo(const std::string& deviceID, AccessTokenID tokenID) { MessageParcel data; data.WriteInterfaceToken(ITokenSyncManager::GetDescriptor()); - if (!data.WriteString(bundleName)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write bundleName", __func__); + if (!data.WriteString(deviceID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write deviceID"); + return -1; + } + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write tokenID"); + return -1; + } + + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return -1; + } + int32_t requestResult = remote->SendRequest( + static_cast(ITokenSyncManager::InterfaceCode::GET_REMOTE_HAP_TOKEN_INFO), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); return -1; } - if (!data.WriteString(permissionName)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write permissionName", __func__); + + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", result); + return result; +} + +int TokenSyncManagerProxy::DeleteRemoteHapTokenInfo(AccessTokenID tokenID) +{ + MessageParcel data; + data.WriteInterfaceToken(ITokenSyncManager::GetDescriptor()); + if (!data.WriteUint32(tokenID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write tokenID"); return -1; } - if (!data.WriteInt32(userId)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: Failed to write userId", __func__); + + MessageParcel reply; + MessageOption option; + sptr remote = Remote(); + if (remote == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); + return -1; + } + int32_t requestResult = remote->SendRequest( + static_cast(ITokenSyncManager::InterfaceCode::DELETE_REMOTE_HAP_TOKEN_INFO), data, reply, option); + if (requestResult != NO_ERROR) { + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); + return -1; + } + + int32_t result = reply.ReadInt32(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", result); + return result; +} + +int TokenSyncManagerProxy::UpdateRemoteHapTokenInfo(const HapTokenInfoForSync& tokenInfo) +{ + MessageParcel data; + data.WriteInterfaceToken(ITokenSyncManager::GetDescriptor()); + + HapTokenInfoForSyncParcel tokenInfoParcel; + tokenInfoParcel.hapTokenInfoForSyncParams = tokenInfo; + + if (!data.WriteParcelable(&tokenInfoParcel)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Failed to write tokenInfo"); return -1; } @@ -55,18 +109,18 @@ int TokenSyncManagerProxy::VerifyPermission( MessageOption option; sptr remote = Remote(); if (remote == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "remote service null."); return -1; } int32_t requestResult = remote->SendRequest( - static_cast(ITokenSyncManager::InterfaceCode::VERIFY_PERMISSION), data, reply, option); + static_cast(ITokenSyncManager::InterfaceCode::UPDATE_REMOTE_HAP_TOKEN_INFO), data, reply, option); if (requestResult != NO_ERROR) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult); + ACCESSTOKEN_LOG_ERROR(LABEL, "send request fail, result: %{public}d", requestResult); return -1; } int32_t result = reply.ReadInt32(); - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result); + ACCESSTOKEN_LOG_DEBUG(LABEL, "get result from server data = %{public}d", result); return result; } } // namespace AccessToken diff --git a/interfaces/innerkits/tokensync/src/tokensync_manager_proxy.h b/interfaces/innerkits/tokensync/src/token_sync_manager_proxy.h similarity index 74% rename from interfaces/innerkits/tokensync/src/tokensync_manager_proxy.h rename to interfaces/innerkits/tokensync/src/token_sync_manager_proxy.h index c92e8be00..6e251e961 100644 --- a/interfaces/innerkits/tokensync/src/tokensync_manager_proxy.h +++ b/interfaces/innerkits/tokensync/src/token_sync_manager_proxy.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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 @@ -18,7 +18,9 @@ #include -#include "i_tokensync_manager.h" +#include "access_token.h" +#include "hap_token_info_for_sync_parcel.h" +#include "i_token_sync_manager.h" #include "iremote_broker.h" #include "iremote_proxy.h" @@ -30,7 +32,9 @@ public: explicit TokenSyncManagerProxy(const sptr& impl); virtual ~TokenSyncManagerProxy() override; - int VerifyPermission(const std::string& packageName, const std::string& permissionName, int userId) override; + int GetRemoteHapTokenInfo(const std::string& deviceID, AccessTokenID tokenID) override; + int DeleteRemoteHapTokenInfo(AccessTokenID tokenID) override; + int UpdateRemoteHapTokenInfo(const HapTokenInfoForSync& tokenInfo) override; private: static inline BrokerDelegator delegator_; diff --git a/interfaces/innerkits/tokensync/test/BUILD.gn b/interfaces/innerkits/tokensync/test/BUILD.gn index 867549338..6744501c4 100644 --- a/interfaces/innerkits/tokensync/test/BUILD.gn +++ b/interfaces/innerkits/tokensync/test/BUILD.gn @@ -26,7 +26,7 @@ ohos_unittest("libtokensync_sdk_test") { "//base/security/access_token/interfaces/innerkits/tokensync/include", ] - sources = [ "unittest/src/tokensync_kit_test.cpp" ] + sources = [ "unittest/src/token_sync_kit_test.cpp" ] cflags_cc = [ "-DHILOG_ENABLE" ] diff --git a/interfaces/innerkits/tokensync/test/unittest/src/tokensync_kit_test.cpp b/interfaces/innerkits/tokensync/test/unittest/src/token_sync_kit_test.cpp similarity index 93% rename from interfaces/innerkits/tokensync/test/unittest/src/tokensync_kit_test.cpp rename to interfaces/innerkits/tokensync/test/unittest/src/token_sync_kit_test.cpp index fab924095..f4587575b 100644 --- a/interfaces/innerkits/tokensync/test/unittest/src/tokensync_kit_test.cpp +++ b/interfaces/innerkits/tokensync/test/unittest/src/token_sync_kit_test.cpp @@ -13,9 +13,9 @@ * limitations under the License. */ -#include "tokensync_kit_test.h" +#include "token_sync_kit_test.h" -#include "tokensync_kit.h" +#include "token_sync_kit.h" using namespace testing::ext; using namespace OHOS::Security::AccessToken; diff --git a/interfaces/innerkits/tokensync/test/unittest/src/tokensync_kit_test.h b/interfaces/innerkits/tokensync/test/unittest/src/token_sync_kit_test.h similarity index 100% rename from interfaces/innerkits/tokensync/test/unittest/src/tokensync_kit_test.h rename to interfaces/innerkits/tokensync/test/unittest/src/token_sync_kit_test.h diff --git a/interfaces/kits/accesstoken/BUILD.gn b/interfaces/kits/accesstoken/BUILD.gn index 619418cab..1c864538f 100644 --- a/interfaces/kits/accesstoken/BUILD.gn +++ b/interfaces/kits/accesstoken/BUILD.gn @@ -51,7 +51,8 @@ ohos_shared_library("libabilityaccessctrl") { ] cflags_cc = [ "-DHILOG_ENABLE" ] external_deps = [ - "ability_base:want", + "ability_runtime:app_manager", + "ability_runtime:want", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", ] diff --git a/services/accesstokenmanager/BUILD.gn b/services/accesstokenmanager/BUILD.gn index a77a08994..62358bea1 100644 --- a/services/accesstokenmanager/BUILD.gn +++ b/services/accesstokenmanager/BUILD.gn @@ -33,6 +33,7 @@ ohos_shared_library("accesstoken_manager_service") { "//base/security/access_token/frameworks/common/include", "//base/security/access_token/frameworks/accesstoken/include", "//base/security/access_token/interfaces/innerkits/accesstoken/include", + "//base/security/access_token/interfaces/innerkits/tokensync/include", "//third_party/json/include", ] @@ -52,9 +53,11 @@ ohos_shared_library("accesstoken_manager_service") { "main/cpp/src/service/accesstoken_manager_stub.cpp", "main/cpp/src/token/accesstoken_id_manager.cpp", "main/cpp/src/token/accesstoken_info_manager.cpp", + "main/cpp/src/token/accesstoken_remote_token_manager.cpp", "main/cpp/src/token/hap_token_info_inner.cpp", "main/cpp/src/token/native_token_info_inner.cpp", "main/cpp/src/token/native_token_receptor.cpp", + "main/cpp/src/token/token_modify_notifier.cpp", ] cflags_cc = [ "-DHILOG_ENABLE" ] @@ -64,6 +67,7 @@ ohos_shared_library("accesstoken_manager_service") { #"//base/security/accesstoken/frameworks/accesstooken/common:permission_standard_infrastructure_cxx", "//base/security/access_token/frameworks/accesstoken:accesstoken_communication_adapter_cxx", "//base/security/access_token/frameworks/common:accesstoken_common_cxx", + "//base/security/access_token/interfaces/innerkits/tokensync:libtokensync_sdk", "//base/security/access_token/services/accesstokenmanager:access_token.rc", "//third_party/sqlite:sqlite", "//utils/native/base:utils", diff --git a/services/accesstokenmanager/main/cpp/include/permission/permission_policy_set.h b/services/accesstokenmanager/main/cpp/include/permission/permission_policy_set.h index 84dc327c7..3208b6f20 100644 --- a/services/accesstokenmanager/main/cpp/include/permission/permission_policy_set.h +++ b/services/accesstokenmanager/main/cpp/include/permission/permission_policy_set.h @@ -48,6 +48,7 @@ public: int QueryPermissionFlag(const std::string& permissionName); void UpdatePermissionStatus(const std::string& permissionName, bool isGranted, int flag); void ToString(std::string& info); + void GetPermissionStateList(std::vector& stateList); private: static void MergePermissionStateFull(std::vector& permStateList, diff --git a/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_service.h b/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_service.h index 401437f40..cbb3cfa14 100644 --- a/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_service.h +++ b/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_service.h @@ -25,6 +25,7 @@ #include "singleton.h" #include "system_ability.h" #include "hap_token_info.h" +#include "access_token.h" namespace OHOS { namespace Security { @@ -57,7 +58,15 @@ public: int GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfoParcel& InfoParcel) override; int UpdateHapToken(AccessTokenID tokenID, const std::string& appIDDesc, const HapPolicyParcel& policyParcel) override; + int GetHapTokenInfoFromRemote(AccessTokenID tokenID, HapTokenInfoForSyncParcel& hapSyncParcel) override; + int GetAllNativeTokenInfo(std::vector& nativeTokenInfosRes) override; + int SetRemoteHapTokenInfo(const std::string& deviceID, HapTokenInfoForSyncParcel& hapSyncParcel) override; + int SetRemoteNativeTokenInfo(const std::string& deviceID, + std::vector& nativeTokenInfoParcel) override; + int DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID) override; + int DeleteRemoteDeviceTokens(const std::string& deviceID) override; + int DumpToken(std::string& dumpInfo) override; private: bool Initialize() const; diff --git a/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_stub.h b/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_stub.h index f01b0edec..c4fbb77e1 100644 --- a/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_stub.h +++ b/services/accesstokenmanager/main/cpp/include/service/accesstoken_manager_stub.h @@ -53,6 +53,15 @@ private: void CheckNativeDCapInner(MessageParcel& data, MessageParcel& reply); void GetTokenTypeInner(MessageParcel& data, MessageParcel& reply); + void GetHapTokenInfoFromRemoteInner(MessageParcel& data, MessageParcel& reply); + void GetAllNativeTokenInfoInner(MessageParcel& data, MessageParcel& reply); + void SetRemoteHapTokenInfoInner(MessageParcel& data, MessageParcel& reply); + void SetRemoteNativeTokenInfoInner(MessageParcel& data, MessageParcel& reply); + void DeleteRemoteTokenInner(MessageParcel& data, MessageParcel& reply); + void DeleteRemoteDeviceTokensInner(MessageParcel& data, MessageParcel& reply); + void GetRemoteHapTokenIDInner(MessageParcel& data, MessageParcel& reply); + void DumpTokenInner(MessageParcel& data, MessageParcel& reply); + bool IsAuthorizedCalling() const; static const int SYSTEM_UID = 1000; static const int ROOT_UID = 0; diff --git a/services/accesstokenmanager/main/cpp/include/token/accesstoken_info_manager.h b/services/accesstokenmanager/main/cpp/include/token/accesstoken_info_manager.h index c8a337350..3e32c69a7 100644 --- a/services/accesstokenmanager/main/cpp/include/token/accesstoken_info_manager.h +++ b/services/accesstokenmanager/main/cpp/include/token/accesstoken_info_manager.h @@ -53,6 +53,17 @@ public: void Dump(std::string& dumpInfo); void RefreshTokenInfoIfNeeded(); + /* tokensync needed */ + int GetHapTokenSync(AccessTokenID tokenID, HapTokenInfoForSync& hapSync); + int GetHapTokenInfoFromRemote(AccessTokenID tokenID, + HapTokenInfoForSync& hapSync); + void GetAllNativeTokenInfo(std::vector& nativeTokenInfosRes); + int SetRemoteHapTokenInfo(const std::string& deviceID, HapTokenInfoForSync& hapSync); + int SetRemoteNativeTokenInfo(const std::string& deviceID, + std::vector& nativeTokenInfoList); + int DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID); + int DeleteRemoteDeviceTokens(const std::string& deviceID); + private: AccessTokenInfoManager(); DISALLOW_COPY_AND_MOVE(AccessTokenInfoManager); diff --git a/services/accesstokenmanager/main/cpp/include/token/accesstoken_remote_token_manager.h b/services/accesstokenmanager/main/cpp/include/token/accesstoken_remote_token_manager.h new file mode 100644 index 000000000..0897d600d --- /dev/null +++ b/services/accesstokenmanager/main/cpp/include/token/accesstoken_remote_token_manager.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 ACCESSTOKEN_TOKEN_REMOTE_TOKEN_MANAGER_H +#define ACCESSTOKEN_TOKEN_REMOTE_TOKEN_MANAGER_H + +#include +#include +#include + +#include "access_token.h" +#include "hap_token_info.h" +#include "hap_token_info_inner.h" +#include "native_token_info.h" +#include "native_token_info_inner.h" +#include "nocopyable.h" +#include "rwlock.h" +#include "thread_pool.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { + +class AccessTokenRemoteDevice final { +public: + std::string DeviceID_; // networkID + std::map MappingTokenIDPairMap_; +}; + +class AccessTokenRemoteTokenManager final { +public: + static AccessTokenRemoteTokenManager& GetInstance(); + ~AccessTokenRemoteTokenManager(); + AccessTokenID MapRemoteDeviceTokenToLocal(const std::string& deviceID, AccessTokenID remoteID); + int GetDeviceAllRemoteTokenID(const std::string& deviceID, std::vector& mapIDs); + AccessTokenID GetDeviceMappingTokenID(const std::string& deviceID, AccessTokenID remoteID); + int RemoveDeviceMappingTokenID(const std::string& deviceID, AccessTokenID remoteID); + +private: + AccessTokenRemoteTokenManager(); + DISALLOW_COPY_AND_MOVE(AccessTokenRemoteTokenManager); + + OHOS::Utils::RWLock remoteDeviceLock_; + std::map remoteDeviceMap_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // ACCESSTOKEN_TOKEN_REMOTE_TOKEN_MANAGER_H + diff --git a/services/accesstokenmanager/main/cpp/include/token/hap_token_info_inner.h b/services/accesstokenmanager/main/cpp/include/token/hap_token_info_inner.h index 9d3557e43..b41808fbc 100644 --- a/services/accesstokenmanager/main/cpp/include/token/hap_token_info_inner.h +++ b/services/accesstokenmanager/main/cpp/include/token/hap_token_info_inner.h @@ -32,11 +32,12 @@ namespace Security { namespace AccessToken { class HapTokenInfoInner final { public: - HapTokenInfoInner() : ver_(DEFAULT_TOKEN_VERSION), tokenID_(0), tokenAttr_(0), userID_(0), - instIndex_(0), apl_(APL_NORMAL) {}; + HapTokenInfoInner(); + HapTokenInfoInner(AccessTokenID id, const HapInfoParams& info, const HapPolicyParams& policy); + HapTokenInfoInner(AccessTokenID id, const HapTokenInfo &info, + const std::vector& permStateList); virtual ~HapTokenInfoInner(); - void Init(AccessTokenID id, const HapInfoParams& info, const HapPolicyParams& policy); void Update(const std::string& appIDDesc, const HapPolicyParams& policy); void TranslateToHapTokenInfo(HapTokenInfo& InfoParcel) const; void StoreHapInfo(std::vector& hapInfoValues, @@ -46,26 +47,25 @@ public: const std::vector& permDefRes, const std::vector& permStateRes); std::shared_ptr GetHapInfoPermissionPolicySet() const; + HapTokenInfo GetHapInfoBasic() const; int GetUserID() const; std::string GetBundleName() const; int GetInstIndex() const; AccessTokenID GetTokenID() const; void ToString(std::string& info) const; + bool IsRemote() const; + void SetRemote(bool isRemote); private: void StoreHapBasicInfo(std::vector& valueList) const; void TranslationIntoGenericValues(GenericValues& outGenericValues) const; int RestoreHapTokenBasicInfo(const GenericValues& inGenericValues); - char ver_; - AccessTokenID tokenID_; - AccessTokenAttr tokenAttr_; - int userID_; - std::string bundleName_; - int instIndex_; - std::string appID_; - std::string deviceID_; - ATokenAplEnum apl_; + HapTokenInfo tokenInfoBasic_; + + // true means sync from remote. + bool isRemote_; + std::shared_ptr permPolicySet_; }; } // namespace AccessToken diff --git a/services/accesstokenmanager/main/cpp/include/token/native_token_info_inner.h b/services/accesstokenmanager/main/cpp/include/token/native_token_info_inner.h index 1a646f8c1..527d176d1 100644 --- a/services/accesstokenmanager/main/cpp/include/token/native_token_info_inner.h +++ b/services/accesstokenmanager/main/cpp/include/token/native_token_info_inner.h @@ -34,7 +34,7 @@ static const std::string JSON_DCAPS = "dcaps"; class NativeTokenInfoInner final { public: - NativeTokenInfoInner() : ver_(DEFAULT_TOKEN_VERSION), tokenID_(0), tokenAttr_(0), apl_(APL_NORMAL) {}; + NativeTokenInfoInner(); NativeTokenInfoInner(NativeTokenInfo& info); virtual ~NativeTokenInfoInner(); @@ -51,18 +51,17 @@ public: std::vector GetDcap() const; AccessTokenID GetTokenID() const; std::string GetProcessName() const; - bool FromJsonString(const std::string& jsonString); + NativeTokenInfo GetNativeTokenInfo() const; + bool IsRemote() const; + void SetRemote(bool isRemote); private: int TranslationIntoGenericValues(GenericValues& outGenericValues) const; std::string DcapToString(const std::vector& dcap) const; - char ver_; - AccessTokenID tokenID_; - AccessTokenAttr tokenAttr_; - std::string processName_; - ATokenAplEnum apl_; - std::vector dcap_; + // true means sync from remote. + bool isRemote_; + NativeTokenInfo tokenInfoBasic_; }; } // namespace AccessToken } // namespace Security diff --git a/services/accesstokenmanager/main/cpp/include/token/token_modify_notifier.h b/services/accesstokenmanager/main/cpp/include/token/token_modify_notifier.h new file mode 100644 index 000000000..c884f37b2 --- /dev/null +++ b/services/accesstokenmanager/main/cpp/include/token/token_modify_notifier.h @@ -0,0 +1,56 @@ +/* + * 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 TOKEN_MODIFY_NOTIFIER_H +#define TOKEN_MODIFY_NOTIFIER_H + +#include +#include + +#include "access_token.h" +#include "nocopyable.h" +#include "rwlock.h" +#include "thread_pool.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class TokenModifyNotifier final { +public: + static TokenModifyNotifier& GetInstance(); + ~TokenModifyNotifier(); + void AddHapTokenObservation(AccessTokenID tokenID); + void NotifyTokenDelete(AccessTokenID tokenID); + void NotifyTokenModify(AccessTokenID tokenID); + void NotifyTokenChangedIfNeed(); + void NotifyTokenSyncTask(); + +private: + TokenModifyNotifier(); + DISALLOW_COPY_AND_MOVE(TokenModifyNotifier); + + bool hasInited_; + OHOS::Utils::RWLock initLock_; + OHOS::Utils::RWLock Notifylock_; + OHOS::ThreadPool notifyTokenWorker_; + std::set observationSet_; + std::vector deleteTokenList_; + std::vector modifiedTokenList_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // TOKEN_MODIFY_NOTIFIER_H + diff --git a/services/accesstokenmanager/main/cpp/src/database/data_translator.cpp b/services/accesstokenmanager/main/cpp/src/database/data_translator.cpp index 4052d8210..d601e0ed4 100644 --- a/services/accesstokenmanager/main/cpp/src/database/data_translator.cpp +++ b/services/accesstokenmanager/main/cpp/src/database/data_translator.cpp @@ -51,7 +51,7 @@ int DataTranslator::TranslationIntoPermissionDef(const GenericValues& inGenericV outPermissionDef.grantMode = inGenericValues.GetInt(FIELD_GRANT_MODE); int aplNum = inGenericValues.GetInt(FIELD_AVAILABLE_LEVEL); if (!DataValidator::IsAplNumValid(aplNum)) { - ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s:Apl is wrong.", __func__); + ACCESSTOKEN_LOG_WARN(LABEL, "Apl is wrong."); return RET_FAILED; } outPermissionDef.availableLevel = (ATokenAplEnum)aplNum; @@ -69,7 +69,7 @@ int DataTranslator::TranslationIntoGenericValues(const PermissionStateFull& inPe { if (grantIndex >= inPermissionState.resDeviceID.size() || grantIndex >= inPermissionState.grantStatus.size() || grantIndex >= inPermissionState.grantFlags.size()) { - ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s: perm status grant size is wrong", __func__); + ACCESSTOKEN_LOG_WARN(LABEL, "perm status grant size is wrong"); return RET_FAILED; } outGenericValues.Put(FIELD_PERMISSION_NAME, inPermissionState.permissionName); @@ -86,27 +86,27 @@ int DataTranslator::TranslationIntoPermissionStateFull(const GenericValues& inGe outPermissionState.isGeneral = ((inGenericValues.GetInt(FIELD_GRANT_IS_GENERAL) == 1) ? true : false); outPermissionState.permissionName = inGenericValues.GetString(FIELD_PERMISSION_NAME); if (!DataValidator::IsPermissionNameValid(outPermissionState.permissionName)) { - ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s: permission name is wrong", __func__); + ACCESSTOKEN_LOG_WARN(LABEL, "permission name is wrong"); return RET_FAILED; } std::string devID = inGenericValues.GetString(FIELD_DEVICE_ID); if (!DataValidator::IsDeviceIdValid(devID)) { - ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s: devID is wrong", __func__); + ACCESSTOKEN_LOG_WARN(LABEL, "devID is wrong"); return RET_FAILED; } outPermissionState.resDeviceID.push_back(devID); int grantStatus = (PermissionState)inGenericValues.GetInt(FIELD_GRANT_STATE); if (!PermissionValidator::IsGrantStatusValid(grantStatus)) { - ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s: grantStatus is wrong", __func__); + ACCESSTOKEN_LOG_WARN(LABEL, "grantStatus is wrong"); return RET_FAILED; } outPermissionState.grantStatus.push_back(grantStatus); int grantFlag = (PermissionState)inGenericValues.GetInt(FIELD_GRANT_FLAG); if (!PermissionValidator::IsPermissionFlagValid(grantFlag)) { - ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s: grantFlag is wrong", __func__); + ACCESSTOKEN_LOG_WARN(LABEL, "grantFlag is wrong"); return RET_FAILED; } outPermissionState.grantFlags.push_back(grantFlag); diff --git a/services/accesstokenmanager/main/cpp/src/database/sqlite_helper.cpp b/services/accesstokenmanager/main/cpp/src/database/sqlite_helper.cpp index 618b9cf2d..0e878fd33 100644 --- a/services/accesstokenmanager/main/cpp/src/database/sqlite_helper.cpp +++ b/services/accesstokenmanager/main/cpp/src/database/sqlite_helper.cpp @@ -66,7 +66,7 @@ void SqliteHelper::Open() void SqliteHelper::Close() { if (db_ == nullptr) { - ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s: do open data base first!", __func__); + ACCESSTOKEN_LOG_WARN(LABEL, "do open data base first!"); return; } int ret = sqlite3_close(db_); @@ -80,14 +80,14 @@ void SqliteHelper::Close() int SqliteHelper::BeginTransaction() const { if (db_ == nullptr) { - ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s: do open data base first!", __func__); + ACCESSTOKEN_LOG_WARN(LABEL, "do open data base first!"); return GENERAL_ERROR; } char* errorMessage = nullptr; int result = 0; int ret = sqlite3_exec(db_, "BEGIN;", nullptr, nullptr, &errorMessage); if (ret != SQLITE_OK) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: failed, errorMsg: %{public}s", __func__, errorMessage); + ACCESSTOKEN_LOG_ERROR(LABEL, "failed, errorMsg: %{public}s", errorMessage); result = GENERAL_ERROR; } sqlite3_free(errorMessage); @@ -97,14 +97,14 @@ int SqliteHelper::BeginTransaction() const int SqliteHelper::CommitTransaction() const { if (db_ == nullptr) { - ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s: do open data base first!", __func__); + ACCESSTOKEN_LOG_WARN(LABEL, "do open data base first!"); return GENERAL_ERROR; } char* errorMessage = nullptr; int result = 0; int ret = sqlite3_exec(db_, "COMMIT;", nullptr, nullptr, &errorMessage); if (ret != SQLITE_OK) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: failed, errorMsg: %{public}s", __func__, errorMessage); + ACCESSTOKEN_LOG_ERROR(LABEL, "failed, errorMsg: %{public}s", errorMessage); result = GENERAL_ERROR; } sqlite3_free(errorMessage); @@ -114,14 +114,14 @@ int SqliteHelper::CommitTransaction() const int SqliteHelper::RollbackTransaction() const { if (db_ == nullptr) { - ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s: do open data base first!", __func__); + ACCESSTOKEN_LOG_WARN(LABEL, "do open data base first!"); return GENERAL_ERROR; } int result = 0; char* errorMessage = nullptr; int ret = sqlite3_exec(db_, "ROLLBACK;", nullptr, nullptr, &errorMessage); if (ret != SQLITE_OK) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: failed, errorMsg: %{public}s", __func__, errorMessage); + ACCESSTOKEN_LOG_ERROR(LABEL, "failed, errorMsg: %{public}s", errorMessage); result = GENERAL_ERROR; } sqlite3_free(errorMessage); @@ -136,14 +136,14 @@ Statement SqliteHelper::Prepare(const std::string& sql) const int SqliteHelper::ExecuteSql(const std::string& sql) const { if (db_ == nullptr) { - ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s: do open data base first!", __func__); + ACCESSTOKEN_LOG_WARN(LABEL, "do open data base first!"); return GENERAL_ERROR; } char* errorMessage = nullptr; int result = 0; int res = sqlite3_exec(db_, sql.c_str(), nullptr, nullptr, &errorMessage); if (res != SQLITE_OK) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: failed, errorMsg: %{public}s", __func__, errorMessage); + ACCESSTOKEN_LOG_ERROR(LABEL, "failed, errorMsg: %{public}s", errorMessage); result = GENERAL_ERROR; } sqlite3_free(errorMessage); @@ -153,7 +153,7 @@ int SqliteHelper::ExecuteSql(const std::string& sql) const int SqliteHelper::GetVersion() const { if (db_ == nullptr) { - ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s: do open data base first!", __func__); + ACCESSTOKEN_LOG_WARN(LABEL, "do open data base first!"); return GENERAL_ERROR; } auto statement = Prepare(PRAGMA_VERSION_COMMAND); @@ -161,14 +161,14 @@ int SqliteHelper::GetVersion() const while (statement.Step() == Statement::State::ROW) { version = statement.GetColumnInt(0); } - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s: version: %{public}d", __func__, version); + ACCESSTOKEN_LOG_INFO(LABEL, "version: %{public}d", version); return version; } void SqliteHelper::SetVersion() const { if (db_ == nullptr) { - ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s: do open data base first!", __func__); + ACCESSTOKEN_LOG_WARN(LABEL, "do open data base first!"); return; } auto statement = Prepare(PRAGMA_VERSION_COMMAND + " = " + std::to_string(currentVersion_)); @@ -178,7 +178,7 @@ void SqliteHelper::SetVersion() const std::string SqliteHelper::SpitError() const { if (db_ == nullptr) { - ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s: do open data base first!", __func__); + ACCESSTOKEN_LOG_WARN(LABEL, "do open data base first!"); return ""; } return sqlite3_errmsg(db_); diff --git a/services/accesstokenmanager/main/cpp/src/database/sqlite_storage.cpp b/services/accesstokenmanager/main/cpp/src/database/sqlite_storage.cpp index 46c1d3797..f929760e3 100644 --- a/services/accesstokenmanager/main/cpp/src/database/sqlite_storage.cpp +++ b/services/accesstokenmanager/main/cpp/src/database/sqlite_storage.cpp @@ -112,17 +112,17 @@ int SqliteStorage::Add(const DataType type, const std::vector& va } int ret = statement.Step(); if (ret != Statement::State::DONE) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: failed, errorMsg: %{public}s", __func__, SpitError().c_str()); + ACCESSTOKEN_LOG_ERROR(LABEL, "failed, errorMsg: %{public}s", SpitError().c_str()); isExecuteSuccessfully = false; } statement.Reset(); } if (!isExecuteSuccessfully) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: rollback transaction.", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "rollback transaction."); RollbackTransaction(); return FAILURE; } - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s: commit transaction.", __func__); + ACCESSTOKEN_LOG_INFO(LABEL, "commit transaction."); CommitTransaction(); return SUCCESS; } @@ -190,17 +190,17 @@ int SqliteStorage::RefreshAll(const DataType type, const std::vector cacheGuard(this->cacheLock_); auto it = permissionDefinitionMap_.find(info.permissionName); if (it != permissionDefinitionMap_.end()) { - ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s: info for permission: %{public}s has been insert, please check!", - __func__, info.permissionName.c_str()); + ACCESSTOKEN_LOG_WARN(LABEL, "info for permission: %{public}s has been insert, please check!", + info.permissionName.c_str()); return false; } permissionDefinitionMap_[info.permissionName] = info; @@ -77,7 +77,7 @@ int PermissionDefinitionCache::FindByPermissionName(const std::string& permissio Utils::UniqueReadGuard cacheGuard(this->cacheLock_); auto it = permissionDefinitionMap_.find(permissionName); if (it == permissionDefinitionMap_.end()) { - ACCESSTOKEN_LOG_DEBUG(LABEL, "%{public}s: can not find definition info for permission: %{public}s", __func__, + ACCESSTOKEN_LOG_DEBUG(LABEL, "can not find definition info for permission: %{public}s", permissionName.c_str()); return RET_FAILED; } diff --git a/services/accesstokenmanager/main/cpp/src/permission/permission_manager.cpp b/services/accesstokenmanager/main/cpp/src/permission/permission_manager.cpp index f648a59b3..018a3f2fa 100644 --- a/services/accesstokenmanager/main/cpp/src/permission/permission_manager.cpp +++ b/services/accesstokenmanager/main/cpp/src/permission/permission_manager.cpp @@ -19,6 +19,7 @@ #include "accesstoken_log.h" #include "permission_definition_cache.h" #include "permission_validator.h" +#include "token_modify_notifier.h" namespace OHOS { namespace Security { @@ -54,7 +55,7 @@ void PermissionManager::AddDefPermissions(std::shared_ptr tok permPolicySet->GetDefPermissions(permList); for (auto perm : permList) { if (!PermissionValidator::IsPermissionDefValid(perm)) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s: invalid permission definition info: %{public}s", __func__, + ACCESSTOKEN_LOG_INFO(LABEL, "invalid permission definition info: %{public}s", TransferPermissionDefToString(perm).c_str()); continue; } @@ -67,7 +68,7 @@ void PermissionManager::AddDefPermissions(std::shared_ptr tok if (!PermissionDefinitionCache::GetInstance().HasDefinition(perm.permissionName)) { PermissionDefinitionCache::GetInstance().Insert(perm); } else { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s: permission %{public}s has define", __func__, + ACCESSTOKEN_LOG_INFO(LABEL, "permission %{public}s has define", TransferPermissionDefToString(perm).c_str()); } } @@ -79,7 +80,7 @@ void PermissionManager::RemoveDefPermissions(AccessTokenID tokenID) std::shared_ptr tokenInfo = AccessTokenInfoManager::GetInstance().GetHapTokenInfoInner(tokenID); if (tokenInfo == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: invalid params(tokenID: 0x%{public}x)!", __func__, tokenID); + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params(tokenID: 0x%{public}x)!", tokenID); return; } std::string bundleName = tokenInfo->GetBundleName(); @@ -91,18 +92,25 @@ int PermissionManager::VerifyAccessToken(AccessTokenID tokenID, const std::strin ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, tokenID: 0x%{public}x, permissionName: %{public}s", __func__, tokenID, permissionName.c_str()); if (!PermissionValidator::IsPermissionNameValid(permissionName)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params!"); return PERMISSION_DENIED; } - if (!PermissionDefinitionCache::GetInstance().HasDefinition(permissionName)) { + std::shared_ptr tokenInfoPtr = + AccessTokenInfoManager::GetInstance().GetHapTokenInfoInner(tokenID); + if (tokenInfoPtr == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "can not find tokenInfo!"); + return PERMISSION_DENIED; + } + + if (!tokenInfoPtr->IsRemote() && !PermissionDefinitionCache::GetInstance().HasDefinition(permissionName)) { ACCESSTOKEN_LOG_ERROR( - LABEL, "%{public}s: no definition for permission: %{public}s!", __func__, permissionName.c_str()); + LABEL, "no definition for permission: %{public}s!", permissionName.c_str()); return PERMISSION_DENIED; } std::shared_ptr permPolicySet = AccessTokenInfoManager::GetInstance().GetHapPermissionPolicySet(tokenID); if (permPolicySet == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params!"); return PERMISSION_DENIED; } @@ -113,12 +121,12 @@ int PermissionManager::GetDefPermission(const std::string& permissionName, Permi { ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permissionName: %{public}s", __func__, permissionName.c_str()); if (!PermissionValidator::IsPermissionNameValid(permissionName)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params!"); return RET_FAILED; } if (!PermissionDefinitionCache::GetInstance().HasDefinition(permissionName)) { ACCESSTOKEN_LOG_ERROR( - LABEL, "%{public}s: no definition for permission: %{public}s!", __func__, permissionName.c_str()); + LABEL, "no definition for permission: %{public}s!", permissionName.c_str()); return RET_FAILED; } return PermissionDefinitionCache::GetInstance().FindByPermissionName(permissionName, permissionDefResult); @@ -130,7 +138,7 @@ int PermissionManager::GetDefPermissions(AccessTokenID tokenID, std::vector permPolicySet = AccessTokenInfoManager::GetInstance().GetHapPermissionPolicySet(tokenID); if (permPolicySet == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params!"); return RET_FAILED; } @@ -146,7 +154,7 @@ int PermissionManager::GetReqPermissions( std::shared_ptr permPolicySet = AccessTokenInfoManager::GetInstance().GetHapPermissionPolicySet(tokenID); if (permPolicySet == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params!"); return RET_FAILED; } @@ -168,18 +176,18 @@ int PermissionManager::GetPermissionFlag(AccessTokenID tokenID, const std::strin ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, tokenID: 0x%{public}x, permissionName: %{public}s", __func__, tokenID, permissionName.c_str()); if (!PermissionValidator::IsPermissionNameValid(permissionName)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params!"); return DEFAULT_PERMISSION_FLAGS; } if (!PermissionDefinitionCache::GetInstance().HasDefinition(permissionName)) { ACCESSTOKEN_LOG_ERROR( - LABEL, "%{public}s: no definition for permission: %{public}s!", __func__, permissionName.c_str()); + LABEL, "no definition for permission: %{public}s!", permissionName.c_str()); return DEFAULT_PERMISSION_FLAGS; } std::shared_ptr permPolicySet = AccessTokenInfoManager::GetInstance().GetHapPermissionPolicySet(tokenID); if (permPolicySet == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params!"); return DEFAULT_PERMISSION_FLAGS; } return permPolicySet->QueryPermissionFlag(permissionName); @@ -191,11 +199,15 @@ void PermissionManager::UpdateTokenPermissionState( std::shared_ptr permPolicySet = AccessTokenInfoManager::GetInstance().GetHapPermissionPolicySet(tokenID); if (permPolicySet == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params!"); return; } permPolicySet->UpdatePermissionStatus(permissionName, isGranted, flag); + std::shared_ptr infoPtr = AccessTokenInfoManager::GetInstance().GetHapTokenInfoInner(tokenID); + if (infoPtr != nullptr && !infoPtr->IsRemote()) { + TokenModifyNotifier::GetInstance().NotifyTokenModify(tokenID); + } AccessTokenInfoManager::GetInstance().RefreshTokenInfoIfNeeded(); } @@ -205,16 +217,16 @@ void PermissionManager::GrantPermission(AccessTokenID tokenID, const std::string "%{public}s called, tokenID: 0x%{public}x, permissionName: %{public}s, flag: %{public}d", __func__, tokenID, permissionName.c_str(), flag); if (!PermissionValidator::IsPermissionNameValid(permissionName)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params!"); return; } if (!PermissionDefinitionCache::GetInstance().HasDefinition(permissionName)) { ACCESSTOKEN_LOG_ERROR( - LABEL, "%{public}s: no definition for permission: %{public}s!", __func__, permissionName.c_str()); + LABEL, "no definition for permission: %{public}s!", permissionName.c_str()); return; } if (!PermissionValidator::IsPermissionFlagValid(flag)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params!"); return; } UpdateTokenPermissionState(tokenID, permissionName, true, flag); @@ -226,16 +238,16 @@ void PermissionManager::RevokePermission(AccessTokenID tokenID, const std::strin "%{public}s called, tokenID: 0x%{public}x, permissionName: %{public}s, flag: %{public}d", __func__, tokenID, permissionName.c_str(), flag); if (!PermissionValidator::IsPermissionNameValid(permissionName)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params!"); return; } if (!PermissionDefinitionCache::GetInstance().HasDefinition(permissionName)) { ACCESSTOKEN_LOG_ERROR( - LABEL, "%{public}s: no definition for permission: %{public}s!", __func__, permissionName.c_str()); + LABEL, "no definition for permission: %{public}s!", permissionName.c_str()); return; } if (!PermissionValidator::IsPermissionFlagValid(flag)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params!"); return; } UpdateTokenPermissionState(tokenID, permissionName, false, flag); @@ -247,7 +259,7 @@ void PermissionManager::ClearUserGrantedPermissionState(AccessTokenID tokenID) std::shared_ptr permPolicySet = AccessTokenInfoManager::GetInstance().GetHapPermissionPolicySet(tokenID); if (permPolicySet == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params!"); return; } diff --git a/services/accesstokenmanager/main/cpp/src/permission/permission_policy_set.cpp b/services/accesstokenmanager/main/cpp/src/permission/permission_policy_set.cpp index 31e64a4a0..98e560f4c 100644 --- a/services/accesstokenmanager/main/cpp/src/permission/permission_policy_set.cpp +++ b/services/accesstokenmanager/main/cpp/src/permission/permission_policy_set.cpp @@ -96,7 +96,7 @@ std::shared_ptr PermissionPolicySet::RestorePermissionPolic { std::shared_ptr policySet = std::make_shared(); if (policySet == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: tokenId 0x%{public}x new failed.", __func__, tokenId); + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId 0x%{public}x new failed.", tokenId); return nullptr; } policySet->tokenId_ = tokenId; @@ -108,7 +108,7 @@ std::shared_ptr PermissionPolicySet::RestorePermissionPolic if (ret == RET_SUCCESS) { policySet->permList_.emplace_back(def); } else { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: tokenId 0x%{public}x permDef is wrong.", __func__, tokenId); + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId 0x%{public}x permDef is wrong.", tokenId); } } } @@ -120,8 +120,7 @@ std::shared_ptr PermissionPolicySet::RestorePermissionPolic if (ret == RET_SUCCESS) { MergePermissionStateFull(policySet->permStateList_, state); } else { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: tokenId 0x%{public}x permState is wrong.", - __func__, tokenId); + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId 0x%{public}x permState is wrong.", tokenId); } } } @@ -238,6 +237,14 @@ void PermissionPolicySet::UpdatePermissionStatus(const std::string& permissionNa } } +void PermissionPolicySet::GetPermissionStateList(std::vector& stateList) +{ + Utils::UniqueReadGuard infoGuard(this->permPolicySetLock_); + for(auto& state : permStateList_) { + stateList.emplace_back(state); + } +} + void PermissionPolicySet::PermDefToString(const PermissionDef& def, std::string& info) const { info.append(R"({"permissionName": ")" + def.permissionName + R"(")"); @@ -288,8 +295,10 @@ void PermissionPolicySet::PermStateFullToString(const PermissionStateFull& state void PermissionPolicySet::ToString(std::string& info) { Utils::UniqueReadGuard infoGuard(this->permPolicySetLock_); - info.append(R"(, "permDefList": [)"); + info.append(",\n\t"); + info.append(R"("permDefList": [)"); for (auto iter = permList_.begin(); iter != permList_.end(); iter++) { + info.append("\n\t\t"); PermDefToString(*iter, info); if (iter != (permList_.end() - 1)) { info.append(","); @@ -297,8 +306,10 @@ void PermissionPolicySet::ToString(std::string& info) } info.append("]"); - info.append(R"(, "permStateList": [)"); + info.append(",\n\t"); + info.append(R"("permStateList": [)"); for (auto iter = permStateList_.begin(); iter != permStateList_.end(); iter++) { + info.append("\n\t\t"); PermStateFullToString(*iter, info); if (iter != (permStateList_.end() - 1)) { info.append(","); diff --git a/services/accesstokenmanager/main/cpp/src/permission/permission_validator.cpp b/services/accesstokenmanager/main/cpp/src/permission/permission_validator.cpp index 3647ab976..848675ec4 100644 --- a/services/accesstokenmanager/main/cpp/src/permission/permission_validator.cpp +++ b/services/accesstokenmanager/main/cpp/src/permission/permission_validator.cpp @@ -116,8 +116,6 @@ void PermissionValidator::DeduplicateResDevID(const PermissionStateFull& permSta result.resDeviceID.emplace_back(*it); result.grantStatus.emplace_back(*stateIter); result.grantFlags.emplace_back(*flagIter); - ++stateIter; - ++flagIter; } result.permissionName = permState.permissionName; result.isGeneral = permState.isGeneral; diff --git a/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_service.cpp b/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_service.cpp index df942dcf3..4fe4e741b 100644 --- a/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_service.cpp +++ b/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_service.cpp @@ -167,7 +167,7 @@ AccessTokenIDEx AccessTokenManagerService::AllocHapToken(const HapInfoParcel& in int ret = AccessTokenInfoManager::GetInstance().CreateHapTokenInfo( info.hapInfoParameter, policy.hapPolicyParameter, tokenIdEx); if (ret != RET_SUCCESS) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, hap token info create failed", __func__); + ACCESSTOKEN_LOG_INFO(LABEL, "hap token info create failed"); } return tokenIdEx; } @@ -231,6 +231,74 @@ int AccessTokenManagerService::GetNativeTokenInfo(AccessTokenID tokenID, NativeT return AccessTokenInfoManager::GetInstance().GetNativeTokenInfo(tokenID, InfoParcel.nativeTokenInfoParams); } +int AccessTokenManagerService::GetHapTokenInfoFromRemote(AccessTokenID tokenID, + HapTokenInfoForSyncParcel& hapSyncParcel) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, tokenID: 0x%{public}x", __func__, tokenID); + + return AccessTokenInfoManager::GetInstance().GetHapTokenInfoFromRemote(tokenID, + hapSyncParcel.hapTokenInfoForSyncParams); +} + +int AccessTokenManagerService::GetAllNativeTokenInfo(std::vector& nativeTokenInfosRes) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called", __func__); + + std::vector nativeVec; + AccessTokenInfoManager::GetInstance().GetAllNativeTokenInfo(nativeVec); + for (auto& native : nativeVec) { + NativeTokenInfoParcel nativeParcel; + nativeParcel.nativeTokenInfoParams = native; + nativeTokenInfosRes.emplace_back(nativeParcel); + } + + return RET_SUCCESS; +} + +int AccessTokenManagerService::SetRemoteHapTokenInfo(const std::string& deviceID, + HapTokenInfoForSyncParcel& hapSyncParcel) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID: 0x%{public}s", __func__, deviceID.c_str()); + + return AccessTokenInfoManager::GetInstance().SetRemoteHapTokenInfo(deviceID, + hapSyncParcel.hapTokenInfoForSyncParams); +} + +int AccessTokenManagerService::SetRemoteNativeTokenInfo(const std::string& deviceID, + std::vector& nativeTokenInfoParcel) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID: 0x%{public}s", __func__, deviceID.c_str()); + + std::vector nativeList; + + for (auto& nativeParcel : nativeTokenInfoParcel) { + nativeList.emplace_back(nativeParcel.nativeTokenInfoParams); + } + + return AccessTokenInfoManager::GetInstance().SetRemoteNativeTokenInfo(deviceID, nativeList); +} + +int AccessTokenManagerService::DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID: %{public}s, token id %{public}d", + __func__, deviceID.c_str(), tokenID); + + return AccessTokenInfoManager::GetInstance().DeleteRemoteToken(deviceID, tokenID); +} + +int AccessTokenManagerService::DeleteRemoteDeviceTokens(const std::string& deviceID) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, deviceID: %{public}s", __func__, deviceID.c_str()); + + return AccessTokenInfoManager::GetInstance().DeleteRemoteDeviceTokens(deviceID); +} + +int AccessTokenManagerService::DumpToken(std::string& dumpInfo) +{ + AccessTokenInfoManager::GetInstance().Dump(dumpInfo); + return 0; +} + bool AccessTokenManagerService::Initialize() const { AccessTokenInfoManager::GetInstance().Init(); diff --git a/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_stub.cpp b/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_stub.cpp index 377c5dd1e..afb050cda 100644 --- a/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_stub.cpp +++ b/services/accesstokenmanager/main/cpp/src/service/accesstoken_manager_stub.cpp @@ -51,7 +51,7 @@ int32_t AccessTokenManagerStub::OnRemoteRequest( void AccessTokenManagerStub::DeleteTokenInfoInner(MessageParcel& data, MessageParcel& reply) { if (!IsAuthorizedCalling()) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__); + ACCESSTOKEN_LOG_INFO(LABEL, "permission denied"); reply.WriteInt32(RET_FAILED); return; } @@ -98,7 +98,7 @@ void AccessTokenManagerStub::GetReqPermissionsInner(MessageParcel& data, Message std::vector permList; int result = this->GetReqPermissions(tokenID, permList, isSystemGrant); - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permList size: %{public}d", __func__, (int) permList.size()); + ACCESSTOKEN_LOG_INFO(LABEL, "permList size: %{public}d", (int) permList.size()); reply.WriteInt32((int32_t)permList.size()); for (auto permDef : permList) { reply.WriteParcelable(&permDef); @@ -116,7 +116,7 @@ void AccessTokenManagerStub::GetPermissionFlagInner(MessageParcel& data, Message VerifyAccessToken(callingTokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS") == PERMISSION_DENIED && VerifyAccessToken(callingTokenID, "ohos.permission.REVOKE_SENSITIVE_PERMISSIONS") == PERMISSION_DENIED && VerifyAccessToken(callingTokenID, "ohos.permission.GET_SENSITIVE_PERMISSIONS") == PERMISSION_DENIED) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__); + ACCESSTOKEN_LOG_INFO(LABEL, "permission denied"); reply.WriteInt32(DEFAULT_PERMISSION_FLAGS); return; } @@ -133,7 +133,7 @@ void AccessTokenManagerStub::GrantPermissionInner(MessageParcel& data, MessagePa int flag = data.ReadInt32(); if (!IsAuthorizedCalling() && VerifyAccessToken(callingTokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS") == PERMISSION_DENIED) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__); + ACCESSTOKEN_LOG_INFO(LABEL, "permission denied"); reply.WriteInt32(RET_FAILED); return; } @@ -150,7 +150,7 @@ void AccessTokenManagerStub::RevokePermissionInner(MessageParcel& data, MessageP int flag = data.ReadInt32(); if (!IsAuthorizedCalling() && VerifyAccessToken(callingTokenID, "ohos.permission.REVOKE_SENSITIVE_PERMISSIONS") == PERMISSION_DENIED) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__); + ACCESSTOKEN_LOG_INFO(LABEL, "permission denied"); reply.WriteInt32(RET_FAILED); return; } @@ -276,6 +276,111 @@ void AccessTokenManagerStub::GetNativeTokenInfoInner(MessageParcel& data, Messag reply.WriteInt32(result); } +void AccessTokenManagerStub::GetHapTokenInfoFromRemoteInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsAuthorizedCalling()) { + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + AccessTokenID tokenID = data.ReadUint32(); + HapTokenInfoForSyncParcel hapTokenParcel; + + int result = this->GetHapTokenInfoFromRemote(tokenID, hapTokenParcel); + reply.WriteParcelable(&hapTokenParcel); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::GetAllNativeTokenInfoInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsAuthorizedCalling()) { + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + std::vector nativeTokenInfosRes; + int result = this->GetAllNativeTokenInfo(nativeTokenInfosRes); + reply.WriteUint32(nativeTokenInfosRes.size()); + for (auto native : nativeTokenInfosRes) { + reply.WriteParcelable(&native); + } + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::SetRemoteHapTokenInfoInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsAuthorizedCalling()) { + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + std::string deviceID = data.ReadString(); + sptr hapTokenParcel = data.ReadParcelable(); + int result = this->SetRemoteHapTokenInfo(deviceID, *hapTokenParcel); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::SetRemoteNativeTokenInfoInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsAuthorizedCalling()) { + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + std::string deviceID = data.ReadString(); + + std::vector nativeTokenInfoParcel; + uint32_t size = data.ReadUint32(); + + for (uint32_t i = 0; i < size; i++) { + sptr nativeParcel = data.ReadParcelable(); + nativeTokenInfoParcel.emplace_back(*nativeParcel); + } + + int result = this->SetRemoteNativeTokenInfo(deviceID, nativeTokenInfoParcel); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::DeleteRemoteTokenInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsAuthorizedCalling()) { + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + std::string deviceID = data.ReadString(); + AccessTokenID tokenID = data.ReadUint32(); + + int result = this->DeleteRemoteToken(deviceID, tokenID); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::DeleteRemoteDeviceTokensInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsAuthorizedCalling()) { + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + std::string deviceID = data.ReadString(); + + int result = this->DeleteRemoteDeviceTokens(deviceID); + reply.WriteInt32(result); +} + +void AccessTokenManagerStub::DumpTokenInner(MessageParcel& data, MessageParcel& reply) +{ + if (!IsAuthorizedCalling()) { + ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__); + reply.WriteInt32(RET_FAILED); + return; + } + std::string dumpInfo; + int result = this->DumpToken(dumpInfo); + reply.WriteString(dumpInfo); + reply.WriteUint32(result); +} + bool AccessTokenManagerStub::IsAuthorizedCalling() const { int callingUid = IPCSkeleton::GetCallingUid(); @@ -319,6 +424,20 @@ AccessTokenManagerStub::AccessTokenManagerStub() &AccessTokenManagerStub::GetHapTokenInfoInner; requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::UPDATE_HAP_TOKEN)] = &AccessTokenManagerStub::UpdateHapTokenInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::GET_HAP_TOKEN_FROM_REMOTE)] = + &AccessTokenManagerStub::GetHapTokenInfoFromRemoteInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::GET_ALL_NATIVE_TOKEN_FROM_REMOTE)] = + &AccessTokenManagerStub::GetAllNativeTokenInfoInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::SET_REMOTE_HAP_TOKEN_INFO)] = + &AccessTokenManagerStub::SetRemoteHapTokenInfoInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::SET_REMOTE_NATIVE_TOKEN_INFO)] = + &AccessTokenManagerStub::SetRemoteNativeTokenInfoInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::DELETE_REMOTE_TOKEN_INFO)] = + &AccessTokenManagerStub::DeleteRemoteTokenInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::DELETE_REMOTE_DEVICE_TOKEN)] = + &AccessTokenManagerStub::DeleteRemoteDeviceTokensInner; + requestFuncMap_[static_cast(IAccessTokenManager::InterfaceCode::DUMP)] = + &AccessTokenManagerStub::DumpTokenInner; } AccessTokenManagerStub::~AccessTokenManagerStub() diff --git a/services/accesstokenmanager/main/cpp/src/token/accesstoken_id_manager.cpp b/services/accesstokenmanager/main/cpp/src/token/accesstoken_id_manager.cpp index 4237a5104..7bedb7555 100644 --- a/services/accesstokenmanager/main/cpp/src/token/accesstoken_id_manager.cpp +++ b/services/accesstokenmanager/main/cpp/src/token/accesstoken_id_manager.cpp @@ -65,7 +65,7 @@ AccessTokenID AccessTokenIDManager::CreateTokenId(ATokenTypeEnum type) const { unsigned int rand = GetRandomUint32(); if (rand == 0) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, get random failed", __func__); + ACCESSTOKEN_LOG_INFO(LABEL, "get random failed"); return 0; } @@ -85,7 +85,7 @@ AccessTokenID AccessTokenIDManager::CreateAndRegisterTokenId(ATokenTypeEnum type for (int i = 0; i < MAX_CREATE_TOKEN_ID_RETRY; i++) { tokenId = CreateTokenId(type); if (tokenId == 0) { - ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s called, create tokenId failed", __func__); + ACCESSTOKEN_LOG_WARN(LABEL, "create tokenId failed"); return 0; } @@ -93,9 +93,9 @@ AccessTokenID AccessTokenIDManager::CreateAndRegisterTokenId(ATokenTypeEnum type if (ret == RET_SUCCESS) { break; } else if (i == MAX_CREATE_TOKEN_ID_RETRY - 1) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, reigster tokenId failed, maybe repeat, retry", __func__); + ACCESSTOKEN_LOG_INFO(LABEL, "reigster tokenId failed, maybe repeat, retry"); } else { - ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s called, reigster tokenId finally failed", __func__); + ACCESSTOKEN_LOG_WARN(LABEL, "reigster tokenId finally failed"); } } return tokenId; @@ -105,7 +105,7 @@ void AccessTokenIDManager::ReleaseTokenId(AccessTokenID id) { Utils::UniqueWriteGuard idGuard(this->tokenIdLock_); if (tokenIdSet_.count(id) == 0) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, id %{public}x is not exist", __func__, id); + ACCESSTOKEN_LOG_INFO(LABEL, "id %{public}x is not exist", id); return; } tokenIdSet_.erase(id); diff --git a/services/accesstokenmanager/main/cpp/src/token/accesstoken_info_manager.cpp b/services/accesstokenmanager/main/cpp/src/token/accesstoken_info_manager.cpp index 1c7483c47..b15505867 100644 --- a/services/accesstokenmanager/main/cpp/src/token/accesstoken_info_manager.cpp +++ b/services/accesstokenmanager/main/cpp/src/token/accesstoken_info_manager.cpp @@ -17,6 +17,7 @@ #include "accesstoken_id_manager.h" #include "accesstoken_log.h" +#include "accesstoken_remote_token_manager.h" #include "data_storage.h" #include "data_translator.h" #include "data_validator.h" @@ -24,6 +25,8 @@ #include "generic_values.h" #include "hap_token_info_inner.h" #include "permission_manager.h" +#include "token_modify_notifier.h" +#include "token_sync_kit.h" namespace OHOS { namespace Security { @@ -32,8 +35,7 @@ namespace { static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "AccessTokenInfoManager"}; } -AccessTokenInfoManager::AccessTokenInfoManager() : hasInited_(false) -{} +AccessTokenInfoManager::AccessTokenInfoManager() : hasInited_(false) {} AccessTokenInfoManager::~AccessTokenInfoManager() { @@ -73,32 +75,31 @@ void AccessTokenInfoManager::InitHapTokenInfos() AccessTokenID tokenId = (AccessTokenID)tokenValue.GetInt(FIELD_TOKEN_ID); int ret = AccessTokenIDManager::GetInstance().RegisterTokenId(tokenId, TOKEN_HAP); if (ret != RET_SUCCESS) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: tokenId 0x%{public}x add id failed.", - __func__, tokenId); + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId 0x%{public}x add id failed.", tokenId); continue; } std::shared_ptr hap = std::make_shared(); if (hap == nullptr) { AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId); - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: tokenId 0x%{public}x alloc failed.", __func__, tokenId); + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId 0x%{public}x alloc failed.", tokenId); continue; } ret = hap->RestoreHapTokenInfo(tokenId, tokenValue, permDefRes, permStateRes); if (ret != RET_SUCCESS) { AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId); - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: tokenId 0x%{public}x restore failed.", __func__, tokenId); + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId 0x%{public}x restore failed.", tokenId); continue; } ret = AddHapTokenInfo(hap); if (ret != RET_SUCCESS) { AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId); - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: tokenId 0x%{public}x add failed.", __func__, tokenId); + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId 0x%{public}x add failed.", tokenId); continue; } ACCESSTOKEN_LOG_INFO(LABEL, - "%{public}s:restore hap token 0x%{public}x bundle name %{public}s user %{public}d inst %{public}d ok!", - __func__, tokenId, hap->GetBundleName().c_str(), hap->GetUserID(), hap->GetInstIndex()); + " restore hap token 0x%{public}x bundle name %{public}s user %{public}d inst %{public}d ok!", + tokenId, hap->GetBundleName().c_str(), hap->GetUserID(), hap->GetInstIndex()); } } @@ -110,32 +111,32 @@ void AccessTokenInfoManager::InitNativeTokenInfos() AccessTokenID tokenId = (AccessTokenID)nativeTokenValue.GetInt(FIELD_TOKEN_ID); int ret = AccessTokenIDManager::GetInstance().RegisterTokenId(tokenId, TOKEN_NATIVE); if (ret != RET_SUCCESS) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: tokenId 0x%{public}x add failed.", __func__, tokenId); + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId 0x%{public}x add failed.", tokenId); continue; } std::shared_ptr native = std::make_shared(); if (native == nullptr) { AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId); - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: tokenId 0x%{public}x alloc failed.", __func__, tokenId); + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId 0x%{public}x alloc failed.", tokenId); continue; } ret = native->RestoreNativeTokenInfo(tokenId, nativeTokenValue); if (ret != RET_SUCCESS) { AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId); - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: tokenId 0x%{public}x restore failed.", __func__, tokenId); + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId 0x%{public}x restore failed.", tokenId); continue; } ret = AddNativeTokenInfo(native); if (ret != RET_SUCCESS) { AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId); - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: tokenId 0x%{public}x add failed.", __func__, tokenId); + ACCESSTOKEN_LOG_ERROR(LABEL, "tokenId 0x%{public}x add failed.", tokenId); continue; } ACCESSTOKEN_LOG_INFO(LABEL, - "%{public}s:restore native token 0x%{public}x process name %{public}s ok!", - __func__, tokenId, native->GetProcessName().c_str()); + "restore native token 0x%{public}x process name %{public}s ok!", + tokenId, native->GetProcessName().c_str()); } } @@ -156,7 +157,7 @@ std::string AccessTokenInfoManager::GetHapUniqueStr(const std::shared_ptr& info) { if (info == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: token info is null.", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "token info is null."); return RET_FAILED; } AccessTokenID id = info->GetTokenID(); @@ -164,45 +165,51 @@ int AccessTokenInfoManager::AddHapTokenInfo(const std::shared_ptr infoGuard(this->hapTokenInfoLock_); if (hapTokenInfoMap_.count(id) > 0) { - ACCESSTOKEN_LOG_ERROR( - LABEL, "%{public}s: token %{public}x info has exist.", __func__, id); + ACCESSTOKEN_LOG_ERROR(LABEL, "token %{public}x info has exist.", id); return RET_FAILED; } - std::string HapUniqueKey = GetHapUniqueStr(info); - if (hapTokenIdMap_.count(HapUniqueKey) > 0) { - ACCESSTOKEN_LOG_ERROR( - LABEL, "%{public}s: token %{public}x Unique info has exist.", __func__, id); - return RET_FAILED; + if (!info->IsRemote()) { + std::string HapUniqueKey = GetHapUniqueStr(info); + if (hapTokenIdMap_.count(HapUniqueKey) > 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "token %{public}x Unique info has exist.", id); + return RET_FAILED; + } + hapTokenIdMap_[HapUniqueKey] = id; } - hapTokenInfoMap_[id] = info; - hapTokenIdMap_[HapUniqueKey] = id; } - PermissionManager::GetInstance().AddDefPermissions(info, false); - + if (!info->IsRemote()) { + PermissionManager::GetInstance().AddDefPermissions(info, false); + } return RET_SUCCESS; } int AccessTokenInfoManager::AddNativeTokenInfo(const std::shared_ptr& info) { if (info == nullptr) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: token info is null.", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "token info is null."); return RET_FAILED; } AccessTokenID id = info->GetTokenID(); std::string processName = info->GetProcessName(); Utils::UniqueWriteGuard infoGuard(this->nativeTokenInfoLock_); - if (nativeTokenInfoMap_.count(id) > 0 - || nativeTokenIdMap_.count(processName) > 0) { + if (nativeTokenInfoMap_.count(id) > 0) { ACCESSTOKEN_LOG_ERROR( - LABEL, "%{public}s: token %{public}x process name %{public}s has exist.", - __func__, id, processName.c_str()); + LABEL, "token %{public}x has exist.", id); return RET_FAILED; } + if (!info->IsRemote()) { + if (nativeTokenIdMap_.count(processName) > 0) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "token %{public}x process name %{public}s has exist.", id, processName.c_str()); + return RET_FAILED; + } + nativeTokenIdMap_[processName] = id; + } nativeTokenInfoMap_[id] = info; - nativeTokenIdMap_[processName] = id; + return RET_SUCCESS; } @@ -211,7 +218,7 @@ std::shared_ptr AccessTokenInfoManager::GetHapTokenInfoInner( Utils::UniqueReadGuard infoGuard(this->hapTokenInfoLock_); if (hapTokenInfoMap_.count(id) == 0) { ACCESSTOKEN_LOG_ERROR( - LABEL, "%{public}s: token %{public}x is invalid.", __func__, id); + LABEL, "token %{public}x is invalid.", id); return nullptr; } return hapTokenInfoMap_[id]; @@ -222,7 +229,7 @@ int AccessTokenInfoManager::GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfo& std::shared_ptr infoPtr = GetHapTokenInfoInner(tokenID); if (infoPtr == nullptr) { ACCESSTOKEN_LOG_ERROR( - LABEL, "%{public}s: token %{public}x is invalid.", __func__, tokenID); + LABEL, "token %{public}x is invalid.", tokenID); return RET_FAILED; } infoPtr->TranslateToHapTokenInfo(InfoParcel); @@ -234,7 +241,7 @@ std::shared_ptr AccessTokenInfoManager::GetHapPermissionPol std::shared_ptr infoPtr = GetHapTokenInfoInner(id); if (infoPtr == nullptr) { ACCESSTOKEN_LOG_ERROR( - LABEL, "%{public}s: token %{public}x is invalid.", __func__, id); + LABEL, "token %{public}x is invalid.", id); return nullptr; } return infoPtr->GetHapInfoPermissionPolicySet(); @@ -245,7 +252,7 @@ std::shared_ptr AccessTokenInfoManager::GetNativeTokenInfo Utils::UniqueReadGuard infoGuard(this->nativeTokenInfoLock_); if (nativeTokenInfoMap_.count(id) == 0) { ACCESSTOKEN_LOG_ERROR( - LABEL, "%{public}s: token %{public}x is invalid.", __func__, id); + LABEL, "token %{public}x is invalid.", id); return nullptr; } return nativeTokenInfoMap_[id]; @@ -256,7 +263,7 @@ int AccessTokenInfoManager::GetNativeTokenInfo(AccessTokenID tokenID, NativeToke std::shared_ptr infoPtr = GetNativeTokenInfoInner(tokenID); if (infoPtr == nullptr) { ACCESSTOKEN_LOG_ERROR( - LABEL, "%{public}s: token %{public}x is invalid.", __func__, tokenID); + LABEL, "token %{public}x is invalid.", tokenID); return RET_FAILED; } @@ -269,35 +276,42 @@ int AccessTokenInfoManager::RemoveHapTokenInfo(AccessTokenID id) ATokenTypeEnum type = AccessTokenIDManager::GetInstance().GetTokenIdType(id); if (type != TOKEN_HAP) { ACCESSTOKEN_LOG_ERROR( - LABEL, "%{public}s: token %{public}x is not hap.", __func__, id); + LABEL, "token %{public}x is not hap.", id); + return RET_FAILED; } + bool isRemote = false; // make sure that RemoveDefPermissions is called outside of the lock to avoid deadlocks. PermissionManager::GetInstance().RemoveDefPermissions(id); { Utils::UniqueWriteGuard infoGuard(this->hapTokenInfoLock_); if (hapTokenInfoMap_.count(id) == 0) { - ACCESSTOKEN_LOG_ERROR( - LABEL, "%{public}s: hap token %{public}x is null.", __func__, id); + ACCESSTOKEN_LOG_ERROR(LABEL, "hap token %{public}x no exist.", id); return RET_FAILED; } const std::shared_ptr info = hapTokenInfoMap_[id]; if (info == nullptr) { - ACCESSTOKEN_LOG_ERROR( - LABEL, "%{public}s: hap token %{public}x is null.", __func__, id); + ACCESSTOKEN_LOG_ERROR(LABEL, "hap token %{public}x is null.", id); return RET_FAILED; } - std::string HapUniqueKey = GetHapUniqueStr(info); - if (hapTokenIdMap_.count(HapUniqueKey) != 0) { - hapTokenIdMap_.erase(HapUniqueKey); + isRemote = info->IsRemote(); + if (!info->IsRemote()) { + std::string HapUniqueKey = GetHapUniqueStr(info); + if (hapTokenIdMap_.count(HapUniqueKey) != 0) { + hapTokenIdMap_.erase(HapUniqueKey); + } } - hapTokenInfoMap_.erase(id); } + AccessTokenIDManager::GetInstance().ReleaseTokenId(id); - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s:remove hap token 0x%{public}x ok!", __func__, id); - RefreshTokenInfoIfNeeded(); + ACCESSTOKEN_LOG_INFO(LABEL, "remove hap token 0x%{public}x ok!", id); + if (!isRemote) { + RefreshTokenInfoIfNeeded(); + TokenModifyNotifier::GetInstance().NotifyTokenDelete(id); + } + return RET_SUCCESS; } @@ -306,26 +320,34 @@ int AccessTokenInfoManager::RemoveNativeTokenInfo(AccessTokenID id) ATokenTypeEnum type = AccessTokenIDManager::GetInstance().GetTokenIdType(id); if (type != TOKEN_NATIVE) { ACCESSTOKEN_LOG_ERROR( - LABEL, "%{public}s: token %{public}x is not hap.", __func__, id); + LABEL, "token %{public}x is not hap.", id); + return RET_FAILED; } + bool isRemote = false; { Utils::UniqueWriteGuard infoGuard(this->nativeTokenInfoLock_); if (nativeTokenInfoMap_.count(id) == 0) { ACCESSTOKEN_LOG_ERROR( - LABEL, "%{public}s: native token %{public}x is null.", __func__, id); + LABEL, "native token %{public}x is null.", id); return RET_FAILED; } - std::string processName = nativeTokenInfoMap_[id]->GetProcessName(); - if (nativeTokenIdMap_.count(processName) != 0) { - nativeTokenIdMap_.erase(processName); + std::shared_ptr info = nativeTokenInfoMap_[id]; + isRemote = info->IsRemote(); + if (!isRemote) { + std::string processName = nativeTokenInfoMap_[id]->GetProcessName(); + if (nativeTokenIdMap_.count(processName) != 0) { + nativeTokenIdMap_.erase(processName); + } } nativeTokenInfoMap_.erase(id); } AccessTokenIDManager::GetInstance().ReleaseTokenId(id); - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s:remove hap token 0x%{public}x ok!", __func__, id); - RefreshTokenInfoIfNeeded(); + ACCESSTOKEN_LOG_INFO(LABEL, "remove native token 0x%{public}x ok!", id); + if (!isRemote) { + RefreshTokenInfoIfNeeded(); + } return RET_SUCCESS; } @@ -334,34 +356,32 @@ int AccessTokenInfoManager::CreateHapTokenInfo( { if (!DataValidator::IsUserIdValid(info.userID) || !DataValidator::IsBundleNameValid(info.bundleName) || !DataValidator::IsAppIDDescValid(info.appIDDesc) || !DataValidator::IsDomainValid(policy.domain)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, hap token param failed", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "hap token param failed"); return RET_FAILED; } AccessTokenID tokenId = AccessTokenIDManager::GetInstance().CreateAndRegisterTokenId(TOKEN_HAP); if (tokenId == 0) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, token Id create failed", __func__); + ACCESSTOKEN_LOG_INFO(LABEL, "token Id create failed"); return RET_FAILED; } - std::shared_ptr tokenInfo = std::make_shared(); + std::shared_ptr tokenInfo = std::make_shared(tokenId, info, policy); if (tokenInfo == nullptr) { AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId); - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, alloc token info failed", __func__); + ACCESSTOKEN_LOG_INFO(LABEL, "alloc token info failed"); return RET_FAILED; } - tokenInfo->Init(tokenId, info, policy); int ret = AddHapTokenInfo(tokenInfo); if (ret != RET_SUCCESS) { - ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s called, %{public}s add token info failed", - __func__, info.bundleName.c_str()); + ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s add token info failed", info.bundleName.c_str()); AccessTokenIDManager::GetInstance().ReleaseTokenId(tokenId); return RET_FAILED; } ACCESSTOKEN_LOG_INFO(LABEL, - "%{public}s:create hap token 0x%{public}x bundle name %{public}s user %{public}d inst %{public}d ok!", - __func__, tokenId, tokenInfo->GetBundleName().c_str(), tokenInfo->GetUserID(), tokenInfo->GetInstIndex()); + "create hap token 0x%{public}x bundle name %{public}s user %{public}d inst %{public}d ok!", + tokenId, tokenInfo->GetBundleName().c_str(), tokenInfo->GetUserID(), tokenInfo->GetInstIndex()); tokenIdEx.tokenIdExStruct.tokenID = tokenId; tokenIdEx.tokenIdExStruct.tokenAttr = 0; @@ -374,7 +394,7 @@ int AccessTokenInfoManager::CheckNativeDCap(AccessTokenID tokenID, const std::st std::shared_ptr infoPtr = GetNativeTokenInfoInner(tokenID); if (infoPtr == nullptr) { ACCESSTOKEN_LOG_ERROR( - LABEL, "%{public}s: token %{public}x is invalid.", __func__, tokenID); + LABEL, "token %{public}x is invalid.", tokenID); return RET_FAILED; } @@ -397,16 +417,10 @@ AccessTokenID AccessTokenInfoManager::GetHapTokenID(int userID, const std::strin return 0; } -AccessTokenID AccessTokenInfoManager::AllocLocalTokenID(const std::string& remoteDeviceID, - AccessTokenID remoteTokenID) -{ - return 0; -} - bool AccessTokenInfoManager::TryUpdateExistNativeToken(const std::shared_ptr& infoPtr) { if (infoPtr == nullptr) { - ACCESSTOKEN_LOG_WARN(LABEL, "%{public}s called, info is null", __func__); + ACCESSTOKEN_LOG_WARN(LABEL, "info is null"); return false; } @@ -418,7 +432,7 @@ bool AccessTokenInfoManager::TryUpdateExistNativeToken(const std::shared_ptrGetTokenID(), infoPtr->GetProcessName().c_str()); + "token 0x%{public}x process name %{public}s is new, add to manager!", + infoPtr->GetTokenID(), infoPtr->GetProcessName().c_str()); AccessTokenID id = infoPtr->GetTokenID(); int ret = AccessTokenIDManager::GetInstance().RegisterTokenId(id, TOKEN_NATIVE); if (ret != RET_SUCCESS) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s called, token Id register fail", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "token Id register fail"); continue; } ret = AddNativeTokenInfo(infoPtr); if (ret != RET_SUCCESS) { AccessTokenIDManager::GetInstance().ReleaseTokenId(id); ACCESSTOKEN_LOG_ERROR(LABEL, - "%{public}s: token 0x%{public}x process name %{public}s add to manager failed!", - __func__, infoPtr->GetTokenID(), infoPtr->GetProcessName().c_str()); + "token 0x%{public}x process name %{public}s add to manager failed!", + infoPtr->GetTokenID(), infoPtr->GetProcessName().c_str()); } } } @@ -476,12 +490,12 @@ int AccessTokenInfoManager::UpdateHapToken(AccessTokenID tokenID, const std::string& appIDDesc, const HapPolicyParams& policy) { if (!DataValidator::IsAppIDDescValid(appIDDesc)) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s:token 0x%{public}x parm format error!", __func__, tokenID); + ACCESSTOKEN_LOG_INFO(LABEL, "token 0x%{public}x parm format error!", tokenID); return RET_FAILED; } std::shared_ptr infoPtr = GetHapTokenInfoInner(tokenID); if (infoPtr == nullptr) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s:token 0x%{public}x is null, can not update!", __func__, tokenID); + ACCESSTOKEN_LOG_INFO(LABEL, "token 0x%{public}x is null, can not update!", tokenID); return RET_FAILED; } @@ -489,15 +503,238 @@ int AccessTokenInfoManager::UpdateHapToken(AccessTokenID tokenID, Utils::UniqueWriteGuard infoGuard(this->hapTokenInfoLock_); infoPtr->Update(appIDDesc, policy); ACCESSTOKEN_LOG_INFO(LABEL, - "%{public}s: token 0x%{public}x bundle name %{public}s user %{public}d inst %{public}d update ok!", - __func__, tokenID, infoPtr->GetBundleName().c_str(), infoPtr->GetUserID(), infoPtr->GetInstIndex()); + "token 0x%{public}x bundle name %{public}s user %{public}d inst %{public}d update ok!", + tokenID, infoPtr->GetBundleName().c_str(), infoPtr->GetUserID(), infoPtr->GetInstIndex()); } PermissionManager::GetInstance().AddDefPermissions(infoPtr, true); + if (!infoPtr->IsRemote()) { + TokenModifyNotifier::GetInstance().NotifyTokenModify(tokenID); + } RefreshTokenInfoIfNeeded(); return RET_SUCCESS; } +int AccessTokenInfoManager::GetHapTokenSync(AccessTokenID tokenID, HapTokenInfoForSync& hapSync) +{ + std::shared_ptr infoPtr = GetHapTokenInfoInner(tokenID); + if (infoPtr == nullptr) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "token %{public}x is invalid.", tokenID); + return RET_FAILED; + } + hapSync.baseInfo = infoPtr->GetHapInfoBasic(); + std::shared_ptr permSetPtr = infoPtr->GetHapInfoPermissionPolicySet(); + if (permSetPtr == nullptr) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "token %{public}x permSet is invalid.", tokenID); + return RET_FAILED; + } + permSetPtr->GetPermissionStateList(hapSync.permStateList); + return RET_SUCCESS; +} + +int AccessTokenInfoManager::GetHapTokenInfoFromRemote(AccessTokenID tokenID, + HapTokenInfoForSync& hapSync) +{ + int ret = GetHapTokenSync(tokenID, hapSync); + TokenModifyNotifier::GetInstance().AddHapTokenObservation(tokenID); + return ret; +} + +void AccessTokenInfoManager::GetAllNativeTokenInfo(std::vector& nativeTokenInfosRes) +{ + Utils::UniqueReadGuard infoGuard(this->nativeTokenInfoLock_); + for (auto nativeTokenInner : nativeTokenInfoMap_) { + std::shared_ptr nativeTokenInnerPtr = nativeTokenInner.second; + if (nativeTokenInnerPtr == nullptr || nativeTokenInnerPtr->IsRemote()) { + continue; + } + NativeTokenInfo token; + nativeTokenInnerPtr->TranslateToNativeTokenInfo(token); + nativeTokenInfosRes.emplace_back(token); + } + return; +} + +int AccessTokenInfoManager::SetRemoteHapTokenInfo(const std::string& deviceID, HapTokenInfoForSync& hapSync) +{ + if (!DataValidator::IsDeviceIdValid(deviceID) + || !DataValidator::IsUserIdValid(hapSync.baseInfo.userID) + || !DataValidator::IsBundleNameValid(hapSync.baseInfo.bundleName)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s parms invalid", deviceID.c_str()); + return RET_FAILED; + } + + AccessTokenID remoteID = hapSync.baseInfo.tokenID; + AccessTokenID mapID = AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(deviceID, remoteID); + if (mapID != 0) { + ACCESSTOKEN_LOG_INFO(LABEL, "device %{public}s token %{public}x update exist remote hap token %{public}x.", + deviceID.c_str(), remoteID, mapID); + HapPolicyParams policy = { + .apl = hapSync.baseInfo.apl, + .domain = "", // domain not used + .permList = {}, // permission define list never sync. + .permStateList = hapSync.permStateList + }; + return UpdateHapToken(mapID, hapSync.baseInfo.appID, policy); + } + + mapID = AccessTokenRemoteTokenManager::GetInstance().MapRemoteDeviceTokenToLocal(deviceID, remoteID); + if (mapID == 0) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "device %{public}s token %{public}x map failed.", deviceID.c_str(), remoteID); + return RET_FAILED; + } + hapSync.baseInfo.tokenID = mapID; + ACCESSTOKEN_LOG_INFO(LABEL, "device %{public}s token %{public}x map to local token %{public}x.", + deviceID.c_str(), remoteID, mapID); + + // update remote token mapping id + hapSync.baseInfo.tokenID = mapID; + std::shared_ptr hap = std::make_shared(mapID, + hapSync.baseInfo, hapSync.permStateList); + if (hap == nullptr) { + AccessTokenRemoteTokenManager::GetInstance().RemoveDeviceMappingTokenID(deviceID, mapID); + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s tokenId 0x%{public}x alloc local token failed.", + deviceID.c_str(), remoteID); + return RET_FAILED; + } + hap->SetRemote(true); + + int ret = AddHapTokenInfo(hap); + if (ret != RET_SUCCESS) { + AccessTokenRemoteTokenManager::GetInstance().RemoveDeviceMappingTokenID(deviceID, mapID); + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s tokenId 0x%{public}x add local token failed.", + deviceID.c_str(), remoteID); + return RET_FAILED; + } + + ACCESSTOKEN_LOG_INFO(LABEL, "device %{public}s token %{public}x new map token %{public}x.", + deviceID.c_str(), remoteID, mapID); + return RET_SUCCESS; +} + +int AccessTokenInfoManager::SetRemoteNativeTokenInfo(const std::string& deviceID, + std::vector& nativeTokenInfoList) +{ + if (!DataValidator::IsDeviceIdValid(deviceID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s parms invalid", deviceID.c_str()); + return RET_FAILED; + } + + for (NativeTokenInfo& nativeToken : nativeTokenInfoList) { + if (!DataValidator::IsAplNumValid(nativeToken.apl) + || nativeToken.ver != DEFAULT_TOKEN_VERSION + || !DataValidator::IsProcessNameValid(nativeToken.processName)) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "device %{public}s token %{public}x is invalid.", deviceID.c_str(), nativeToken.tokenID); + continue; + } + + AccessTokenID remoteID = nativeToken.tokenID; + AccessTokenID mapID = AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(deviceID, remoteID); + if (mapID == 0) { + mapID = AccessTokenRemoteTokenManager::GetInstance().MapRemoteDeviceTokenToLocal(deviceID, remoteID); + } + if (mapID == 0) { + AccessTokenRemoteTokenManager::GetInstance().RemoveDeviceMappingTokenID(deviceID, mapID); + ACCESSTOKEN_LOG_ERROR( + LABEL, "device %{public}s token %{public}x map failed.", + deviceID.c_str(), remoteID); + continue; + } + nativeToken.tokenID = mapID; + ACCESSTOKEN_LOG_INFO(LABEL, "device %{public}s token %{public}x map to local token %{public}x.", + deviceID.c_str(), remoteID, mapID); + + std::shared_ptr nativePtr = std::make_shared(nativeToken); + if (nativePtr == nullptr) { + AccessTokenRemoteTokenManager::GetInstance().RemoveDeviceMappingTokenID(deviceID, mapID); + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s tokenId 0x%{public}x alloc local token failed.", + deviceID.c_str(), remoteID); + continue; + } + nativePtr->SetRemote(true); + int ret = AddNativeTokenInfo(nativePtr); + if (ret != RET_SUCCESS) { + AccessTokenRemoteTokenManager::GetInstance().RemoveDeviceMappingTokenID(deviceID, mapID); + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s tokenId 0x%{public}x add local token failed.", + deviceID.c_str(), remoteID); + continue; + } + ACCESSTOKEN_LOG_INFO(LABEL, "device %{public}s token %{public}x map token %{public}x add success.", + deviceID.c_str(), remoteID, mapID); + } + + return RET_SUCCESS; +} + +int AccessTokenInfoManager::DeleteRemoteToken(const std::string& deviceID, AccessTokenID tokenID) +{ + if (!DataValidator::IsDeviceIdValid(deviceID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s parms invalid", deviceID.c_str()); + return RET_FAILED; + } + AccessTokenID mapID = AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(deviceID, tokenID); + if (mapID == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s tokenId 0x%{public}x is not mapped", + deviceID.c_str(), tokenID); + return RET_FAILED; + } + + ATokenTypeEnum type = AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(mapID); + if (type == TOKEN_HAP) { + RemoveHapTokenInfo(mapID); + } else if (type == TOKEN_NATIVE) { + RemoveNativeTokenInfo(mapID); + } else { + ACCESSTOKEN_LOG_ERROR(LABEL, "mapping tokenId 0x%{public}x type is unknown", mapID); + } + + return AccessTokenRemoteTokenManager::GetInstance().RemoveDeviceMappingTokenID(deviceID, tokenID); +} + +int AccessTokenInfoManager::DeleteRemoteDeviceTokens(const std::string& deviceID) +{ + if (!DataValidator::IsDeviceIdValid(deviceID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s parms invalid", deviceID.c_str()); + return RET_FAILED; + } + std::vector remoteTokens; + int ret = AccessTokenRemoteTokenManager::GetInstance().GetDeviceAllRemoteTokenID(deviceID, remoteTokens); + if (ret == RET_FAILED) { + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s have no remote token", deviceID.c_str()); + return RET_FAILED; + } + for (AccessTokenID remoteID : remoteTokens) { + DeleteRemoteToken(deviceID, remoteID); + } + return RET_SUCCESS; +} + +AccessTokenID AccessTokenInfoManager::AllocLocalTokenID(const std::string& remoteDeviceID, + AccessTokenID remoteTokenID) +{ + if (!DataValidator::IsDeviceIdValid(remoteDeviceID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s parms invalid", remoteDeviceID.c_str()); + return 0; + } + AccessTokenID mapID = AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(remoteDeviceID, + remoteTokenID); + if (mapID != 0) { + return mapID; + } + int ret = TokenSyncKit::GetRemoteHapTokenInfo(remoteDeviceID, remoteTokenID); + if (ret != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s token %{public}x sync failed", + remoteDeviceID.c_str(), remoteTokenID); + return 0; + } + + return AccessTokenRemoteTokenManager::GetInstance().GetDeviceMappingTokenID(remoteDeviceID, remoteTokenID); +} + AccessTokenInfoManager& AccessTokenInfoManager::GetInstance() { static AccessTokenInfoManager instance; @@ -537,9 +774,10 @@ void AccessTokenInfoManager::StoreAllTokenInfo() void AccessTokenInfoManager::RefreshTokenInfoIfNeeded() { if (tokenDataWorker_.GetCurTaskNum() > 1) { - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s: has refresh task!", __func__); + ACCESSTOKEN_LOG_INFO(LABEL, "has refresh task!"); return; } + tokenDataWorker_.AddTask([]() { AccessTokenInfoManager::GetInstance().StoreAllTokenInfo(); @@ -553,14 +791,18 @@ void AccessTokenInfoManager::Dump(std::string& dumpInfo) Utils::UniqueReadGuard hapInfoGuard(this->hapTokenInfoLock_); for (auto iter = hapTokenInfoMap_.begin(); iter != hapTokenInfoMap_.end(); iter++) { if (iter->second != nullptr) { + dumpInfo.append("\n"); iter->second->ToString(dumpInfo); + dumpInfo.append("\n"); } } Utils::UniqueReadGuard nativeInfoGuard(this->nativeTokenInfoLock_); for (auto iter = nativeTokenInfoMap_.begin(); iter != nativeTokenInfoMap_.end(); iter++) { if (iter->second != nullptr) { + dumpInfo.append("\n"); iter->second->ToString(dumpInfo); + dumpInfo.append("\n"); } } } diff --git a/services/accesstokenmanager/main/cpp/src/token/accesstoken_remote_token_manager.cpp b/services/accesstokenmanager/main/cpp/src/token/accesstoken_remote_token_manager.cpp new file mode 100644 index 000000000..17cb414d0 --- /dev/null +++ b/services/accesstokenmanager/main/cpp/src/token/accesstoken_remote_token_manager.cpp @@ -0,0 +1,154 @@ +/* + * 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 "accesstoken_remote_token_manager.h" + +#include "accesstoken_id_manager.h" +#include "accesstoken_log.h" +#include "data_validator.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, + SECURITY_DOMAIN_ACCESSTOKEN, "AccessTokenRemoteTokenManager"}; +} +AccessTokenRemoteTokenManager::AccessTokenRemoteTokenManager() +{} + +AccessTokenRemoteTokenManager::~AccessTokenRemoteTokenManager() +{ +} + +AccessTokenRemoteTokenManager& AccessTokenRemoteTokenManager::GetInstance() +{ + static AccessTokenRemoteTokenManager instance; + return instance; +} + +AccessTokenID AccessTokenRemoteTokenManager::MapRemoteDeviceTokenToLocal(const std::string& deviceID, + AccessTokenID remoteID) +{ + if (!DataValidator::IsDeviceIdValid(deviceID) || !DataValidator::IsTokenIDValid(remoteID)) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "device %{public}s or token %{public}x is invalid.", deviceID.c_str(), remoteID); + return 0; + } + ATokenTypeEnum tokeType = AccessTokenIDManager::GetInstance().GetTokenIdTypeEnum(remoteID); + if (tokeType != TOKEN_HAP && tokeType != TOKEN_NATIVE) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "token %{public}x type is invalid.", remoteID); + return 0; + } + + AccessTokenID mapID = 0; + Utils::UniqueWriteGuard infoGuard(this->remoteDeviceLock_); + std::map* mapPtr = nullptr; + if (remoteDeviceMap_.count(deviceID) > 0) { + AccessTokenRemoteDevice& device = remoteDeviceMap_[deviceID]; + if (device.MappingTokenIDPairMap_.count(remoteID) > 0) { + mapID = device.MappingTokenIDPairMap_[remoteID]; + ACCESSTOKEN_LOG_ERROR( + LABEL, "device %{public}s token %{public}x has already mapped, maptokenID is %{public}x.", + deviceID.c_str(), remoteID, mapID); + return mapID; + } + mapPtr = &device.MappingTokenIDPairMap_; + } else { + AccessTokenRemoteDevice device; + remoteDeviceMap_[deviceID] = device; + mapPtr = &remoteDeviceMap_[deviceID].MappingTokenIDPairMap_; + } + + mapID = AccessTokenIDManager::GetInstance().CreateAndRegisterTokenId(tokeType); + if (mapID == 0) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "device %{public}s token %{public}x map local Token failed.", + deviceID.c_str(), remoteID); + return 0; + } + mapPtr->insert(std::pair(remoteID, mapID)); + return mapID; +} + +int AccessTokenRemoteTokenManager::GetDeviceAllRemoteTokenID(const std::string& deviceID, + std::vector& remoteIDs) +{ + if (!DataValidator::IsDeviceIdValid(deviceID)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s is valid.", deviceID.c_str()); + return RET_FAILED; + } + Utils::UniqueReadGuard infoGuard(this->remoteDeviceLock_); + if (remoteDeviceMap_.count(deviceID) < 1) { + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s has not mapping.", deviceID.c_str()); + return RET_FAILED; + } + + for (auto mapEntry : remoteDeviceMap_[deviceID].MappingTokenIDPairMap_) { + remoteIDs.emplace_back(mapEntry.first); + } + return RET_SUCCESS; +} + +AccessTokenID AccessTokenRemoteTokenManager::GetDeviceMappingTokenID(const std::string& deviceID, + AccessTokenID remoteID) +{ + if (!DataValidator::IsDeviceIdValid(deviceID) || !DataValidator::IsTokenIDValid(remoteID)) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "device %{public}s or token %{public}x is invalid.", deviceID.c_str(), remoteID); + return 0; + } + + Utils::UniqueReadGuard infoGuard(this->remoteDeviceLock_); + if (remoteDeviceMap_.count(deviceID) < 1 || + remoteDeviceMap_[deviceID].MappingTokenIDPairMap_.count(remoteID) < 1) { + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s has not mapping.", deviceID.c_str()); + return 0; + } + + return remoteDeviceMap_[deviceID].MappingTokenIDPairMap_[remoteID]; +} + +int AccessTokenRemoteTokenManager::RemoveDeviceMappingTokenID(const std::string& deviceID, + AccessTokenID remoteID) +{ + if (!DataValidator::IsDeviceIdValid(deviceID) || !DataValidator::IsTokenIDValid(remoteID)) { + ACCESSTOKEN_LOG_ERROR( + LABEL, "device %{public}s or token %{public}x is invalid.", deviceID.c_str(), remoteID); + return RET_FAILED; + } + + Utils::UniqueWriteGuard infoGuard(this->remoteDeviceLock_); + if (remoteDeviceMap_.count(deviceID) < 1 || + remoteDeviceMap_[deviceID].MappingTokenIDPairMap_.count(remoteID) < 1) { + ACCESSTOKEN_LOG_ERROR(LABEL, "device %{public}s has not mapping.", deviceID.c_str()); + return RET_FAILED; + } + + AccessTokenID mapID = remoteDeviceMap_[deviceID].MappingTokenIDPairMap_[remoteID]; + AccessTokenIDManager::GetInstance().ReleaseTokenId(mapID); + + remoteDeviceMap_[deviceID].MappingTokenIDPairMap_.erase(remoteID); + + if (remoteDeviceMap_[deviceID].MappingTokenIDPairMap_.size() == 0) { + remoteDeviceMap_.erase(deviceID); + } + return RET_SUCCESS; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + diff --git a/services/accesstokenmanager/main/cpp/src/token/hap_token_info_inner.cpp b/services/accesstokenmanager/main/cpp/src/token/hap_token_info_inner.cpp index d603a133b..ead8e42fb 100644 --- a/services/accesstokenmanager/main/cpp/src/token/hap_token_info_inner.cpp +++ b/services/accesstokenmanager/main/cpp/src/token/hap_token_info_inner.cpp @@ -28,30 +28,51 @@ namespace { static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "HapTokenInfoInner"}; } -HapTokenInfoInner::~HapTokenInfoInner() +HapTokenInfoInner::HapTokenInfoInner() : isRemote_(false) { - ACCESSTOKEN_LOG_DEBUG(LABEL, - "%{public}s called, tokenID: 0x%{public}x destruction", __func__, tokenID_); + tokenInfoBasic_.ver = DEFAULT_TOKEN_VERSION; + tokenInfoBasic_.tokenID = 0; + tokenInfoBasic_.tokenAttr = 0; + tokenInfoBasic_.userID = 0; + tokenInfoBasic_.instIndex = 0; + tokenInfoBasic_.apl = APL_NORMAL; } -void HapTokenInfoInner::Init(AccessTokenID id, const HapInfoParams &info, const HapPolicyParams &policy) +HapTokenInfoInner::HapTokenInfoInner(AccessTokenID id, + const HapInfoParams &info, const HapPolicyParams &policy) : isRemote_(false) { - tokenID_ = id; - userID_ = info.userID; - bundleName_ = info.bundleName; - instIndex_ = info.instIndex; - appID_ = info.appIDDesc; - deviceID_ = "0"; - apl_ = policy.apl; + tokenInfoBasic_.tokenID = id; + tokenInfoBasic_.userID = info.userID; + tokenInfoBasic_.ver = DEFAULT_TOKEN_VERSION; + tokenInfoBasic_.tokenAttr = 0; + tokenInfoBasic_.bundleName = info.bundleName; + tokenInfoBasic_.instIndex = info.instIndex; + tokenInfoBasic_.appID = info.appIDDesc; + tokenInfoBasic_.deviceID = "0"; + tokenInfoBasic_.apl = policy.apl; permPolicySet_ = PermissionPolicySet::BuildPermissionPolicySet(id, policy.permList, policy.permStateList); } +HapTokenInfoInner::HapTokenInfoInner(AccessTokenID id, + const HapTokenInfo &info, const std::vector& permStateList) : isRemote_(false) +{ + tokenInfoBasic_ = info; + const std::vector permDefList; + permPolicySet_ = PermissionPolicySet::BuildPermissionPolicySet(id, permDefList, permStateList); +} + +HapTokenInfoInner::~HapTokenInfoInner() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, + "tokenID: 0x%{public}x destruction", tokenInfoBasic_.tokenID); +} + void HapTokenInfoInner::Update(const std::string& appIDDesc, const HapPolicyParams& policy) { - appID_ = appIDDesc; - apl_ = policy.apl; + tokenInfoBasic_.appID = appIDDesc; + tokenInfoBasic_.apl = policy.apl; if (permPolicySet_ == nullptr) { - permPolicySet_ = PermissionPolicySet::BuildPermissionPolicySet(tokenID_, + permPolicySet_ = PermissionPolicySet::BuildPermissionPolicySet(tokenInfoBasic_.tokenID, policy.permList, policy.permStateList); return; } @@ -62,69 +83,63 @@ void HapTokenInfoInner::Update(const std::string& appIDDesc, const HapPolicyPara void HapTokenInfoInner::TranslateToHapTokenInfo(HapTokenInfo& InfoParcel) const { - InfoParcel.apl = apl_; - InfoParcel.ver = ver_; - InfoParcel.userID = userID_; - InfoParcel.bundleName = bundleName_; - InfoParcel.instIndex = instIndex_; - InfoParcel.appID = appID_; - InfoParcel.deviceID = deviceID_; - InfoParcel.tokenID = tokenID_; - InfoParcel.tokenAttr = tokenAttr_; + InfoParcel = tokenInfoBasic_; } void HapTokenInfoInner::TranslationIntoGenericValues(GenericValues& outGenericValues) const { - outGenericValues.Put(FIELD_TOKEN_ID, tokenID_); - outGenericValues.Put(FIELD_USER_ID, userID_); - outGenericValues.Put(FIELD_BUNDLE_NAME, bundleName_); - outGenericValues.Put(FIELD_INST_INDEX, instIndex_); - outGenericValues.Put(FIELD_APP_ID, appID_); - outGenericValues.Put(FIELD_DEVICE_ID, deviceID_); - outGenericValues.Put(FIELD_APL, apl_); - outGenericValues.Put(FIELD_TOKEN_VERSION, ver_); - outGenericValues.Put(FIELD_TOKEN_ATTR, tokenAttr_); + outGenericValues.Put(FIELD_TOKEN_ID, tokenInfoBasic_.tokenID); + outGenericValues.Put(FIELD_USER_ID, tokenInfoBasic_.userID); + outGenericValues.Put(FIELD_BUNDLE_NAME, tokenInfoBasic_.bundleName); + outGenericValues.Put(FIELD_INST_INDEX, tokenInfoBasic_.instIndex); + outGenericValues.Put(FIELD_APP_ID, tokenInfoBasic_.appID); + outGenericValues.Put(FIELD_DEVICE_ID, tokenInfoBasic_.deviceID); + outGenericValues.Put(FIELD_APL, tokenInfoBasic_.apl); + outGenericValues.Put(FIELD_TOKEN_VERSION, tokenInfoBasic_.ver); + outGenericValues.Put(FIELD_TOKEN_ATTR, tokenInfoBasic_.tokenAttr); } int HapTokenInfoInner::RestoreHapTokenBasicInfo(const GenericValues& inGenericValues) { - userID_ = inGenericValues.GetInt(FIELD_USER_ID); - bundleName_ = inGenericValues.GetString(FIELD_BUNDLE_NAME); - if (!DataValidator::IsBundleNameValid(bundleName_)) { + tokenInfoBasic_.userID = inGenericValues.GetInt(FIELD_USER_ID); + tokenInfoBasic_.bundleName = inGenericValues.GetString(FIELD_BUNDLE_NAME); + if (!DataValidator::IsBundleNameValid(tokenInfoBasic_.bundleName)) { ACCESSTOKEN_LOG_ERROR(LABEL, - "%{public}s called, tokenID: 0x%{public}x bundle name is error", __func__, tokenID_); + "tokenID: 0x%{public}x bundle name is error", tokenInfoBasic_.tokenID); return RET_FAILED; } - instIndex_ = inGenericValues.GetInt(FIELD_INST_INDEX); - appID_ = inGenericValues.GetString(FIELD_APP_ID); - if (!DataValidator::IsAppIDDescValid(appID_)) { + tokenInfoBasic_.instIndex = inGenericValues.GetInt(FIELD_INST_INDEX); + tokenInfoBasic_.appID = inGenericValues.GetString(FIELD_APP_ID); + if (!DataValidator::IsAppIDDescValid(tokenInfoBasic_.appID)) { ACCESSTOKEN_LOG_ERROR(LABEL, - "%{public}s called, tokenID: 0x%{public}x appID is error", __func__, tokenID_); + "tokenID: 0x%{public}x appID is error", tokenInfoBasic_.tokenID); return RET_FAILED; } - deviceID_ = inGenericValues.GetString(FIELD_DEVICE_ID); - if (!DataValidator::IsDeviceIdValid(deviceID_)) { + tokenInfoBasic_.deviceID = inGenericValues.GetString(FIELD_DEVICE_ID); + if (!DataValidator::IsDeviceIdValid(tokenInfoBasic_.deviceID)) { ACCESSTOKEN_LOG_ERROR(LABEL, - "%{public}s called, tokenID: 0x%{public}x devId is error", __func__, tokenID_); + "tokenID: 0x%{public}x devId is error", tokenInfoBasic_.tokenID); return RET_FAILED; } int aplNum = inGenericValues.GetInt(FIELD_APL); if (DataValidator::IsAplNumValid(aplNum)) { - apl_ = (ATokenAplEnum)aplNum; + tokenInfoBasic_.apl = (ATokenAplEnum)aplNum; } else { ACCESSTOKEN_LOG_ERROR(LABEL, - "%{public}s called, tokenID: 0x%{public}x apl is error, value %{public}d", __func__, tokenID_, aplNum); + "tokenID: 0x%{public}x apl is error, value %{public}d", + tokenInfoBasic_.tokenID, aplNum); return RET_FAILED; } - ver_ = (char)inGenericValues.GetInt(FIELD_TOKEN_VERSION); - if (ver_ != DEFAULT_TOKEN_VERSION) { + tokenInfoBasic_.ver = (char)inGenericValues.GetInt(FIELD_TOKEN_VERSION); + if (tokenInfoBasic_.ver != DEFAULT_TOKEN_VERSION) { ACCESSTOKEN_LOG_ERROR(LABEL, - "%{public}s called, tokenID: 0x%{public}x version is error, version %{public}d", __func__, tokenID_, ver_); + "tokenID: 0x%{public}x version is error, version %{public}d", + tokenInfoBasic_.tokenID, tokenInfoBasic_.ver); return RET_FAILED; } - tokenAttr_ = (uint32_t)inGenericValues.GetInt(FIELD_TOKEN_ATTR); + tokenInfoBasic_.tokenAttr = (uint32_t)inGenericValues.GetInt(FIELD_TOKEN_ATTR); return RET_SUCCESS; } @@ -132,7 +147,7 @@ int HapTokenInfoInner::RestoreHapTokenInfo(AccessTokenID tokenId, GenericValues& tokenValue, const std::vector& permDefRes, const std::vector& permStateRes) { - tokenID_ = tokenId; + tokenInfoBasic_.tokenID = tokenId; int ret = RestoreHapTokenBasicInfo(tokenValue); if (ret != RET_SUCCESS) { return RET_FAILED; @@ -153,6 +168,11 @@ void HapTokenInfoInner::StoreHapInfo(std::vector& hapInfoValues, std::vector& permDefValues, std::vector& permStateValues) const { + if (isRemote_) { + ACCESSTOKEN_LOG_INFO(LABEL, + "token %{public}x is remote hap token, will not store", tokenInfoBasic_.tokenID); + return; + } StoreHapBasicInfo(hapInfoValues); if (permPolicySet_ != nullptr) { permPolicySet_->StorePermissionPolicySet(permDefValues, permStateValues); @@ -166,35 +186,51 @@ std::shared_ptr HapTokenInfoInner::GetHapInfoPermissionPoli int HapTokenInfoInner::GetUserID() const { - return userID_; + return tokenInfoBasic_.userID; } std::string HapTokenInfoInner::GetBundleName() const { - return bundleName_; + return tokenInfoBasic_.bundleName; } int HapTokenInfoInner::GetInstIndex() const { - return instIndex_; + return tokenInfoBasic_.instIndex; } AccessTokenID HapTokenInfoInner::GetTokenID() const { - return tokenID_; + return tokenInfoBasic_.tokenID; +} + +HapTokenInfo HapTokenInfoInner::GetHapInfoBasic() const +{ + return tokenInfoBasic_; +} + +bool HapTokenInfoInner::IsRemote() const +{ + return isRemote_; +} + +void HapTokenInfoInner::SetRemote(bool isRemote) +{ + isRemote_ = isRemote; } void HapTokenInfoInner::ToString(std::string& info) const { - info.append(R"({"tokenID": )" + std::to_string(tokenID_)); - info.append(R"(, "tokenAttr": )" + std::to_string(tokenAttr_)); - info.append(R"(, "ver": )" + std::to_string(ver_)); - info.append(R"(, "userId": )" + std::to_string(userID_)); - info.append(R"(, "bundleName": ")" + bundleName_ + R"(")"); - info.append(R"(, "instIndex": )" + std::to_string(instIndex_)); - info.append(R"(, "appID": ")" + appID_ + R"(")"); - info.append(R"(, "deviceID": ")" + deviceID_ + R"(")"); - info.append(R"(, "apl": )" + std::to_string(apl_)); + info.append(R"({"tokenID": )" + std::to_string(tokenInfoBasic_.tokenID)); + info.append(R"(, "tokenAttr": )" + std::to_string(tokenInfoBasic_.tokenAttr)); + info.append(R"(, "ver": )" + std::to_string(tokenInfoBasic_.ver)); + info.append(R"(, "userId": )" + std::to_string(tokenInfoBasic_.userID)); + info.append(R"(, "bundleName": ")" + tokenInfoBasic_.bundleName + R"(")"); + info.append(R"(, "instIndex": )" + std::to_string(tokenInfoBasic_.instIndex)); + info.append(R"(, "appID": ")" + tokenInfoBasic_.appID + R"(")"); + info.append(R"(, "deviceID": ")" + tokenInfoBasic_.deviceID + R"(")"); + info.append(R"(, "apl": )" + std::to_string(tokenInfoBasic_.apl)); + info.append(R"(, "isRemote": )" + std::to_string(isRemote_)); if (permPolicySet_ != nullptr) { permPolicySet_->ToString(info); diff --git a/services/accesstokenmanager/main/cpp/src/token/native_token_info_inner.cpp b/services/accesstokenmanager/main/cpp/src/token/native_token_info_inner.cpp index ccdc9b415..0e5f70d85 100644 --- a/services/accesstokenmanager/main/cpp/src/token/native_token_info_inner.cpp +++ b/services/accesstokenmanager/main/cpp/src/token/native_token_info_inner.cpp @@ -29,35 +29,43 @@ namespace { static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "NativeTokenInfoInner"}; } +NativeTokenInfoInner::NativeTokenInfoInner() : isRemote_(false) +{ + tokenInfoBasic_.ver = DEFAULT_TOKEN_VERSION; + tokenInfoBasic_.tokenID = 0; + tokenInfoBasic_.tokenAttr = 0; + tokenInfoBasic_.apl = APL_NORMAL; +} + NativeTokenInfoInner::NativeTokenInfoInner(NativeTokenInfo& native) - : ver_(native.ver), tokenID_(native.tokenID), tokenAttr_(native.tokenAttr), - processName_(native.processName), apl_(native.apl), dcap_(native.dcap) -{} +{ + tokenInfoBasic_ = native; +} NativeTokenInfoInner::~NativeTokenInfoInner() { ACCESSTOKEN_LOG_DEBUG(LABEL, - "%{public}s called, tokenID: 0x%{public}x destruction", __func__, tokenID_); + "tokenID: 0x%{public}x destruction", tokenInfoBasic_.tokenID); } int NativeTokenInfoInner::Init(AccessTokenID id, const std::string& processName, int apl, const std::vector& dcap) { - tokenID_ = id; + tokenInfoBasic_.tokenID = id; if (!DataValidator::IsProcessNameValid(processName)) { ACCESSTOKEN_LOG_ERROR(LABEL, - "%{public}s called, tokenID: 0x%{public}x process name is null", __func__, tokenID_); + "tokenID: 0x%{public}x process name is null", tokenInfoBasic_.tokenID); return RET_FAILED; } - processName_ = processName; + tokenInfoBasic_.processName = processName; if (!DataValidator::IsAplNumValid(apl)) { ACCESSTOKEN_LOG_ERROR(LABEL, - "%{public}s called, tokenID: 0x%{public}x init failed, apl %{public}d is invalid", - __func__, tokenID_, apl); + "tokenID: 0x%{public}x init failed, apl %{public}d is invalid", + tokenInfoBasic_.tokenID, apl); return RET_FAILED; } - apl_ = (ATokenAplEnum)apl; - dcap_ = dcap; + tokenInfoBasic_.apl = (ATokenAplEnum)apl; + tokenInfoBasic_.dcap = dcap; return RET_SUCCESS; } @@ -75,111 +83,89 @@ std::string NativeTokenInfoInner::DcapToString(const std::vector& d int NativeTokenInfoInner::TranslationIntoGenericValues(GenericValues& outGenericValues) const { - outGenericValues.Put(FIELD_TOKEN_ID, tokenID_); - outGenericValues.Put(FIELD_PROCESS_NAME, processName_); - outGenericValues.Put(FIELD_APL, apl_); - outGenericValues.Put(FIELD_TOKEN_VERSION, ver_); - outGenericValues.Put(FIELD_DCAP, DcapToString(dcap_)); - outGenericValues.Put(FIELD_TOKEN_ATTR, tokenAttr_); + outGenericValues.Put(FIELD_TOKEN_ID, tokenInfoBasic_.tokenID); + outGenericValues.Put(FIELD_PROCESS_NAME, tokenInfoBasic_.processName); + outGenericValues.Put(FIELD_APL, tokenInfoBasic_.apl); + outGenericValues.Put(FIELD_TOKEN_VERSION, tokenInfoBasic_.ver); + outGenericValues.Put(FIELD_DCAP, DcapToString(tokenInfoBasic_.dcap)); + outGenericValues.Put(FIELD_TOKEN_ATTR, tokenInfoBasic_.tokenAttr); return RET_SUCCESS; } int NativeTokenInfoInner::RestoreNativeTokenInfo(AccessTokenID tokenId, const GenericValues& inGenericValues) { - tokenID_ = tokenId; - processName_ = inGenericValues.GetString(FIELD_PROCESS_NAME); - if (!DataValidator::IsProcessNameValid(processName_)) { + tokenInfoBasic_.tokenID = tokenId; + tokenInfoBasic_.processName = inGenericValues.GetString(FIELD_PROCESS_NAME); + if (!DataValidator::IsProcessNameValid(tokenInfoBasic_.processName)) { ACCESSTOKEN_LOG_ERROR(LABEL, - "%{public}s called, tokenID: 0x%{public}x process name is null", __func__, tokenID_); + "tokenID: 0x%{public}x process name is null", tokenInfoBasic_.tokenID); return RET_FAILED; } int aplNum = inGenericValues.GetInt(FIELD_APL); if (!DataValidator::IsAplNumValid(aplNum)) { ACCESSTOKEN_LOG_ERROR(LABEL, - "%{public}s called, tokenID: 0x%{public}x apl is error, value %{public}d", __func__, tokenID_, aplNum); + "tokenID: 0x%{public}x apl is error, value %{public}d", + tokenInfoBasic_.tokenID, aplNum); return RET_FAILED; } - apl_ = (ATokenAplEnum)aplNum; - ver_ = (char)inGenericValues.GetInt(FIELD_TOKEN_VERSION); - if (ver_ != DEFAULT_TOKEN_VERSION) { + tokenInfoBasic_.apl = (ATokenAplEnum)aplNum; + tokenInfoBasic_.ver = (char)inGenericValues.GetInt(FIELD_TOKEN_VERSION); + if (tokenInfoBasic_.ver != DEFAULT_TOKEN_VERSION) { ACCESSTOKEN_LOG_ERROR(LABEL, - "%{public}s called, tokenID: 0x%{public}x version is error, version %{public}d", __func__, tokenID_, ver_); + "tokenID: 0x%{public}x version is error, version %{public}d", + tokenInfoBasic_.tokenID, tokenInfoBasic_.ver); return RET_FAILED; } SetDcaps(inGenericValues.GetString(FIELD_DCAP)); - tokenAttr_ = (uint32_t)inGenericValues.GetInt(FIELD_TOKEN_ATTR); + tokenInfoBasic_.tokenAttr = (uint32_t)inGenericValues.GetInt(FIELD_TOKEN_ATTR); return RET_SUCCESS; } void NativeTokenInfoInner::TranslateToNativeTokenInfo(NativeTokenInfo& InfoParcel) const { - InfoParcel.apl = apl_; - InfoParcel.ver = ver_; - InfoParcel.processName = processName_; - InfoParcel.dcap = dcap_; - InfoParcel.tokenID = tokenID_; - InfoParcel.tokenAttr = tokenAttr_; + InfoParcel.apl = tokenInfoBasic_.apl; + InfoParcel.ver = tokenInfoBasic_.ver; + InfoParcel.processName = tokenInfoBasic_.processName; + InfoParcel.dcap = tokenInfoBasic_.dcap; + InfoParcel.tokenID = tokenInfoBasic_.tokenID; + InfoParcel.tokenAttr = tokenInfoBasic_.tokenAttr; } void NativeTokenInfoInner::StoreNativeInfo(std::vector& valueList) const { + if (isRemote_) { + return; + } GenericValues genericValues; TranslationIntoGenericValues(genericValues); valueList.emplace_back(genericValues); } -bool NativeTokenInfoInner::FromJsonString(const std::string& jsonString) +AccessTokenID NativeTokenInfoInner::GetTokenID() const { - nlohmann::json jsonObject = nlohmann::json::parse(jsonString); - if (jsonObject.is_discarded()) { - return false; - } - - if (jsonObject.find(JSON_PROCESS_NAME) != jsonObject.end()) { - processName_ = jsonObject.at(JSON_PROCESS_NAME).get(); - } - - if (jsonObject.find(JSON_APL) != jsonObject.end()) { - int aplNum = jsonObject.at(JSON_APL).get(); - if (DataValidator::IsAplNumValid(aplNum)) { - apl_ = (ATokenAplEnum)aplNum; - } - } - - if (jsonObject.find(JSON_VERSION) != jsonObject.end()) { - ver_ = jsonObject.at(JSON_VERSION).get(); - } - - if (jsonObject.find(JSON_TOKEN_ID) != jsonObject.end()) { - tokenID_ = jsonObject.at(JSON_TOKEN_ID).get(); - } - - if (jsonObject.find(JSON_TOKEN_ATTR) != jsonObject.end()) { - tokenAttr_ = jsonObject.at(JSON_TOKEN_ATTR).get(); - } - - if (jsonObject.find(JSON_DCAPS) != jsonObject.end()) { - dcap_ = jsonObject.at(JSON_DCAPS).get>(); - } + return tokenInfoBasic_.tokenID; +} - return true; +std::vector NativeTokenInfoInner::GetDcap() const +{ + return tokenInfoBasic_.dcap; } -AccessTokenID NativeTokenInfoInner::GetTokenID() const +std::string NativeTokenInfoInner::GetProcessName() const { - return tokenID_; + return tokenInfoBasic_.processName; } -std::vector NativeTokenInfoInner::GetDcap() const +bool NativeTokenInfoInner::IsRemote() const { - return dcap_; + return isRemote_; } -std::string NativeTokenInfoInner::GetProcessName() const +void NativeTokenInfoInner::SetRemote(bool isRemote) { - return processName_; + isRemote_ = isRemote; } void NativeTokenInfoInner::SetDcaps(const std::string& dcapStr) @@ -188,22 +174,23 @@ void NativeTokenInfoInner::SetDcaps(const std::string& dcapStr) while (true) { std::string::size_type offset = dcapStr.find(',', start); if (offset == std::string::npos) { - dcap_.push_back(dcapStr.substr(start)); + tokenInfoBasic_.dcap.push_back(dcapStr.substr(start)); break; } - dcap_.push_back(dcapStr.substr(start, offset)); + tokenInfoBasic_.dcap.push_back(dcapStr.substr(start, offset)); start = offset + 1; } } void NativeTokenInfoInner::ToString(std::string& info) const { - info.append(R"({"tokenID": )" + std::to_string(tokenID_)); - info.append(R"(, "tokenAttr": )" + std::to_string(tokenAttr_)); - info.append(R"(, "ver": )" + std::to_string(ver_)); - info.append(R"(, "processName": ")" + processName_ + R"(")"); - info.append(R"(, "apl": )" + std::to_string(apl_)); - info.append(R"(, "dcap": ")" + DcapToString(dcap_) + R"(")"); + info.append(R"({"tokenID": )" + std::to_string(tokenInfoBasic_.tokenID)); + info.append(R"(, "tokenAttr": )" + std::to_string(tokenInfoBasic_.tokenAttr)); + info.append(R"(, "ver": )" + std::to_string(tokenInfoBasic_.ver)); + info.append(R"(, "processName": ")" + tokenInfoBasic_.processName + R"(")"); + info.append(R"(, "apl": )" + std::to_string(tokenInfoBasic_.apl)); + info.append(R"(, "dcap": ")" + DcapToString(tokenInfoBasic_.dcap) + R"(")"); + info.append(R"(, "isRemote": )" + std::to_string(isRemote_)); info.append("}"); } } // namespace AccessToken diff --git a/services/accesstokenmanager/main/cpp/src/token/native_token_receptor.cpp b/services/accesstokenmanager/main/cpp/src/token/native_token_receptor.cpp index d5ee4ac8e..c6369f017 100644 --- a/services/accesstokenmanager/main/cpp/src/token/native_token_receptor.cpp +++ b/services/accesstokenmanager/main/cpp/src/token/native_token_receptor.cpp @@ -105,24 +105,24 @@ int NativeTokenReceptor::ReadCfgFile(std::string& nativeRawData) { int32_t fd = open(NATIVE_TOKEN_CONFIG_FILE.c_str(), O_RDONLY); if (fd < 0) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: open failed errno %{public}d.", __func__, errno); + ACCESSTOKEN_LOG_ERROR(LABEL, "open failed errno %{public}d.", errno); return RET_FAILED; } struct stat statBuffer; if (fstat(fd, &statBuffer) != 0) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: fstat failed.", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "fstat failed."); close(fd); return RET_FAILED; } if (statBuffer.st_size == 0) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: config file size is invalid.", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "config file size is invalid."); close(fd); return RET_FAILED; } if (statBuffer.st_size > MAX_NATIVE_CONFIG_FILE_SIZE) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: config file size is too large.", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "config file size is too large."); close(fd); return RET_FAILED; } @@ -144,14 +144,14 @@ int NativeTokenReceptor::ReadCfgFile(std::string& nativeRawData) int NativeTokenReceptor::Init() { if (ready_) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: native token has been inited.", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "native token has been inited."); return RET_SUCCESS; } std::string nativeRawData; int ret = ReadCfgFile(nativeRawData); if (ret != RET_SUCCESS) { - ACCESSTOKEN_LOG_ERROR(LABEL, "%{public}s: readCfgFile failed.", __func__); + ACCESSTOKEN_LOG_ERROR(LABEL, "readCfgFile failed."); return RET_FAILED; } std::vector> tokenInfos; @@ -159,7 +159,7 @@ int NativeTokenReceptor::Init() AccessTokenInfoManager::GetInstance().ProcessNativeTokenInfos(tokenInfos); ready_ = true; - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s: init ok.", __func__); + ACCESSTOKEN_LOG_INFO(LABEL, "init ok."); return RET_SUCCESS; } diff --git a/services/accesstokenmanager/main/cpp/src/token/token_modify_notifier.cpp b/services/accesstokenmanager/main/cpp/src/token/token_modify_notifier.cpp new file mode 100644 index 000000000..49ba60e8f --- /dev/null +++ b/services/accesstokenmanager/main/cpp/src/token/token_modify_notifier.cpp @@ -0,0 +1,119 @@ +/* + * 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 "token_modify_notifier.h" + +#include "accesstoken_id_manager.h" +#include "accesstoken_info_manager.h" +#include "accesstoken_log.h" +#include "hap_token_info.h" +#include "hap_token_info_inner.h" +#include "token_sync_kit.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "TokenModifyNotifier"}; +} + +TokenModifyNotifier::TokenModifyNotifier() : hasInited_(false) {} + +TokenModifyNotifier::~TokenModifyNotifier() {} + +void TokenModifyNotifier::AddHapTokenObservation(AccessTokenID tokenID) +{ + if (AccessTokenIDManager::GetInstance().GetTokenIdType(tokenID) != TOKEN_HAP) { + ACCESSTOKEN_LOG_INFO(LABEL, "Observation token is not hap token"); + return; + } + Utils::UniqueWriteGuard infoGuard(this->Notifylock_); + if (observationSet_.count(tokenID) <= 0) { + observationSet_.insert(tokenID); + } +} + +void TokenModifyNotifier::NotifyTokenDelete(AccessTokenID tokenID) +{ + Utils::UniqueWriteGuard infoGuard(this->Notifylock_); + if (observationSet_.count(tokenID) <= 0) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "hap token is not observed"); + return; + } + observationSet_.erase(tokenID); + deleteTokenList_.emplace_back(tokenID); + NotifyTokenChangedIfNeed(); +} + +void TokenModifyNotifier::NotifyTokenModify(AccessTokenID tokenID) +{ + Utils::UniqueWriteGuard infoGuard(this->Notifylock_); + if (observationSet_.count(tokenID) <= 0) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "hap token is not observed"); + return; + } + modifiedTokenList_.emplace_back(tokenID); + NotifyTokenChangedIfNeed(); +} + +TokenModifyNotifier& TokenModifyNotifier::GetInstance() +{ + static TokenModifyNotifier instance; + + if (!instance.hasInited_) { + Utils::UniqueWriteGuard infoGuard(instance.initLock_); + if (!instance.hasInited_) { + instance.notifyTokenWorker_.Start(1); + instance.hasInited_ = true; + } + } + + return instance; +} + +void TokenModifyNotifier::NotifyTokenSyncTask() +{ + Utils::UniqueWriteGuard infoGuard(this->Notifylock_); + for (AccessTokenID deleteToken : deleteTokenList_) { + TokenSyncKit::DeleteRemoteHapTokenInfo(deleteToken); + } + + for (AccessTokenID modifyToken : modifiedTokenList_) { + HapTokenInfoForSync hapSync; + int ret = AccessTokenInfoManager::GetInstance().GetHapTokenSync(modifyToken, hapSync); + if (ret != RET_SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "the hap token 0x%{public}x need to sync is not found!", modifyToken); + continue; + } + TokenSyncKit::UpdateRemoteHapTokenInfo(hapSync); + } + deleteTokenList_.clear(); + modifiedTokenList_.clear(); +} +void TokenModifyNotifier::NotifyTokenChangedIfNeed() +{ + if (notifyTokenWorker_.GetCurTaskNum() > 1) { + ACCESSTOKEN_LOG_INFO(LABEL, " has notify task!"); + return; + } + + notifyTokenWorker_.AddTask([]() { + TokenModifyNotifier::GetInstance().NotifyTokenSyncTask(); + }); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + diff --git a/services/tokensyncmanager/BUILD.gn b/services/tokensyncmanager/BUILD.gn index 42ca7f73b..599f6f026 100644 --- a/services/tokensyncmanager/BUILD.gn +++ b/services/tokensyncmanager/BUILD.gn @@ -27,25 +27,60 @@ ohos_shared_library("token_sync_manager_service") { include_dirs = [ "include/service", "include/remote", + "include/command", + "include/common", + "include/device", + "include/protocol", + "//third_party/json/include", "//utils/system/safwk/native/include", + "//third_party/json/include", "//base/security/access_token/frameworks/common/include", + "//base/security/access_token/frameworks/accesstoken/include", "//base/security/access_token/frameworks/tokensync/include", "//base/security/access_token/interfaces/innerkits/accesstoken/include", "//foundation/communication/dsoftbus/interfaces/kits/transport", "//foundation/communication/dsoftbus/interfaces/kits/common", "//foundation/communication/dsoftbus/interfaces/kits/bus_center", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", + "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp/include", + "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp:devicemanagersdk", ] sources = [ + "src/command/base_remote_command.cpp", + "src/command/delete_remote_token_command.cpp", + "src/command/sync_remote_hap_token_command.cpp", + "src/command/sync_remote_native_token_command.cpp", + "src/command/update_remote_hap_token_command.cpp", + "src/common/constant.cpp", + "src/device/device_info_manager.cpp", + "src/device/device_info_repository.cpp", + "src/remote/remote_command_executor.cpp", + "src/remote/remote_command_factory.cpp", + "src/remote/remote_command_manager.cpp", + "src/remote/soft_bus_channel.cpp", + "src/remote/soft_bus_device_connection_listener.cpp", "src/remote/soft_bus_manager.cpp", - "src/service/tokensync_manager_service.cpp", - "src/service/tokensync_manager_stub.cpp", + "src/remote/soft_bus_session_listener.cpp", + "src/service/token_sync_event_handler.cpp", + "src/service/token_sync_manager_service.cpp", + "src/service/token_sync_manager_stub.cpp", ] cflags_cc = [ "-DHILOG_ENABLE" ] deps = [ + "//base/security/access_token/frameworks/accesstoken:accesstoken_communication_adapter_cxx", + "//base/security/access_token/frameworks/common:accesstoken_common_cxx", + "//base/security/access_token/interfaces/innerkits/accesstoken:libaccesstoken_sdk", "//base/security/access_token/services/tokensyncmanager:token_sync.rc", + "//base/startup/syspara_lite/interfaces/innerkits/native/syspara:syspara", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", + "//foundation/distributedhardware/devicemanager/interfaces/inner_kits/native_cpp:devicemanagersdk", + "//third_party/zlib:libz", "//utils/native/base:utils", ] diff --git a/services/tokensyncmanager/include/command/base_remote_command.h b/services/tokensyncmanager/include/command/base_remote_command.h new file mode 100644 index 000000000..6af5f58a0 --- /dev/null +++ b/services/tokensyncmanager/include/command/base_remote_command.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef BASE_REMOTE_COMMON_H +#define BASE_REMOTE_COMMON_H + +#include + +#include "constant.h" +#include "hap_token_info.h" +#include "native_token_info.h" +#include "nlohmann/json.hpp" +#include "permission_state_full.h" +#include "remote_protocol.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +/** + * The base class for command. You can treat this as remote command header. + */ +class BaseRemoteCommand { +public: + BaseRemoteCommand() = default; + virtual ~BaseRemoteCommand() = default; + + /* Prepare() is called in requestor */ + virtual void Prepare() = 0; + + /* Execute() is called in responser */ + virtual void Execute() = 0; + + /* Finish() is called in requestor, after get response, but the command object is not same with the request */ + virtual void Finish() = 0; + + virtual std::string ToJsonPayload() = 0; + nlohmann::json ToRemoteProtocolJson(); + void FromRemoteProtocolJson(const nlohmann::json& jsonObject); + + void ToPermStateJson(nlohmann::json& permStateJson, const PermissionStateFull& state); + void FromPermStateListJson(const nlohmann::json& hapTokenJson, + std::vector& permStateList); + + void FromHapTokenBasicInfoJson(const nlohmann::json& hapTokenJson, + HapTokenInfo& hapTokenBasicInfo); + + nlohmann::json ToHapTokenInfosJson(const HapTokenInfoForSync &tokenInfo); + void FromHapTokenInfoJson(const nlohmann::json& hapTokenJson, HapTokenInfoForSync& hapTokenInfo); + nlohmann::json ToNativeTokenInfoJson(const NativeTokenInfo& tokenInfo); + void FromNativeTokenInfoJson(const nlohmann::json& nativeTokenJson, NativeTokenInfo& nativeTokenInfo); + RemoteProtocol remoteProtocol_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // BASE_REMOTE_COMMON_H diff --git a/services/tokensyncmanager/include/command/delete_remote_token_command.h b/services/tokensyncmanager/include/command/delete_remote_token_command.h new file mode 100644 index 000000000..97e3a2444 --- /dev/null +++ b/services/tokensyncmanager/include/command/delete_remote_token_command.h @@ -0,0 +1,52 @@ +/* + * 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 DELETE_REMOTE_TOKEN_COMMAND_H +#define DELETE_REMOTE_TOKEN_COMMAND_H + +#include "base_remote_command.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +/** + * Command which used to get all native token info from other device. + */ +class DeleteRemoteTokenCommand : public BaseRemoteCommand { +public: + void Prepare() override; + + void Execute() override; + + void Finish() override; + + std::string ToJsonPayload() override; + + DeleteRemoteTokenCommand(const std::string &json); + DeleteRemoteTokenCommand(const std::string &srcDeviceId, const std::string &dstDeviceId, + AccessTokenID deleteID); + virtual ~DeleteRemoteTokenCommand() = default; + +private: + /** + * The command name. Should be equal to class name. + */ + const std::string COMMAND_NAME = "DeleteRemoteTokenCommand"; + AccessTokenID deleteTokenId_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif \ No newline at end of file diff --git a/services/tokensyncmanager/include/command/sync_remote_hap_token_command.h b/services/tokensyncmanager/include/command/sync_remote_hap_token_command.h new file mode 100644 index 000000000..3783c0c9c --- /dev/null +++ b/services/tokensyncmanager/include/command/sync_remote_hap_token_command.h @@ -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. + */ + +#ifndef SYNC_REMOTE_HAP_TOKEN_COMMAND_H +#define SYNC_REMOTE_HAP_TOKEN_COMMAND_H + +#include + +#include "access_token.h" +#include "base_remote_command.h" +#include "hap_token_info.h" +#include "permission_state_full.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +/** + * Command which used to get all native token info from other device. + */ +class SyncRemoteHapTokenCommand : public BaseRemoteCommand { +public: + void Prepare() override; + + void Execute() override; + + void Finish() override; + + std::string ToJsonPayload() override; + + SyncRemoteHapTokenCommand(const std::string &json); + SyncRemoteHapTokenCommand( const std::string &srcDeviceId, + const std::string &dstDeviceId, AccessTokenID id); + virtual ~SyncRemoteHapTokenCommand() = default; + +private: + /** + * The command name. Should be equal to class name. + */ + const std::string COMMAND_NAME = "SyncRemoteHapTokenCommand"; + HapTokenInfoForSync hapTokenInfo_; + AccessTokenID requestTokenId_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif + diff --git a/services/tokensyncmanager/include/command/sync_remote_native_token_command.h b/services/tokensyncmanager/include/command/sync_remote_native_token_command.h new file mode 100644 index 000000000..e398d7804 --- /dev/null +++ b/services/tokensyncmanager/include/command/sync_remote_native_token_command.h @@ -0,0 +1,55 @@ +/* + * 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 SYNC_REMOTE_NATIVE_TOKEN_COMMAND_H +#define SYNC_REMOTE_NATIVE_TOKEN_COMMAND_H + +#include +#include + +#include "base_remote_command.h" +#include "native_token_info.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +/** + * Command which used to get all native token info from other device. + */ +class SyncRemoteNativeTokenCommand : public BaseRemoteCommand { +public: + void Prepare() override; + + void Execute() override; + + void Finish() override; + + std::string ToJsonPayload() override; + + SyncRemoteNativeTokenCommand(const std::string &json); + SyncRemoteNativeTokenCommand(const std::string &srcDeviceId, const std::string &dstDeviceId); + virtual ~SyncRemoteNativeTokenCommand() = default; + +private: + /** + * The command name. Should be equal to class name. + */ + const std::string COMMAND_NAME = "SyncRemoteNativeTokenCommand"; + std::vector nativeTokenInfo_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif \ No newline at end of file diff --git a/services/tokensyncmanager/include/command/update_remote_hap_token_command.h b/services/tokensyncmanager/include/command/update_remote_hap_token_command.h new file mode 100644 index 000000000..1e6f88919 --- /dev/null +++ b/services/tokensyncmanager/include/command/update_remote_hap_token_command.h @@ -0,0 +1,56 @@ +/* + * 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 UPDATE_REMOTE_HAP_TOKEN_COMMAND_H +#define UPDATE_REMOTE_HAP_TOKEN_COMMAND_H + +#include + +#include "access_token.h" +#include "base_remote_command.h" +#include "hap_token_info.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +/** + * Command which used to get all native token info from other device. + */ +class UpdateRemoteHapTokenCommand : public BaseRemoteCommand { +public: + void Prepare() override; + + void Execute() override; + + void Finish() override; + + std::string ToJsonPayload() override; + + UpdateRemoteHapTokenCommand(const std::string &json); + UpdateRemoteHapTokenCommand(const std::string &srcDeviceId, const std::string &dstDeviceId, + const HapTokenInfoForSync& tokenInfo); + virtual ~UpdateRemoteHapTokenCommand() = default; + +private: + /** + * The command name. Should be equal to class name. + */ + const std::string COMMAND_NAME = "UpdateRemoteHapTokenCommand"; + HapTokenInfoForSync updateTokenInfo_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif \ No newline at end of file diff --git a/services/tokensyncmanager/include/common/constant.h b/services/tokensyncmanager/include/common/constant.h new file mode 100644 index 000000000..6c8205a14 --- /dev/null +++ b/services/tokensyncmanager/include/common/constant.h @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef CONSTANT_H +#define CONSTANT_H + +#include +#include +#include +#include + +namespace OHOS { +namespace Security { +namespace AccessToken { +class Constant { +public: + /** + * Indicates message format version, should be compatible. + */ + const static int32_t DISTRIBUTED_ACCESS_TOKEN_SERVICE_VERSION = 2; + + /** + * Status code, indicates general success. + */ + const static int32_t SUCCESS = 0; + + /** + * Status code, indicates general failure. + */ + const static int32_t FAILURE = -1; + + /** + * Status code, indicates failure but can retry. + */ + const static int32_t FAILURE_BUT_CAN_RETRY = -2; + + /** + * Status Code, indicates invalid command. + */ + const static int32_t INVALID_COMMAND = -14; + + /** + * Session Id, indicates invalid session. + */ + const static int32_t INVALID_SESSION = -1; + + /** + * Command status code, indicate a status of command before RPC call. + */ + const static int32_t STATUS_CODE_BEFORE_RPC = 100001; + + /** + * Command result string, indicates success. + */ + static const std::string COMMAND_RESULT_SUCCESS; + + /** + * Command result string, indicates failed. + */ + static const std::string COMMAND_RESULT_FAILED; + + /** + * Device id length. + */ + const static int32_t DEVICE_UUID_LENGTH = 65; + + /** + * Command status code, indicate a status of command before RPC call. + */ + const static int32_t DELAY_SYNC_TOKEN_MS = 3000; + + static constexpr int32_t ENCRYPTLEN = 4; + static constexpr int32_t ENCRYPTBEGIN = 0; + static constexpr int32_t ENCRYPTEND = 3; + static std::string EncryptDevId(std::string deviceId); + + /** + * GetLocalDeviceId + */ + static std::string GetLocalDeviceId(); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // CONSTANT_H \ No newline at end of file diff --git a/services/tokensyncmanager/include/device/device_info.h b/services/tokensyncmanager/include/device/device_info.h new file mode 100644 index 000000000..958aa0803 --- /dev/null +++ b/services/tokensyncmanager/include/device/device_info.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 DEVICE_INFO_H +#define DEVICE_INFO_H + +#include + +namespace OHOS { +namespace Security { +namespace AccessToken { +enum DeviceIdType { + NETWORK_ID, + UNIVERSALLY_UNIQUE_ID, + UNIQUE_DISABILITY_ID, + UNKNOWN, +}; + +struct DeviceId { + std::string networkId; + std::string universallyUniqueId; + std::string uniqueDisabilityId; +}; + +struct DeviceInfo { + DeviceId deviceId; + std::string deviceName; + std::string deviceType; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // DEVICE_INFO_H \ No newline at end of file diff --git a/services/tokensyncmanager/include/device/device_info_manager.h b/services/tokensyncmanager/include/device/device_info_manager.h new file mode 100644 index 000000000..b5be6c827 --- /dev/null +++ b/services/tokensyncmanager/include/device/device_info_manager.h @@ -0,0 +1,104 @@ +/* + * 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 DEVICE_INFO_MANAGER_H +#define DEVICE_INFO_MANAGER_H + +#include + +#include "accesstoken_log.h" +#include "data_validator.h" +#include "device_info_repository.h" +#include "ipc_skeleton.h" +#include "parameter.h" +#include "soft_bus_manager.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class DeviceInfoManager { +public: + static DeviceInfoManager &GetInstance(); + + /** + * Get device info by device id. + * + * @param nodeId Device id. + * @param deviceIdType Device id type {@link DeviceIdType} + * @return Optional deviceInfo + */ + bool GetDeviceInfo(const std::string &nodeId, DeviceIdType deviceIdType, DeviceInfo &deviceInfo) const; + + /** + * Check device info exist. Online and local device info will be here. + * + * @param nodeId Device id. + * @param deviceIdType Device id type {@link DeviceIdType} + * @return True for exist, false otherwise. + */ + bool ExistDeviceInfo(const std::string &nodeId, DeviceIdType deviceIdType) const; + + /** + * Add device info with device ids and device properties. + * + * @param networkId Device networkId. + * @param universallyUniqueId Device uuid. + * @param uniqueDisabilityId Device udid. + * @param deviceName Device name. + * @param deviceType Device type. + */ + void AddDeviceInfo(const std::string &networkId, const std::string &universallyUniqueId, + const std::string &uniqueDisabilityId, const std::string &deviceName, const std::string &deviceType); + + /** + * Remote all device info. + */ + void RemoveAllRemoteDeviceInfo(); + + /** + * Remove one device info. + * + * @param nodeId Device id. + */ + void RemoveRemoteDeviceInfo(const std::string &nodeId, DeviceIdType deviceIdType); + + /** + * Convert nodeId to deviceId(UUID) if possible. + * + * @param nodeId which is considered as indefinite id, maybe deviceId(UUID) or networkId. + * @return The deviceId if local or device online, otherwise return empty string. + */ + std::string ConvertToUniversallyUniqueIdOrFetch(const std::string &nodeId) const; + + /** + * Convert nodeId to deviceId(UDID) if possible. + * + * @param nodeId which is considered as indefinite id, maybe deviceId(UDID) or networkId. + * @return The deviceId if local or device online, otherwise return empty string. + */ + std::string ConvertToUniqueDisabilityIdOrFetch(const std::string &nodeId) const; + + /** + * Check nodeId is uuid or not. + * + * @param nodeId Node id. + * @return True if node id is uuid. False otherwise. + */ + bool IsDeviceUniversallyUniqueId(const std::string &nodeId) const; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // DEVICE_INFO_MANAGER_H \ No newline at end of file diff --git a/services/tokensyncmanager/include/device/device_info_repository.h b/services/tokensyncmanager/include/device/device_info_repository.h new file mode 100644 index 000000000..319e76838 --- /dev/null +++ b/services/tokensyncmanager/include/device/device_info_repository.h @@ -0,0 +1,77 @@ +/* + * 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 DEVICE_INFO_REPOSITORY_H +#define DEVICE_INFO_REPOSITORY_H + +#include +#include +#include +#include + +#include "constant.h" +#include "device_info.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class DeviceInfoRepository { +public: + static DeviceInfoRepository &GetInstance(); + + std::vector ListDeviceInfo(); + + bool FindDeviceInfo(const std::string &nodeId, DeviceIdType type, DeviceInfo &deviceInfo); + + void DeleteAllDeviceInfoExceptOne(const DeviceInfo deviceInfo); + + void SaveDeviceInfo(const DeviceInfo deviceInfo); + + void SaveDeviceInfo(const DeviceId deviceId, const std::string &deviceName, const std::string &deviceType); + + void SaveDeviceInfo(const std::string &networkId, const std::string &universallyUniqueId, + const std::string &uniqueDisabilityId, const std::string &deviceName, const std::string &deviceType); + + void DeleteDeviceInfo(const std::string &nodeId, const DeviceIdType type); + + void Clear(); + +private: + bool FindDeviceIdByNodeIdLocked(const std::string &nodeId, const DeviceIdType type, DeviceId &deviceId) const; + + bool FindDeviceInfoByDeviceIdLocked(const DeviceId deviceId, DeviceInfo &deviceInfo) const; + + bool FindDeviceIdByNetworkIdLocked(const std::string &networkId, DeviceId &deviceId) const; + + bool FindDeviceIdByUniversallyUniqueIdLocked(const std::string &universallyUniqueId, DeviceId &deviceId) const; + + bool FindDeviceIdByUniqueDisabilityIdLocked(const std::string &uniqueDisabilityId, DeviceId &deviceId) const; + + void DeleteDeviceInfoByDeviceIdLocked(const DeviceId deviceId); + + std::map deviceIdMapByNetworkId_; + + std::map deviceIdMapByUniversallyUniqueId_; + + std::map deviceIdMapByUniqueDisabilityId_; + + std::map deviceInfoMap_; + + std::recursive_mutex stackLock_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // DEVICE_INFO_REPOSITORY_H \ No newline at end of file diff --git a/services/tokensyncmanager/include/protocol/remote_protocol.h b/services/tokensyncmanager/include/protocol/remote_protocol.h new file mode 100644 index 000000000..97ada420b --- /dev/null +++ b/services/tokensyncmanager/include/protocol/remote_protocol.h @@ -0,0 +1,38 @@ +/* + * 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 REMOTE_PROTOCOL_H +#define REMOTE_PROTOCOL_H + +namespace OHOS { +namespace Security { +namespace AccessToken { +struct RemoteProtocol { + std::string commandName; + std::string uniqueId; + int32_t requestVersion; + std::string srcDeviceId; + std::string srcDeviceLevel; + std::string dstDeviceId; + std::string dstDeviceLevel; + int32_t statusCode; + std::string message; + int32_t responseVersion; + std::string responseDeviceId; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif \ No newline at end of file diff --git a/services/tokensyncmanager/include/remote/remote_command_executor.h b/services/tokensyncmanager/include/remote/remote_command_executor.h new file mode 100644 index 000000000..f8982a9b5 --- /dev/null +++ b/services/tokensyncmanager/include/remote/remote_command_executor.h @@ -0,0 +1,158 @@ +/* + * 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 REMOTE_COMMAND_EXECUTOR_H +#define REMOTE_COMMAND_EXECUTOR_H + +#include +#include + +#include "accesstoken_log.h" +#include "base_remote_command.h" +#include "remote_command_factory.h" +#include "rpc_channel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class RemoteCommandExecutor final { +public: + RemoteCommandExecutor(const std::string &targetNodeId); + virtual ~RemoteCommandExecutor(); + + const std::shared_ptr &GetChannel() const + { + return ptrChannel_; + } + void SetChannel(const std::shared_ptr &ptrChannel) + { + ptrChannel_ = ptrChannel; + } + + /** + * @brief Factory method to create a rpc channel. we will only create SoftBusChannel by now. + * + * @param targetNodeId target device node id(udid) + * @return Returns a shared_ptr if the operation is successful, returns nullptr otherwise. + * @see SoftBusChannel + * @since 1.0 + * @version 1.0 + */ + static const std::shared_ptr CreateChannel(const std::string &targetNodeId); + + /** + * @brief Process one command given. + * + * @param ptrCommand BaseRemoteCommand to execute. + * @return Returns SUCCESS if the operation is successful, returns minus integer otherwise. + * @see void + * @since 1.0 + * @version 1.0 + */ + int ProcessOneCommand(const std::shared_ptr &ptrCommand); + + /** + * @brief Add one command into the buffer + * + * @param ptrCommand BaseRemoteCommand to execute. + * @return Returns SUCCESS if the operation is successful, returns INVALID_COMMAND otherwise. + * @see ProcessBufferedCommands + * @since 1.0 + * @version 1.0 + */ + int AddCommand(const std::shared_ptr &ptrCommand); + + /** + * @brief Process all the command in the buffer + * + * @param standalone true if run in a new thread or event runner, otherwise false. + * @return Returns SUCCESS if the operation is successful, returns FAILURE otherwise. + * @see AddCommand ProcessOneCommand + * @since 1.0 + * @version 1.0 + */ + int ProcessBufferedCommands(bool standalone = false); + + /** + * @brief Process all the command in the buffer within a new thread. in deconstruct, we need to join this thread if + * needed. + * + * @param ptrCommand BaseRemoteCommand to execute. + * @return void + * @see ProcessBufferedCommands + * @since 1.0 + * @version 1.0 + */ + void ProcessBufferedCommandsWithThread(); + +private: + /** + * @brief execute a command in a specific place. + * for remote command, transfor the command json string by channel to softbus, and wait for softbus to response a + * json string. while remote response a json string, construct a remote command and finish it. + * if command buffer is empty, close the rpc channel. + * + * @param ptrCommand BaseRemoteCommand to execute. + * @param isRemote where to run. true for remote, false for local. + * @return Returns SUCCESS if the operation is successful, returns FAILURE otherwise. + * @see ProcessBufferedCommands + * @since 1.0 + * @version 1.0 + */ + int ExecuteRemoteCommand(const std::shared_ptr &ptrCommand, bool isRemote); + + /** + * @brief create a rpc channel if not exist. + * + * @param ptrCommand BaseRemoteCommand to execute. + * @param isRemote where to run. true for remote, false for local. + * @return void + * @see ProcessBufferedCommands + * @since 1.0 + * @version 1.0 + */ + void CreateChannelIfNeeded(); + + /** + * @brief finish a command + * + * @param ptrCommand BaseRemoteCommand to execute. + * @return Returns SUCCESS if the operation is successful, returns FAILURE otherwise. + * @see ProcessBufferedCommands + * @since 1.0 + * @version 1.0 + */ + int ClientProcessResult(const std::shared_ptr &ptrCommand); + +private: + // target device node id(udid) + std::string targetNodeId_; + + // cached channel for buffered commands + std::shared_ptr ptrChannel_; + + // mutex to lock commands buffer for concurrent access. + std::recursive_mutex mutex_; + + // commands buffer + std::deque> commands_; + + // consumer running flag, true if the consumer is RUNNING, false otherwise. @see ProcessBufferedCommands + bool running_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // REMOTE_COMMAND_EXECUTOR_H diff --git a/services/tokensyncmanager/include/remote/remote_command_factory.h b/services/tokensyncmanager/include/remote/remote_command_factory.h new file mode 100644 index 000000000..f9967cc20 --- /dev/null +++ b/services/tokensyncmanager/include/remote/remote_command_factory.h @@ -0,0 +1,58 @@ +/* + * 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 REMOTE_COMMAND_FACTORY_H +#define REMOTE_COMMAND_FACTORY_H + +#include +#include +#include + +#include "access_token.h" +#include "delete_remote_token_command.h" +#include "hap_token_info.h" +#include "sync_remote_hap_token_command.h" +#include "sync_remote_native_token_command.h" +#include "update_remote_hap_token_command.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class RemoteCommandFactory { +public: + static RemoteCommandFactory &GetInstance(); + + std::shared_ptr NewSyncRemoteHapTokenCommand(const std::string &srcDeviceId, + const std::string &dstDeviceId, AccessTokenID tokenID); + + std::shared_ptr NewDeleteRemoteTokenCommand(const std::string &srcDeviceId, + const std::string &dstDeviceId, AccessTokenID tokenID); + + std::shared_ptr NewUpdateRemoteHapTokenCommand(const std::string &srcDeviceId, + const std::string &dstDeviceId, const HapTokenInfoForSync& tokenInfo); + + std::shared_ptr NewSyncRemoteNativeTokenCommand(const std::string &srcDeviceId, + const std::string &dstDeviceId); + + std::shared_ptr NewRemoteCommandFromJson( + const std::string &commandName, const std::string &commandJsonString); + +private: + const std::string TAG = "RemoteCommandFactory"; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // REMOTE_COMMAND_FACTORY_H diff --git a/services/tokensyncmanager/include/remote/remote_command_manager.h b/services/tokensyncmanager/include/remote/remote_command_manager.h new file mode 100644 index 000000000..b40619eda --- /dev/null +++ b/services/tokensyncmanager/include/remote/remote_command_manager.h @@ -0,0 +1,165 @@ +/* + * 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 REMOTE_COMMAND_MANAGER_H +#define REMOTE_COMMAND_MANAGER_H + +#include +#include +#include +#include + +#include "accesstoken_log.h" +#include "base_remote_command.h" +#include "constant.h" +#include "data_validator.h" +#include "remote_command_executor.h" +#include "rpc_channel.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class RemoteCommandManager final { +public: + ~RemoteCommandManager(); + + /** + * @brief Singleton instance get method. + * + * @since 1.0 + * @version 1.0 + */ + static RemoteCommandManager &GetInstance(); + + /** + * @brief Init method. + * + * @see + * @since 1.0 + * @version 1.0 + */ + void Init(); + + /** + * @brief Execute a command now. + * + * @param udid The udid of a device which you want to execute on. if udid is empty, return -1. + * @param command A command extend BaseRemoteCommand. if command is nullptr, return -1. + * @return The execute result, returned from RemoteCommandExecutor. + * @see RemoteCommandExecutor.ExecuteOneCommand + * @since 1.0 + * @version 1.0 + */ + int ExecuteCommand(const std::string &udid, const std::shared_ptr &command); + + /** + * @brief Add a command to buffer. + * + * @param udid The udid of a device which you want to execute on. + * @param command A command extend BaseRemoteCommand. + * @return The add result, returned from RemoteCommandExecutor. by now, SUCCESS: 0. INVALID_COMMAND: -14 + * @see RemoteCommandExecutor.AddCommand + * @since 1.0 + * @version 1.0 + */ + int AddCommand(const std::string &udid, const std::shared_ptr &command); + + /** + * @brief Execute all buffered commands for given device. + * + * @param udid The udid of a device which you want to execute on. + * @return The execute result. SUCCESS: 0; FAILURE: -1. + * @see RemoteCommandExecutor.ProcessBufferedCommands + * @since 1.0 + * @version 1.0 + */ + int ProcessDeviceCommandImmediately(const std::string &udid); + + /** + * @brief Execute all buffered commands for all device asynchronized. + * + * @return The loop result. SUCCESS: 0. + * @see RemoteCommandExecutor.ProcessBufferedCommandsWithThread + * @since 1.0 + * @version 1.0 + */ + int Loop(); + + /** + * @brief Clear buffered commands. + * + * @since 1.0 + * @version 1.0 + */ + void Clear(); + + /** + * @brief Remove a command from buffer. + * + * @param udid The udid of a device which you want to remove. + */ + void RemoveCommand(const std::string &udid); + + /** + * @brief For event of device online, prepare channel and build connection with peer device. + * + * @param peerNodeId The udid of peer device. + * @return Result code indicates if notify successfully. SUCCESS: 0, FAILURE: -1. + * @since 1.0 + * @version 1.0 + */ + int NotifyDeviceOnline(const std::string &peerNodeId); + + /** + * @brief For event of device offline, clean caches related to peer device. + * + * @param peerNodeId The peer device's nodeId, maybe uuid or udid . + * @return Result code indicates if notify successfully. SUCCESS: 0, FAILURE: -1. + * @since 1.0 + * @version 1.0 + */ + int NotifyDeviceOffline(const std::string &peerNodeId); + + /** + * @brief Get remote command executor's channel for given nodeId. + * + * @param nodeId The peer device's nodeId, maybe uuid or udid or networkId. + * @return Channel instance if remote command executor has been created, null otherwise. + */ + std::shared_ptr GetExecutorChannel(const std::string &nodeId); + +private: + RemoteCommandManager(); + + // executors buffer + std::map> executors_; + // executors buffer mutex + std::mutex mutex_; + + /** + * @brief Fetch a executor from executors buffer. If not found, create one and cache it to buffer. + * + * @param nodeId The udid of a device which you want to get executor. + * @see void + * @since 1.0 + * @version 1.0 + */ + std::shared_ptr GetOrCreateRemoteCommandExecutor(const std::string &nodeId); +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif diff --git a/services/tokensyncmanager/include/remote/rpc_channel.h b/services/tokensyncmanager/include/remote/rpc_channel.h new file mode 100644 index 000000000..3443d25c4 --- /dev/null +++ b/services/tokensyncmanager/include/remote/rpc_channel.h @@ -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. + */ + +#ifndef RPC_CHANNEL_H +#define RPC_CHANNEL_H + +namespace OHOS { +namespace Security { +namespace AccessToken { +/* + * Channel used for communicate with peer devices. + */ +class RpcChannel { +public: + /** + * @brief Build connection with peer device. + * + * @return Result code represent if build successfully. 0 indicates success, -1 indicates failure. + * @since 1.0 + * @version 1.0 + */ + virtual int BuildConnection() = 0; + + /** + * @brief Execute BaseRemoteCommand at peer device. + * + * @param commandName The name of Command. + * @param jsonPayload The json payload of command. + * @return Executed result response string. + * @since 1.0 + * @version 1.0 + */ + virtual std::string ExecuteCommand(const std::string &commandName, const std::string &jsonPayload) = 0; + + /** + * @brief Handle data received. This interface only use for soft bus channel. + * + * @param session Session with peer device. + * @param bytes Data sent from the peer device. + * @param length Data length sent from the peer device. + * @since 1.0 + * @version 1.0 + */ + virtual void HandleDataReceived(int session, const unsigned char *bytes, int length) + {} + + /** + * @brief Close rpc connection when no data is being transmitted. + * + * @since 1.0 + * @version 1.0 + */ + virtual void CloseConnection() + {} + + /** + * @brief Release resources when the device offline. + * + * @since 1.0 + * @version 1.0 + */ + virtual void Release(){}; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/services/tokensyncmanager/include/remote/soft_bus_channel.h b/services/tokensyncmanager/include/remote/soft_bus_channel.h new file mode 100644 index 000000000..f7e52e79e --- /dev/null +++ b/services/tokensyncmanager/include/remote/soft_bus_channel.h @@ -0,0 +1,365 @@ +/* + * 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 SOFT_BUS_CHANNEL_H +#define SOFT_BUS_CHANNEL_H + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "accesstoken_log.h" +#include "nlohmann/json.hpp" +#include "rpc_channel.h" +#include "session.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class SoftBusChannel final : public RpcChannel, public std::enable_shared_from_this { +public: + SoftBusChannel(const std::string &deviceId); + virtual ~SoftBusChannel(); + + /** + * @brief Build connection with peer device. + * + * @return Result code, 0 indicated build successfully, -1 indicates failure. + * @since 1.0 + * @version 1.0 + * @see Release + */ + int BuildConnection() override; + + /** + * @brief Execute BaseRemoteCommand at peer device. + * + * @param commandName The name of Command. + * @param jsonPayload The json payload of command. + * @return Executed result response string. + * @since 1.0 + * @version 1.0 + */ + std::string ExecuteCommand(const std::string &commandName, const std::string &jsonPayload) override; + + /** + * @brief Handle data received. This interface only use for soft bus channel. + * + * @param session Session with peer device. + * @param bytes Data sent from the peer device. + * @param length Data length sent from the peer device. + * @since 1.0 + * @version 1.0 + */ + void HandleDataReceived(int session, const unsigned char *bytes, int length) override; + + /** + * @brief Close rpc connection when no data is being transmitted. it will run in a delayed task. + * + * @since 1.0 + * @version 1.0 + */ + void CloseConnection() override; + + /** + * @brief Release resources when the device offline. + * + * @since 1.0 + * @version 1.0 + */ + void Release() override; + +private: + /** + * @brief compress json command to char array command. + * + * @param type request or response + * @param id unique message id + * @param commandName command name + * @param jsonPayload command notated by json string + * @param bytes transfer data array + * @param bytesLength transfer data length + * @return The execute result, SUCCESS: 0; FAILURE: -1. + * @see Compress + * @since 1.0 + * @version 1.0 + */ + int PrepareBytes(const std::string &type, const std::string &id, const std::string &commandName, + const std::string &jsonPayload, const unsigned char *bytes, int &bytesLength); + + /** + * @brief compress string to char array. + * + * @param json string to be compressed + * @param compressedBytes compressed data array + * @param compressedLength compressed data length + * @return The execute result, SUCCESS: 0; FAILURE: -1. + * @since 1.0 + * @version 1.0 + */ + int Compress(const std::string &json, const unsigned char *compressedBytes, int &compressedLength); + + /** + * @brief decompress char array to string. + * + * @param bytes compressed data array + * @param length compressed data length + * @return decompressed string + * @since 1.0 + * @version 1.0 + */ + std::string Decompress(const unsigned char *bytes, const int length); + + /** + * @brief transfer request data to soft bus. + * + * @param bytes data array to transfer + * @param bytesLength data length + * @return The execute result, SUCCESS: 0; FAILURE: -1. + * @since 1.0 + * @version 1.0 + */ + int SendRequestBytes(const unsigned char *bytes, const int bytesLength); + + /** + * @brief transfer response data to soft bus. + * + * @param session response session id + * @param bytes data array to transfer + * @param bytesLength data length + * @return The execute result, SUCCESS: 0; FAILURE: -1. + * @since 1.0 + * @version 1.0 + */ + int SendResponseBytes(int session, const unsigned char *bytes, const int bytesLength); + + /** + * @brief enforce session is available. if session is opened, reopen it. + * + * @return The execute result, SUCCESS: 0; FAILURE: -1. + * @since 1.0 + * @version 1.0 + */ + int CheckSessionMayReopenLocked(); + + /** + * @brief check session is available. + * + * @return The execute result, available: true, otherwise: false. + * @since 1.0 + * @version 1.0 + */ + bool IsSessionAvailable(); + + /** + * @brief cancel closing connection. + * + * @since 1.0 + * @version 1.0 + */ + void CancelCloseConnectionIfNeeded(); + + /** + * @brief request callback for HandleDataReceived + * + * @param id unique message id + * @param commandName command name + * @param jsonPayload command notated by json string + * @return decompressed string + * @see HandleDataReceived + * @since 1.0 + * @version 1.0 + */ + void HandleRequest( + int session, const std::string &id, const std::string &commandName, const std::string &jsonPayload); + + /** + * @brief response callback for HandleDataReceived + * + * @param id unique message id + * @param jsonPayload command notated by json string + * @return decompressed string + * @see HandleDataReceived + * @since 1.0 + * @version 1.0 + */ + void HandleResponse(const std::string &id, const std::string &jsonPayload); + + /** + * @brief temp function to generate uuid. + * + * @param buf uuid string + * @param bufSize uuid string size + * @since 1.0 + * @version 1.0 + */ + void random_uuid(char buf[37], int bufSize) + { + const int xbase = 15; + const int bbase = 255; + const int index6 = 6; + const int index8 = 8; + const int index3 = 3; + const int index5 = 5; + const int index7 = 7; + const int index9 = 9; + const int blen = 2; + const int uuidlen = 16; + const char *c = "89ab"; + char *p = buf; + int n; + + for (n = 0; n < uuidlen; ++n) { + int b = rand() % bbase; + switch (n) { + case index6: + if (sprintf_s(p, bufSize, "4%x", b % xbase) < 0) { + return; + } + break; + case index8: + if (sprintf_s(p, bufSize, "%c%x", c[rand() % strlen(c)], b % xbase) < 0) { + return; + } + break; + default: + if (sprintf_s(p, bufSize, "%02x", b) < 0) { + return; + } + break; + } + p += blen; + if (n == index3 || n == index5 || n == index7 || n == index9) { + *p++ = '-'; + break; + } + } + *p = 0; + // prevent array length warning + if (p - buf == bufSize) { + return; + } + n = 0; + } + + // bind device id for this channel + std::string deviceId_; + + // channel mutex + std::mutex mutex_; + + // connection closing state. true: in closing, false: otherwise + bool isDelayClosing_; + + // soft bus session mutex + std::mutex sessionMutex_; + + // soft bus session id, -1 for invalid session id. + int session_; + + // soft bus session busy flag, true: busy, false: otherwise + bool isSessionUsing_; + + // communication callbacks map. key: unique message id, value: response callback. + std::map> callbacks_; + + // callback function arguments: response string variable + std::string responseResult_; + // callback function execute variable + std::condition_variable loadedCond_; +}; + +class SoftBusMessage { +public: + SoftBusMessage( + const std::string &type, const std::string &id, const std::string &commandName, const std::string &jsonPayload) + : type_(type), id_(id), commandName_(commandName), jsonPayload_(jsonPayload) + {} + ~SoftBusMessage() = default; + + bool IsValid() const + { + if (this->type_.empty()) { + return false; + } + if (this->id_.empty()) { + return false; + } + if (this->commandName_.empty()) { + return false; + } + return !(this->jsonPayload_.empty()); + } + + /** + * Convert SoftBusMessage object to corresponding json string. + * + * @return Soft bus message json string. + */ + std::string ToJson() const + { + nlohmann::json json; + json["type"] = this->type_; + json["id"] = this->id_; + json["commandName"] = this->commandName_; + json["jsonPayload"] = this->jsonPayload_; + return json.dump(); + } + + const std::string &GetType() const + { + return type_; + } + const std::string &GetId() const + { + return id_; + } + const std::string &GetCommandName() const + { + return commandName_; + } + const std::string &GetJsonPayload() const + { + return jsonPayload_; + } + + static std::shared_ptr FromJson(const std::string &jsonString) + { + nlohmann::json json; + if (!json.accept(jsonString)) { + return nullptr; + } + json = json.parse(jsonString); + std::shared_ptr message = std::make_shared( + json.at("type"), json.at("id"), json.at("commandName"), json.at("jsonPayload")); + return message; + } + +private: + std::string type_; + std::string id_; + std::string commandName_; + std::string jsonPayload_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + +#endif // SOFT_BUS_CHANNEL_H diff --git a/services/tokensyncmanager/include/remote/soft_bus_device_connection_listener.h b/services/tokensyncmanager/include/remote/soft_bus_device_connection_listener.h new file mode 100644 index 000000000..c8722cbe1 --- /dev/null +++ b/services/tokensyncmanager/include/remote/soft_bus_device_connection_listener.h @@ -0,0 +1,76 @@ +/* + * 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 SOFT_BUS_DEVICE_CONNECTION_LISTENER_H +#define SOFT_BUS_DEVICE_CONNECTION_LISTENER_H + +#include +#include +#include + +#include "accesstoken_log.h" +#include "device_manager_callback.h" +#include "dm_device_info.h" +#include "softbus_bus_center.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +using OHOS::DistributedHardware::DeviceStateCallback; +using OHOS::DistributedHardware::DmDeviceInfo; +using OHOS::DistributedHardware::DmInitCallback; + +class MyDmInitCallback final : public DmInitCallback { + void OnRemoteDied() override + {} +}; + +class SoftBusDeviceConnectionListener final : public DeviceStateCallback { +public: + SoftBusDeviceConnectionListener(); + ~SoftBusDeviceConnectionListener(); + + /** + * @brief node online callback + * + * @param deviceInfo node info + */ + void OnDeviceOnline(const DmDeviceInfo &deviceInfo) override; + + /** + * @brief node offline callback + * + * @param deviceInfo node info + */ + void OnDeviceOffline(const DmDeviceInfo &deviceInfo) override; + + /** + * @brief node ready callback + * + * @param deviceInfo node info + */ + void OnDeviceReady(const DmDeviceInfo &deviceInfo) override; + + /** + * @brief node changed callback + * + * @param deviceInfo node info + */ + void OnDeviceChanged(const DmDeviceInfo &deviceInfo) override; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif diff --git a/services/tokensyncmanager/include/remote/soft_bus_manager.h b/services/tokensyncmanager/include/remote/soft_bus_manager.h index d7ab6e7e3..0cbfd84ea 100644 --- a/services/tokensyncmanager/include/remote/soft_bus_manager.h +++ b/services/tokensyncmanager/include/remote/soft_bus_manager.h @@ -19,13 +19,15 @@ #include #include #include -#include #include #include #include "accesstoken_log.h" -#include "rwlock.h" +#include "device_manager.h" +#include "remote_command_executor.h" #include "session.h" +#include "soft_bus_device_connection_listener.h" +#include "soft_bus_session_listener.h" namespace OHOS { namespace Security { @@ -33,23 +35,71 @@ namespace AccessToken { class SoftBusManager final { public: virtual ~SoftBusManager(); + + /** + * @brief Get instance of SoftBusManager + * + * @return SoftBusManager's instance. + * @since 1.0 + * @version 1.0 + */ static SoftBusManager &GetInstance(); + + /** + * @brief Bind soft bus service. + * + * @since 1.0 + * @version 1.0 + */ void Initialize(); + + /** + * @brief Unbind soft bus service when DPMS has been destroyed. + * + * @since 1.0 + * @version 1.0 + */ void Destroy(); - static int OnSessionOpend(int sessionId, int result); - static void OnSessionClosed(int sessionId); - static void OnBytesReceived(int sessionId, const void *data, unsigned int dataLen); - static void OnMessageReceived(int sessionId, const void *data, unsigned int dataLen); - static void isSessionRespond(int sessionId); + /** + * @brief Open session with the peer device sychronized. + * + * @param deviceUdid The udid of peer device. + * @return Session id if open successfully, otherwise return -1(Constant::FAILURE). + * @since 1.0 + * @version 1.0 + */ + int OpenSession(const std::string &deviceUdid); - void InsertSessionRespondStatus(int sessionId); - bool IsSessionRespond(int sessionId); - int32_t SendRequest(); - bool IsSessionWaitingOpen(int sessionId); - bool IsSessionOpen(int sessionId); - void ModifySessionStatus(int sessionId); - void SetSessionWaitingOpen(int sessionId); + /** + * @brief Close session with the peer device. + * + * @param session The session id need to close. + * @return 0 if close successfully, otherwise return -1(Constant::FAILURE). + * @since 1.0 + * @version 1.0 + */ + int CloseSession(int sessionId); + + /** + * @brief Get UUID(networkId) by deviceNodeId. + * + * @param deviceNodeId The valid networkId or deviceId(UDID) or deviceUuid. + * @return uuid if deviceManager is ready, empty string otherwise. + * @since 1.0 + * @version 1.0 + */ + std::string GetUniversallyUniqueIdByNodeId(const std::string &deviceNodeId); + + /** + * @brief Get deviceId(UDID) by deviceNodeId. + * + * @param deviceNodeId The valid networkId or deviceId(UDID) or deviceUuid. + * @return udid if deviceManager work correctly, empty string otherwise. + * @since 1.0 + * @version 1.0 + */ + std::string GetUniqueDisabilityIdByNodeId(const std::string &deviceNodeId); public: static const std::string SESSION_NAME; @@ -57,7 +107,18 @@ public: private: SoftBusManager(); - static const std::string ACCESS_TOKEN_PACKAGE_NAME; + /** + * @brief Fulfill local device info + * + * @return 0 if operate successfully, otherwise return -1(Constant::FAILURE). + * @since 1.0 + * @version 1.0 + */ + int FulfillLocalDeviceInfo(); + std::string GetUuidByNodeId(const std::string &nodeId) const; + std::string GetUdidByNodeId(const std::string &nodeId) const; + + const static std::string ACCESS_TOKEN_PACKAGE_NAME; // soft bus session server opened flag bool isSoftBusServiceBindSuccess_; @@ -66,8 +127,8 @@ private: // init mutex std::mutex mutex_; - OHOS::Utils::RWLock sessIdLock_; - std::set sessOpenSet_; + // fulfill thread mutex + std::mutex fulfillMutex_; }; } // namespace AccessToken } // namespace Security diff --git a/services/tokensyncmanager/include/remote/soft_bus_session_listener.h b/services/tokensyncmanager/include/remote/soft_bus_session_listener.h new file mode 100644 index 000000000..1b0a1f69a --- /dev/null +++ b/services/tokensyncmanager/include/remote/soft_bus_session_listener.h @@ -0,0 +1,114 @@ +/* + * 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 SOFT_BUS_SESSION_LISTENER_H +#define SOFT_BUS_SESSION_LISTENER_H + +#include +#include +#include + +#include "accesstoken_log.h" +#include "session.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class SoftBusSessionListener final { +public: + /** + * @brief Called when a session is opened. + * + * This function can be used to verify the session or initialize resources related to the session. + * + * @param sessionId Indicates the session ID. + * @param result 0 if the session is opened successfully, returns an error code otherwise. + * @return Returns 0 if the session connection is accepted; returns a non-zero value + * otherwise (you do not need to call {@link CloseSession} to close the session). + * @since 1.0 + * @version 1.0 + */ + static int32_t OnSessionOpened(int32_t sessionId, int32_t result); + + /** + * @brief Called when a session is closed. + * + * This function can be used to release resources related to the session. + * You do not need to call {@link CloseSession}. + * + * @param sessionId Indicates the session ID. + * @since 1.0 + * @version 1.0 + */ + static void OnSessionClosed(int32_t sessionId); + + /** + * @brief Called when data is received. + * + * This function is used to notify that data is received. + * + * @param sessionId Indicates the session ID. + * @param data Indicates the pointer to the data received. + * @param dataLen Indicates the length of the data received. + * @since 1.0 + * @version 1.0 + */ + static void OnMessageReceived(int32_t sessionId, const void *data, uint32_t dataLen); + + /** + * @brief Called when message is received. + * + * This function is used to notify that message is received. + * + * @param sessionId Indicates the session ID. + * @param data Indicates the pointer to the message data received. + * @param dataLen Indicates the length of the message received. + * @since 1.0 + * @version 1.0 + */ + static void OnBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen); + + /** + * @brief get the state of a session. + * + * This function is used to verify that session is opened. + * + * @param sessionId Indicates the session ID. + * @return -2: sessionId not used, -1: session is in opening, greater than 0: session is opened. + * @since 1.0 + * @version 1.0 + */ + static int64_t GetSessionState(int32_t sessionId); + + static void DeleteSessionIdFromMap(int32_t sessionId); + + static const int64_t STATE_OPENING = -1; + static const int64_t STATE_NOTFOUND = -2; + +private: + /** + * key: sessionId, value: status. + * status: -1: opening, >0: opened timestamp + */ + static std::map g_SessionOpenedMap_; + /** + * mutex for map + */ + static std::mutex g_SessionMutex_; +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // SOFT_BUS_SESSION_LISTENER_H diff --git a/services/tokensyncmanager/include/service/token_sync_event_handler.h b/services/tokensyncmanager/include/service/token_sync_event_handler.h new file mode 100644 index 000000000..f9a0caf36 --- /dev/null +++ b/services/tokensyncmanager/include/service/token_sync_event_handler.h @@ -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. + */ + +#ifndef TOKEN_SYNC_EVENT_HANDLER_H +#define TOKEN_SYNC_EVENT_HANDLER_H + +#include + +#include "event_handler.h" +#include "event_runner.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +class TokenSyncEventHandler : public AppExecFwk::EventHandler { +public: + TokenSyncEventHandler(const std::shared_ptr &runner); + virtual ~TokenSyncEventHandler(); + + bool ProxyPostTask(const Callback &callback, int64_t delayTime); + + bool ProxyPostTask(const Callback &callback, const std::string &name = std::string(), int64_t delayTime = 0); + + void ProxyRemoveTask(const std::string &name); + +private: +}; +} // namespace AccessToken +} // namespace Security +} // namespace OHOS +#endif // TOKEN_SYNC_EVENT_HANDLER_H diff --git a/services/tokensyncmanager/src/service/tokensync_manager_service.h b/services/tokensyncmanager/include/service/token_sync_manager_service.h similarity index 56% rename from services/tokensyncmanager/src/service/tokensync_manager_service.h rename to services/tokensyncmanager/include/service/token_sync_manager_service.h index 9af5026e9..620989974 100644 --- a/services/tokensyncmanager/src/service/tokensync_manager_service.h +++ b/services/tokensyncmanager/include/service/token_sync_manager_service.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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 @@ -13,16 +13,19 @@ * limitations under the License. */ -#ifndef TOKENSYNC_MANAGER_SERVICE_H -#define TOKENSYNC_MANAGER_SERVICE_H +#ifndef TOKEN_SYNC_MANAGER_SERVICE_H +#define TOKEN_SYNC_MANAGER_SERVICE_H #include +#include "event_handler.h" +#include "hap_token_info_for_sync_parcel.h" #include "iremote_object.h" #include "nocopyable.h" #include "singleton.h" #include "system_ability.h" -#include "tokensync_manager_stub.h" +#include "token_sync_event_handler.h" +#include "token_sync_manager_stub.h" namespace OHOS { namespace Security { @@ -36,14 +39,22 @@ public: void OnStart() override; void OnStop() override; - int VerifyPermission(const std::string& bundleName, const std::string& permissionName, int userId) override; + std::shared_ptr GetSendEventHandler(); + std::shared_ptr GetRecvEventHandler(); + int GetRemoteHapTokenInfo(const std::string& deviceID, AccessTokenID tokenID) override; + int DeleteRemoteHapTokenInfo(AccessTokenID tokenID) override; + int UpdateRemoteHapTokenInfo(const HapTokenInfoForSync& tokenInfo) override; private: - bool Initialize() const; + bool Initialize(); + std::shared_ptr sendRunner_; + std::shared_ptr recvRunner_; + std::shared_ptr sendHandler_; + std::shared_ptr recvHandler_; ServiceRunningState state_; }; } // namespace AccessToken } // namespace Security } // namespace OHOS -#endif // TOKENSYNC_MANAGER_SERVICE_H +#endif // TOKEN_SYNC_MANAGER_SERVICE_H diff --git a/services/tokensyncmanager/src/service/tokensync_manager_stub.h b/services/tokensyncmanager/include/service/token_sync_manager_stub.h similarity index 70% rename from services/tokensyncmanager/src/service/tokensync_manager_stub.h rename to services/tokensyncmanager/include/service/token_sync_manager_stub.h index a8d530d2e..f16fd8dd7 100644 --- a/services/tokensyncmanager/src/service/tokensync_manager_stub.h +++ b/services/tokensyncmanager/include/service/token_sync_manager_stub.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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 @@ -13,11 +13,10 @@ * limitations under the License. */ -#ifndef TOKENSYNC_MANAGER_STUB_H -#define TOKENSYNC_MANAGER_STUB_H - -#include "i_tokensync_manager.h" +#ifndef TOKEN_SYNC_MANAGER_STUB_H +#define TOKEN_SYNC_MANAGER_STUB_H +#include "i_token_sync_manager.h" #include "iremote_stub.h" #include "nocopyable.h" @@ -32,9 +31,11 @@ public: int OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& options) override; private: - void VerifyPermissionInner(MessageParcel& data, MessageParcel& reply); + void GetRemoteHapTokenInfoInner(MessageParcel& data, MessageParcel& reply); + void DeleteRemoteHapTokenInfoInner(MessageParcel& data, MessageParcel& reply); + void UpdateRemoteHapTokenInfoInner(MessageParcel& data, MessageParcel& reply); }; } // namespace AccessToken } // namespace Security } // namespace OHOS -#endif // TOKENSYNC_MANAGER_STUB_H +#endif // TOKEN_SYNC_MANAGER_STUB_H diff --git a/services/tokensyncmanager/src/command/base_remote_command.cpp b/services/tokensyncmanager/src/command/base_remote_command.cpp new file mode 100644 index 000000000..f582a2cb8 --- /dev/null +++ b/services/tokensyncmanager/src/command/base_remote_command.cpp @@ -0,0 +1,260 @@ +/* + * 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 "base_remote_command.h" + +#include "accesstoken_log.h" +#include "data_validator.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "BaseRemoteCommand"}; +} + +void BaseRemoteCommand::FromRemoteProtocolJson(const nlohmann::json& jsonObject) +{ + if (jsonObject.find("commandName") != jsonObject.end() && jsonObject.at("commandName").is_string()) { + remoteProtocol_.commandName = jsonObject.at("commandName").get(); + } + if (jsonObject.find("uniqueId") != jsonObject.end() && jsonObject.at("uniqueId").is_string()) { + remoteProtocol_.uniqueId = jsonObject.at("uniqueId").get(); + } + if (jsonObject.find("requestVersion") != jsonObject.end() && jsonObject.at("requestVersion").is_number()) { + remoteProtocol_.requestVersion = jsonObject.at("requestVersion").get(); + } + if (jsonObject.find("srcDeviceId") != jsonObject.end() && jsonObject.at("srcDeviceId").is_string()) { + remoteProtocol_.srcDeviceId = jsonObject.at("srcDeviceId").get(); + } + if (jsonObject.find("srcDeviceLevel") != jsonObject.end() && jsonObject.at("srcDeviceLevel").is_string()) { + remoteProtocol_.srcDeviceLevel = jsonObject.at("srcDeviceLevel").get(); + } + if (jsonObject.find("dstDeviceId") != jsonObject.end() && jsonObject.at("dstDeviceId").is_string()) { + remoteProtocol_.dstDeviceId = jsonObject.at("dstDeviceId").get(); + } + if (jsonObject.find("dstDeviceLevel") != jsonObject.end() && jsonObject.at("dstDeviceLevel").is_string()) { + remoteProtocol_.dstDeviceLevel = jsonObject.at("dstDeviceLevel").get(); + } + if (jsonObject.find("statusCode") != jsonObject.end() && jsonObject.at("statusCode").is_number()) { + remoteProtocol_.statusCode = jsonObject.at("statusCode").get(); + } + if (jsonObject.find("message") != jsonObject.end() && jsonObject.at("message").is_string()) { + remoteProtocol_.message = jsonObject.at("message").get(); + } + if (jsonObject.find("responseVersion") != jsonObject.end() && jsonObject.at("responseVersion").is_number()) { + remoteProtocol_.responseVersion = jsonObject.at("responseVersion").get(); + } + if (jsonObject.find("responseDeviceId") != jsonObject.end() && jsonObject.at("responseDeviceId").is_string()) { + remoteProtocol_.responseDeviceId = jsonObject.at("responseDeviceId").get(); + } +} + +nlohmann::json BaseRemoteCommand::ToRemoteProtocolJson() +{ + nlohmann::json j; + j["commandName"] = remoteProtocol_.commandName; + j["uniqueId"] = remoteProtocol_.uniqueId; + j["requestVersion"] = remoteProtocol_.requestVersion; + j["srcDeviceId"] = remoteProtocol_.srcDeviceId; + j["srcDeviceLevel"] = remoteProtocol_.srcDeviceLevel; + j["dstDeviceId"] = remoteProtocol_.dstDeviceId; + j["dstDeviceLevel"] = remoteProtocol_.dstDeviceLevel; + j["statusCode"] = remoteProtocol_.statusCode; + j["message"] = remoteProtocol_.message; + j["responseVersion"] = remoteProtocol_.responseVersion; + j["responseDeviceId"] = remoteProtocol_.responseDeviceId; + return j; +} + +nlohmann::json BaseRemoteCommand::ToNativeTokenInfoJson(const NativeTokenInfo& tokenInfo) +{ + nlohmann::json DcapsJson = nlohmann::json(tokenInfo.dcap); + nlohmann::json nativeTokenJson = nlohmann::json{ + {"processName", tokenInfo.processName}, + {"apl", tokenInfo.apl}, + {"version", tokenInfo.ver}, + {"tokenId", tokenInfo.tokenID}, + {"tokenAttr", tokenInfo.tokenAttr}, + {"dcaps", DcapsJson}, + }; + return nativeTokenJson; +} + +void BaseRemoteCommand::ToPermStateJson(nlohmann::json& permStateJson, const PermissionStateFull& state) +{ + if (state.resDeviceID.size() != state.grantStatus.size() || state.resDeviceID.size() != state.grantFlags.size()) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "state grant config size is invalid, %{public}d %{public}d %{public}d", + state.resDeviceID.size(), state.grantStatus.size(), state.grantFlags.size()); + return; + } + nlohmann::json permConfigsJson; + int size = state.resDeviceID.size(); + for (int i = 0; i < size; i++) { + nlohmann::json permConfigJson = nlohmann::json { + {"resDeviceID", state.resDeviceID[i]}, + {"grantStatus", state.grantStatus[i]}, + {"grantFlags", state.grantFlags[i]}, + }; + permConfigsJson.emplace_back(permConfigJson); + } + + permStateJson["permissionName"] = state.permissionName; + permStateJson["isGeneral"] = state.isGeneral; + permStateJson["grantConfig"] = permConfigsJson; +} + +nlohmann::json BaseRemoteCommand::ToHapTokenInfosJson(const HapTokenInfoForSync& tokenInfo) +{ + nlohmann::json permStatesJson; + for (auto& permState : tokenInfo.permStateList) { + nlohmann::json permStateJson; + ToPermStateJson(permStateJson, permState); + permStatesJson.emplace_back(permStateJson); + } + + nlohmann::json hapTokensJson = nlohmann::json { + {"version", tokenInfo.baseInfo.ver}, + {"tokenID", tokenInfo.baseInfo.tokenID}, + {"tokenAttr", tokenInfo.baseInfo.tokenAttr}, + {"userID", tokenInfo.baseInfo.userID}, + {"bundleName", tokenInfo.baseInfo.bundleName}, + {"instIndex", tokenInfo.baseInfo.instIndex}, + {"appID", tokenInfo.baseInfo.appID}, + {"deviceID", tokenInfo.baseInfo.deviceID}, + {"apl", tokenInfo.baseInfo.apl}, + {"permState", permStatesJson} + }; + return hapTokensJson; +} + +void BaseRemoteCommand::FromHapTokenBasicInfoJson(const nlohmann::json& hapTokenJson, + HapTokenInfo& hapTokenBasicInfo) +{ + if (hapTokenJson.find("version") != hapTokenJson.end() && hapTokenJson.at("version").is_number()) { + hapTokenJson.at("version").get_to(hapTokenBasicInfo.ver); } + if (hapTokenJson.find("tokenID") != hapTokenJson.end() && hapTokenJson.at("tokenID").is_number()) { + hapTokenJson.at("tokenID").get_to(hapTokenBasicInfo.tokenID); + } + if (hapTokenJson.find("tokenAttr") != hapTokenJson.end() && hapTokenJson.at("tokenAttr").is_number()) { + hapTokenJson.at("tokenAttr").get_to(hapTokenBasicInfo.tokenAttr); + } + if (hapTokenJson.find("userID") != hapTokenJson.end() && hapTokenJson.at("userID").is_number()) { + hapTokenJson.at("userID").get_to(hapTokenBasicInfo.userID); + } + if (hapTokenJson.find("bundleName") != hapTokenJson.end() && hapTokenJson.at("bundleName").is_string()) { + hapTokenJson.at("bundleName").get_to(hapTokenBasicInfo.bundleName); + } + if (hapTokenJson.find("instIndex") != hapTokenJson.end() && hapTokenJson.at("instIndex").is_number()) { + hapTokenJson.at("instIndex").get_to(hapTokenBasicInfo.instIndex); + } + if (hapTokenJson.find("appID") != hapTokenJson.end() && hapTokenJson.at("appID").is_string()) { + hapTokenJson.at("appID").get_to(hapTokenBasicInfo.appID); + } + if (hapTokenJson.find("deviceID") != hapTokenJson.end() && hapTokenJson.at("deviceID").is_string()) { + hapTokenJson.at("deviceID").get_to(hapTokenBasicInfo.deviceID); + } + if (hapTokenJson.find("apl") != hapTokenJson.end() && hapTokenJson.at("apl").is_number()) { + int apl = hapTokenJson.at("apl").get(); + if (DataValidator::IsAplNumValid(apl)) { + hapTokenBasicInfo.apl = (ATokenAplEnum)apl; + } + } +} + +void BaseRemoteCommand::FromPermStateListJson(const nlohmann::json& hapTokenJson, + std::vector& permStateList) +{ + if (hapTokenJson.find("permState") != hapTokenJson.end() + && hapTokenJson.at("permState").is_array() + && hapTokenJson.at("permState").size() > 0) { + nlohmann::json permissionsJson = hapTokenJson.at("permState").get(); + for (auto permissionJson : permissionsJson) { + PermissionStateFull permission; + if (permissionJson.find("permissionName") == permissionJson.end() + || !permissionJson.at("permissionName").is_string() + || permissionJson.find("isGeneral") == permissionJson.end() + || !permissionJson.at("isGeneral").is_boolean() + || permissionJson.find("grantConfig") == permissionJson.end() + || !permissionJson.at("grantConfig").is_array() + || permissionJson.at("grantConfig").size() == 0) { + continue; + } + permissionJson.at("permissionName").get_to(permission.permissionName); + permissionJson.at("isGeneral").get_to(permission.isGeneral); + nlohmann::json grantConfigsJson = permissionJson.at("grantConfig").get(); + for (auto grantConfigJson :grantConfigsJson) { + if (grantConfigJson.find("resDeviceID") == grantConfigJson.end() + || !grantConfigJson.at("resDeviceID").is_string() + || grantConfigJson.find("grantStatus") == grantConfigJson.end() + || !grantConfigJson.at("grantStatus").is_number() + || grantConfigJson.find("grantFlags") == grantConfigJson.end() + || !grantConfigJson.at("grantFlags").is_number()) { + continue; + } + std::string deviceID; + grantConfigJson.at("resDeviceID").get_to(deviceID); + int grantStatus; + grantConfigJson.at("grantStatus").get_to(grantStatus); + int grantFlags; + grantConfigJson.at("grantFlags").get_to(grantFlags); + permission.resDeviceID.emplace_back(deviceID); + permission.grantStatus.emplace_back(grantStatus); + permission.grantFlags.emplace_back(grantFlags); + } + permStateList.emplace_back(permission); + } + } +} + +void BaseRemoteCommand::FromHapTokenInfoJson(const nlohmann::json& hapTokenJson, + HapTokenInfoForSync& hapTokenInfo) +{ + FromHapTokenBasicInfoJson(hapTokenJson, hapTokenInfo.baseInfo); + if (hapTokenInfo.baseInfo.tokenID == 0) { + ACCESSTOKEN_LOG_INFO(LABEL, "Hap token basic info is error."); + return; + } + FromPermStateListJson(hapTokenJson, hapTokenInfo.permStateList); +} + +void BaseRemoteCommand::FromNativeTokenInfoJson(const nlohmann::json& nativeTokenJson, + NativeTokenInfo& nativeTokenInfo) +{ + if (nativeTokenJson.find("processName") != nativeTokenJson.end() && nativeTokenJson.at("processName").is_string()) { + nativeTokenInfo.processName = nativeTokenJson.at("processName").get(); + } + if (nativeTokenJson.find("apl") != nativeTokenJson.end() && nativeTokenJson.at("apl").is_number()) { + int apl = nativeTokenJson.at("apl").get(); + if (DataValidator::IsAplNumValid(apl)) { + nativeTokenInfo.apl = (ATokenAplEnum)apl; + } + } + if (nativeTokenJson.find("version") != nativeTokenJson.end() && nativeTokenJson.at("version").is_number()) { + nativeTokenInfo.ver = nativeTokenJson.at("version").get(); + } + if (nativeTokenJson.find("tokenId") != nativeTokenJson.end() && nativeTokenJson.at("tokenId").is_number()) { + nativeTokenInfo.tokenID = nativeTokenJson.at("tokenId").get(); + } + if (nativeTokenJson.find("tokenAttr") != nativeTokenJson.end() && nativeTokenJson.at("tokenAttr").is_number()) { + nativeTokenInfo.tokenAttr = nativeTokenJson.at("tokenAttr").get(); + } + if (nativeTokenJson.find("dcaps") != nativeTokenJson.end() && nativeTokenJson.at("dcaps").is_array() + && nativeTokenJson.at("dcaps").size() > 0 && (nativeTokenJson.at("dcaps"))[0].is_string()) { + nativeTokenInfo.dcap = nativeTokenJson.at("dcaps").get>(); + } +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/services/tokensyncmanager/src/command/delete_remote_token_command.cpp b/services/tokensyncmanager/src/command/delete_remote_token_command.cpp new file mode 100644 index 000000000..65a3c04af --- /dev/null +++ b/services/tokensyncmanager/src/command/delete_remote_token_command.cpp @@ -0,0 +1,104 @@ +/* + * 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 "delete_remote_token_command.h" + +#include "accesstoken_kit.h" +#include "accesstoken_log.h" +#include "base_remote_command.h" +#include "device_info.h" +#include "device_info_manager.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "DeleteRemoteTokenCommand"}; +} + +DeleteRemoteTokenCommand::DeleteRemoteTokenCommand( + const std::string &srcDeviceId, const std::string &dstDeviceId, AccessTokenID deleteID) + : deleteTokenId_(deleteID) +{ + remoteProtocol_.commandName = COMMAND_NAME; + remoteProtocol_.uniqueId = COMMAND_NAME; + remoteProtocol_.srcDeviceId = srcDeviceId; + remoteProtocol_.dstDeviceId = dstDeviceId; + remoteProtocol_.responseVersion = Constant::DISTRIBUTED_ACCESS_TOKEN_SERVICE_VERSION; + remoteProtocol_.requestVersion = Constant::DISTRIBUTED_ACCESS_TOKEN_SERVICE_VERSION; +} + +DeleteRemoteTokenCommand::DeleteRemoteTokenCommand(const std::string& json) +{ + nlohmann::json jsonObject = nlohmann::json::parse(json, nullptr, false); + BaseRemoteCommand::FromRemoteProtocolJson(jsonObject); + + if (jsonObject.find("tokenId") != jsonObject.end() && jsonObject.at("tokenId").is_number()) { + deleteTokenId_ = jsonObject.at("tokenId").get(); + } +} + +std::string DeleteRemoteTokenCommand::ToJsonPayload() +{ + nlohmann::json j = BaseRemoteCommand::ToRemoteProtocolJson(); + j["tokenId"] = deleteTokenId_; + return j.dump(); +} + +void DeleteRemoteTokenCommand::Prepare() +{ + remoteProtocol_.statusCode = Constant::SUCCESS; + remoteProtocol_.message = Constant::COMMAND_RESULT_SUCCESS; + ACCESSTOKEN_LOG_DEBUG(LABEL, "end as: DeleteRemoteTokenCommand"); +} + +void DeleteRemoteTokenCommand::Execute() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "execute: start as: DeleteRemoteTokenCommand"); + remoteProtocol_.responseDeviceId = Constant::GetLocalDeviceId(); + remoteProtocol_.responseVersion = Constant::DISTRIBUTED_ACCESS_TOKEN_SERVICE_VERSION; + + DeviceInfo devInfo; + bool result = DeviceInfoManager::GetInstance().GetDeviceInfo(remoteProtocol_.srcDeviceId, + DeviceIdType::UNKNOWN, devInfo); + if (!result) { + ACCESSTOKEN_LOG_INFO(LABEL, "error: get remote networkId failed"); + remoteProtocol_.statusCode = Constant::FAILURE_BUT_CAN_RETRY; + return; + } + + std::string networkID = devInfo.deviceId.networkId; + int ret = AccessTokenKit::DeleteRemoteToken(networkID, deleteTokenId_); + if (ret != RET_SUCCESS) { + remoteProtocol_.statusCode = Constant::FAILURE_BUT_CAN_RETRY; + remoteProtocol_.message = Constant::COMMAND_RESULT_FAILED; + } else { + remoteProtocol_.statusCode = Constant::SUCCESS; + remoteProtocol_.message = Constant::COMMAND_RESULT_SUCCESS; + } + + ACCESSTOKEN_LOG_INFO(LABEL, "execute: end as: DeleteRemoteTokenCommand"); +} + +void DeleteRemoteTokenCommand::Finish() +{ + remoteProtocol_.statusCode = Constant::SUCCESS; + ACCESSTOKEN_LOG_INFO(LABEL, "Finish: end as: DeleteUidPermissionCommand"); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + diff --git a/services/tokensyncmanager/src/command/sync_remote_hap_token_command.cpp b/services/tokensyncmanager/src/command/sync_remote_hap_token_command.cpp new file mode 100644 index 000000000..fde09adb0 --- /dev/null +++ b/services/tokensyncmanager/src/command/sync_remote_hap_token_command.cpp @@ -0,0 +1,109 @@ +/* + * 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 "sync_remote_hap_token_command.h" + +#include "accesstoken_kit.h" +#include "accesstoken_log.h" +#include "base_remote_command.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "SyncRemoteHapTokenCommand"}; +} + +SyncRemoteHapTokenCommand::SyncRemoteHapTokenCommand( + const std::string &srcDeviceId, const std::string &dstDeviceId, AccessTokenID id) : requestTokenId_(id) +{ + remoteProtocol_.commandName = COMMAND_NAME; + remoteProtocol_.uniqueId = COMMAND_NAME; + remoteProtocol_.srcDeviceId = srcDeviceId; + remoteProtocol_.dstDeviceId = dstDeviceId; + remoteProtocol_.responseVersion = Constant::DISTRIBUTED_ACCESS_TOKEN_SERVICE_VERSION; + remoteProtocol_.requestVersion = Constant::DISTRIBUTED_ACCESS_TOKEN_SERVICE_VERSION; + hapTokenInfo_.baseInfo.apl = APL_NORMAL; + hapTokenInfo_.baseInfo.appID = ""; + hapTokenInfo_.baseInfo.bundleName = ""; + hapTokenInfo_.baseInfo.deviceID = ""; + hapTokenInfo_.baseInfo.instIndex = 0; + hapTokenInfo_.baseInfo.tokenAttr = 0; + hapTokenInfo_.baseInfo.tokenID = 0; + hapTokenInfo_.baseInfo.userID = 0; + hapTokenInfo_.baseInfo.ver = DEFAULT_TOKEN_VERSION; +} + +SyncRemoteHapTokenCommand::SyncRemoteHapTokenCommand(const std::string &json) +{ + nlohmann::json jsonObject = nlohmann::json::parse(json, nullptr, false); + BaseRemoteCommand::FromRemoteProtocolJson(jsonObject); + if (jsonObject.find("requestTokenId") != jsonObject.end() && jsonObject.at("requestTokenId").is_number()) { + jsonObject.at("requestTokenId").get_to(requestTokenId_); + } + + if (jsonObject.find("HapTokenInfo") != jsonObject.end()) { + nlohmann::json hapTokenJson = jsonObject.at("HapTokenInfo").get(); + BaseRemoteCommand::FromHapTokenInfoJson(hapTokenJson, hapTokenInfo_); + } +} + +std::string SyncRemoteHapTokenCommand::ToJsonPayload() +{ + nlohmann::json j = BaseRemoteCommand::ToRemoteProtocolJson(); + j["requestTokenId"] = requestTokenId_; + j["HapTokenInfo"] = BaseRemoteCommand::ToHapTokenInfosJson(hapTokenInfo_); + return j.dump(); +} + +void SyncRemoteHapTokenCommand::Prepare() +{ + remoteProtocol_.statusCode = Constant::SUCCESS; + remoteProtocol_.message = Constant::COMMAND_RESULT_SUCCESS; + ACCESSTOKEN_LOG_DEBUG(LABEL, " end as: SyncRemoteHapTokenCommand"); +} + +void SyncRemoteHapTokenCommand::Execute() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "execute: start as: SyncRemoteHapTokenCommand"); + remoteProtocol_.responseDeviceId = Constant::GetLocalDeviceId(); + remoteProtocol_.responseVersion = Constant::DISTRIBUTED_ACCESS_TOKEN_SERVICE_VERSION; + + int ret = AccessTokenKit::GetHapTokenInfoFromRemote(requestTokenId_, hapTokenInfo_); + if (ret != RET_SUCCESS) { + remoteProtocol_.statusCode = Constant::FAILURE_BUT_CAN_RETRY; + remoteProtocol_.message = Constant::COMMAND_RESULT_FAILED; + } else { + remoteProtocol_.statusCode = Constant::SUCCESS; + remoteProtocol_.message = Constant::COMMAND_RESULT_SUCCESS; + } + + ACCESSTOKEN_LOG_INFO(LABEL, "execute: end as: SyncRemoteHapTokenCommand"); +} + +void SyncRemoteHapTokenCommand::Finish() +{ + if (remoteProtocol_.statusCode != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Finish: end as: SyncRemoteHapTokenCommand get remote result error."); + return; + } + AccessTokenKit::SetRemoteHapTokenInfo(remoteProtocol_.dstDeviceId, hapTokenInfo_); + remoteProtocol_.statusCode = Constant::SUCCESS; + ACCESSTOKEN_LOG_INFO(LABEL, "Finish: end as: SyncRemoteHapTokenCommand"); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/services/tokensyncmanager/src/command/sync_remote_native_token_command.cpp b/services/tokensyncmanager/src/command/sync_remote_native_token_command.cpp new file mode 100644 index 000000000..4f45e6423 --- /dev/null +++ b/services/tokensyncmanager/src/command/sync_remote_native_token_command.cpp @@ -0,0 +1,120 @@ +/* + * 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 "sync_remote_native_token_command.h" + +#include "accesstoken_kit.h" +#include "accesstoken_log.h" +#include "base_remote_command.h" +#include "device_info_manager.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "SyncRemoteNativeTokenCommand"}; +} + +SyncRemoteNativeTokenCommand::SyncRemoteNativeTokenCommand( + const std::string &srcDeviceId, const std::string &dstDeviceId) +{ + remoteProtocol_.commandName = COMMAND_NAME; + remoteProtocol_.uniqueId = COMMAND_NAME; + remoteProtocol_.srcDeviceId = srcDeviceId; + remoteProtocol_.dstDeviceId = dstDeviceId; + remoteProtocol_.responseVersion = Constant::DISTRIBUTED_ACCESS_TOKEN_SERVICE_VERSION; + remoteProtocol_.requestVersion = Constant::DISTRIBUTED_ACCESS_TOKEN_SERVICE_VERSION; +} + +SyncRemoteNativeTokenCommand::SyncRemoteNativeTokenCommand(const std::string &json) +{ + nlohmann::json jsonObject = nlohmann::json::parse(json, nullptr, false); + BaseRemoteCommand::FromRemoteProtocolJson(jsonObject); + + if (jsonObject.find("NativeTokenInfos") != jsonObject.end() && jsonObject.at("NativeTokenInfos").is_array()) { + nlohmann::json nativeTokenListJson = jsonObject.at("NativeTokenInfos"); + for (auto& tokenJson : nativeTokenListJson) { + NativeTokenInfo token; + BaseRemoteCommand::FromNativeTokenInfoJson(tokenJson, token); + nativeTokenInfo_.emplace_back(token); + } + } +} + +std::string SyncRemoteNativeTokenCommand::ToJsonPayload() +{ + nlohmann::json j = BaseRemoteCommand::ToRemoteProtocolJson(); + nlohmann::json nativeTokensJson; + for (auto token : nativeTokenInfo_) { + nlohmann::json tokenJson = BaseRemoteCommand::ToNativeTokenInfoJson(token); + nativeTokensJson.emplace_back(tokenJson); + } + j["NativeTokenInfos"] = nativeTokensJson; + return j.dump(); +} + +void SyncRemoteNativeTokenCommand::Prepare() +{ + remoteProtocol_.statusCode = Constant::SUCCESS; + remoteProtocol_.message = Constant::COMMAND_RESULT_SUCCESS; + ACCESSTOKEN_LOG_DEBUG(LABEL, "end as: SyncRemoteNativeTokenCommand"); +} + +void SyncRemoteNativeTokenCommand::Execute() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "execute: start as: SyncRemoteNativeTokenCommand"); + remoteProtocol_.responseDeviceId = Constant::GetLocalDeviceId(); + remoteProtocol_.responseVersion = Constant::DISTRIBUTED_ACCESS_TOKEN_SERVICE_VERSION; + + int ret = AccessTokenKit::GetAllNativeTokenInfo(nativeTokenInfo_); + if (ret != RET_SUCCESS) { + remoteProtocol_.statusCode = Constant::FAILURE_BUT_CAN_RETRY; + remoteProtocol_.message = Constant::COMMAND_RESULT_FAILED; + } else { + remoteProtocol_.statusCode = Constant::SUCCESS; + remoteProtocol_.message = Constant::COMMAND_RESULT_SUCCESS; + } + + ACCESSTOKEN_LOG_INFO(LABEL, "execute: end as: SyncRemoteNativeTokenCommand"); +} + +void SyncRemoteNativeTokenCommand::Finish() +{ + if (remoteProtocol_.statusCode != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Finish: end as: SyncRemoteHapTokenCommand get remote result error."); + return; + } + + DeviceInfo devInfo; + bool result = DeviceInfoManager::GetInstance().GetDeviceInfo(remoteProtocol_.dstDeviceId, + DeviceIdType::UNKNOWN, devInfo); + if (!result) { + ACCESSTOKEN_LOG_ERROR(LABEL, "SyncRemoteNativeTokenCommand: get remote networkId failed"); + remoteProtocol_.statusCode = Constant::FAILURE_BUT_CAN_RETRY; + return; + } + int ret = AccessTokenKit::SetRemoteNativeTokenInfo(devInfo.deviceId.networkId, nativeTokenInfo_); + if (ret == RET_SUCCESS) { + remoteProtocol_.statusCode = Constant::SUCCESS; + } else { + remoteProtocol_.statusCode = Constant::FAILURE_BUT_CAN_RETRY; + } + ACCESSTOKEN_LOG_INFO(LABEL, "Finish: end as: SyncRemoteNativeTokenCommand ret %{public}d", ret); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + diff --git a/services/tokensyncmanager/src/command/update_remote_hap_token_command.cpp b/services/tokensyncmanager/src/command/update_remote_hap_token_command.cpp new file mode 100644 index 000000000..6910c984c --- /dev/null +++ b/services/tokensyncmanager/src/command/update_remote_hap_token_command.cpp @@ -0,0 +1,105 @@ +/* + * 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 "update_remote_hap_token_command.h" + +#include "accesstoken_kit.h" +#include "accesstoken_log.h" +#include "base_remote_command.h" +#include "device_info_manager.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "UpdateRemoteHapTokenCommand"}; +} + +UpdateRemoteHapTokenCommand::UpdateRemoteHapTokenCommand( + const std::string &srcDeviceId, const std::string &dstDeviceId, const HapTokenInfoForSync& tokenInfo) + : updateTokenInfo_(tokenInfo) +{ + remoteProtocol_.commandName = COMMAND_NAME; + remoteProtocol_.uniqueId = COMMAND_NAME; + remoteProtocol_.srcDeviceId = srcDeviceId; + remoteProtocol_.dstDeviceId = dstDeviceId; + remoteProtocol_.responseVersion = Constant::DISTRIBUTED_ACCESS_TOKEN_SERVICE_VERSION; + remoteProtocol_.requestVersion = Constant::DISTRIBUTED_ACCESS_TOKEN_SERVICE_VERSION; +} + +UpdateRemoteHapTokenCommand::UpdateRemoteHapTokenCommand(const std::string &json) +{ + nlohmann::json jsonObject = nlohmann::json::parse(json, nullptr, false); + BaseRemoteCommand::FromRemoteProtocolJson(jsonObject); + + if (jsonObject.find("HapTokenInfos") != jsonObject.end()) { + nlohmann::json hapTokenJson = jsonObject.at("HapTokenInfos").get(); + BaseRemoteCommand::FromHapTokenInfoJson(hapTokenJson, updateTokenInfo_); + } +} + +std::string UpdateRemoteHapTokenCommand::ToJsonPayload() +{ + nlohmann::json j = BaseRemoteCommand::ToRemoteProtocolJson(); + j["HapTokenInfos"] = BaseRemoteCommand::ToHapTokenInfosJson(updateTokenInfo_); + return j.dump(); +} + +void UpdateRemoteHapTokenCommand::Prepare() +{ + remoteProtocol_.statusCode = Constant::SUCCESS; + remoteProtocol_.message = Constant::COMMAND_RESULT_SUCCESS; + ACCESSTOKEN_LOG_DEBUG(LABEL, "end as: UpdateRemoteHapTokenCommand"); +} + +void UpdateRemoteHapTokenCommand::Execute() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "execute: start as: UpdateRemoteHapTokenCommand"); + + remoteProtocol_.responseDeviceId = Constant::GetLocalDeviceId(); + remoteProtocol_.responseVersion = Constant::DISTRIBUTED_ACCESS_TOKEN_SERVICE_VERSION; + + DeviceInfo devInfo; + bool result = DeviceInfoManager::GetInstance().GetDeviceInfo(remoteProtocol_.srcDeviceId, + DeviceIdType::UNKNOWN, devInfo); + if (!result) { + ACCESSTOKEN_LOG_INFO(LABEL, "UpdateRemoteHapTokenCommand: get remote networkId failed"); + remoteProtocol_.statusCode = Constant::FAILURE_BUT_CAN_RETRY; + return; + } + + std::string networkID = devInfo.deviceId.networkId; + int ret = AccessTokenKit::SetRemoteHapTokenInfo(networkID, updateTokenInfo_); + if (ret != RET_SUCCESS) { + remoteProtocol_.statusCode = Constant::FAILURE_BUT_CAN_RETRY; + remoteProtocol_.message = Constant::COMMAND_RESULT_FAILED; + } else { + remoteProtocol_.statusCode = Constant::SUCCESS; + remoteProtocol_.message = Constant::COMMAND_RESULT_SUCCESS; + } + + ACCESSTOKEN_LOG_INFO(LABEL, "execute: end as: UpdateRemoteHapTokenCommand"); +} + +void UpdateRemoteHapTokenCommand::Finish() +{ + remoteProtocol_.statusCode = Constant::SUCCESS; + ACCESSTOKEN_LOG_INFO(LABEL, "Finish: end as: DeleteUidPermissionCommand"); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS + diff --git a/services/tokensyncmanager/src/common/constant.cpp b/services/tokensyncmanager/src/common/constant.cpp new file mode 100644 index 000000000..0221e1bbc --- /dev/null +++ b/services/tokensyncmanager/src/common/constant.cpp @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "constant.h" +#include "parameter.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { + +const std::string Constant::COMMAND_RESULT_SUCCESS = "success"; +const std::string Constant::COMMAND_RESULT_FAILED = "execute command failed"; + +std::string Constant::EncryptDevId(std::string deviceId) +{ + std::string result = deviceId; + if (deviceId.size() >= ENCRYPTLEN) { + result.replace(ENCRYPTBEGIN, ENCRYPTEND, "****"); + } else { + result.replace(ENCRYPTBEGIN, result.size() - 1, "****"); + } + return result; +} + +std::string Constant::GetLocalDeviceId() +{ + char deviceIdCharArray[Constant::DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(deviceIdCharArray, Constant::DEVICE_UUID_LENGTH); + return deviceIdCharArray; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/services/tokensyncmanager/src/device/device_info_manager.cpp b/services/tokensyncmanager/src/device/device_info_manager.cpp new file mode 100644 index 000000000..4c91c522c --- /dev/null +++ b/services/tokensyncmanager/src/device/device_info_manager.cpp @@ -0,0 +1,167 @@ +/* + * 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 "device_info_manager.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "DeviceInfoManager"}; +} +DeviceInfoManager &DeviceInfoManager::GetInstance() +{ + static DeviceInfoManager instance; + return instance; +} + +bool DeviceInfoManager::GetDeviceInfo( + const std::string &nodeId, DeviceIdType deviceIdType, DeviceInfo &deviceInfo) const +{ + return DeviceInfoRepository::GetInstance().FindDeviceInfo(nodeId, deviceIdType, deviceInfo); +} + +bool DeviceInfoManager::ExistDeviceInfo(const std::string &nodeId, DeviceIdType deviceIdType) const +{ + DeviceInfo deviceInfo; + return DeviceInfoRepository::GetInstance().FindDeviceInfo(nodeId, deviceIdType, deviceInfo); +} + +void DeviceInfoManager::AddDeviceInfo(const std::string &networkId, const std::string &universallyUniqueId, + const std::string &uniqueDisabilityId, const std::string &deviceName, const std::string &deviceType) +{ + if (!DataValidator::IsDeviceIdValid(networkId) || + !DataValidator::IsDeviceIdValid(universallyUniqueId) || + !DataValidator::IsDeviceIdValid(uniqueDisabilityId) || deviceName.empty() || deviceType.empty()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "addDeviceInfo: input param is invalid"); + } + DeviceInfoRepository::GetInstance().SaveDeviceInfo( + networkId, universallyUniqueId, uniqueDisabilityId, deviceName, deviceType); +} + +void DeviceInfoManager::RemoveAllRemoteDeviceInfo() +{ + char deviceIdCharArray[Constant::DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(deviceIdCharArray, Constant::DEVICE_UUID_LENGTH); + DeviceInfo localDeviceInfoOpt; + if (DeviceInfoRepository::GetInstance().FindDeviceInfo( + deviceIdCharArray, DeviceIdType::UNIQUE_DISABILITY_ID, localDeviceInfoOpt)) { + DeviceInfoRepository::GetInstance().DeleteAllDeviceInfoExceptOne(localDeviceInfoOpt); + } +} + +void DeviceInfoManager::RemoveRemoteDeviceInfo(const std::string &nodeId, DeviceIdType deviceIdType) +{ + if (!DataValidator::IsDeviceIdValid(nodeId)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "removeDeviceInfoByNetworkId: nodeId is invalid"); + } else { + DeviceInfo deviceInfo; + char deviceIdCharArray[Constant::DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(deviceIdCharArray, Constant::DEVICE_UUID_LENGTH); + if (DeviceInfoRepository::GetInstance().FindDeviceInfo(nodeId, deviceIdType, deviceInfo)) { + if (deviceInfo.deviceId.uniqueDisabilityId != deviceIdCharArray) { + DeviceInfoRepository::GetInstance().DeleteDeviceInfo(nodeId, deviceIdType); + } + } + } +} + +std::string DeviceInfoManager::ConvertToUniversallyUniqueIdOrFetch(const std::string &nodeId) const +{ + std::string result; + if (!DataValidator::IsDeviceIdValid(nodeId)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ConvertToUniversallyUniqueIdOrFetch: nodeId is invalid."); + return result; + } + DeviceInfo deviceInfo; + if (DeviceInfoRepository::GetInstance().FindDeviceInfo(nodeId, DeviceIdType::UNKNOWN, deviceInfo)) { + std::string universallyUniqueId = deviceInfo.deviceId.universallyUniqueId; + if (universallyUniqueId.empty()) { + std::string udid = SoftBusManager::GetInstance().GetUniversallyUniqueIdByNodeId(nodeId); + if (!udid.empty()) { + result = udid; + } + } else { + result = universallyUniqueId; + } + } + return result; +} + +std::string DeviceInfoManager::ConvertToUniqueDisabilityIdOrFetch(const std::string &nodeId) const +{ + std::string result; + if (!DataValidator::IsDeviceIdValid(nodeId)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "ConvertToUniqueDisabilityIdOrFetch: nodeId is invalid."); + return result; + } + DeviceInfo deviceInfo; + if (DeviceInfoRepository::GetInstance().FindDeviceInfo(nodeId, DeviceIdType::UNKNOWN, deviceInfo)) { + std::string uniqueDisabilityId = deviceInfo.deviceId.uniqueDisabilityId; + if (uniqueDisabilityId.empty()) { + std::string udid = SoftBusManager::GetInstance().GetUniqueDisabilityIdByNodeId(nodeId); + if (!udid.empty()) { + result = udid; + } else { + ACCESSTOKEN_LOG_DEBUG(LABEL, + "FindDeviceInfo succeed, udid and local udid is empty, nodeId(%{public}s)", + Constant::EncryptDevId(nodeId).c_str()); + } + } else { + ACCESSTOKEN_LOG_DEBUG(LABEL, + "FindDeviceInfo succeed, udid is empty, nodeId(%{public}s) ", + Constant::EncryptDevId(nodeId).c_str()); + result = uniqueDisabilityId; + } + } else { + ACCESSTOKEN_LOG_DEBUG( + LABEL, "FindDeviceInfo failed, nodeId(%{public}s)", Constant::EncryptDevId(nodeId).c_str()); + auto list = DeviceInfoRepository::GetInstance().ListDeviceInfo(); + auto iter = list.begin(); + for (; iter != list.end(); iter++) { + DeviceInfo info = (*iter); + ACCESSTOKEN_LOG_DEBUG( + LABEL, ">>> DeviceInfoRepository device name: %{public}s", info.deviceName.c_str()); + ACCESSTOKEN_LOG_DEBUG( + LABEL, ">>> DeviceInfoRepository device type: %{public}s", info.deviceType.c_str()); + ACCESSTOKEN_LOG_DEBUG(LABEL, + ">>> DeviceInfoRepository device network id: %{public}s", + Constant::EncryptDevId(info.deviceId.networkId).c_str()); + ACCESSTOKEN_LOG_DEBUG(LABEL, + ">>> DeviceInfoRepository device udid: %{public}s", + Constant::EncryptDevId(info.deviceId.uniqueDisabilityId).c_str()); + ACCESSTOKEN_LOG_DEBUG(LABEL, + ">>> DeviceInfoRepository device uuid: %{public}s", + Constant::EncryptDevId(info.deviceId.universallyUniqueId).c_str()); + } + } + return result; +} + +bool DeviceInfoManager::IsDeviceUniversallyUniqueId(const std::string &nodeId) const +{ + if (!DataValidator::IsDeviceIdValid(nodeId)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "IsDeviceUniversallyUniqueId: nodeId is invalid"); + return false; + } + DeviceInfo deviceInfo; + if (DeviceInfoRepository::GetInstance().FindDeviceInfo(nodeId, DeviceIdType::UNIVERSALLY_UNIQUE_ID, deviceInfo)) { + return deviceInfo.deviceId.universallyUniqueId == nodeId; + } + return false; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/services/tokensyncmanager/src/device/device_info_repository.cpp b/services/tokensyncmanager/src/device/device_info_repository.cpp new file mode 100644 index 000000000..6bbff99c1 --- /dev/null +++ b/services/tokensyncmanager/src/device/device_info_repository.cpp @@ -0,0 +1,191 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "device_info_repository.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +DeviceInfoRepository &DeviceInfoRepository::GetInstance() +{ + static DeviceInfoRepository instance; + return instance; +} + +std::vector DeviceInfoRepository::ListDeviceInfo() +{ + std::lock_guard guard(stackLock_); + std::vector deviceInfo; + + std::map::iterator it; + std::map::iterator itEnd; + it = deviceInfoMap_.begin(); + itEnd = deviceInfoMap_.end(); + while (it != itEnd) { + deviceInfo.push_back(it->second); + it++; + } + return deviceInfo; +} + +bool DeviceInfoRepository::FindDeviceInfo(const std::string &nodeId, DeviceIdType type, DeviceInfo &deviceInfo) +{ + std::lock_guard guard(stackLock_); + DeviceId deviceId; + if (FindDeviceIdByNodeIdLocked(nodeId, type, deviceId)) { + return FindDeviceInfoByDeviceIdLocked(deviceId, deviceInfo); + } + return false; +} + +bool DeviceInfoRepository::FindDeviceIdByNodeIdLocked( + const std::string &nodeId, const DeviceIdType type, DeviceId &deviceId) const +{ + if (type == DeviceIdType::NETWORK_ID) { + return FindDeviceIdByNetworkIdLocked(nodeId, deviceId); + } else if (type == DeviceIdType::UNIVERSALLY_UNIQUE_ID) { + return FindDeviceIdByUniversallyUniqueIdLocked(nodeId, deviceId); + } else if (type == DeviceIdType::UNIQUE_DISABILITY_ID) { + return FindDeviceIdByUniqueDisabilityIdLocked(nodeId, deviceId); + } else if (type == DeviceIdType::UNKNOWN) { + if (FindDeviceIdByNetworkIdLocked(nodeId, deviceId)) { + return true; + } else if (FindDeviceIdByUniversallyUniqueIdLocked(nodeId, deviceId)) { + return true; + } else if (FindDeviceIdByUniqueDisabilityIdLocked(nodeId, deviceId)) { + return true; + } + return false; + } else { + return false; + } +} + +bool DeviceInfoRepository::FindDeviceInfoByDeviceIdLocked(const DeviceId deviceId, DeviceInfo &deviceInfo) const +{ + std::string deviceInfoKey = deviceId.networkId + deviceId.universallyUniqueId + deviceId.uniqueDisabilityId; + if (deviceInfoMap_.count(deviceInfoKey) > 0) { + deviceInfo = deviceInfoMap_.at(deviceInfoKey); + return true; + } + return false; +} + +bool DeviceInfoRepository::FindDeviceIdByNetworkIdLocked(const std::string &networkId, DeviceId &deviceId) const +{ + if (deviceIdMapByNetworkId_.count(networkId) > 0) { + deviceId = deviceIdMapByNetworkId_.at(networkId); + return true; + } + return false; +} + +bool DeviceInfoRepository::FindDeviceIdByUniversallyUniqueIdLocked( + const std::string &universallyUniqueId, DeviceId &deviceId) const +{ + if (deviceIdMapByUniversallyUniqueId_.count(universallyUniqueId) > 0) { + deviceId = deviceIdMapByUniversallyUniqueId_.at(universallyUniqueId); + return true; + } + return false; +} + +bool DeviceInfoRepository::FindDeviceIdByUniqueDisabilityIdLocked( + const std::string &uniqueDisabilityId, DeviceId &deviceId) const +{ + if (deviceIdMapByUniqueDisabilityId_.count(uniqueDisabilityId) > 0) { + deviceId = deviceIdMapByUniqueDisabilityId_.at(uniqueDisabilityId); + return true; + } + return false; +} + +void DeviceInfoRepository::DeleteAllDeviceInfoExceptOne(const DeviceInfo deviceInfo) +{ + std::lock_guard guard(stackLock_); + deviceIdMapByNetworkId_.clear(); + deviceIdMapByUniversallyUniqueId_.clear(); + deviceIdMapByUniqueDisabilityId_.clear(); + deviceInfoMap_.clear(); + SaveDeviceInfo(deviceInfo); +} + +void DeviceInfoRepository::SaveDeviceInfo(const DeviceInfo deviceInfo) +{ + SaveDeviceInfo(deviceInfo.deviceId, deviceInfo.deviceName, deviceInfo.deviceType); +} + +void DeviceInfoRepository::SaveDeviceInfo( + const DeviceId deviceId, const std::string &deviceName, const std::string &deviceType) +{ + SaveDeviceInfo( + deviceId.networkId, deviceId.universallyUniqueId, deviceId.uniqueDisabilityId, deviceName, deviceType); +} + +void DeviceInfoRepository::SaveDeviceInfo(const std::string &networkId, const std::string &universallyUniqueId, + const std::string &uniqueDisabilityId, const std::string &deviceName, const std::string &deviceType) +{ + std::lock_guard guard(stackLock_); + + DeleteDeviceInfo(networkId, DeviceIdType::NETWORK_ID); + DeleteDeviceInfo(universallyUniqueId, DeviceIdType::UNIVERSALLY_UNIQUE_ID); + DeleteDeviceInfo(uniqueDisabilityId, DeviceIdType::UNIQUE_DISABILITY_ID); + + DeviceId deviceId; + deviceId.networkId = networkId; + deviceId.universallyUniqueId = universallyUniqueId; + deviceId.uniqueDisabilityId = uniqueDisabilityId; + + DeviceInfo deviceInfo; + deviceInfo.deviceId = deviceId; + deviceInfo.deviceName = deviceName; + deviceInfo.deviceType = deviceType; + + const std::string deviceInfoKey = networkId + universallyUniqueId + uniqueDisabilityId; + deviceIdMapByNetworkId_.insert(std::pair(networkId, deviceId)); + deviceIdMapByUniversallyUniqueId_.insert(std::pair(universallyUniqueId, deviceId)); + deviceIdMapByUniqueDisabilityId_.insert(std::pair(uniqueDisabilityId, deviceId)); + deviceInfoMap_.insert(std::pair(deviceInfoKey, deviceInfo)); +} + +void DeviceInfoRepository::DeleteDeviceInfo(const std::string &nodeId, const DeviceIdType type) +{ + std::lock_guard guard(stackLock_); + DeviceId deviceId; + if (FindDeviceIdByNodeIdLocked(nodeId, type, deviceId)) { + DeleteDeviceInfoByDeviceIdLocked(deviceId); + } +} + +void DeviceInfoRepository::DeleteDeviceInfoByDeviceIdLocked(const DeviceId deviceId) +{ + deviceIdMapByNetworkId_.erase(deviceId.networkId); + deviceIdMapByUniversallyUniqueId_.erase(deviceId.universallyUniqueId); + deviceIdMapByUniqueDisabilityId_.erase(deviceId.uniqueDisabilityId); + const std::string deviceInfoKey = deviceId.networkId + deviceId.universallyUniqueId + deviceId.uniqueDisabilityId; + deviceInfoMap_.erase(deviceInfoKey); +} + +void DeviceInfoRepository::Clear() +{ + std::lock_guard guard(stackLock_); + deviceIdMapByNetworkId_.clear(); + deviceIdMapByUniversallyUniqueId_.clear(); + deviceIdMapByUniqueDisabilityId_.clear(); + deviceInfoMap_.clear(); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/services/tokensyncmanager/src/remote/remote_command_executor.cpp b/services/tokensyncmanager/src/remote/remote_command_executor.cpp new file mode 100644 index 000000000..acab82f7a --- /dev/null +++ b/services/tokensyncmanager/src/remote/remote_command_executor.cpp @@ -0,0 +1,328 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "remote_command_executor.h" + +#include "device_info_manager.h" +#include "parameter.h" +#include "singleton.h" +#include "soft_bus_channel.h" +#include "token_sync_event_handler.h" +#include "token_sync_manager_service.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "RemoteCommandExecutor"}; +static const std::string TASK_NAME = "RemoteCommandExecutor::ProcessBufferedCommandsWithThread"; +} // namespace +RemoteCommandExecutor::RemoteCommandExecutor(const std::string &targetNodeId) + : targetNodeId_(targetNodeId), ptrChannel_(nullptr), mutex_(), commands_(), running_(false) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "RemoteCommandExecutor()"); +} + +RemoteCommandExecutor::~RemoteCommandExecutor() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "~RemoteCommandExecutor() begin"); + running_ = false; + ACCESSTOKEN_LOG_DEBUG(LABEL, "~RemoteCommandExecutor() end"); +} + +const std::shared_ptr RemoteCommandExecutor::CreateChannel(const std::string &targetNodeId) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "CreateChannel: targetNodeId=%{public}s", targetNodeId.c_str()); + // only consider SoftBusChannel + std::shared_ptr ptrChannel = std::make_shared(targetNodeId); + if (ptrChannel == nullptr) { + ACCESSTOKEN_LOG_INFO( + LABEL, "CreateChannel: create channel failed, targetNodeId=%{public}s", targetNodeId.c_str()); + } + return ptrChannel; +} + +/* + * called by RemoteCommandExecutor, RemoteCommandManager + */ +int RemoteCommandExecutor::ProcessOneCommand(const std::shared_ptr &ptrCommand) +{ + if (ptrCommand == nullptr) { + ACCESSTOKEN_LOG_WARN( + LABEL, "targetNodeId %{public}s, attempt to process on null command.", targetNodeId_.c_str()); + return Constant::SUCCESS; + } + const std::string uniqueId = ptrCommand->remoteProtocol_.uniqueId; + ACCESSTOKEN_LOG_INFO(LABEL, + "targetNodeId %{public}s, process one command start, uniqueId: %{public}s", + targetNodeId_.c_str(), + uniqueId.c_str()); + + ptrCommand->Prepare(); + int status = ptrCommand->remoteProtocol_.statusCode; + if (status != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, + "targetNodeId %{public}s, process one command error, uniqueId: %{public}s, message: " + "prepare failure code %{public}d", + targetNodeId_.c_str(), + uniqueId.c_str(), + status); + return status; + } + + char localUdid[Constant::DEVICE_UUID_LENGTH] = {0}; + ::GetDevUdid(localUdid, Constant::DEVICE_UUID_LENGTH); + if (targetNodeId_ == localUdid) { + return ExecuteRemoteCommand(ptrCommand, false); + } + + // otherwise a remote device + CreateChannelIfNeeded(); + if (ptrChannel_ == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "targetNodeId %{public}s, channel is null.", targetNodeId_.c_str()); + return Constant::FAILURE; + } + if (ptrChannel_->BuildConnection() != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "targetNodeId %{public}s, channel is not ready.", targetNodeId_.c_str()); + return Constant::FAILURE; + } + + return ExecuteRemoteCommand(ptrCommand, true); +} + +/* + * called by RemoteCommandManager + */ +int RemoteCommandExecutor::AddCommand(const std::shared_ptr &ptrCommand) +{ + if (ptrCommand == nullptr) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "targetNodeId %{public}s, attempt to add an empty command.", targetNodeId_.c_str()); + return Constant::INVALID_COMMAND; + } + + const std::string uniqueId = ptrCommand->remoteProtocol_.uniqueId; + ACCESSTOKEN_LOG_DEBUG( + LABEL, "targetNodeId %{public}s, add uniqueId %{public}s", targetNodeId_.c_str(), uniqueId.c_str()); + + std::unique_lock lock(mutex_); + + // make sure do not have the same command in the command buffer + for (auto bufferedCommand : commands_) { + if (bufferedCommand->remoteProtocol_.uniqueId == uniqueId) { + ACCESSTOKEN_LOG_WARN(LABEL, + "targetNodeId %{public}s, add uniqueId %{public}s, already exist in the buffer, skip", + targetNodeId_.c_str(), + uniqueId.c_str()); + return Constant::SUCCESS; + } + } + + commands_.push_back(ptrCommand); + return Constant::SUCCESS; +} + +/* + * called by RemoteCommandExecutor.ProcessCommandThread, RemoteCommandManager + */ +int RemoteCommandExecutor::ProcessBufferedCommands(bool standalone) +{ + ACCESSTOKEN_LOG_INFO( + LABEL, "begin, targetNodeId: %{public}s, standalone: %{public}d", targetNodeId_.c_str(), standalone); + + std::unique_lock lock(mutex_); + + if (commands_.empty()) { + ACCESSTOKEN_LOG_WARN(LABEL, "no command, targetNodeId %{public}s", targetNodeId_.c_str()); + running_ = false; + return Constant::SUCCESS; + } + + running_ = true; + while (true) { + // interrupt + if (running_ == false) { + ACCESSTOKEN_LOG_INFO( + LABEL, "end with running flag == false, targetNodeId: %{public}s", targetNodeId_.c_str()); + return Constant::FAILURE; + } + // end + if (commands_.empty()) { + running_ = false; + ACCESSTOKEN_LOG_INFO(LABEL, "end, no command left, targetNodeId: %{public}s", targetNodeId_.c_str()); + return Constant::SUCCESS; + } + + // consume queue to execute + const std::shared_ptr bufferedCommand = commands_.front(); + int status = ProcessOneCommand(bufferedCommand); + if (status == Constant::SUCCESS) { + commands_.pop_front(); + continue; + } else if (status == Constant::FAILURE_BUT_CAN_RETRY) { + ACCESSTOKEN_LOG_WARN(LABEL, + "execute failed and wait to retry, targetNodeId: %{public}s, message: %{public}s, and will retry ", + targetNodeId_.c_str(), + bufferedCommand->remoteProtocol_.message.c_str()); + + // now, the retry at once will have no effective because the network problem + // so if the before the step, one command is added, and run this function + // it should also not need to restart to process the commands buffer at once. + running_ = false; + return Constant::FAILURE; + } else { + // this command failed, move on to execute next command + commands_.pop_front(); + ACCESSTOKEN_LOG_ERROR(LABEL, + "execute failed, targetNodeId: %{public}s, commandName: %{public}s, message: %{public}s", + targetNodeId_.c_str(), + bufferedCommand->remoteProtocol_.commandName.c_str(), + bufferedCommand->remoteProtocol_.message.c_str()); + } + } +} + +/* + * called by RemoteCommandManager + */ +void RemoteCommandExecutor::ProcessBufferedCommandsWithThread() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "begin, targetNodeId: %{public}s", targetNodeId_.c_str()); + + std::unique_lock lock(mutex_); + + if (commands_.empty()) { + ACCESSTOKEN_LOG_INFO(LABEL, "No buffered commands. targetNodeId: %{public}s", targetNodeId_.c_str()); + return; + } + if (running_) { + // task is running, do not need to start one more + ACCESSTOKEN_LOG_WARN(LABEL, "task busy. targetNodeId: %{public}s", targetNodeId_.c_str()); + return; + } + + running_ = true; + const std::function runner = std::bind(&RemoteCommandExecutor::ProcessBufferedCommands, this, true); + + std::shared_ptr handler = + DelayedSingleton::GetInstance()->GetSendEventHandler(); + if (handler == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "fail to get EventHandler"); + return; + } + bool result = handler->ProxyPostTask(runner, TASK_NAME); + if (result == false) { + ACCESSTOKEN_LOG_ERROR(LABEL, "post task failed, targetNodeId: %{public}s", targetNodeId_.c_str()); + } + ACCESSTOKEN_LOG_INFO(LABEL, + "post task succeed, targetNodeId: %{public}s, taskName: %{public}s", + targetNodeId_.c_str(), + TASK_NAME.c_str()); +} + +int RemoteCommandExecutor::ExecuteRemoteCommand( + const std::shared_ptr &ptrCommand, const bool isRemote) +{ + std::string uniqueId = ptrCommand->remoteProtocol_.uniqueId; + ACCESSTOKEN_LOG_INFO(LABEL, + "targetNodeId %{public}s, uniqueId %{public}s, remote %{public}d: start to execute", + targetNodeId_.c_str(), + uniqueId.c_str(), + isRemote); + + ptrCommand->remoteProtocol_.statusCode = Constant::STATUS_CODE_BEFORE_RPC; + + if (!isRemote) { + // Local device, play myself. + ptrCommand->Execute(); + int code = ClientProcessResult(ptrCommand); + ACCESSTOKEN_LOG_DEBUG(LABEL, + "command finished with status: %{public}d, message: %{public}s", + ptrCommand->remoteProtocol_.statusCode, + ptrCommand->remoteProtocol_.message.c_str()); + return code; + } + + std::string responseString = + ptrChannel_->ExecuteCommand(ptrCommand->remoteProtocol_.commandName, ptrCommand->ToJsonPayload()); + ACCESSTOKEN_LOG_INFO(LABEL, "command executed uniqueId %{public}s", uniqueId.c_str()); + if (responseString.empty()) { + ACCESSTOKEN_LOG_WARN(LABEL, + "targetNodeId %{public}s, uniqueId %{public}s, execute remote command error, response is empty.", + targetNodeId_.c_str(), + uniqueId.c_str()); + return Constant::FAILURE; + } + + std::shared_ptr ptrResponseCommand = + RemoteCommandFactory::GetInstance().NewRemoteCommandFromJson( + ptrCommand->remoteProtocol_.commandName, responseString); + if (ptrResponseCommand == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "targetNodeId %{public}s, get null response command!", targetNodeId_.c_str()); + return Constant::FAILURE; + } + int32_t result = ClientProcessResult(ptrResponseCommand); + if (commands_.empty()) { + ptrChannel_->CloseConnection(); + } + ACCESSTOKEN_LOG_DEBUG(LABEL, + "command finished with status: %{public}d, message: %{public}s", + ptrResponseCommand->remoteProtocol_.statusCode, + ptrResponseCommand->remoteProtocol_.message.c_str()); + return result; +} + +void RemoteCommandExecutor::CreateChannelIfNeeded() +{ + std::unique_lock lock(mutex_); + if (ptrChannel_ != nullptr) { + ACCESSTOKEN_LOG_INFO(LABEL, "targetNodeId %{public}s, channel is exist.", targetNodeId_.c_str()); + return; + } + + ptrChannel_ = CreateChannel(targetNodeId_); +} + +int RemoteCommandExecutor::ClientProcessResult(const std::shared_ptr &ptrCommand) +{ + std::string uniqueId = ptrCommand->remoteProtocol_.uniqueId; + if (ptrCommand->remoteProtocol_.statusCode == Constant::STATUS_CODE_BEFORE_RPC) { + ACCESSTOKEN_LOG_ERROR(LABEL, + "targetNodeId %{public}s, uniqueId %{public}s, status code after RPC is same as before, the remote side " + "may not " + "support this command", + targetNodeId_.c_str(), + uniqueId.c_str()); + return Constant::FAILURE; + } + + ptrCommand->Finish(); + int status = ptrCommand->remoteProtocol_.statusCode; + if (status != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, + "targetNodeId %{public}s, uniqueId %{public}s, execute failed, message: %{public}s", + targetNodeId_.c_str(), + uniqueId.c_str(), + ptrCommand->remoteProtocol_.message.c_str()); + } else { + ACCESSTOKEN_LOG_INFO(LABEL, + "targetNodeId %{public}s, uniqueId %{public}s, execute succeed.", + targetNodeId_.c_str(), + uniqueId.c_str()); + } + return status; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/services/tokensyncmanager/src/remote/remote_command_factory.cpp b/services/tokensyncmanager/src/remote/remote_command_factory.cpp new file mode 100644 index 000000000..48ab1107a --- /dev/null +++ b/services/tokensyncmanager/src/remote/remote_command_factory.cpp @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include "nlohmann/json.hpp" +#include "remote_command_factory.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +RemoteCommandFactory &RemoteCommandFactory::GetInstance() +{ + static RemoteCommandFactory instance; + return instance; +} + +std::shared_ptr RemoteCommandFactory::NewSyncRemoteHapTokenCommand( + const std::string &srcDeviceId, const std::string &dstDeviceId, AccessTokenID tokenID) +{ + return std::make_shared(srcDeviceId, dstDeviceId, tokenID); +} + +std::shared_ptr RemoteCommandFactory::NewDeleteRemoteTokenCommand( + const std::string &srcDeviceId, const std::string &dstDeviceId, AccessTokenID tokenID) +{ + return std::make_shared(srcDeviceId, dstDeviceId, tokenID); +} + +std::shared_ptr RemoteCommandFactory::NewUpdateRemoteHapTokenCommand( + const std::string &srcDeviceId, const std::string &dstDeviceId, const HapTokenInfoForSync& tokenInfo) +{ + return std::make_shared(srcDeviceId, dstDeviceId, tokenInfo); +} + +std::shared_ptr RemoteCommandFactory::NewSyncRemoteNativeTokenCommand( + const std::string &srcDeviceId, const std::string &dstDeviceId) +{ + return std::make_shared(srcDeviceId, dstDeviceId); +} + +std::shared_ptr RemoteCommandFactory::NewRemoteCommandFromJson( + const std::string &commandName, const std::string &commandJsonString) +{ + const std::string SYNC_HAP_COMMAND_NAME = "SyncRemoteHapTokenCommand"; + const std::string DELETE_TOKEN_COMMAND_NAME = "DeleteRemoteTokenCommand"; + const std::string UPDATE_HAP_COMMAND_NAME = "UpdateRemoteHapTokenCommand"; + const std::string SYNC_NATIVE_COMMAND_NAME = "SyncRemoteNativeTokenCommand"; + + if (commandName == SYNC_HAP_COMMAND_NAME) { + return std::make_shared(commandJsonString); + } else if (commandName == DELETE_TOKEN_COMMAND_NAME) { + return std::make_shared(commandJsonString); + } else if (commandName == UPDATE_HAP_COMMAND_NAME) { + return std::make_shared(commandJsonString); + } else if (commandName == SYNC_NATIVE_COMMAND_NAME) { + return std::make_shared(commandJsonString); + } else { + return nullptr; + } +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/services/tokensyncmanager/src/remote/remote_command_manager.cpp b/services/tokensyncmanager/src/remote/remote_command_manager.cpp new file mode 100644 index 000000000..9d98fada7 --- /dev/null +++ b/services/tokensyncmanager/src/remote/remote_command_manager.cpp @@ -0,0 +1,292 @@ +/* + * 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 "remote_command_manager.h" +#include "device_info_manager.h" +#include "sync_remote_native_token_command.h" +#include "remote_command_factory.h" +#include "token_sync_event_handler.h" +#include "token_sync_manager_service.h" +#include "accesstoken_kit.h" + +#include + + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "RemoteCommandManager"}; +} +RemoteCommandManager::RemoteCommandManager() : executors_(), mutex_() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "RemoteCommandManager()"); +} + +RemoteCommandManager::~RemoteCommandManager() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "~RemoteCommandManager()"); +} + +RemoteCommandManager &RemoteCommandManager::GetInstance() +{ + static RemoteCommandManager instance; + return instance; +} + +void RemoteCommandManager::Init() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "Init()"); +} + +int RemoteCommandManager::AddCommand(const std::string &udid, const std::shared_ptr &command) +{ + if (udid.empty() || command == nullptr) { + ACCESSTOKEN_LOG_WARN(LABEL, "invalid udid: %{public}s, or null command", udid.c_str()); + return Constant::FAILURE; + } + std::string uniqueId = command->remoteProtocol_.uniqueId; + ACCESSTOKEN_LOG_INFO(LABEL, "udid: %{public}s, add uniqueId: %{public}s", udid.c_str(), uniqueId.c_str()); + + std::shared_ptr executor = GetOrCreateRemoteCommandExecutor(udid); + if (executor == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "cannot get or create remote command executor"); + return Constant::FAILURE; + } + + int result = executor->AddCommand(command); + ACCESSTOKEN_LOG_INFO(LABEL, "udid: %{public}s, add command result: %{public}d ", udid.c_str(), result); + return result; +} + +void RemoteCommandManager::RemoveCommand(const std::string &udid) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "remove command, udid: %{public}s", udid.c_str()); + executors_.erase(udid); +} + +int RemoteCommandManager::ExecuteCommand(const std::string &udid, const std::shared_ptr &command) +{ + if (udid.empty() || command == nullptr) { + ACCESSTOKEN_LOG_WARN(LABEL, "invalid udid: %{public}s, or null command", udid.c_str()); + return Constant::FAILURE; + } + std::string uniqueId = command->remoteProtocol_.uniqueId; + ACCESSTOKEN_LOG_INFO(LABEL, "start with udid: %{public}s , uniqueId: %{public}s ", udid.c_str(), uniqueId.c_str()); + + std::shared_ptr executor = GetOrCreateRemoteCommandExecutor(udid); + if (executor == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "cannot get or create remote command executor"); + return Constant::FAILURE; + } + + int result = executor->ProcessOneCommand(command); + ACCESSTOKEN_LOG_INFO(LABEL, "remoteCommandExecutor processOneCommand result:%{public}d ", result); + return result; +} + +int RemoteCommandManager::ProcessDeviceCommandImmediately(const std::string &udid) +{ + if (udid.empty()) { + ACCESSTOKEN_LOG_WARN(LABEL, "invalid udid: %{public}s", udid.c_str()); + return Constant::FAILURE; + } + ACCESSTOKEN_LOG_INFO(LABEL, "start with udid:%{public}s ", udid.c_str()); + auto executorIt = executors_.find(udid); + if (executorIt == executors_.end()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "no executor found, udid:%{public}s", udid.c_str()); + return Constant::FAILURE; + } + + auto executor = executorIt->second; + if (executor == nullptr) { + ACCESSTOKEN_LOG_INFO(LABEL, "RemoteCommandExecutor is null for udid %{public}s ", udid.c_str()); + return Constant::FAILURE; + } + + int result = executor->ProcessBufferedCommands(); + ACCESSTOKEN_LOG_INFO(LABEL, "processBufferedCommands result: %{public}d", result); + return result; +} + +int RemoteCommandManager::Loop() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "start"); + for (auto it = executors_.begin(); it != executors_.end(); it++) { + ACCESSTOKEN_LOG_INFO(LABEL, "udid:%{public}s", it->first.c_str()); + (*it).second->ProcessBufferedCommandsWithThread(); + } + return Constant::SUCCESS; +} + +/** + * caller: service connection listener + */ +void RemoteCommandManager::Clear() +{ + ACCESSTOKEN_LOG_INFO(LABEL, "remove all remote command executors."); + + std::map> dummy; + executors_.swap(dummy); + executors_.clear(); +} + +/** + * caller: device listener + */ +int RemoteCommandManager::NotifyDeviceOnline(const std::string &nodeId) +{ + if (!DataValidator::IsDeviceIdValid(nodeId)) { + ACCESSTOKEN_LOG_INFO(LABEL, "invalid nodeId: %{public}s", nodeId.c_str()); + return Constant::FAILURE; + } + ACCESSTOKEN_LOG_INFO(LABEL, "operation start with nodeId: %{public}s", nodeId.c_str()); + + auto executor = GetOrCreateRemoteCommandExecutor(nodeId); + std::unique_lock lock(mutex_); + if (executor == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "cannot get or create remote command executor"); + return Constant::FAILURE; + } + + if (executor->GetChannel() == nullptr) { + auto channel = RemoteCommandExecutor::CreateChannel(nodeId); + if (channel == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "create channel failed."); + return Constant::FAILURE; + } + executor->SetChannel(channel); + } + + lock.unlock(); + + std::function delayed = ([=]() { + const std::shared_ptr syncRemoteNativeTokenCommand = + RemoteCommandFactory::GetInstance().NewSyncRemoteNativeTokenCommand(Constant::GetLocalDeviceId(), + nodeId); + + const int32_t resultCode = RemoteCommandManager::GetInstance().ExecuteCommand( + nodeId, syncRemoteNativeTokenCommand); + if (resultCode != Constant::SUCCESS) { + ACCESSTOKEN_LOG_INFO(LABEL, + "%{public}s: RemoteExecutorManager executeCommand syncRemoteNativeTokenCommand failed, return %d", + __func__, resultCode); + return; + } + }); + + std::shared_ptr handler = + DelayedSingleton::GetInstance()->GetSendEventHandler(); + if (handler == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "fail to get EventHandler"); + return Constant::FAILURE; + } + handler->ProxyPostTask(delayed, "HandleDeviceOnline", Constant::DELAY_SYNC_TOKEN_MS); + + return Constant::SUCCESS; +} + +/** + * caller: device listener + */ +int RemoteCommandManager::NotifyDeviceOffline(const std::string &nodeId) +{ + if (!DataValidator::IsDeviceIdValid(nodeId)) { + ACCESSTOKEN_LOG_INFO(LABEL, "invalid nodeId: %{public}s", nodeId.c_str()); + return Constant::FAILURE; + } + ACCESSTOKEN_LOG_INFO(LABEL, "operation start with nodeId: %{public}s", nodeId.c_str()); + + auto channel = GetExecutorChannel(nodeId); + if (channel != nullptr) { + channel->Release(); + } + + std::unique_lock lock(mutex_); + RemoveCommand(nodeId); + lock.unlock(); + + DeviceInfo devInfo; + bool result = DeviceInfoManager::GetInstance().GetDeviceInfo(nodeId, DeviceIdType::UNKNOWN, devInfo); + if (!result) { + ACCESSTOKEN_LOG_INFO(LABEL, "get remote networkId failed"); + return Constant::FAILURE; + } + std::string networkId = devInfo.deviceId.networkId; + std::function delayed = ([=]() { + AccessTokenKit::DeleteRemoteDeviceTokens(networkId); + }); + + std::shared_ptr handler = + DelayedSingleton::GetInstance()->GetSendEventHandler(); + if (handler == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "fail to get EventHandler"); + return Constant::FAILURE; + } + handler->ProxyPostTask(delayed, "HandleDeviceOffline"); + + ACCESSTOKEN_LOG_INFO(LABEL, "complete"); + return Constant::SUCCESS; +} + +std::shared_ptr RemoteCommandManager::GetOrCreateRemoteCommandExecutor(const std::string &nodeId) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "begin, nodeId %{public}s", nodeId.c_str()); + + std::unique_lock lock(mutex_); + auto executorIter = executors_.find(nodeId); + if (executorIter != executors_.end()) { + return executorIter->second; + } + + auto executor = std::make_shared(nodeId); + if (executor == nullptr) { + ACCESSTOKEN_LOG_INFO(LABEL, "cannot create remote command executor, nodeId: %{public}s", nodeId.c_str()); + return nullptr; + } + + executors_.insert(std::pair>(nodeId, executor)); + ACCESSTOKEN_LOG_DEBUG(LABEL, "executor added, nodeId: %{public}s", nodeId.c_str()); + return executor; +} + +/** + * caller: session listener(onBytesReceived), device listener(offline) + */ +std::shared_ptr RemoteCommandManager::GetExecutorChannel(const std::string &nodeId) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "convert udid start, nodeId:%{public}s", nodeId.c_str()); + std::string udid = DeviceInfoManager::GetInstance().ConvertToUniqueDisabilityIdOrFetch(nodeId); + ACCESSTOKEN_LOG_DEBUG(LABEL, "convert udid, nodeId:%{public}s, udid: %{public}s", nodeId.c_str(), udid.c_str()); + if (!DataValidator::IsDeviceIdValid(udid)) { + ACCESSTOKEN_LOG_WARN( + LABEL, "converted udid is invalid, nodeId:%{public}s, udid: %{public}s", nodeId.c_str(), udid.c_str()); + return nullptr; + } + std::map>::iterator iter = executors_.find(udid); + if (iter == executors_.end()) { + ACCESSTOKEN_LOG_INFO(LABEL, "executor not found"); + return nullptr; + } + std::shared_ptr executor = iter->second; + if (executor == nullptr) { + ACCESSTOKEN_LOG_INFO(LABEL, "executor is null"); + return nullptr; + } + return executor->GetChannel(); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/services/tokensyncmanager/src/remote/soft_bus_channel.cpp b/services/tokensyncmanager/src/remote/soft_bus_channel.cpp new file mode 100644 index 000000000..97e028db7 --- /dev/null +++ b/services/tokensyncmanager/src/remote/soft_bus_channel.cpp @@ -0,0 +1,416 @@ +/* + * 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 "soft_bus_channel.h" + +#include + +#include "device_info_manager.h" +#include "token_sync_event_handler.h" +#include "token_sync_manager_service.h" +#include "singleton.h" +#include "soft_bus_manager.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "SoftBusChannel"}; +} +namespace { +static const std::string REQUEST_TYPE = "request"; +static const std::string RESPONSE_TYPE = "response"; +static const std::string TASK_NAME_CLOSE_SESSION = "atm_soft_bus_channel_close_session"; +static const long EXECUTE_COMMAND_TIME_OUT = 3000; +static const long WAIT_SESSION_CLOSE_MILLISECONDS = 5 * 1000; +// send buf size for header +static const int RPC_TRANSFER_HEAD_BYTES_LENGTH = 1024 * 256; +// decompress buf size +static const int RPC_TRANSFER_BYTES_MAX_LENGTH = 1024 * 1024; +} // namespace +SoftBusChannel::SoftBusChannel(const std::string &deviceId) + : deviceId_(deviceId), mutex_(), callbacks_(), responseResult_(""), loadedCond_() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "SoftBusChannel(deviceId)"); + isDelayClosing_ = false; + session_ = Constant::INVALID_SESSION; + isSessionUsing_ = false; +} + +SoftBusChannel::~SoftBusChannel() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "~SoftBusChannel()"); +} + +int SoftBusChannel::BuildConnection() +{ + CancelCloseConnectionIfNeeded(); + if (session_ != Constant::INVALID_SESSION) { + ACCESSTOKEN_LOG_INFO(LABEL, "session is exist, no need open again."); + return Constant::SUCCESS; + } + + std::unique_lock lock(sessionMutex_); + if (session_ == Constant::INVALID_SESSION) { + ACCESSTOKEN_LOG_INFO(LABEL, "open session with device: %{public}s", (deviceId_.c_str())); + int session = SoftBusManager::GetInstance().OpenSession(deviceId_); + if (session == Constant::INVALID_SESSION) { + ACCESSTOKEN_LOG_ERROR(LABEL, "open session failed."); + return Constant::FAILURE; + } + session_ = session; + } + return Constant::SUCCESS; +} + +void SoftBusChannel::CloseConnection() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "close connection"); + std::unique_lock lock(mutex_); + if (isDelayClosing_) { + return; + } + + std::shared_ptr handler = + DelayedSingleton::GetInstance()->GetSendEventHandler(); + if (handler == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "fail to get EventHandler"); + return; + } + auto thisPtr = shared_from_this(); + std::function delayed = ([thisPtr]() { + std::unique_lock lock(thisPtr->sessionMutex_); + if (thisPtr->isSessionUsing_) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "session is in using, cancel close session"); + } else { + SoftBusManager::GetInstance().CloseSession(thisPtr->session_); + thisPtr->session_ = Constant::INVALID_SESSION; + ACCESSTOKEN_LOG_INFO(LABEL, "close session for device: %{public}s", thisPtr->deviceId_.c_str()); + } + thisPtr->isDelayClosing_ = false; + }); + + ACCESSTOKEN_LOG_DEBUG(LABEL, "close session after %{public}ld ms", WAIT_SESSION_CLOSE_MILLISECONDS); + handler->ProxyPostTask(delayed, TASK_NAME_CLOSE_SESSION, WAIT_SESSION_CLOSE_MILLISECONDS); + + isDelayClosing_ = true; +} + +void SoftBusChannel::Release() +{ + std::shared_ptr handler = + DelayedSingleton::GetInstance()->GetSendEventHandler(); + if (handler == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "fail to get EventHandler"); + return; + } + handler->ProxyRemoveTask(TASK_NAME_CLOSE_SESSION); +} + +std::string SoftBusChannel::ExecuteCommand(const std::string &commandName, const std::string &jsonPayload) +{ + if (commandName.empty() || jsonPayload.empty()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params, commandName: %{public}s, jsonPayload: %{public}s", + commandName.c_str(), jsonPayload.c_str()); + return ""; + } + + // to use a lib like libuuid + int uuidStrLen = 37; // 32+4+1 + char uuidbuf[uuidStrLen]; + random_uuid(uuidbuf, uuidStrLen); + std::string uuid(uuidbuf); + ACCESSTOKEN_LOG_DEBUG(LABEL, "generated message uuid: %{public}s", uuid.c_str()); + + int len = RPC_TRANSFER_HEAD_BYTES_LENGTH + jsonPayload.length(); + unsigned char *buf = (unsigned char *) malloc(len + 1); + if (buf == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "no enough memory: %{public}d", len); + return ""; + } + memset_s(buf, len + 1, 0, len + 1); + int result = PrepareBytes(REQUEST_TYPE, uuid, commandName, jsonPayload, buf, len); + if (result != Constant::SUCCESS) { + free(buf); + return ""; + } + + std::unique_lock lock(sessionMutex_); + std::function callback = [&](const std::string &result) { + ACCESSTOKEN_LOG_INFO(LABEL, "onResponse called, data: %{public}s", result.c_str()); + responseResult_ = std::string(result); + loadedCond_.notify_all(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "onResponse called end"); + }; + callbacks_.insert(std::pair>(uuid, callback)); + + isSessionUsing_ = true; + lock.unlock(); + + int retCode = SendRequestBytes(buf, len); + free(buf); + + std::unique_lock lock2(sessionMutex_); + if (retCode != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "send request data failed: %{public}d ", retCode); + callbacks_.erase(uuid); + isSessionUsing_ = false; + return ""; + } + + ACCESSTOKEN_LOG_DEBUG(LABEL, "wait command response"); + if (loadedCond_.wait_for(lock2, std::chrono::milliseconds(EXECUTE_COMMAND_TIME_OUT)) == std::cv_status::timeout) { + ACCESSTOKEN_LOG_WARN(LABEL, "time out to wait response."); + callbacks_.erase(uuid); + isSessionUsing_ = false; + return ""; + } + + isSessionUsing_ = false; + return responseResult_; +} + +void SoftBusChannel::HandleDataReceived(int session, const unsigned char *bytes, int length) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "HandleDataReceived"); + + if (session <= 0 || length <= 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid params: session: %{public}d, data length: %{public}d", session, length); + return; + } + std::string receiveData = Decompress(bytes, length); + if (receiveData.empty()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid parameter bytes"); + return; + } + std::shared_ptr message = SoftBusMessage::FromJson(receiveData); + if (message == nullptr) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "invalid json string: %{public}s", receiveData.c_str()); + return; + } + if (!message->IsValid()) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "invalid data, has empty field: %{public}s", receiveData.c_str()); + return; + } + + std::string type = message->GetType(); + if (REQUEST_TYPE == (type)) { + std::function delayed = ([=]() { + HandleRequest(session, message->GetId(), message->GetCommandName(), message->GetJsonPayload()); + }); + + std::shared_ptr handler = + DelayedSingleton::GetInstance()->GetRecvEventHandler(); + if (handler == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "fail to get EventHandler"); + return; + } + handler->ProxyPostTask(delayed, "HandleDataReceived_HandleRequest"); + } else if (RESPONSE_TYPE == (type)) { + HandleResponse(message->GetId(), message->GetJsonPayload()); + } else { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid type: %{public}s ", type.c_str()); + } +} + +int SoftBusChannel::PrepareBytes(const std::string &type, const std::string &id, const std::string &commandName, + const std::string &jsonPayload, const unsigned char *bytes, int &bytesLength) +{ + SoftBusMessage messageEntity(type, id, commandName, jsonPayload); + std::string json = messageEntity.ToJson(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "softbus message json: %{public}s", json.c_str()); + return Compress(json, bytes, bytesLength); +} + +int SoftBusChannel::Compress(const std::string &json, const unsigned char *compressedBytes, int &compressedLength) +{ + uLong len = compressBound(json.size()); + // length will not so that long + if (compressedLength > 0 && (int) len > compressedLength) { + ACCESSTOKEN_LOG_ERROR(LABEL, + "compress error. data length overflow, bound length: %{public}d, buffer length: %{public}d", (int) len, + compressedLength); + return Constant::FAILURE; + } + + int result = compress((Byte *) compressedBytes, &len, (unsigned char *) json.c_str(), json.size() + 1); + if (result != Z_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "compress failed! error code: %{public}d", result); + return result; + } + ACCESSTOKEN_LOG_DEBUG(LABEL, "compress complete. compress %{public}d bytes to %{public}d", compressedLength, + (int) len); + compressedLength = len; + return Constant::SUCCESS; +} + +std::string SoftBusChannel::Decompress(const unsigned char *bytes, const int length) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "input length: %{public}d", length); + uLong len = RPC_TRANSFER_BYTES_MAX_LENGTH; + unsigned char *buf = (unsigned char *) malloc(len + 1); + if (buf == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "no enough memory!"); + return ""; + } + memset_s(buf, len + 1, 0, len + 1); + int result = uncompress(buf, &len, (unsigned char *) bytes, length); + if (result != Z_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, + "uncompress failed, error code: %{public}d, bound length: %{public}d, buffer length: %{public}d", result, + (int) len, length); + free(buf); + return ""; + } + buf[len] = '\0'; + std::string str((char *) buf); + free(buf); + ACCESSTOKEN_LOG_DEBUG(LABEL, "done, output: %{public}s", str.c_str()); + return str; +} + +int SoftBusChannel::SendRequestBytes(const unsigned char *bytes, const int bytesLength) +{ + if (bytesLength == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "bytes data is invalid."); + return Constant::FAILURE; + } + + std::unique_lock lock(sessionMutex_); + if (CheckSessionMayReopenLocked() != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "session invalid and reopen failed!"); + return Constant::FAILURE; + } + + ACCESSTOKEN_LOG_DEBUG(LABEL, "send len (after compress len)= %{public}d", bytesLength); + int result = ::SendBytes(session_, bytes, bytesLength); + if (result != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "fail to send! result= %{public}d", result); + return Constant::FAILURE; + } + ACCESSTOKEN_LOG_DEBUG(LABEL, "send successfully."); + return Constant::SUCCESS; +} + +int SoftBusChannel::CheckSessionMayReopenLocked() +{ + // when session is opened, we got a valid sessionid, when session closed, we will reset sessionid. + if (IsSessionAvailable()) { + return Constant::SUCCESS; + } + int session = SoftBusManager::GetInstance().OpenSession(deviceId_); + if (session != Constant::INVALID_SESSION) { + session_ = session; + return Constant::SUCCESS; + } + return Constant::FAILURE; +} + +bool SoftBusChannel::IsSessionAvailable() +{ + if (session_ == Constant::INVALID_SESSION) { + return false; + } + return session_ > Constant::INVALID_SESSION; +} + +void SoftBusChannel::CancelCloseConnectionIfNeeded() +{ + std::unique_lock lock(mutex_); + if (!isDelayClosing_) { + return; + } + ACCESSTOKEN_LOG_DEBUG(LABEL, "cancel close connection"); + + Release(); + isDelayClosing_ = false; +} + +void SoftBusChannel::HandleRequest(int session, const std::string &id, const std::string &commandName, + const std::string &jsonPayload) +{ + std::shared_ptr command = + RemoteCommandFactory::GetInstance().NewRemoteCommandFromJson(commandName, jsonPayload); + if (command == nullptr) { + // send result back directly + ACCESSTOKEN_LOG_WARN(LABEL, "command %{public}s cannot get from json %{public}s", commandName.c_str(), + jsonPayload.c_str()); + + int sendlen = RPC_TRANSFER_HEAD_BYTES_LENGTH + jsonPayload.length(); + unsigned char *sendbuf = (unsigned char *) malloc(sendlen + 1); + if (sendbuf == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "no enough memory: %{public}d", sendlen); + return; + } + memset_s(sendbuf, sendlen + 1, 0, sendlen + 1); + int sendResult = PrepareBytes(RESPONSE_TYPE, id, commandName, jsonPayload, sendbuf, sendlen); + if (sendResult != Constant::SUCCESS) { + free(sendbuf); + return; + } + int sendResultCode = SendResponseBytes(session, sendbuf, sendlen); + free(sendbuf); + ACCESSTOKEN_LOG_DEBUG(LABEL, "send response result= %{public}d ", sendResultCode); + return; + } + + // execute command + command->Execute(); + ACCESSTOKEN_LOG_DEBUG(LABEL, "command uniqueId: %{public}s, finish with status: %{public}d, message: %{public}s", + command->remoteProtocol_.uniqueId.c_str(), command->remoteProtocol_.statusCode, + command->remoteProtocol_.message.c_str()); + + // send result back + std::string resultJsonPayload = command->ToJsonPayload(); + int len = RPC_TRANSFER_HEAD_BYTES_LENGTH + resultJsonPayload.length(); + unsigned char *buf = (unsigned char *) malloc(len + 1); + if (buf == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "no enough memory: %{public}d", len); + return; + } + memset_s(buf, len + 1, 0, len + 1); + int result = PrepareBytes(RESPONSE_TYPE, id, commandName, resultJsonPayload, buf, len); + if (result != Constant::SUCCESS) { + free(buf); + return; + } + int retCode = SendResponseBytes(session, buf, len); + free(buf); + ACCESSTOKEN_LOG_DEBUG(LABEL, "send response result= %{public}d", retCode); +} + +void SoftBusChannel::HandleResponse(const std::string &id, const std::string &jsonPayload) +{ + std::unique_lock lock(sessionMutex_); + auto callback = callbacks_.find(id); + if (callback != callbacks_.end()) { + (callback->second)(jsonPayload); + callbacks_.erase(callback); + } +} + +int SoftBusChannel::SendResponseBytes(int session, const unsigned char *bytes, const int bytesLength) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "send len (after compress len)= %{public}d", bytesLength); + int result = ::SendBytes(session, bytes, bytesLength); + if (result != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "fail to send! result= %{public}d", result); + return Constant::FAILURE; + } + ACCESSTOKEN_LOG_DEBUG(LABEL, "send successfully."); + return Constant::SUCCESS; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/services/tokensyncmanager/src/remote/soft_bus_device_connection_listener.cpp b/services/tokensyncmanager/src/remote/soft_bus_device_connection_listener.cpp new file mode 100644 index 000000000..f10ba7cfa --- /dev/null +++ b/services/tokensyncmanager/src/remote/soft_bus_device_connection_listener.cpp @@ -0,0 +1,93 @@ +/* + * 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 "soft_bus_device_connection_listener.h" +#include "remote_command_manager.h" +#include "soft_bus_manager.h" +#include "device_info_manager.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "SoftBusDeviceConnectionListener"}; +} +SoftBusDeviceConnectionListener::SoftBusDeviceConnectionListener() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "SoftBusDeviceConnectionListener()"); +} +SoftBusDeviceConnectionListener::~SoftBusDeviceConnectionListener() +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "~SoftBusDeviceConnectionListener()"); +} + +void SoftBusDeviceConnectionListener::OnDeviceOnline(const DmDeviceInfo &info) +{ + std::string networkId = info.deviceId; + std::string uuid = SoftBusManager::GetInstance().GetUniversallyUniqueIdByNodeId(networkId); + std::string udid = SoftBusManager::GetInstance().GetUniqueDisabilityIdByNodeId(networkId); + + ACCESSTOKEN_LOG_INFO(LABEL, + "networkId: %{public}s, uuid: %{public}s, udid: %{public}s", + networkId.c_str(), + uuid.c_str(), + udid.c_str()); + + if (uuid != "" && udid != "") { + DeviceInfoManager::GetInstance().AddDeviceInfo( + networkId, uuid, udid, info.deviceName, std::to_string(info.deviceTypeId)); + RemoteCommandManager::GetInstance().NotifyDeviceOnline(udid); + } else { + ACCESSTOKEN_LOG_ERROR(LABEL, "uuid or udid is empty, online failed."); + } + // no need to load local permissions by now. +} + +void SoftBusDeviceConnectionListener::OnDeviceOffline(const DmDeviceInfo &info) +{ + std::string networkId = info.deviceId; + std::string uuid = DeviceInfoManager::GetInstance().ConvertToUniversallyUniqueIdOrFetch(networkId); + std::string udid = DeviceInfoManager::GetInstance().ConvertToUniqueDisabilityIdOrFetch(networkId); + + ACCESSTOKEN_LOG_INFO(LABEL, + "networkId: %{public}s, uuid: %{public}s, udid: %{public}s", + networkId.c_str(), + uuid.c_str(), + udid.c_str()); + + if (uuid != "" && udid != "") { + RemoteCommandManager::GetInstance().NotifyDeviceOffline(uuid); + RemoteCommandManager::GetInstance().NotifyDeviceOffline(udid); + DeviceInfoManager::GetInstance().RemoveRemoteDeviceInfo(networkId, DeviceIdType::NETWORK_ID); + } else { + ACCESSTOKEN_LOG_ERROR(LABEL, "uuid or udid is empty, offline failed."); + } +} + +void SoftBusDeviceConnectionListener::OnDeviceReady(const DmDeviceInfo &info) +{ + std::string networkId = info.deviceId; + ACCESSTOKEN_LOG_INFO(LABEL, "networkId: %{public}s", networkId.c_str()); +} + +void SoftBusDeviceConnectionListener::OnDeviceChanged(const DmDeviceInfo &info) +{ + std::string networkId = info.deviceId; + ACCESSTOKEN_LOG_INFO(LABEL, "networkId: %{public}s", networkId.c_str()); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/services/tokensyncmanager/src/remote/soft_bus_manager.cpp b/services/tokensyncmanager/src/remote/soft_bus_manager.cpp index c0d294b9e..5bb3b5487 100644 --- a/services/tokensyncmanager/src/remote/soft_bus_manager.cpp +++ b/services/tokensyncmanager/src/remote/soft_bus_manager.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -12,12 +12,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "soft_bus_manager.h" - #include - -#include "accesstoken.h" -#include "softbus_bus_center.h" +#include "soft_bus_manager.h" +#include "parameter.h" +#include "device_info_manager.h" namespace OHOS { namespace Security { @@ -25,27 +23,27 @@ namespace AccessToken { namespace { static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "SoftBusManager"}; } - namespace { +static const std::string SESSION_GROUP_ID = "atm_dsoftbus_session_group_id"; static const SessionAttribute SESSION_ATTR = {.dataType = TYPE_BYTES}; static const int REASON_EXIST = -3; -static const int OPENSESSION_RETRY_TIMES = 100; +static const int OPENSESSION_RETRY_TIMES = 10 * 3; static const int OPENSESSION_RETRY_INTERVAL_MS = 100; -static const int CREAT_SERVER_RETRY_INTERVAL_MS = 1000; +static const int UDID_MAX_LENGTH = 128; // udid/uuid max length } // namespace const std::string SoftBusManager::ACCESS_TOKEN_PACKAGE_NAME = "ohos.security.distributed_access_token"; const std::string SoftBusManager::SESSION_NAME = "ohos.security.atm_channel"; -SoftBusManager::SoftBusManager() : isSoftBusServiceBindSuccess_(false), inited_(false), mutex_() +SoftBusManager::SoftBusManager() : isSoftBusServiceBindSuccess_(false), inited_(false), mutex_(), fulfillMutex_() { - ACCESSTOKEN_LOG_INFO(LABEL, "SoftBusManager()"); + ACCESSTOKEN_LOG_DEBUG(LABEL, "SoftBusManager()"); } SoftBusManager::~SoftBusManager() { - ACCESSTOKEN_LOG_INFO(LABEL, "~SoftBusManager()"); + ACCESSTOKEN_LOG_DEBUG(LABEL, "~SoftBusManager()"); } SoftBusManager &SoftBusManager::GetInstance() @@ -54,85 +52,65 @@ SoftBusManager &SoftBusManager::GetInstance() return instance; } -int SoftBusManager::OnSessionOpend(int sessionId, int result) -{ - if (result != 0) { - ACCESSTOKEN_LOG_INFO(LABEL, "session is open failed, result %{public}d", result); - return RET_FAILED; - } - SoftBusManager::GetInstance().ModifySessionStatus(sessionId); - ACCESSTOKEN_LOG_INFO(LABEL, "session is open"); - return 0; -} - -void SoftBusManager::OnSessionClosed(int sessionId) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "session is closed"); -} - -void SoftBusManager::OnBytesReceived(int sessionId, const void *data, unsigned int dataLen) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "session receive data."); -} - -void SoftBusManager::OnMessageReceived(int sessionId, const void *data, unsigned int dataLen) -{ - ACCESSTOKEN_LOG_INFO(LABEL, "session receive message."); -} - -bool SoftBusManager::IsSessionOpen(int sessionId) -{ - Utils::UniqueReadGuard idGuard(this->sessIdLock_); - if (sessOpenSet_.count(sessionId) == 0) { - return true; - } - return false; -} - -void SoftBusManager::ModifySessionStatus(int sessionId) -{ - Utils::UniqueWriteGuard idGuard(this->sessIdLock_); - if (sessOpenSet_.count(sessionId) > 0) { - sessOpenSet_.erase(sessionId); - } -} - -void SoftBusManager::SetSessionWaitingOpen(int sessionId) -{ - Utils::UniqueWriteGuard idGuard(this->sessIdLock_); - sessOpenSet_.insert(sessionId); -} - void SoftBusManager::Initialize() { bool inited = false; // cas failed means already inited. if (!inited_.compare_exchange_strong(inited, true)) { - ACCESSTOKEN_LOG_ERROR(LABEL, "already initialized, skip"); + ACCESSTOKEN_LOG_DEBUG(LABEL, "already initialized, skip"); return; } - while (1) { - std::unique_lock lock(mutex_); - // register session listener - ISessionListener sessionListener; - sessionListener.OnSessionOpened = SoftBusManager::OnSessionOpend; - sessionListener.OnSessionClosed = SoftBusManager::OnSessionClosed; - sessionListener.OnBytesReceived = SoftBusManager::OnBytesReceived; - sessionListener.OnMessageReceived = SoftBusManager::OnMessageReceived; - - int ret = ::CreateSessionServer(ACCESS_TOKEN_PACKAGE_NAME.c_str(), SESSION_NAME.c_str(), &sessionListener); - ACCESSTOKEN_LOG_INFO(LABEL, "Initialize: createSessionServer, result: %{public}d", ret); - // REASON_EXIST - if ((ret != 0) && (ret != REASON_EXIST)) { - auto sleepTime = std::chrono::milliseconds(CREAT_SERVER_RETRY_INTERVAL_MS); - std::this_thread::sleep_for(sleepTime); - continue; + std::function runner = [&]() { + auto sleepTime = std::chrono::milliseconds(1000); + while (1) { + std::unique_lock lock(mutex_); + std::string packageName = ACCESS_TOKEN_PACKAGE_NAME; + std::shared_ptr ptrDmInitCallback = std::make_shared(); + int ret = + DistributedHardware::DeviceManager::GetInstance().InitDeviceManager(packageName, ptrDmInitCallback); + if (ret != ERR_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Initialize: InitDeviceManager error, result: %{public}d", ret); + std::this_thread::sleep_for(sleepTime); + continue; + } + + std::string extra = ""; + std::shared_ptr ptrDeviceStateCallback = + std::make_shared(); + ret = DistributedHardware::DeviceManager::GetInstance().RegisterDevStateCallback(packageName, extra, + ptrDeviceStateCallback); + if (ret != ERR_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Initialize: RegisterDevStateCallback error, result: %{public}d", ret); + std::this_thread::sleep_for(sleepTime); + continue; + } + + // register session listener + ISessionListener sessionListener; + sessionListener.OnSessionOpened = SoftBusSessionListener::OnSessionOpened; + sessionListener.OnSessionClosed = SoftBusSessionListener::OnSessionClosed; + sessionListener.OnBytesReceived = SoftBusSessionListener::OnBytesReceived; + sessionListener.OnMessageReceived = SoftBusSessionListener::OnMessageReceived; + + ret = ::CreateSessionServer(ACCESS_TOKEN_PACKAGE_NAME.c_str(), SESSION_NAME.c_str(), &sessionListener); + ACCESSTOKEN_LOG_INFO(LABEL, "Initialize: createSessionServer, result: %{public}d", ret); + // REASON_EXIST + if ((ret != Constant::SUCCESS) && (ret != REASON_EXIST)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "Initialize: CreateSessionServer error, result: %{public}d", ret); + + std::this_thread::sleep_for(sleepTime); + continue; + } + + isSoftBusServiceBindSuccess_ = true; + this->FulfillLocalDeviceInfo(); + return; } - isSoftBusServiceBindSuccess_ = true; - break; - } + }; + std::thread initThread(runner); + initThread.detach(); ACCESSTOKEN_LOG_DEBUG(LABEL, "Initialize thread started"); } @@ -142,54 +120,61 @@ void SoftBusManager::Destroy() isSoftBusServiceBindSuccess_); if (inited_.load() == false) { - ACCESSTOKEN_LOG_ERROR(LABEL, "not inited, skip"); + ACCESSTOKEN_LOG_DEBUG(LABEL, "not inited, skip"); return; } std::unique_lock lock(mutex_); if (inited_.load() == false) { - ACCESSTOKEN_LOG_ERROR(LABEL, "not inited, skip"); + ACCESSTOKEN_LOG_DEBUG(LABEL, "not inited, skip"); return; } if (isSoftBusServiceBindSuccess_) { int32_t ret = ::RemoveSessionServer(ACCESS_TOKEN_PACKAGE_NAME.c_str(), SESSION_NAME.c_str()); - ACCESSTOKEN_LOG_ERROR(LABEL, "destroy, RemoveSessionServer: %{public}d", ret); + ACCESSTOKEN_LOG_DEBUG(LABEL, "destroy, RemoveSessionServer: %{public}d", ret); isSoftBusServiceBindSuccess_ = false; } + std::string packageName = ACCESS_TOKEN_PACKAGE_NAME; + int ret = DistributedHardware::DeviceManager::GetInstance().UnRegisterDevStateCallback(packageName); + if (ret != ERR_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "UnRegisterDevStateCallback failed, code: %{public}d", ret); + } + ret = DistributedHardware::DeviceManager::GetInstance().UnInitDeviceManager(packageName); + if (ret != ERR_OK) { + ACCESSTOKEN_LOG_ERROR(LABEL, "UnInitDeviceManager failed, code: %{public}d", ret); + } + inited_.store(false); ACCESSTOKEN_LOG_DEBUG(LABEL, "destroy, done"); } -int32_t SoftBusManager::SendRequest() +int32_t SoftBusManager::OpenSession(const std::string &deviceId) { - NodeBasicInfo *info = nullptr; - int32_t infoNum; - int ret = GetAllNodeDeviceInfo(ACCESS_TOKEN_PACKAGE_NAME.c_str(), &info, &infoNum); - if (ret != 0) { - ACCESSTOKEN_LOG_ERROR(LABEL, "can not get node device"); - return RET_FAILED; + DeviceInfo info; + bool result = DeviceInfoManager::GetInstance().GetDeviceInfo(deviceId, DeviceIdType::UNKNOWN, info); + if (result == false) { + ACCESSTOKEN_LOG_WARN(LABEL, "device info notfound for deviceId %{public}s", deviceId.c_str()); + return Constant::FAILURE; } + std::string networkId = info.deviceId.networkId; + ACCESSTOKEN_LOG_INFO(LABEL, "openSession, networkId: %{public}s", networkId.c_str()); // async open session, should waitting for OnSessionOpened event. - int sessionId = ::OpenSession(SESSION_NAME.c_str(), SESSION_NAME.c_str(), info[0].networkId, - "0", &SESSION_ATTR); - if (sessionId < 0) { - ACCESSTOKEN_LOG_ERROR(LABEL, "open session failed"); - return RET_FAILED; - } + int sessionId = ::OpenSession(SESSION_NAME.c_str(), SESSION_NAME.c_str(), networkId.c_str(), + SESSION_GROUP_ID.c_str(), &SESSION_ATTR); - SetSessionWaitingOpen(sessionId); + ACCESSTOKEN_LOG_DEBUG(LABEL, "session info: sessionId: %{public}d, uuid: %{public}s, udid: %{public}s", sessionId, + info.deviceId.universallyUniqueId.c_str(), info.deviceId.uniqueDisabilityId.c_str()); // wait session opening int retryTimes = 0; int logSpan = 10; auto sleepTime = std::chrono::milliseconds(OPENSESSION_RETRY_INTERVAL_MS); - bool isOpen = false; while (retryTimes++ < OPENSESSION_RETRY_TIMES) { - if (!IsSessionOpen(sessionId)) { + if (SoftBusSessionListener::GetSessionState(sessionId) < 0) { std::this_thread::sleep_for(sleepTime); if (retryTimes % logSpan == 0) { ACCESSTOKEN_LOG_INFO(LABEL, "openSession, waitting for: %{public}d ms", @@ -197,18 +182,163 @@ int32_t SoftBusManager::SendRequest() } continue; } - isOpen = true; break; } - int cmd = 0; - ret = ::SendBytes(sessionId, &cmd, sizeof(int)); - if (ret != 0) { - ::CloseSession(sessionId); - ACCESSTOKEN_LOG_ERROR(LABEL, "send cmd failed ret = %{public}d", ret); - return RET_FAILED; + int64_t state = SoftBusSessionListener::GetSessionState(sessionId); + if (state < 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "openSession, timeout, session: %{public}" PRId64, state); + return Constant::FAILURE; } + + SoftBusSessionListener::DeleteSessionIdFromMap(sessionId); + + ACCESSTOKEN_LOG_DEBUG(LABEL, "openSession, succeed, session: %{public}" PRId64, state); + return sessionId; +} + +int SoftBusManager::CloseSession(int sessionId) +{ + if (sessionId < 0) { + ACCESSTOKEN_LOG_INFO(LABEL, "closeSession: session is invalid"); + return Constant::FAILURE; + } + ::CloseSession(sessionId); - return RET_SUCCESS; + ACCESSTOKEN_LOG_INFO(LABEL, "closeSession "); + return Constant::SUCCESS; +} + + +std::string SoftBusManager::GetUniversallyUniqueIdByNodeId(const std::string &nodeId) +{ + if (!DataValidator::IsDeviceIdValid(nodeId)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid nodeId: %{public}s", nodeId.c_str()); + return ""; + } + + std::string uuid = GetUuidByNodeId(nodeId); + if (uuid.empty()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "softbus return null or empty string [%{public}s]", uuid.c_str()); + return ""; + } + + DeviceInfo info; + bool result = DeviceInfoManager::GetInstance().GetDeviceInfo(uuid, DeviceIdType::UNIVERSALLY_UNIQUE_ID, info); + if (result == false) { + ACCESSTOKEN_LOG_DEBUG(LABEL, "local device info not found for uuid %{public}s", uuid.c_str()); + } else { + std::string dimUuid = info.deviceId.universallyUniqueId; + if (uuid == dimUuid) { + // refresh cache + std::function fulfillDeviceInfo = std::bind(&SoftBusManager::FulfillLocalDeviceInfo, this); + std::thread fulfill(fulfillDeviceInfo); + fulfill.detach(); + } + } + + return uuid; +} + +std::string SoftBusManager::GetUniqueDisabilityIdByNodeId(const std::string &nodeId) +{ + if (!DataValidator::IsDeviceIdValid(nodeId)) { + ACCESSTOKEN_LOG_ERROR(LABEL, "invalid nodeId: %{public}s", nodeId.c_str()); + return ""; + } + std::string udid = GetUdidByNodeId(nodeId); + if (udid.empty()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "softbus return null or empty string: %{public}s", udid.c_str()); + return ""; + } + char localUdid[Constant::DEVICE_UUID_LENGTH] = {0}; + ::GetDevUdid(localUdid, Constant::DEVICE_UUID_LENGTH); + if (udid == localUdid) { + // refresh cache + std::function fulfillDeviceInfo = std::bind(&SoftBusManager::FulfillLocalDeviceInfo, this); + std::thread fulfill(fulfillDeviceInfo); + fulfill.detach(); + } + return udid; +} + +std::string SoftBusManager::GetUuidByNodeId(const std::string &nodeId) const +{ + uint8_t *info = (uint8_t *) malloc(UDID_MAX_LENGTH + 1); + if (info == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "no enough memory: %{public}d", UDID_MAX_LENGTH); + return ""; + } + memset_s(info, UDID_MAX_LENGTH + 1, 0, UDID_MAX_LENGTH + 1); + int32_t ret = ::GetNodeKeyInfo(ACCESS_TOKEN_PACKAGE_NAME.c_str(), nodeId.c_str(), NodeDeivceInfoKey::NODE_KEY_UUID, info, + UDID_MAX_LENGTH); + if (ret != Constant::SUCCESS) { + free(info); + ACCESSTOKEN_LOG_WARN(LABEL, "GetNodeKeyInfo error, return code: %{public}d", ret); + return ""; + } + std::string uuid((char *) info); + free(info); + ACCESSTOKEN_LOG_DEBUG(LABEL, "call softbus finished. nodeId(in): %{public}s, uuid: %{public}s", nodeId.c_str(), + uuid.c_str()); + return uuid; +} + +std::string SoftBusManager::GetUdidByNodeId(const std::string &nodeId) const +{ + uint8_t *info = (uint8_t *) malloc(UDID_MAX_LENGTH + 1); + if (info == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "no enough memory: %{public}d", UDID_MAX_LENGTH); + return ""; + } + memset_s(info, UDID_MAX_LENGTH + 1, 0, UDID_MAX_LENGTH + 1); + int32_t ret = ::GetNodeKeyInfo(ACCESS_TOKEN_PACKAGE_NAME.c_str(), nodeId.c_str(), NodeDeivceInfoKey::NODE_KEY_UDID, info, + UDID_MAX_LENGTH); + if (ret != Constant::SUCCESS) { + free(info); + ACCESSTOKEN_LOG_WARN(LABEL, "GetNodeKeyInfo error, code: %{public}d", ret); + return ""; + } + std::string udid((char *) info); + free(info); + ACCESSTOKEN_LOG_DEBUG(LABEL, "call softbus finished: nodeId(in): %{public}s, udid: %{public}s", nodeId.c_str(), + udid.c_str()); + return udid; +} + +int SoftBusManager::FulfillLocalDeviceInfo() +{ + // repeated task will just skip + if (!fulfillMutex_.try_lock()) { + ACCESSTOKEN_LOG_INFO(LABEL, "FulfillLocalDeviceInfo already running, skip."); + return Constant::SUCCESS; + } + + NodeBasicInfo info; + int32_t ret = ::GetLocalNodeDeviceInfo(ACCESS_TOKEN_PACKAGE_NAME.c_str(), &info); + if (ret != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "GetLocalNodeDeviceInfo error"); + fulfillMutex_.unlock(); + return Constant::FAILURE; + } + + ACCESSTOKEN_LOG_DEBUG(LABEL, "call softbus finished, networkId:%{public}s, name:%{public}s, type:%{public}d", + info.networkId, info.deviceName, info.deviceTypeId); + + std::string uuid = GetUuidByNodeId(info.networkId); + std::string udid = GetUdidByNodeId(info.networkId); + if (uuid.empty() || udid.empty()) { + ACCESSTOKEN_LOG_ERROR(LABEL, "FulfillLocalDeviceInfo: uuid or udid is empty, abort."); + fulfillMutex_.unlock(); + return Constant::FAILURE; + } + + DeviceInfoManager::GetInstance().AddDeviceInfo(info.networkId, uuid, udid, info.deviceName, + std::to_string(info.deviceTypeId)); + ACCESSTOKEN_LOG_DEBUG(LABEL, "AddDeviceInfo finished, networkId:%{public}s, uuid:%{public}s, udid:%{public}s", + info.networkId, uuid.c_str(), udid.c_str()); + + fulfillMutex_.unlock(); + return Constant::SUCCESS; } } // namespace AccessToken } // namespace Security diff --git a/services/tokensyncmanager/src/remote/soft_bus_session_listener.cpp b/services/tokensyncmanager/src/remote/soft_bus_session_listener.cpp new file mode 100644 index 000000000..e138da60a --- /dev/null +++ b/services/tokensyncmanager/src/remote/soft_bus_session_listener.cpp @@ -0,0 +1,135 @@ +/* + * 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 "soft_bus_session_listener.h" +#include "remote_command_manager.h" +#include "soft_bus_manager.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "SoftBusSessionListener"}; +} +namespace { +// Indicates the pointer to the session name, which is the unique ID of the session server. The value cannot be empty +// and can contain a maximum of 64 characters. +static const int32_t SESSION_NAME_MAXLENGTH = 64; +static const int32_t SESSION_ACCEPTED = 0; +static const int32_t SESSION_REFUSED = -1; +} // namespace + +std::mutex SoftBusSessionListener::g_SessionMutex_; +std::map SoftBusSessionListener::g_SessionOpenedMap_; + +int32_t SoftBusSessionListener::OnSessionOpened(int32_t session, int32_t result) +{ + if (result != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "OnSessionOpened, result: %{public}d", result); + return SESSION_REFUSED; + } + + int32_t len = SESSION_NAME_MAXLENGTH + 1; + char contents[len]; + int32_t resultCode = ::GetPeerSessionName(session, contents, len); + if (resultCode != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "OnSessionOpened, GetPeerSessionName failed, result: %{public}d", resultCode); + return SESSION_REFUSED; + } + std::string peerSessionName(contents); + if (SoftBusManager::SESSION_NAME != peerSessionName) { + ACCESSTOKEN_LOG_ERROR(LABEL, "OnSessionOpened, unknown session name."); + return SESSION_REFUSED; + } + + ACCESSTOKEN_LOG_INFO(LABEL, "OnSessionOpened, id = %{public}d", session); + + // store session state: opening + std::lock_guard guard(g_SessionMutex_); + auto iter = g_SessionOpenedMap_.find(session); + if (iter == g_SessionOpenedMap_.end()) { + g_SessionOpenedMap_.insert(std::pair(session, (int64_t) 1)); + } else { + iter->second = iter->second + 1; + } + + return SESSION_ACCEPTED; +} + +void SoftBusSessionListener::OnSessionClosed(int32_t session) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "OnSessionClosed"); + + // clear session state + std::lock_guard guard(g_SessionMutex_); + auto iter = g_SessionOpenedMap_.find(session); + if (iter != g_SessionOpenedMap_.end()) { + g_SessionOpenedMap_.erase(iter); + } +} + +void SoftBusSessionListener::OnMessageReceived(int32_t sessionId, const void *data, uint32_t dataLen) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "OnMessageReceived: data length = %{public}u", dataLen); +} + +void SoftBusSessionListener::OnBytesReceived(int32_t sessionId, const void *data, uint32_t dataLen) +{ + if (sessionId == Constant::INVALID_SESSION || dataLen == 0) { + ACCESSTOKEN_LOG_ERROR(LABEL, "params invalid, data length: %{public}d", dataLen); + return; + } + + int32_t len = SESSION_NAME_MAXLENGTH + 1; + char contents[len]; + int32_t resultCode = ::GetPeerDeviceId(sessionId, contents, len); + if (resultCode != Constant::SUCCESS) { + ACCESSTOKEN_LOG_ERROR(LABEL, "GetPeerDeviceId, failed, result: %{public}d", resultCode); + return; + } + std::string networkId(contents); + ACCESSTOKEN_LOG_INFO(LABEL, "networkId = %{public}s, data length = %{public}u", contents, dataLen); + auto channel = RemoteCommandManager::GetInstance().GetExecutorChannel(networkId); + if (channel == nullptr) { + ACCESSTOKEN_LOG_ERROR(LABEL, "GetExecutorChannel, failed, networkId: %{public}s", contents); + return; + } + channel->HandleDataReceived(sessionId, (unsigned char *) data, dataLen); +} + +int64_t SoftBusSessionListener::GetSessionState(int32_t sessionId) +{ + // get session state + std::lock_guard guard(g_SessionMutex_); + auto iter = g_SessionOpenedMap_.find(sessionId); + if (iter == g_SessionOpenedMap_.end()) { + return STATE_NOTFOUND; + } + return (iter->second); +} + +void SoftBusSessionListener::DeleteSessionIdFromMap(int32_t sessionID) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "DeleteSessionIdFromMap"); + // delete sessionId in map + std::lock_guard guard(g_SessionMutex_); + auto iter = g_SessionOpenedMap_.find(sessionID); + if (iter != g_SessionOpenedMap_.end()) { + g_SessionOpenedMap_.erase(iter); + } +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/services/tokensyncmanager/src/service/token_sync_event_handler.cpp b/services/tokensyncmanager/src/service/token_sync_event_handler.cpp new file mode 100644 index 000000000..5aa524193 --- /dev/null +++ b/services/tokensyncmanager/src/service/token_sync_event_handler.cpp @@ -0,0 +1,54 @@ +/* + * 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 "token_sync_event_handler.h" + +#include "accesstoken_log.h" + +namespace OHOS { +namespace Security { +namespace AccessToken { +namespace { +static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { + LOG_CORE, SECURITY_DOMAIN_ACCESSTOKEN, "TokenSyncEventHandler"}; +} +TokenSyncEventHandler::TokenSyncEventHandler( + const std::shared_ptr &runner) + : AppExecFwk::EventHandler(runner) +{ + ACCESSTOKEN_LOG_INFO(LABEL, "enter"); +} +TokenSyncEventHandler::~TokenSyncEventHandler() = default; + +bool TokenSyncEventHandler::ProxyPostTask(const Callback &callback, int64_t delayTime) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "PostTask without name"); + return AppExecFwk::EventHandler::PostTask(callback, delayTime); +} + +bool TokenSyncEventHandler::ProxyPostTask( + const Callback &callback, const std::string &name, int64_t delayTime) +{ + ACCESSTOKEN_LOG_DEBUG(LABEL, "PostTask with name"); + return AppExecFwk::EventHandler::PostTask(callback, name, delayTime); +} + +void TokenSyncEventHandler::ProxyRemoveTask(const std::string &name) +{ + AppExecFwk::EventHandler::RemoveTask(name); +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/services/tokensyncmanager/src/service/tokensync_manager_service.cpp b/services/tokensyncmanager/src/service/token_sync_manager_service.cpp similarity index 31% rename from services/tokensyncmanager/src/service/tokensync_manager_service.cpp rename to services/tokensyncmanager/src/service/token_sync_manager_service.cpp index c471fa466..5a3c034b8 100644 --- a/services/tokensyncmanager/src/service/tokensync_manager_service.cpp +++ b/services/tokensyncmanager/src/service/token_sync_manager_service.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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 @@ -13,10 +13,14 @@ * limitations under the License. */ -#include "tokensync_manager_service.h" +#include "token_sync_manager_service.h" #include + #include "accesstoken_log.h" +#include "device_info_repository.h" +#include "device_info.h" +#include "remote_command_manager.h" #include "soft_bus_manager.h" namespace OHOS { @@ -66,19 +70,126 @@ void TokenSyncManagerService::OnStop() state_ = ServiceRunningState::STATE_NOT_START; } -int TokenSyncManagerService::VerifyPermission( - const std::string& bundleName, const std::string& permissionName, int userId) +std::shared_ptr TokenSyncManagerService::GetSendEventHandler() { - ACCESSTOKEN_LOG_INFO(LABEL, - "%{public}s called, packageName: %{public}s, permissionName: %{public}s, userId: %{public}d", __func__, - bundleName.c_str(), permissionName.c_str(), userId); - int ret = SoftBusManager::GetInstance().SendRequest(); - ACCESSTOKEN_LOG_INFO(LABEL, "%{public}s called, ret %{public}d", __func__, ret); - return ret; + return sendHandler_; } -bool TokenSyncManagerService::Initialize() const +std::shared_ptr TokenSyncManagerService::GetRecvEventHandler() { + return recvHandler_; +} + +int TokenSyncManagerService::GetRemoteHapTokenInfo(const std::string& deviceID, AccessTokenID tokenID) +{ + if (!DataValidator::IsDeviceIdValid(deviceID) || tokenID == 0) { + ACCESSTOKEN_LOG_INFO(LABEL, "Params is wrong."); + return RET_FAILED; + } + DeviceInfo devInfo; + bool result = DeviceInfoRepository::GetInstance().FindDeviceInfo(deviceID, DeviceIdType::UNKNOWN, devInfo); + if (!result) { + ACCESSTOKEN_LOG_INFO(LABEL, "FindDeviceInfo failed"); + return Constant::FAILURE; + } + std::string udid = devInfo.deviceId.uniqueDisabilityId; + const std::shared_ptr syncRemoteHapTokenCommand = + RemoteCommandFactory::GetInstance().NewSyncRemoteHapTokenCommand(Constant::GetLocalDeviceId(), + deviceID, tokenID); + + const int32_t resultCode = RemoteCommandManager::GetInstance().ExecuteCommand(udid, syncRemoteHapTokenCommand); + if (resultCode != Constant::SUCCESS) { + ACCESSTOKEN_LOG_INFO(LABEL, + "RemoteExecutorManager executeCommand SyncRemoteHapTokenCommand failed, return %d", resultCode); + return resultCode; + } + ACCESSTOKEN_LOG_INFO(LABEL, "get resultCode: %d", resultCode); + return RET_SUCCESS; +} + +int TokenSyncManagerService::DeleteRemoteHapTokenInfo(AccessTokenID tokenID) +{ + if (tokenID == 0) { + ACCESSTOKEN_LOG_INFO(LABEL, "Params is wrong, token id is invalid."); + return RET_FAILED; + } + + std::vector devices = DeviceInfoRepository::GetInstance().ListDeviceInfo(); + std::string localUdid = Constant::GetLocalDeviceId(); + for (DeviceInfo device : devices) { + if (device.deviceId.uniqueDisabilityId == localUdid) { + ACCESSTOKEN_LOG_INFO(LABEL, "no need notify local device"); + continue; + } + const std::shared_ptr deleteRemoteTokenCommand = + RemoteCommandFactory::GetInstance().NewDeleteRemoteTokenCommand(Constant::GetLocalDeviceId(), + device.deviceId.networkId, tokenID); + + const int32_t resultCode = RemoteCommandManager::GetInstance().ExecuteCommand( + device.deviceId.uniqueDisabilityId, deleteRemoteTokenCommand); + if (resultCode != Constant::SUCCESS) { + ACCESSTOKEN_LOG_INFO(LABEL, + "RemoteExecutorManager executeCommand DeleteRemoteTokenCommand failed, return %d", resultCode); + continue; + } + ACCESSTOKEN_LOG_INFO(LABEL, "get resultCode: %d", resultCode); + } + return RET_SUCCESS; +} + +int TokenSyncManagerService::UpdateRemoteHapTokenInfo(const HapTokenInfoForSync& tokenInfo) +{ + std::vector devices = DeviceInfoRepository::GetInstance().ListDeviceInfo(); + std::string localUdid = Constant::GetLocalDeviceId(); + for (DeviceInfo device : devices) { + if (device.deviceId.uniqueDisabilityId == localUdid) { + ACCESSTOKEN_LOG_INFO(LABEL, "no need notify local device"); + continue; + } + + const std::shared_ptr updateRemoteHapTokenCommand = + RemoteCommandFactory::GetInstance().NewUpdateRemoteHapTokenCommand(Constant::GetLocalDeviceId(), + device.deviceId.networkId, tokenInfo); + + const int32_t resultCode = RemoteCommandManager::GetInstance().ExecuteCommand( + device.deviceId.uniqueDisabilityId, updateRemoteHapTokenCommand); + if (resultCode != Constant::SUCCESS) { + ACCESSTOKEN_LOG_INFO(LABEL, + "RemoteExecutorManager executeCommand updateRemoteHapTokenCommand failed, return %d", resultCode); + continue; + } + ACCESSTOKEN_LOG_INFO(LABEL, "get resultCode: %d", resultCode); + } + + return RET_SUCCESS; +} + +bool TokenSyncManagerService::Initialize() +{ + sendRunner_ = AppExecFwk::EventRunner::Create(true); + if (!sendRunner_) { + ACCESSTOKEN_LOG_ERROR(LABEL, "failed to create a sendRunner."); + return false; + } + + sendHandler_ = std::make_shared(sendRunner_); + if (!sendHandler_) { + ACCESSTOKEN_LOG_ERROR(LABEL, "sendHandler_ is nullpter."); + return false; + } + + recvRunner_ = AppExecFwk::EventRunner::Create(true); + if (!recvRunner_) { + ACCESSTOKEN_LOG_ERROR(LABEL, "failed to create a recvRunner."); + return false; + } + + recvHandler_ = std::make_shared(recvRunner_); + if (!recvHandler_) { + ACCESSTOKEN_LOG_ERROR(LABEL, "recvHandler_ is nullpter."); + return false; + } + SoftBusManager::GetInstance().Initialize(); return true; } diff --git a/services/tokensyncmanager/src/service/tokensync_manager_stub.cpp b/services/tokensyncmanager/src/service/token_sync_manager_stub.cpp similarity index 51% rename from services/tokensyncmanager/src/service/tokensync_manager_stub.cpp rename to services/tokensyncmanager/src/service/token_sync_manager_stub.cpp index f6a3506f8..c44fc70bd 100644 --- a/services/tokensyncmanager/src/service/tokensync_manager_stub.cpp +++ b/services/tokensyncmanager/src/service/token_sync_manager_stub.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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 @@ -13,10 +13,10 @@ * limitations under the License. */ -#include "tokensync_manager_stub.h" +#include "token_sync_manager_stub.h" #include "accesstoken_log.h" - +#include "hap_token_info_for_sync_parcel.h" #include "ipc_skeleton.h" #include "string_ex.h" @@ -37,8 +37,14 @@ int32_t TokenSyncManagerStub::OnRemoteRequest( return -1; } switch (code) { - case static_cast(ITokenSyncManager::InterfaceCode::VERIFY_PERMISSION): - VerifyPermissionInner(data, reply); + case static_cast(ITokenSyncManager::InterfaceCode::GET_REMOTE_HAP_TOKEN_INFO): + GetRemoteHapTokenInfoInner(data, reply); + break; + case static_cast(ITokenSyncManager::InterfaceCode::DELETE_REMOTE_HAP_TOKEN_INFO): + DeleteRemoteHapTokenInfoInner(data, reply); + break; + case static_cast(ITokenSyncManager::InterfaceCode::UPDATE_REMOTE_HAP_TOKEN_INFO): + UpdateRemoteHapTokenInfoInner(data, reply); break; default: return IPCObjectStub::OnRemoteRequest(code, data, reply, option); @@ -46,12 +52,31 @@ int32_t TokenSyncManagerStub::OnRemoteRequest( return NO_ERROR; } -void TokenSyncManagerStub::VerifyPermissionInner(MessageParcel& data, MessageParcel& reply) +void TokenSyncManagerStub::GetRemoteHapTokenInfoInner(MessageParcel& data, MessageParcel& reply) { - std::string bundleName = data.ReadString(); - std::string permissionName = data.ReadString(); - int userId = data.ReadInt32(); - int result = this->VerifyPermission(bundleName, permissionName, userId); + std::string deviceID = data.ReadString(); + int tokenID = data.ReadUint32(); + + HapTokenInfoForSync tokenInfo; + int result = this->GetRemoteHapTokenInfo(deviceID, tokenID); + reply.WriteInt32(result); +} + +void TokenSyncManagerStub::DeleteRemoteHapTokenInfoInner(MessageParcel& data, MessageParcel& reply) +{ + std::string deviceID = data.ReadString(); + int tokenID = data.ReadUint32(); + int result = this->DeleteRemoteHapTokenInfo(tokenID); + reply.WriteInt32(result); +} + +void TokenSyncManagerStub::UpdateRemoteHapTokenInfoInner(MessageParcel& data, MessageParcel& reply) +{ + sptr tokenInfoParcelPtr = data.ReadParcelable(); + int result = RET_FAILED; + if (tokenInfoParcelPtr != nullptr) { + result = this->UpdateRemoteHapTokenInfo(tokenInfoParcelPtr->hapTokenInfoForSyncParams); + } reply.WriteInt32(result); } } // namespace AccessToken -- Gitee