From 0204b012c5a23dd668ee4121d1bf1e407c0cc798 Mon Sep 17 00:00:00 2001 From: q30043944 Date: Wed, 23 Oct 2024 16:38:47 +0800 Subject: [PATCH 01/27] 00 Signed-off-by: q30043944 --- common/src/dm_error_message.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/src/dm_error_message.cpp b/common/src/dm_error_message.cpp index 8cf81bdfa..18d2cbe11 100644 --- a/common/src/dm_error_message.cpp +++ b/common/src/dm_error_message.cpp @@ -25,7 +25,7 @@ typedef struct ERROR_INFO { } ERROR_INFO; ERROR_INFO g_errorMessages[] = { - {ERR_DM_FAILED, "dm process execution failed."}, + {ERR_DM_FAILED, "dm process execution failed..."}, {ERR_DM_TIME_OUT, "dm process execution timeout."}, {ERR_DM_NOT_INIT, "dm service is not initialized, please try again later."}, {ERR_DM_INIT_FAILED, "dm service initialize failed."}, -- Gitee From 650eeb78d06554ad4f6eb887ae60fc6152013858 Mon Sep 17 00:00:00 2001 From: q30043944 Date: Sat, 26 Oct 2024 00:50:04 +0800 Subject: [PATCH 02/27] =?UTF-8?q?=E5=88=9D=E5=A7=8B=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: q30043944 --- .../include/multiple_user_connector.h | 2 ++ .../src/multiple_user_connector.cpp | 20 ++++++++++++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/commondependency/include/multiple_user_connector.h b/commondependency/include/multiple_user_connector.h index 6cdbc214b..982653fab 100644 --- a/commondependency/include/multiple_user_connector.h +++ b/commondependency/include/multiple_user_connector.h @@ -85,6 +85,8 @@ public: * @tc.type: FUNC */ static std::string GetSwitchOldAccountName(void); + + static void GetSelfTokenIdAndUserId(uint32_t &tokenId, int32_t &userId); private: static int32_t oldUserId_; static std::string accountId_; diff --git a/commondependency/src/multiple_user_connector.cpp b/commondependency/src/multiple_user_connector.cpp index c284da7b8..a4f226c4b 100644 --- a/commondependency/src/multiple_user_connector.cpp +++ b/commondependency/src/multiple_user_connector.cpp @@ -16,7 +16,7 @@ #include "multiple_user_connector.h" #include "dm_log.h" - +#include "ipc_skeleton.h" #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) #include "account_info.h" #include "ohos_account_kits.h" @@ -90,6 +90,24 @@ std::string MultipleUserConnector::GetOhosAccountName(void) #endif } +void MultipleUserConnector::GetSelfTokenIdAndUserId(uint32_t &tokenId, int32_t &userId) +{ + int32_t uid = OHOS::IPCSkeleton::GetCallingUid(); + tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) + return; +#elif OS_ACCOUNT_PART_EXISTS + ErrCode ret = OsAccountManager::GetOsAccountLocalldFromUid(uid, userId); + if (ret != 0) { + LOGE("GetOsAccountLocalldFromUid error ret: %{public}d", ret); + return; + } + return; +#else // OS_ACCOUNT_PART_EXISTS + return; +#endif +} + void MultipleUserConnector::SetSwitchOldUserId(int32_t userId) { std::lock_guard lock(lock_); -- Gitee From 4fc39650790c629171bc456045a07202c90b2126 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Sun, 27 Oct 2024 16:20:45 +0800 Subject: [PATCH 03/27] =?UTF-8?q?DM=E6=9F=A5=E8=AF=A2=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E5=A4=9A=E7=94=A8=E6=88=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李巍 --- commondependency/include/deviceprofile_connector.h | 2 +- commondependency/src/deviceprofile_connector.cpp | 4 ++-- .../include/device_manager_service_impl.h | 2 +- .../src/device_manager_service_impl.cpp | 4 ++-- services/service/src/device_manager_service.cpp | 13 ++++++++++--- 5 files changed, 16 insertions(+), 9 deletions(-) diff --git a/commondependency/include/deviceprofile_connector.h b/commondependency/include/deviceprofile_connector.h index fb95f058b..95513388d 100644 --- a/commondependency/include/deviceprofile_connector.h +++ b/commondependency/include/deviceprofile_connector.h @@ -99,7 +99,7 @@ public: int32_t PutAccessControlList(DmAclInfo aclInfo, DmAccesser dmAccesser, DmAccessee dmAccessee); int32_t UpdateAccessControlList(int32_t userId, std::string &oldAccountId, std::string &newAccountId); std::unordered_map GetAppTrustDeviceList(const std::string &pkgName, - const std::string &deviceId); + const std::string &deviceId, int32_t &userId); DmOfflineParam GetOfflineParamFromAcl(std::string trustDeviceId, std::string requestDeviceId); std::vector GetBindTypeByPkgName(std::string pkgName, std::string requestDeviceId, std::string trustUdid); diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index 58803d67e..4574a9c53 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -50,9 +50,9 @@ std::vector DeviceProfileConnector::GetAccessControlProfil } std::unordered_map DeviceProfileConnector::GetAppTrustDeviceList(const std::string &pkgName, - const std::string &deviceId) + const std::string &deviceId, int32_t &userId) { - std::vector profiles = GetAccessControlProfile(); + std::vector profiles = GetAccessControlProfileByUserId(userId); std::unordered_map deviceIdMap; for (auto &item : profiles) { std::string trustDeviceId = item.GetTrustDeviceId(); diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index c7f35e4a8..dea5bdff2 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -116,7 +116,7 @@ public: int32_t BindTarget(const std::string &pkgName, const PeerTargetId &targetId, const std::map &bindParam); - std::unordered_map GetAppTrustDeviceIdList(std::string pkgname); + std::unordered_map GetAppTrustDeviceIdList(std::string pkgname, int32_t &userId); int32_t DpAclAdd(const std::string &udid); int32_t IsSameAccount(const std::string &udid); diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index a5efd68a5..75fffc7b3 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -658,12 +658,12 @@ int32_t DeviceManagerServiceImpl::IsSameAccount(const std::string &udid) } std::unordered_map DeviceManagerServiceImpl::GetAppTrustDeviceIdList( - std::string pkgname) + std::string pkgname, int32_t &userId) { char localDeviceId[DEVICE_UUID_LENGTH]; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); std::string deviceId = reinterpret_cast(localDeviceId); - return DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgname, deviceId); + return DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgname, deviceId, userId); } void DeviceManagerServiceImpl::LoadHardwareFwkService() diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index fc07f1c03..4798b1163 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -258,12 +258,19 @@ int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, c } return DM_OK; } - if (onlineDeviceList.size() > 0 && IsDMServiceImplReady()) { + int32_t tokenId = -1; + int32_t userId = -1; + MultipleUserConnector::GetSelfTokenIdAndUserId(tokenId, userId); + if (userId == -1 || tokenId == -1) { + LOGE("userId or tokenId acquire fail!"); + return ERR_DM_INPUT_PARA_INVALID; + } + if (!onlineDeviceList.empty() && IsDMServiceImplReady()) { std::unordered_map udidMap; if (PermissionManager::GetInstance().CheckSystemSA(pkgName)) { - udidMap = dmServiceImpl_->GetAppTrustDeviceIdList(std::string(ALL_PKGNAME)); + udidMap = dmServiceImpl_->GetAppTrustDeviceIdList(std::string(ALL_PKGNAME), userId); } else { - udidMap = dmServiceImpl_->GetAppTrustDeviceIdList(pkgName); + udidMap = dmServiceImpl_->GetAppTrustDeviceIdList(pkgName, userId); } for (auto item : onlineDeviceList) { #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) -- Gitee From 311b0588c7a1fa7f09f473a6b93f5cb4a5eb3e16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Sun, 27 Oct 2024 17:29:31 +0800 Subject: [PATCH 04/27] =?UTF-8?q?DM=E6=9F=A5=E8=AF=A2=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E5=A4=9A=E7=94=A8=E6=88=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李巍 --- commondependency/include/deviceprofile_connector.h | 2 +- commondependency/src/deviceprofile_connector.cpp | 2 +- services/implementation/include/device_manager_service_impl.h | 2 +- .../implementation/include/device_manager_service_impl_lite.h | 2 +- services/implementation/src/device_manager_service_impl.cpp | 2 +- .../implementation/src/device_manager_service_impl_lite.cpp | 3 ++- services/service/include/idevice_manager_service_impl.h | 2 +- 7 files changed, 8 insertions(+), 7 deletions(-) diff --git a/commondependency/include/deviceprofile_connector.h b/commondependency/include/deviceprofile_connector.h index 95513388d..86843d7b7 100644 --- a/commondependency/include/deviceprofile_connector.h +++ b/commondependency/include/deviceprofile_connector.h @@ -99,7 +99,7 @@ public: int32_t PutAccessControlList(DmAclInfo aclInfo, DmAccesser dmAccesser, DmAccessee dmAccessee); int32_t UpdateAccessControlList(int32_t userId, std::string &oldAccountId, std::string &newAccountId); std::unordered_map GetAppTrustDeviceList(const std::string &pkgName, - const std::string &deviceId, int32_t &userId); + const std::string &deviceId, int32_t userId); DmOfflineParam GetOfflineParamFromAcl(std::string trustDeviceId, std::string requestDeviceId); std::vector GetBindTypeByPkgName(std::string pkgName, std::string requestDeviceId, std::string trustUdid); diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index 4574a9c53..297db4e80 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -50,7 +50,7 @@ std::vector DeviceProfileConnector::GetAccessControlProfil } std::unordered_map DeviceProfileConnector::GetAppTrustDeviceList(const std::string &pkgName, - const std::string &deviceId, int32_t &userId) + const std::string &deviceId, int32_t userId) { std::vector profiles = GetAccessControlProfileByUserId(userId); std::unordered_map deviceIdMap; diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index dea5bdff2..72c6c12fc 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -116,7 +116,7 @@ public: int32_t BindTarget(const std::string &pkgName, const PeerTargetId &targetId, const std::map &bindParam); - std::unordered_map GetAppTrustDeviceIdList(std::string pkgname, int32_t &userId); + std::unordered_map GetAppTrustDeviceIdList(std::string pkgname, int32_t userId); int32_t DpAclAdd(const std::string &udid); int32_t IsSameAccount(const std::string &udid); diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index c561b19e6..18d643c3d 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -115,7 +115,7 @@ public: DmPinType pinType, const std::string &payload); int32_t DestroyPinHolder(const std::string &pkgName, const PeerTargetId &targetId, DmPinType pinType, const std::string &payload); - std::unordered_map GetAppTrustDeviceIdList(std::string pkgname); + std::unordered_map GetAppTrustDeviceIdList(std::string pkgname, int32_t userId); int32_t DpAclAdd(const std::string &udid); int32_t IsSameAccount(const std::string &udid); diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 75fffc7b3..b6f324b31 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -658,7 +658,7 @@ int32_t DeviceManagerServiceImpl::IsSameAccount(const std::string &udid) } std::unordered_map DeviceManagerServiceImpl::GetAppTrustDeviceIdList( - std::string pkgname, int32_t &userId) + std::string pkgname, int32_t userId) { char localDeviceId[DEVICE_UUID_LENGTH]; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index 28b66e4e1..5528bd9cf 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -394,9 +394,10 @@ int32_t DeviceManagerServiceImpl::BindTarget(const std::string &pkgName, const P } std::unordered_map DeviceManagerServiceImpl::GetAppTrustDeviceIdList( - std::string pkgname) + std::string pkgname, int32_t userId) { (void)pkgname; + (void)userId; std::unordered_map tmp; return tmp; } diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index eb17b1511..79e0d6753 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -252,7 +252,7 @@ public: */ virtual int32_t UnRegisterUiStateCallback(const std::string &pkgName) = 0; - virtual std::unordered_map GetAppTrustDeviceIdList(std::string pkgname) = 0; + virtual std::unordered_map GetAppTrustDeviceIdList(std::string pkgname, int32_t userId) = 0; virtual int32_t DpAclAdd(const std::string &udid) = 0; virtual int32_t IsSameAccount(const std::string &udid) = 0; virtual void ScreenCommonEventCallback(std::string commonEventType) = 0; -- Gitee From 210ebd5fddcf38ca77730cf56515ecba2022b3ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Tue, 29 Oct 2024 19:33:38 +0800 Subject: [PATCH 05/27] =?UTF-8?q?=E7=BC=96=E8=AF=91=E9=97=AE=E9=A2=98?= =?UTF-8?q?=E6=95=B4=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 李巍 --- commondependency/src/multiple_user_connector.cpp | 4 ++-- services/service/src/device_manager_service.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/commondependency/src/multiple_user_connector.cpp b/commondependency/src/multiple_user_connector.cpp index a4f226c4b..6f5862968 100644 --- a/commondependency/src/multiple_user_connector.cpp +++ b/commondependency/src/multiple_user_connector.cpp @@ -97,9 +97,9 @@ void MultipleUserConnector::GetSelfTokenIdAndUserId(uint32_t &tokenId, int32_t & #if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) return; #elif OS_ACCOUNT_PART_EXISTS - ErrCode ret = OsAccountManager::GetOsAccountLocalldFromUid(uid, userId); + ErrCode ret = OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId); if (ret != 0) { - LOGE("GetOsAccountLocalldFromUid error ret: %{public}d", ret); + LOGE("GetOsAccountLocalIdFromUid error ret: %{public}d", ret); return; } return; diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 4798b1163..33187e6d2 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -258,7 +258,7 @@ int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, c } return DM_OK; } - int32_t tokenId = -1; + uint32_t tokenId = 0; int32_t userId = -1; MultipleUserConnector::GetSelfTokenIdAndUserId(tokenId, userId); if (userId == -1 || tokenId == -1) { -- Gitee From 696e0b7f22f5ab323a3ee6ec3d1d5b387317b4bc Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Wed, 30 Oct 2024 14:08:35 +0800 Subject: [PATCH 06/27] =?UTF-8?q?=E7=BB=91=E5=AE=9A=E9=80=82=E9=85=8D?= =?UTF-8?q?=E5=A4=9A=E7=94=A8=E6=88=B7=20Signed-off-by:=20liuzhongming=20?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common/include/dm_constants.h | 1 + .../include/multiple_user_connector.h | 4 ++ .../src/multiple_user_connector.cpp | 39 ++++++++++ .../src/notify/device_manager_notify.cpp | 8 +-- .../authentication/auth_message_processor.h | 1 + .../include/authentication/dm_auth_manager.h | 5 ++ .../authentication/auth_message_processor.cpp | 7 +- .../src/authentication/dm_auth_manager.cpp | 71 +++++++++++++++---- .../src/device_manager_service_impl.cpp | 24 +++---- .../devicestate/dm_device_state_manager.cpp | 8 +-- .../src/device_manager_service_listener.cpp | 8 +-- utils/include/appInfo/lite/app_manager.h | 2 + utils/include/appInfo/standard/app_manager.h | 2 + utils/src/appInfo/lite/app_manager.cpp | 16 +++++ utils/src/appInfo/standard/app_manager.cpp | 54 ++++++++++++++ 15 files changed, 210 insertions(+), 40 deletions(-) diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index 3a933cd29..026659bb4 100755 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -116,6 +116,7 @@ enum { ERR_DM_SOFTBUS_STOP_DISCOVERY_DEVICE = 96929815, ERR_DM_INVALID_JSON_STRING = 96929816, ERR_DM_GET_DATA_SHA256_HASH = 96929817, + ERR_DM_GET_CALLER_DATA_FAILED = 96929818, }; constexpr const char* TAG_GROUP_ID = "groupId"; diff --git a/commondependency/include/multiple_user_connector.h b/commondependency/include/multiple_user_connector.h index 6cdbc214b..6b62095dd 100644 --- a/commondependency/include/multiple_user_connector.h +++ b/commondependency/include/multiple_user_connector.h @@ -19,6 +19,7 @@ #include #include #include +#include namespace OHOS { namespace DistributedHardware { class MultipleUserConnector { @@ -85,6 +86,9 @@ public: * @tc.type: FUNC */ static std::string GetSwitchOldAccountName(void); + + static std::string GetOhosAccountIdByUserId(int32_t userId); + static int32_t GetForegroundUsers(std::vector userVec); private: static int32_t oldUserId_; static std::string accountId_; diff --git a/commondependency/src/multiple_user_connector.cpp b/commondependency/src/multiple_user_connector.cpp index c284da7b8..b4099aa65 100644 --- a/commondependency/src/multiple_user_connector.cpp +++ b/commondependency/src/multiple_user_connector.cpp @@ -125,5 +125,44 @@ std::string MultipleUserConnector::GetSwitchOldAccountName(void) std::lock_guard lock(lock_); return accountName_; } + +std::string MultipleUserConnector::GetOhosAccountIdByUserId(int32_t userId) +{ +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) + return ""; +#elif OS_ACCOUNT_PART_EXISTS + OhosAccountInfo accountInfo; + ErrCode ret = OhosAccountKits::GetInstance().GetOhosAccountInfoByUserId(userId, accountInfo); + if (ret != 0 || accountInfo.uid_ == "") { + LOGE("error ret: %{public}d", ret); + return ""; + } + return accountInfo.uid_; +#else + return ""; +#endif +} + +int32_t GetForegroundUsers(std::vector &userVec) +{ +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) + userVec.push_back(DEFAULT_OS_ACCOUNT_ID); + return DM_OK; +#elif OS_ACCOUNT_PART_EXISTS + std::vector accounts; + ErrCode ret = OsAccountManager::GetForegroundOsAccounts(accounts); + if (ret != 0 || accounts.empty()) { + LOGE("error ret: %{public}d", ret); + return ret; + } + for (auto &account : accounts) { + userVec.push_back(account.localId); + } + return DM_OK; +#else // OS_ACCOUNT_PART_EXISTS + userVec.push_back(DEFAULT_OS_ACCOUNT_ID); + return DM_OK; +#endif +} } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp index 93a06ad7a..ef741b46a 100644 --- a/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp +++ b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp @@ -261,7 +261,7 @@ void DeviceManagerNotify::OnRemoteDied() } } -void DeviceManagerNotify::OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &deviceInfo) +void DeviceManagerNotify::OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &deviceInfo)//todo { if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); @@ -293,7 +293,7 @@ void DeviceManagerNotify::OnDeviceOnline(const std::string &pkgName, const DmDev #endif } -void DeviceManagerNotify::OnDeviceOnline(const std::string &pkgName, const DmDeviceBasicInfo &deviceBasicInfo) +void DeviceManagerNotify::OnDeviceOnline(const std::string &pkgName, const DmDeviceBasicInfo &deviceBasicInfo)//todo { if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); @@ -325,7 +325,7 @@ void DeviceManagerNotify::OnDeviceOnline(const std::string &pkgName, const DmDev #endif } -void DeviceManagerNotify::OnDeviceOffline(const std::string &pkgName, const DmDeviceInfo &deviceInfo) +void DeviceManagerNotify::OnDeviceOffline(const std::string &pkgName, const DmDeviceInfo &deviceInfo)//todo { if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); @@ -357,7 +357,7 @@ void DeviceManagerNotify::OnDeviceOffline(const std::string &pkgName, const DmDe #endif } -void DeviceManagerNotify::OnDeviceOffline(const std::string &pkgName, const DmDeviceBasicInfo &deviceBasicInfo) +void DeviceManagerNotify::OnDeviceOffline(const std::string &pkgName, const DmDeviceBasicInfo &deviceBasicInfo)//todo { if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); diff --git a/services/implementation/include/authentication/auth_message_processor.h b/services/implementation/include/authentication/auth_message_processor.h index 959d3a87a..e5eb58829 100644 --- a/services/implementation/include/authentication/auth_message_processor.h +++ b/services/implementation/include/authentication/auth_message_processor.h @@ -72,6 +72,7 @@ constexpr const char* TAG_DATA_LEN = "dataLen"; constexpr const char* TAG_IMPORT_AUTH_CODE = "IMPORT_AUTH_CODE"; constexpr const char* TAG_HOST_PKGLABEL = "hostPkgLabel"; constexpr const char* TAG_EDITION = "edition"; +constexpr const char* TAG_BUNDLE_NAME = "bundleName"; class DmAuthManager; struct DmAuthRequestContext; diff --git a/services/implementation/include/authentication/dm_auth_manager.h b/services/implementation/include/authentication/dm_auth_manager.h index bbea5de22..edf4e9d96 100644 --- a/services/implementation/include/authentication/dm_auth_manager.h +++ b/services/implementation/include/authentication/dm_auth_manager.h @@ -103,6 +103,7 @@ typedef struct DmAuthRequestContext { std::string cryptoVer; std::string hostPkgName; std::string targetPkgName; + std::string bundleName; std::string appOperation; std::string appDesc; std::string appName; @@ -145,6 +146,7 @@ typedef struct DmAuthResponseContext { std::string groupName; std::string hostPkgName; std::string targetPkgName; + std::string bundleName; std::string appOperation; std::string appDesc; std::string customDesc; @@ -166,6 +168,7 @@ typedef struct DmAuthResponseContext { std::string localAccountId; int32_t localUserId; int64_t tokenId; + int64_t remoteTokenId; bool authed; std::string dmVersion; std::vector bindType; @@ -531,6 +534,8 @@ private: void DeleteOffLineTimer(int32_t sessionId); bool IsAllowDeviceBind(); int32_t GetBindLevel(int32_t bindLevel); + std::string GetBundleName(nlohmann::json &jsonObject); + int32_t GetBinderInfo(); private: std::shared_ptr softbusConnector_; diff --git a/services/implementation/src/authentication/auth_message_processor.cpp b/services/implementation/src/authentication/auth_message_processor.cpp index de6028f18..eeb719b9b 100644 --- a/services/implementation/src/authentication/auth_message_processor.cpp +++ b/services/implementation/src/authentication/auth_message_processor.cpp @@ -176,6 +176,7 @@ void AuthMessageProcessor::CreateNegotiateMessage(nlohmann::json &json) json[TAG_AUTHED] = authResponseContext_->authed; json[TAG_DMVERSION] = authResponseContext_->dmVersion; json[TAG_HOST] = authResponseContext_->hostPkgName; + json[TAG_BUNDLE_NAME] = authResponseContext_->bundleName; json[TAG_TOKENID] = authResponseContext_->tokenId; json[TAG_IDENTICAL_ACCOUNT] = authResponseContext_->isIdenticalAccount; json[TAG_HAVE_CREDENTIAL] = authResponseContext_->haveCredential; @@ -201,6 +202,7 @@ void AuthMessageProcessor::CreateRespNegotiateMessage(nlohmann::json &json) json[TAG_LOCAL_ACCOUNTID] = authResponseContext_->localAccountId; json[TAG_LOCAL_USERID] = authResponseContext_->localUserId; + json[TAG_TOKENID] = authResponseContext_->tokenId; json[TAG_ISONLINE] = authResponseContext_->isOnline; json[TAG_AUTHED] = authResponseContext_->authed; json[TAG_DMVERSION] = authResponseContext_->dmVersion; @@ -462,7 +464,7 @@ void AuthMessageProcessor::ParsePkgNegotiateMessage(const nlohmann::json &json) authResponseContext_->authed = json[TAG_AUTHED].get(); } if (IsInt64(json, TAG_TOKENID)) { - authResponseContext_->tokenId = json[TAG_TOKENID].get(); + authResponseContext_->remoteTokenId = json[TAG_TOKENID].get(); } if (IsString(json, TAG_DMVERSION)) { authResponseContext_->dmVersion = json[TAG_DMVERSION].get(); @@ -525,6 +527,9 @@ void AuthMessageProcessor::ParseNegotiateMessage(const nlohmann::json &json) if (IsString(json, TAG_EDITION)) { authResponseContext_->edition = json[TAG_EDITION].get(); } + if (IsString(json, TAG_BUNDLE_NAME)) { + authResponseContext_->bundleName = json[TAG_BUNDLE_NAME].get(); + } ParsePkgNegotiateMessage(json); } diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 23041ff9d..08761fe1a 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -92,6 +92,7 @@ constexpr const char* APP_OPERATION_KEY = "appOperation"; constexpr const char* TARGET_PKG_NAME_KEY = "targetPkgName"; constexpr const char* CUSTOM_DESCRIPTION_KEY = "customDescription"; constexpr const char* CANCEL_DISPLAY_KEY = "cancelPinCodeDisplay"; +constexpr const char* BUNDLE_NAME_KEY = "bundleName"; constexpr const char* DM_VERSION_4_1_5_1 = "4.1.5.1"; constexpr const char* DM_VERSION_5_0_1 = "5.0.1"; constexpr const char* DM_VERSION_5_0_2 = "5.0.2"; @@ -200,9 +201,10 @@ void DmAuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, authRequestContext_->deviceId = deviceId; authRequestContext_->addr = deviceId; authRequestContext_->dmVersion = DM_VERSION_5_0_2; - authRequestContext_->localAccountId = MultipleUserConnector::GetOhosAccountId(); + authRequestContext_->localUserId = 100;//todo + authRequestContext_->localAccountId = + MultipleUserConnector::GetOhosAccountIdByUserId(authRequestContext_->localUserId); MultipleUserConnector::SetSwitchOldAccountId(authRequestContext_->localAccountId); - authRequestContext_->localUserId = MultipleUserConnector::GetCurrentAccountUserID(); MultipleUserConnector::SetSwitchOldUserId(authRequestContext_->localUserId); authRequestContext_->isOnline = false; authRequestContext_->authed = !authRequestContext_->bindType.empty(); @@ -229,6 +231,7 @@ void DmAuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, } authRequestContext_->bindLevel = GetBindLevel(authRequestContext_->bindLevel); } + authRequestContext_->bundleName = GetBundleName(jsonObject); authRequestContext_->token = std::to_string(GenRandInt(MIN_PIN_TOKEN, MAX_PIN_TOKEN)); } @@ -349,13 +352,13 @@ int32_t DmAuthManager::DeleteAcl(const std::string &pkgName, const std::string & } if (bindLevel == APP && offlineParam.leftAclNumber != 0) { LOGI("The pkgName unbind app-level type leftAclNumber not zero."); - softbusConnector_->SetPkgName(pkgName); + softbusConnector_->SetPkgName(pkgName);//todo softbusConnector_->HandleDeviceOffline(remoteUdid); return DM_OK; } if (bindLevel == APP && offlineParam.leftAclNumber == 0) { LOGI("The pkgName unbind app-level type leftAclNumber is zero."); - softbusConnector_->SetPkgName(pkgName); + softbusConnector_->SetPkgName(pkgName);//todo hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); return DM_OK; } @@ -761,6 +764,7 @@ void DmAuthManager::StartNegotiate(const int32_t &sessionId) authResponseContext_->deviceId = authRequestContext_->deviceId; authResponseContext_->accountGroupIdHash = GetAccountGroupIdHash(); authResponseContext_->hostPkgName = authRequestContext_->hostPkgName; + authResponseContext_->bundleName = authRequestContext_->bundleName; authResponseContext_->hostPkgLabel = authRequestContext_->hostPkgLabel; authResponseContext_->tokenId = authRequestContext_->tokenId; authResponseContext_->bindLevel = authRequestContext_->bindLevel; @@ -1944,7 +1948,7 @@ void DmAuthManager::SrcAuthDeviceFinish() authResponseContext_->haveCredential)) { if ((authResponseContext_->bindLevel == APP || authResponseContext_->bindLevel == SERVICE) && !authResponseContext_->isIdenticalAccount && !authResponseContext_->hostPkgName.empty()) { - softbusConnector_->SetPkgName(authResponseContext_->hostPkgName); + softbusConnector_->SetPkgName(authResponseContext_->hostPkgName);//todo } softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK)); @@ -1958,7 +1962,7 @@ void DmAuthManager::SrcAuthDeviceFinish() authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT); if ((authResponseContext_->bindLevel == APP || authResponseContext_->bindLevel == SERVICE) && !authResponseContext_->isIdenticalAccount && !authResponseContext_->hostPkgName.empty()) { - softbusConnector_->SetPkgName(authResponseContext_->hostPkgName); + softbusConnector_->SetPkgName(authResponseContext_->hostPkgName);//todo } softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); authRequestState_->TransitionTo(std::make_shared()); @@ -1987,7 +1991,7 @@ void DmAuthManager::SinkAuthDeviceFinish() } if (authResponseContext_->isOnline) { LOGI("The device is online."); - softbusConnector_->SetPkgName(authResponseContext_->hostPkgName); + softbusConnector_->SetPkgName(authResponseContext_->hostPkgName);//todo softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); } } @@ -2106,18 +2110,17 @@ void DmAuthManager::ProcRespNegotiateExt(const int32_t &sessionId) { LOGI("DmAuthManager::ProcRespNegotiateExt start."); remoteDeviceId_ = authResponseContext_->localDeviceId; - std::string accountId = MultipleUserConnector::GetOhosAccountId(); - int32_t userId = MultipleUserConnector::GetCurrentAccountUserID(); - MultipleUserConnector::SetSwitchOldAccountId(accountId); - MultipleUserConnector::SetSwitchOldUserId(userId); + if (GetBinderInfo() != DM_OK) { + authResponseContext_->reply = ERR_DM_GET_CALLER_DATA_FAILED; + } + MultipleUserConnector::SetSwitchOldAccountId(authResponseContext_->localAccountId); + MultipleUserConnector::SetSwitchOldUserId(authResponseContext_->localUserId); authResponseContext_->isIdenticalAccount = false; if (authResponseContext_->localAccountId == accountId && accountId != "ohosAnonymousUid") { authResponseContext_->isIdenticalAccount = true; } authResponseContext_->remoteAccountId = authResponseContext_->localAccountId; - authResponseContext_->localAccountId = accountId; authResponseContext_->remoteUserId = authResponseContext_->localUserId; - authResponseContext_->localUserId = userId; char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); authResponseContext_->deviceId = authResponseContext_->localDeviceId; @@ -2262,25 +2265,27 @@ void DmAuthManager::PutAccessControlList() } aclInfo.deviceIdHash = localUdidHash; DmAccesser accesser; - accesser.requestTokenId = static_cast(authResponseContext_->tokenId); accesser.requestBundleName = authResponseContext_->hostPkgName; if (authRequestState_ != nullptr && authResponseState_ == nullptr) { + accesser.requestTokenId = static_cast(authResponseContext_->tokenId); accesser.requestUserId = authRequestContext_->localUserId; accesser.requestAccountId = authRequestContext_->localAccountId; accesser.requestDeviceId = authRequestContext_->localDeviceId; } else if (authRequestState_ == nullptr && authResponseState_ != nullptr) { + accesser.requestTokenId = static_cast(authResponseContext_->remoteTokenId); accesser.requestUserId = authResponseContext_->remoteUserId; accesser.requestAccountId = authResponseContext_->remoteAccountId; accesser.requestDeviceId = authResponseContext_->localDeviceId; } DmAccessee accessee; - accessee.trustTokenId = static_cast(authResponseContext_->tokenId); accessee.trustBundleName = authResponseContext_->hostPkgName; if (authRequestState_ != nullptr && authResponseState_ == nullptr) { + accessee.trustTokenId = static_cast(authResponseContext_->remoteTokenId); accessee.trustUserId = authRequestContext_->remoteUserId; accessee.trustAccountId = authRequestContext_->remoteAccountId; accessee.trustDeviceId = authResponseContext_->deviceId; } else if (authRequestState_ == nullptr && authResponseState_ != nullptr) { + accessee.trustTokenId = static_cast(authResponseContext_->tokenId); accessee.trustUserId = authResponseContext_->localUserId; accessee.trustAccountId = authResponseContext_->localAccountId; accessee.trustDeviceId = localUdid; @@ -2498,5 +2503,41 @@ int32_t DmAuthManager::GetBindLevel(int32_t bindLevel) } return bindLevel; } + +std::string DmAuthManager::GetBundleName(nlohmann::json &jsonObject) +{ + if (!jsonObject.is_discarded() && IsString(jsonObject, BUNDLE_NAME_KEY)) { + return jsonObject[BUNDLE_NAME_KEY].get(); + } + bool isSystemSA; + std::string bundleName + AppManager::GetInstance().GetCallerName(isSystemSA, bundleName); + return bundleName; +} + +int32_t DmAuthManager::GetBinderInfo() +{ + CHECK_NULL_RETURN(authResponseContext_, ERR_DM_POINT_NULL); + std::vector userVec; + int32_t ret = MultipleUserConnector::GetForegroundUsers(userVec); + if (ret != DM_OK || userVec.size() == 0) { + LOGE("get userid error ret: %{public}d.", ret); + return ERR_DM_FAILED; + } + authResponseContext_->localUserId = userVec[0]; + authResponseContext_->localAccountId = + MultipleUserConnector::GetOhosAccountIdByUserId(authResponseContext_->localUserId); + if (authResponseContext_->bundleName.isEmpty()) { + return DM_OK; + } + ret = AppManager::GetInstance(). + GetNativeTokenIdByName(authResponseContext_->bundleName, authResponseContext_->tokenId); + if (ret == DM_OK) { + return DM_OK; + } + ret = AppManager::GetInstance().GetHapTokenIdByName(authResponseContext_->localUserId, + authResponseContext_->bundleName, 0, authResponseContext_->tokenId); + return ret; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index a5efd68a5..22d6d9a3c 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -213,7 +213,7 @@ void DeviceManagerServiceImpl::HandleOffline(DmDeviceState devState, DmDeviceInf GetDevUdid(localUdid, DEVICE_UUID_LENGTH); std::string requestDeviceId = std::string(localUdid); DmOfflineParam offlineParam = - DeviceProfileConnector::GetInstance().GetOfflineParamFromAcl(trustDeviceId, requestDeviceId); + DeviceProfileConnector::GetInstance().GetOfflineParamFromAcl(trustDeviceId, requestDeviceId);//todo LOGI("The offline device bind type is %{public}d.", offlineParam.bindType); if (offlineParam.leftAclNumber == 0 && offlineParam.bindType == INVALIED_TYPE) { deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); @@ -225,12 +225,12 @@ void DeviceManagerServiceImpl::HandleOffline(DmDeviceState devState, DmDeviceInf deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); } else if (offlineParam.bindType == APP_PEER_TO_PEER_TYPE) { LOGI("The offline device is app-level bind type."); - softbusConnector_->SetPkgNameVec(offlineParam.pkgNameVec); + softbusConnector_->SetPkgNameVec(offlineParam.pkgNameVec);//todo deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); } if (offlineParam.leftAclNumber == 0) { LOGI("Delete credential in HandleDeviceOffline."); - hiChainAuthConnector_->DeleteCredential(trustDeviceId, MultipleUserConnector::GetCurrentAccountUserID()); + hiChainAuthConnector_->DeleteCredential(trustDeviceId, MultipleUserConnector::GetCurrentAccountUserID());//todo } } @@ -250,7 +250,7 @@ void DeviceManagerServiceImpl::HandleOnline(DmDeviceState devState, DmDeviceInfo char localUdid[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localUdid, DEVICE_UUID_LENGTH); std::string requestDeviceId = std::string(localUdid); - uint32_t bindType = DeviceProfileConnector::GetInstance().CheckBindType(trustDeviceId, requestDeviceId); + uint32_t bindType = DeviceProfileConnector::GetInstance().CheckBindType(trustDeviceId, requestDeviceId);//todo LOGI("The online device bind type is %{public}d.", bindType); if (bindType == INVALIED_TYPE && isCredentialType_.load()) { PutIdenticalAccountToAcl(requestDeviceId, trustDeviceId); @@ -263,21 +263,21 @@ void DeviceManagerServiceImpl::HandleOnline(DmDeviceState devState, DmDeviceInfo devInfo.authForm = DmAuthForm::ACROSS_ACCOUNT; } else if (bindType == APP_PEER_TO_PEER_TYPE) { std::vector pkgNameVec = - DeviceProfileConnector::GetInstance().GetPkgNameFromAcl(requestDeviceId, trustDeviceId); + DeviceProfileConnector::GetInstance().GetPkgNameFromAcl(requestDeviceId, trustDeviceId);//todo userid,pkgname if (pkgNameVec.size() == 0) { LOGI("The online device not need report pkgname"); return; } - softbusConnector_->SetPkgNameVec(pkgNameVec); + softbusConnector_->SetPkgNameVec(pkgNameVec);//todo devInfo.authForm = DmAuthForm::PEER_TO_PEER; } else if (bindType == APP_ACROSS_ACCOUNT_TYPE) { std::vector pkgNameVec = - DeviceProfileConnector::GetInstance().GetPkgNameFromAcl(requestDeviceId, trustDeviceId); + DeviceProfileConnector::GetInstance().GetPkgNameFromAcl(requestDeviceId, trustDeviceId);//todo if (pkgNameVec.size() == 0) { LOGI("The online device not need report pkgname"); return; } - softbusConnector_->SetPkgNameVec(pkgNameVec); + softbusConnector_->SetPkgNameVec(pkgNameVec);//todo devInfo.authForm = DmAuthForm::ACROSS_ACCOUNT; } LOGI("DeviceManagerServiceImpl::HandleOnline success devInfo auform %{public}d.", devInfo.authForm); @@ -624,8 +624,8 @@ void DeviceManagerServiceImpl::PutIdenticalAccountToAcl(std::string requestDevic aclInfo.authenticationType = ALLOW_AUTH_ALWAYS; aclInfo.deviceIdHash = localUdidHash; DmAccesser accesser; - accesser.requestUserId = MultipleUserConnector::GetCurrentAccountUserID(); - accesser.requestAccountId = MultipleUserConnector::GetOhosAccountId(); + accesser.requestUserId = MultipleUserConnector::GetCurrentAccountUserID(); //todo + accesser.requestAccountId = MultipleUserConnector::GetOhosAccountId(); //todo MultipleUserConnector::SetSwitchOldUserId(accesser.requestUserId); MultipleUserConnector::SetSwitchOldAccountId(accesser.requestAccountId); accesser.requestDeviceId = requestDeviceId; @@ -811,7 +811,7 @@ void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const return; } CHECK_NULL_VOID(softbusConnector_); - softbusConnector_->SetPkgName(pkgName); + softbusConnector_->SetPkgName(pkgName);//todo softbusConnector_->HandleDeviceOffline(remoteUdid); } @@ -848,7 +848,7 @@ void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devI LOGI("not need report pkgname"); return; } - softbusConnector_->SetPkgNameVec(pkgNameVec); + softbusConnector_->SetPkgNameVec(pkgNameVec);//todo } deviceStateMgr_->HandleDeviceScreenStatusChange(devInfo); } diff --git a/services/implementation/src/devicestate/dm_device_state_manager.cpp b/services/implementation/src/devicestate/dm_device_state_manager.cpp index 18e6b2bef..09b56c4e7 100644 --- a/services/implementation/src/devicestate/dm_device_state_manager.cpp +++ b/services/implementation/src/devicestate/dm_device_state_manager.cpp @@ -169,12 +169,12 @@ void DmDeviceStateManager::ProcessDeviceStateChange(const DmDeviceState devState LOGE("ProcessDeviceStateChange failed, callback_ptr is null."); return; } - std::vector pkgName = softbusConnector_->GetPkgName(); + std::vector pkgName = softbusConnector_->GetPkgName();//todo if (pkgName.size() == 0) { - listener_->OnDeviceStateChange(std::string(DM_PKG_NAME), devState, devInfo); + listener_->OnDeviceStateChange(std::string(DM_PKG_NAME), devState, devInfo);//todo } else { for (auto item : pkgName) { - listener_->OnDeviceStateChange(item, devState, devInfo); + listener_->OnDeviceStateChange(item, devState, devInfo);//todo } } } @@ -515,7 +515,7 @@ void DmDeviceStateManager::HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) LOGE("failed, ptr is null."); return; } - std::vector pkgName = softbusConnector_->GetPkgName(); + std::vector pkgName = softbusConnector_->GetPkgName();//todo LOGI("pkgName size: %{public}zu", pkgName.size()); if (pkgName.size() == 0) { listener_->OnDeviceScreenStateChange(std::string(DM_PKG_NAME), devInfo); diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index 7478a10bf..51deca390 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -85,7 +85,7 @@ void DeviceManagerServiceListener::SetDeviceInfo(std::shared_ptrSetDeviceState(state); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::string appId = ""; - if (AppManager::GetInstance().GetAppIdByPkgName(pkgName, appId) != DM_OK) { + if (AppManager::GetInstance().GetAppIdByPkgName(pkgName, appId) != DM_OK) {//todo pReq->SetDeviceInfo(deviceInfo); pReq->SetDeviceBasicInfo(deviceBasicInfo); return; @@ -121,9 +121,9 @@ void DeviceManagerServiceListener::ProcessDeviceStateChange(const DmDeviceState LOGI("In"); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - std::vector PkgNameVec = ipcServerListener_.GetAllPkgName(); + std::vector PkgNameVec = ipcServerListener_.GetAllPkgName();//todo if (state == DEVICE_STATE_OFFLINE) { - RemoveOnlinePkgName(info); + RemoveOnlinePkgName(info);//todo for (const auto &it : PkgNameVec) { SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); @@ -206,7 +206,7 @@ void DeviceManagerServiceListener::OnDeviceStateChange(const std::string &pkgNam LOGI("OnDeviceStateChange, state = %{public}d", state); DmDeviceBasicInfo deviceBasicInfo; ConvertDeviceInfoToDeviceBasicInfo(pkgName, info, deviceBasicInfo); - if (pkgName == std::string(DM_PKG_NAME)) { + if (pkgName == std::string(DM_PKG_NAME)) {//todo ProcessDeviceStateChange(state, info, deviceBasicInfo); } else { ProcessAppStateChange(pkgName, state, info, deviceBasicInfo); diff --git a/utils/include/appInfo/lite/app_manager.h b/utils/include/appInfo/lite/app_manager.h index 33927be8e..fc69459bc 100644 --- a/utils/include/appInfo/lite/app_manager.h +++ b/utils/include/appInfo/lite/app_manager.h @@ -30,6 +30,8 @@ public: void UnRegisterCallerAppId(const std::string &pkgName); int32_t GetAppIdByPkgName(const std::string &pkgName, std::string &appId); bool IsSystemSA(); + int32_t GetNativeTokenIdByName(std::string &processName, int64_t tokenId); + int32_t GetHapTokenIdByName(int32_t userId, std::string &bundleName, int32_t instIndex, int64_t tokenId); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/utils/include/appInfo/standard/app_manager.h b/utils/include/appInfo/standard/app_manager.h index 684337867..5bb9d3b7a 100644 --- a/utils/include/appInfo/standard/app_manager.h +++ b/utils/include/appInfo/standard/app_manager.h @@ -36,6 +36,8 @@ public: void UnRegisterCallerAppId(const std::string &pkgName); int32_t GetAppIdByPkgName(const std::string &pkgName, std::string &appId); bool IsSystemSA(); + int32_t GetNativeTokenIdByName(std::string &processName, int64_t tokenId); + int32_t GetHapTokenIdByName(int32_t userId, std::string &bundleName, int32_t instIndex, int64_t tokenId); private: bool GetBundleManagerProxy(sptr &bundleManager); std::mutex appIdMapLock_; diff --git a/utils/src/appInfo/lite/app_manager.cpp b/utils/src/appInfo/lite/app_manager.cpp index ea3ab90cc..d79b82535 100644 --- a/utils/src/appInfo/lite/app_manager.cpp +++ b/utils/src/appInfo/lite/app_manager.cpp @@ -46,5 +46,21 @@ bool AppManager::IsSystemSA() { return true; } + +int32_t GetNativeTokenIdByName(std::string &processName, int64_t tokenId) +{ + (void)processName; + (void)tokenId; + return DM_OK; +} + +int32_t GetHapTokenIdByName(int32_t userId, std::string &bundleName, int32_t instIndex, int64_t tokenId) +{ + (void)userId; + (void)bundleName; + (void)instIndex; + (void)tokenId; + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/utils/src/appInfo/standard/app_manager.cpp b/utils/src/appInfo/standard/app_manager.cpp index 63935cd2b..be0c78d93 100644 --- a/utils/src/appInfo/standard/app_manager.cpp +++ b/utils/src/appInfo/standard/app_manager.cpp @@ -151,5 +151,59 @@ bool AppManager::IsSystemSA() } return false; } + +int32_t AppManager::GetCallerName(bool isSystemSA, std::string &callerName) +{ + AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); + if (tokenCaller == 0) { + LOGE("GetCallingTokenID error."); + return ERR_DM_FAILED; + } + LOGI("tokenCaller ID == %{public}s", GetAnonyInt32(tokenCaller).c_str()); + ATokenTypeEnum tokenTypeFlag = AccessTokenKit::GetTokenTypeFlag(tokenCaller); + if (tokenTypeFlag == ATokenTypeEnum::TOKEN_HAP) { + isSystemSA = false; + HapTokenInfo tokenInfo; + if (AccessTokenKit::GetHapTokenInfo(tokenCaller, tokenInfo) != EOK) { + LOGE("GetHapTokenInfo failed."); + return ERR_DM_FAILED; + } + callerName = std::move(tokenInfo.bundleName); + } else if (tokenTypeFlag == ATokenTypeEnum::TOKEN_NATIVE) { + isSystemSA = true; + NativeTokenInfo tokenInfo; + if (AccessTokenKit::GetNativeTokenInfo(tokenCaller, tokenInfo) != EOK) { + LOGE("GetNativeTokenInfo failed."); + return ERR_DM_FAILED; + } + callerName = std::move(tokenInfo.processName); + } else { + LOGE("failed, unsupported process."); + return ERR_DM_FAILED; + } + return DM_OK; +} + +int32_t AppManager::GetNativeTokenIdByName(std::string &processName, int64_t tokenId) +{ + AccessTokenID nativeTokenId = AccessTokenKit::GetNativeTokenId(processName); + if (nativeTokenId == INVALID_TOKENID) { + LOGE("GetNativeTokenId failed."); + return ERR_DM_FAILED; + } + tokenId = static_cast(nativeTokenId); + return DM_OK; +} + +int32_t AppManager::GetHapTokenIdByName(int32_t userId, std::string &bundleName, int32_t instIndex, int64_t tokenId) +{ + AccessTokenIDEx hapTokenId = AccessTokenInfoManager::GetInstance().GetHapTokenId(userId, bundleName, instIndex); + if (hapTokenId == 0) { + LOGE("GetHapTokenId failed."); + return ERR_DM_FAILED; + } + tokenId = static_cast(hapTokenId); + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS -- Gitee From 1b41ad0e2110ebf3b14b7aa299dc4d34498ac2c0 Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Thu, 31 Oct 2024 19:44:16 +0800 Subject: [PATCH 07/27] =?UTF-8?q?=E5=A4=9A=E7=94=A8=E6=88=B7=E5=88=9D?= =?UTF-8?q?=E5=A7=8B=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common/include/ipc/model/ipc_req.h | 13 ++- .../include/deviceprofile_connector.h | 4 +- .../include/multiple_user_connector.h | 4 +- .../src/deviceprofile_connector.cpp | 27 ++++-- .../src/multiple_user_connector.cpp | 31 ++++++- .../native_cpp/include/dm_device_info.h | 24 ++++++ .../dependency/softbus/softbus_connector.h | 14 ++-- .../src/authentication/dm_auth_manager.cpp | 10 +-- .../dependency/softbus/softbus_connector.cpp | 32 +++---- .../src/device_manager_service_impl.cpp | 38 ++++----- .../devicestate/dm_device_state_manager.cpp | 17 ++-- .../service/include/device_manager_service.h | 2 +- .../include/device_manager_service_listener.h | 10 +-- .../include/discovery/discovery_manager.h | 2 +- .../idevice_manager_service_listener.h | 2 +- .../include/ipc/lite/ipc_server_listener.h | 14 +--- .../ipc/standard/ipc_server_listener.h | 14 +--- .../include/ipc/standard/ipc_server_stub.h | 24 ++---- .../service/src/device_manager_service.cpp | 6 +- .../src/device_manager_service_listener.cpp | 41 ++++----- .../src/discovery/discovery_manager.cpp | 6 +- .../src/ipc/lite/ipc_server_listener.cpp | 38 ++------- .../src/ipc/standard/ipc_cmd_parser.cpp | 11 ++- .../src/ipc/standard/ipc_server_listener.cpp | 26 ++---- .../src/ipc/standard/ipc_server_stub.cpp | 84 ++++++++----------- .../UTTest_dm_deviceprofile_connector.cpp | 12 +-- .../device_profile_connector_fuzzer.cpp | 2 +- .../ipc_server_listener_fuzzer.cpp | 1 - .../ipc_server_stub_fuzzer.cpp | 6 +- .../UTTest_device_manager_service.cpp | 5 +- ...UTTest_device_manager_service_listener.cpp | 17 ++-- test/unittest/UTTest_dm_pin_holder.h | 6 +- test/unittest/UTTest_ipc_server_listener.cpp | 81 +----------------- test/unittest/UTTest_ipc_server_stub.cpp | 40 +++++---- test/unittest/mock/ipc_server_listener.cpp | 8 -- test/unittest/mock/ipc_server_listener.h | 14 ++-- 36 files changed, 318 insertions(+), 368 deletions(-) diff --git a/common/include/ipc/model/ipc_req.h b/common/include/ipc/model/ipc_req.h index fd0d0c785..f16984c71 100644 --- a/common/include/ipc/model/ipc_req.h +++ b/common/include/ipc/model/ipc_req.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -19,6 +19,7 @@ #include #include "ipc_def.h" +#include "dm_device_info.h" namespace OHOS { namespace DistributedHardware { @@ -36,8 +37,18 @@ public: pkgName_ = pkgName; } + const ProcessInfo GetProcessInfo() const + { + return processInfo_; + } + + void SetProcessInfo(const ProcessInfo &processInfo) + { + processInfo_ = processInfo; + } private: std::string pkgName_; + ProcessInfo processInfo_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/commondependency/include/deviceprofile_connector.h b/commondependency/include/deviceprofile_connector.h index 86843d7b7..6c79d6af8 100644 --- a/commondependency/include/deviceprofile_connector.h +++ b/commondependency/include/deviceprofile_connector.h @@ -78,7 +78,7 @@ typedef struct DmAccessee { typedef struct DmOfflineParam { uint32_t bindType; - std::vector pkgNameVec; + std::vector processVec; int32_t leftAclNumber; } DmOfflineParam; @@ -110,7 +110,7 @@ public: void DeleteAclForUserRemoved(int32_t userId); DmOfflineParam DeleteAccessControlList(const std::string &pkgName, const std::string &localDeviceId, const std::string &remoteDeviceId, int32_t bindLevel); - std::vector GetPkgNameFromAcl(std::string &localDeviceId, std::string &targetDeviceId); + std::vector GetProcessInfoFromAcl(std::string &localDeviceId, std::string &targetDeviceId); bool CheckIdenticalAccount(int32_t userId, const std::string &accountId); bool CheckSrcDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId); bool CheckSinkDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId); diff --git a/commondependency/include/multiple_user_connector.h b/commondependency/include/multiple_user_connector.h index 26cbaae04..a1d0ba13d 100644 --- a/commondependency/include/multiple_user_connector.h +++ b/commondependency/include/multiple_user_connector.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -87,8 +87,10 @@ public: */ static std::string GetSwitchOldAccountName(void); static void GetSelfTokenIdAndUserId(uint32_t &tokenId, int32_t &userId); + static void GetTokenIdAndUserId(uint32_t &tokenId, int32_t &userId); static std::string GetOhosAccountIdByUserId(int32_t userId); static int32_t GetForegroundUsers(std::vector userVec); + static int32_t GetForegroundUser(void); private: static int32_t oldUserId_; diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index c0b9826f2..2b750aae9 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -165,7 +165,8 @@ int32_t DeviceProfileConnector::HandleDmAuthForm(AccessControlProfile profiles, uint32_t DeviceProfileConnector::CheckBindType(std::string trustDeviceId, std::string requestDeviceId) { LOGI("Start."); - std::vector profiles = GetAccessControlProfile(); + std::vector profiles = + GetAccessControlProfileByUserId(MultipleUserConnector::GetForegroundUser()); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); uint32_t highestPriority = INVALIED_TYPE; for (auto &item : profiles) { @@ -361,13 +362,14 @@ std::vector DeviceProfileConnector::SyncAclByBindType(std::string pkgNa return bindType; } -std::vector DeviceProfileConnector::GetPkgNameFromAcl(std::string &localDeviceId, +std::vector DeviceProfileConnector::GetProcessInfoFromAcl(std::string &localDeviceId, std::string &targetDeviceId) { LOGI("Start."); - std::vector profiles = GetAccessControlProfile(); + std::vector profiles = + GetAccessControlProfileByUserId(MultipleUserConnector::GetForegroundUser()); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); - std::vector pkgNameVec; + std::vector processInfoVec; for (auto &item : profiles) { if (item.GetTrustDeviceId() != targetDeviceId || item.GetStatus() != ACTIVE) { continue; @@ -376,17 +378,22 @@ std::vector DeviceProfileConnector::GetPkgNameFromAcl(std::string & item.GetAccessee().GetAccesseeDeviceId() == targetDeviceId) || (item.GetAccesser().GetAccesserDeviceId() == targetDeviceId && item.GetAccessee().GetAccesseeDeviceId() == localDeviceId)) { - pkgNameVec.push_back(item.GetAccesser().GetAccesserBundleName()); + ProcessInfo processInfo; + processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.userId = item.GetAccesser().GetAccesserUserId(); + processInfo.tokenId = item.GetAccesser().GetAccesserTokenId(); + processInfoVec.push_back(processInfo); } } - return pkgNameVec; + return processInfoVec; } DmOfflineParam DeviceProfileConnector::GetOfflineParamFromAcl(std::string trustDeviceId, std::string requestDeviceId) { LOGI("TrustDeviceId = %{public}s and requestDeviceId = %{public}s", GetAnonyString(trustDeviceId).c_str(), GetAnonyString(requestDeviceId).c_str()); - std::vector profiles = GetAccessControlProfile(); + std::vector profiles = + GetAccessControlProfileByUserId(MultipleUserConnector::GetForegroundUser()); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); DmOfflineParam offlineParam; offlineParam.leftAclNumber = 0; @@ -403,7 +410,11 @@ DmOfflineParam DeviceProfileConnector::GetOfflineParamFromAcl(std::string trustD priority = DEVICE_PEER_TO_PEER_TYPE; } else if (item.GetBindLevel() == DEVICE && item.GetAuthenticationType() == ALLOW_AUTH_ONCE) { priority = DEVICE_PEER_TO_PEER_TYPE; - offlineParam.pkgNameVec.push_back(item.GetAccesser().GetAccesserBundleName()); + ProcessInfo processInfo; + processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.userId = item.GetAccesser().GetAccesserUserId(); + processInfo.tokenId = item.GetAccesser().GetAccesserTokenId(); + offlineParam.pkgNameVec.push_back(processInfo); } else if ((item.GetAccesser().GetAccesserDeviceId() == requestDeviceId && item.GetAccessee().GetAccesseeDeviceId() == trustDeviceId) || (item.GetAccesser().GetAccesserDeviceId() == trustDeviceId && diff --git a/commondependency/src/multiple_user_connector.cpp b/commondependency/src/multiple_user_connector.cpp index 78d43232a..691cd7f90 100644 --- a/commondependency/src/multiple_user_connector.cpp +++ b/commondependency/src/multiple_user_connector.cpp @@ -108,6 +108,24 @@ void MultipleUserConnector::GetSelfTokenIdAndUserId(uint32_t &tokenId, int32_t & #endif } +void MultipleUserConnector::GetTokenIdAndUserId(uint32_t &tokenId, int32_t &userId) +{ + int32_t uid = OHOS::IPCSkeleton::GetCallingUid(); + tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) + return; +#elif OS_ACCOUNT_PART_EXISTS + ErrCode ret = OsAccountManager::GetOsAccountLocalldFromUid(uid, userId); + if (ret != 0) { + LOGE("GetOsAccountLocalldFromUid error ret: %{public}d", ret); + return; + } + return; +#else // OS_ACCOUNT_PART_EXISTS + return; +#endif +} + void MultipleUserConnector::SetSwitchOldUserId(int32_t userId) { std::lock_guard lock(lock_); @@ -161,7 +179,7 @@ std::string MultipleUserConnector::GetOhosAccountIdByUserId(int32_t userId) #endif } -int32_t GetForegroundUsers(std::vector &userVec) +int32_t MultipleUserConnector::GetForegroundUsers(std::vector &userVec) { #if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) userVec.push_back(DEFAULT_OS_ACCOUNT_ID); @@ -182,5 +200,16 @@ int32_t GetForegroundUsers(std::vector &userVec) return DM_OK; #endif } + +int32_t MultipleUserConnector::GetForegroundUser(void) +{ + std::vector userVec; + int32_t ret = GetForegroundUsers(userVec); + if (ret != DM_OK || userVec.size() == 0) { + LOGE("get userid error ret: %{public}d.", ret); + return -1; + } + return userVec[0]; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/interfaces/inner_kits/native_cpp/include/dm_device_info.h b/interfaces/inner_kits/native_cpp/include/dm_device_info.h index 4354ee3ea..1ff016b40 100644 --- a/interfaces/inner_kits/native_cpp/include/dm_device_info.h +++ b/interfaces/inner_kits/native_cpp/include/dm_device_info.h @@ -361,6 +361,30 @@ typedef struct DmAccessCallee { int32_t userId; std::string extra; } DmAccessCallee; + +typedef struct ProcessInfo { + std::string udid; + int32_t userId = -1; + std::string accountId; + uint64_t tokenId = 0; + std::string pkgName; + + bool operator==(const ProcessInfo &other) const + { + return (udid == other.udid) && (userId == other.userId) && (accountId == other.accountId) && + (tokenId == other.tokenId) && (pkgName == other.pkgName); + } + + bool operator<(const ProcessInfo &other) const + { + return (udid < other.udid) || + (udid == other.udid && userId < other.userId) || + (udid == other.udid && userId == other.userId && accountId < other.accountId) || + (udid == other.udid && userId == other.userId && accountId == other.accountId && tokenId < other.tokenId) || + (udid == other.udid && userId == other.userId && accountId == other.accountId && tokenId == other.tokenId && + pkgName < other.pkgName); + } +} ProcessInfo; } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_DEVICE_INFO_H \ No newline at end of file diff --git a/services/implementation/include/dependency/softbus/softbus_connector.h b/services/implementation/include/dependency/softbus/softbus_connector.h index ff406d11d..6ccdf0f40 100644 --- a/services/implementation/include/dependency/softbus/softbus_connector.h +++ b/services/implementation/include/dependency/softbus/softbus_connector.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -143,11 +143,11 @@ public: std::string GetNetworkIdByDeviceId(const std::string &deviceId); void HandleDeviceOnline(std::string deviceId, int32_t authForm); void HandleDeviceOffline(std::string deviceId); - void SetPkgName(std::string pkgName); + void SetProcessInfo(ProcessInfo processInfo); bool CheckIsOnline(const std::string &targetDeviceId); - void SetPkgNameVec(std::vector pkgNameVec); - std::vector GetPkgName(); - void ClearPkgName(); + void SetPkgNameVec(std::vector processInfoVec); + std::vector GetProcessInfo(); + void ClearProcessInfo(); DmDeviceInfo GetDeviceInfoByDeviceId(const std::string &deviceId); void DeleteOffLineTimer(std::string &udidHash); @@ -176,11 +176,11 @@ private: std::shared_ptr deviceStateManagerCallback_; static std::queue discoveryDeviceIdQueue_; static std::unordered_map deviceUdidMap_; - static std::vector pkgNameVec_; + static std::vector processInfoVec_; static std::mutex discoveryCallbackMutex_; static std::mutex discoveryDeviceInfoMutex_; static std::mutex deviceUdidLocks_; - static std::mutex pkgNameVecMutex_; + static std::mutex processInfoVecMutex_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 08761fe1a..1e551e75f 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -352,13 +352,13 @@ int32_t DmAuthManager::DeleteAcl(const std::string &pkgName, const std::string & } if (bindLevel == APP && offlineParam.leftAclNumber != 0) { LOGI("The pkgName unbind app-level type leftAclNumber not zero."); - softbusConnector_->SetPkgName(pkgName);//todo + softbusConnector_->SetProcessInfo(pkgName);//todo softbusConnector_->HandleDeviceOffline(remoteUdid); return DM_OK; } if (bindLevel == APP && offlineParam.leftAclNumber == 0) { LOGI("The pkgName unbind app-level type leftAclNumber is zero."); - softbusConnector_->SetPkgName(pkgName);//todo + softbusConnector_->SetProcessInfo(pkgName);//todo hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); return DM_OK; } @@ -1948,7 +1948,7 @@ void DmAuthManager::SrcAuthDeviceFinish() authResponseContext_->haveCredential)) { if ((authResponseContext_->bindLevel == APP || authResponseContext_->bindLevel == SERVICE) && !authResponseContext_->isIdenticalAccount && !authResponseContext_->hostPkgName.empty()) { - softbusConnector_->SetPkgName(authResponseContext_->hostPkgName);//todo + softbusConnector_->SetProcessInfo(authResponseContext_->hostPkgName);//todo } softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK)); @@ -1962,7 +1962,7 @@ void DmAuthManager::SrcAuthDeviceFinish() authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT); if ((authResponseContext_->bindLevel == APP || authResponseContext_->bindLevel == SERVICE) && !authResponseContext_->isIdenticalAccount && !authResponseContext_->hostPkgName.empty()) { - softbusConnector_->SetPkgName(authResponseContext_->hostPkgName);//todo + softbusConnector_->SetProcessInfo(authResponseContext_->hostPkgName);//todo } softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); authRequestState_->TransitionTo(std::make_shared()); @@ -1991,7 +1991,7 @@ void DmAuthManager::SinkAuthDeviceFinish() } if (authResponseContext_->isOnline) { LOGI("The device is online."); - softbusConnector_->SetPkgName(authResponseContext_->hostPkgName);//todo + softbusConnector_->SetProcessInfo(authResponseContext_->hostPkgName);//todo softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); } } diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index 0cb6a149d..8600ad671 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -48,11 +48,11 @@ std::map> SoftbusConnect std::map> SoftbusConnector::publishCallbackMap_ = {}; std::queue SoftbusConnector::discoveryDeviceIdQueue_ = {}; std::unordered_map SoftbusConnector::deviceUdidMap_ = {}; -std::vector SoftbusConnector::pkgNameVec_ = {}; +std::vector SoftbusConnector::processInfoVec_ = {}; std::mutex SoftbusConnector::discoveryCallbackMutex_; std::mutex SoftbusConnector::discoveryDeviceInfoMutex_; std::mutex SoftbusConnector::deviceUdidLocks_; -std::mutex SoftbusConnector::pkgNameVecMutex_; +std::mutex SoftbusConnector::processInfoVecMutex_; IPublishCb SoftbusConnector::softbusPublishCallback_ = { .OnPublishResult = SoftbusConnector::OnSoftbusPublishResult, @@ -670,32 +670,32 @@ std::string SoftbusConnector::GetNetworkIdByDeviceId(const std::string &deviceId return ""; } -void SoftbusConnector::SetPkgName(std::string pkgName) +void SoftbusConnector::SetProcessInfo(ProcessInfo processInfo) { - LOGI("SoftbusConnector::SetPkgName"); - std::lock_guard lock(pkgNameVecMutex_); - pkgNameVec_.push_back(pkgName); + LOGI("SoftbusConnector::SetProcessInfo"); + std::lock_guard lock(processInfoVecMutex_); + processInfoVec_.push_back(processInfo); } -void SoftbusConnector::SetPkgNameVec(std::vector pkgNameVec) +void SoftbusConnector::SetProcessInfoVec(std::vector processInfoVec) { - LOGI("SoftbusConnector::SetPkgNameVec"); - std::lock_guard lock(pkgNameVecMutex_); - pkgNameVec_ = pkgNameVec; + LOGI("SoftbusConnector::SetProcessInfoVec"); + std::lock_guard lock(processInfoVecMutex_); + processInfoVec_ = processInfoVec; } -std::vector SoftbusConnector::GetPkgName() +std::vector SoftbusConnector::GetProcessInfo() { LOGI("In"); - std::lock_guard lock(pkgNameVecMutex_); - return pkgNameVec_; + std::lock_guard lock(processInfoVecMutex_); + return processInfoVec_; } -void SoftbusConnector::ClearPkgName() +void SoftbusConnector::ClearProcessInfo() { LOGI("In"); - std::lock_guard lock(pkgNameVecMutex_); - pkgNameVec_.clear(); + std::lock_guard lock(processInfoVecMutex_); + processInfoVec_.clear(); } void SoftbusConnector::HandleDeviceOnline(std::string deviceId, int32_t authForm) diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index f0dbb56cc..18fb5c548 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -213,7 +213,7 @@ void DeviceManagerServiceImpl::HandleOffline(DmDeviceState devState, DmDeviceInf GetDevUdid(localUdid, DEVICE_UUID_LENGTH); std::string requestDeviceId = std::string(localUdid); DmOfflineParam offlineParam = - DeviceProfileConnector::GetInstance().GetOfflineParamFromAcl(trustDeviceId, requestDeviceId);//todo + DeviceProfileConnector::GetInstance().GetOfflineParamFromAcl(trustDeviceId, requestDeviceId); LOGI("The offline device bind type is %{public}d.", offlineParam.bindType); if (offlineParam.leftAclNumber == 0 && offlineParam.bindType == INVALIED_TYPE) { deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); @@ -225,12 +225,12 @@ void DeviceManagerServiceImpl::HandleOffline(DmDeviceState devState, DmDeviceInf deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); } else if (offlineParam.bindType == APP_PEER_TO_PEER_TYPE) { LOGI("The offline device is app-level bind type."); - softbusConnector_->SetPkgNameVec(offlineParam.pkgNameVec);//todo + softbusConnector_->SetProcessVec(offlineParam.processVec); deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); } if (offlineParam.leftAclNumber == 0) { LOGI("Delete credential in HandleDeviceOffline."); - hiChainAuthConnector_->DeleteCredential(trustDeviceId, MultipleUserConnector::GetCurrentAccountUserID());//todo + hiChainAuthConnector_->DeleteCredential(trustDeviceId, MultipleUserConnector::GetForegroundUser()); } } @@ -250,7 +250,7 @@ void DeviceManagerServiceImpl::HandleOnline(DmDeviceState devState, DmDeviceInfo char localUdid[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localUdid, DEVICE_UUID_LENGTH); std::string requestDeviceId = std::string(localUdid); - uint32_t bindType = DeviceProfileConnector::GetInstance().CheckBindType(trustDeviceId, requestDeviceId);//todo + uint32_t bindType = DeviceProfileConnector::GetInstance().CheckBindType(trustDeviceId, requestDeviceId); LOGI("The online device bind type is %{public}d.", bindType); if (bindType == INVALIED_TYPE && isCredentialType_.load()) { PutIdenticalAccountToAcl(requestDeviceId, trustDeviceId); @@ -262,22 +262,22 @@ void DeviceManagerServiceImpl::HandleOnline(DmDeviceState devState, DmDeviceInfo } else if (bindType == DEVICE_ACROSS_ACCOUNT_TYPE) { devInfo.authForm = DmAuthForm::ACROSS_ACCOUNT; } else if (bindType == APP_PEER_TO_PEER_TYPE) { - std::vector pkgNameVec = - DeviceProfileConnector::GetInstance().GetPkgNameFromAcl(requestDeviceId, trustDeviceId);//todo userid,pkgname - if (pkgNameVec.size() == 0) { + std::vector processInfoVec = + DeviceProfileConnector::GetInstance().GetProcessInfoFromAcl(requestDeviceId, trustDeviceId); + if (processInfoVec.size() == 0) { LOGI("The online device not need report pkgname"); return; } - softbusConnector_->SetPkgNameVec(pkgNameVec);//todo + softbusConnector_->SetProcessInfoVec(processInfoVec); devInfo.authForm = DmAuthForm::PEER_TO_PEER; } else if (bindType == APP_ACROSS_ACCOUNT_TYPE) { - std::vector pkgNameVec = - DeviceProfileConnector::GetInstance().GetPkgNameFromAcl(requestDeviceId, trustDeviceId);//todo - if (pkgNameVec.size() == 0) { + std::vector processInfoVec = + DeviceProfileConnector::GetInstance().GetProcessInfoFromAcl(requestDeviceId, trustDeviceId); + if (processInfoVec.size() == 0) { LOGI("The online device not need report pkgname"); return; } - softbusConnector_->SetPkgNameVec(pkgNameVec);//todo + softbusConnector_->SetProcessInfoVec(processInfoVec); devInfo.authForm = DmAuthForm::ACROSS_ACCOUNT; } LOGI("DeviceManagerServiceImpl::HandleOnline success devInfo auform %{public}d.", devInfo.authForm); @@ -624,8 +624,8 @@ void DeviceManagerServiceImpl::PutIdenticalAccountToAcl(std::string requestDevic aclInfo.authenticationType = ALLOW_AUTH_ALWAYS; aclInfo.deviceIdHash = localUdidHash; DmAccesser accesser; - accesser.requestUserId = MultipleUserConnector::GetCurrentAccountUserID(); //todo - accesser.requestAccountId = MultipleUserConnector::GetOhosAccountId(); //todo + accesser.requestUserId = MultipleUserConnector::GetForegroundUser(); + accesser.requestAccountId = MultipleUserConnector::GetOhosAccountIdByUserId(accesser.requestUserId); MultipleUserConnector::SetSwitchOldUserId(accesser.requestUserId); MultipleUserConnector::SetSwitchOldAccountId(accesser.requestAccountId); accesser.requestDeviceId = requestDeviceId; @@ -811,7 +811,7 @@ void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const return; } CHECK_NULL_VOID(softbusConnector_); - softbusConnector_->SetPkgName(pkgName);//todo + softbusConnector_->SetProcessInfo(pkgName);//todo softbusConnector_->HandleDeviceOffline(remoteUdid); } @@ -842,13 +842,13 @@ void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devI softbusConnector_->ClearPkgName(); LOGI("networkId: %{public}s", GetAnonyString(devInfo.networkId).c_str()); } else if (bindType == APP_PEER_TO_PEER_TYPE || bindType == APP_ACROSS_ACCOUNT_TYPE) { - std::vector pkgNameVec = - DeviceProfileConnector::GetInstance().GetPkgNameFromAcl(requestDeviceId, trustDeviceId); - if (pkgNameVec.size() == 0) { + std::vector processInfoVec = + DeviceProfileConnector::GetInstance().GetProcessInfoFromAcl(requestDeviceId, trustDeviceId); + if (processInfoVec.size() == 0) { LOGI("not need report pkgname"); return; } - softbusConnector_->SetPkgNameVec(pkgNameVec);//todo + softbusConnector_->SetProcessInfoVec(processInfoVec); } deviceStateMgr_->HandleDeviceScreenStatusChange(devInfo); } diff --git a/services/implementation/src/devicestate/dm_device_state_manager.cpp b/services/implementation/src/devicestate/dm_device_state_manager.cpp index 09b56c4e7..86d42fa58 100644 --- a/services/implementation/src/devicestate/dm_device_state_manager.cpp +++ b/services/implementation/src/devicestate/dm_device_state_manager.cpp @@ -21,6 +21,7 @@ #include "dm_anonymous.h" #include "dm_constants.h" #include "dm_crypto.h" +#include "dm_device_info.h" #include "dm_distributed_hardware_load.h" #include "dm_log.h" #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) @@ -169,12 +170,14 @@ void DmDeviceStateManager::ProcessDeviceStateChange(const DmDeviceState devState LOGE("ProcessDeviceStateChange failed, callback_ptr is null."); return; } - std::vector pkgName = softbusConnector_->GetPkgName();//todo - if (pkgName.size() == 0) { - listener_->OnDeviceStateChange(std::string(DM_PKG_NAME), devState, devInfo);//todo + std::vector processInfoVec = softbusConnector_->GetProcessInfo(); + if (processInfoVec.size() == 0) { + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + listener_->OnDeviceStateChange(processInfo, devState, devInfo); } else { - for (auto item : pkgName) { - listener_->OnDeviceStateChange(item, devState, devInfo);//todo + for (auto item : processInfoVec) { + listener_->OnDeviceStateChange(item, devState, devInfo); } } } @@ -201,7 +204,9 @@ void DmDeviceStateManager::OnDbReady(const std::string &pkgName, const std::stri } if (listener_ != nullptr) { DmDeviceState state = DEVICE_INFO_READY; - listener_->OnDeviceStateChange(pkgName, state, saveInfo); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + listener_->OnDeviceStateChange(processInfo, state, saveInfo); } } diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index 59cd724f9..3490e79ee 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -195,7 +195,7 @@ public: void HandleDeviceTrustedChange(const std::string &msg); int32_t SetDnPolicy(const std::string &pkgName, std::map &policy); - void ClearDiscoveryCache(const std::string &pkgName); + void ClearDiscoveryCache(const ProcessInfo &processInfo); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); int32_t GetDeviceScreenStatus(const std::string &pkgName, const std::string &networkId, int32_t &screenStatus); diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index e3df75866..5c8b63c80 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -39,7 +39,8 @@ public: DeviceManagerServiceListener() {}; virtual ~DeviceManagerServiceListener() {}; - void OnDeviceStateChange(const std::string &pkgName, const DmDeviceState &state, const DmDeviceInfo &info) override; + void OnDeviceStateChange(const ProcessInfo &processInfo, const DmDeviceState &state, + const DmDeviceInfo &info) override; void OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, const DmDeviceInfo &info) override; @@ -79,13 +80,12 @@ public: private: void ConvertDeviceInfoToDeviceBasicInfo(const std::string &pkgName, const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo); - void SetDeviceInfo(std::shared_ptr pReq, const std::string &pkgName, + void SetDeviceInfo(std::shared_ptr pReq, const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &deviceInfo, const DmDeviceBasicInfo &deviceBasicInfo); void ProcessDeviceStateChange(const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); - void ProcessAppStateChange(const std::string &pkgName, const DmDeviceState &state, + void ProcessAppStateChange(const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); - std::string ComposeOnlineKey(const std::string &pkgName, const std::string &devId); void SetDeviceScreenInfo(std::shared_ptr pReq, const std::string &pkgName, const DmDeviceInfo &deviceInfo); void RemoveOnlinePkgName(const DmDeviceInfo &info); @@ -98,7 +98,7 @@ private: #if !defined(__LITEOS_M__) IpcServerListener ipcServerListener_; static std::mutex alreadyOnlinePkgNameLock_; - static std::unordered_map alreadyOnlinePkgName_; + static std::unordered_map alreadyOnlinePkgName_; #endif }; } // namespace DistributedHardware diff --git a/services/service/include/discovery/discovery_manager.h b/services/service/include/discovery/discovery_manager.h index 04c5deef3..ce7ab495e 100644 --- a/services/service/include/discovery/discovery_manager.h +++ b/services/service/include/discovery/discovery_manager.h @@ -71,7 +71,7 @@ public: static bool IsCommonDependencyReady(); static bool CloseCommonDependencyObj(); #endif - void ClearDiscoveryCache(const std::string &pkgName); + void ClearDiscoveryCache(const ProcessInfo &processInfo); private: void StartDiscoveryTimer(const std::string &pkgName); diff --git a/services/service/include/idevice_manager_service_listener.h b/services/service/include/idevice_manager_service_listener.h index a1d276dca..e52280475 100644 --- a/services/service/include/idevice_manager_service_listener.h +++ b/services/service/include/idevice_manager_service_listener.h @@ -32,7 +32,7 @@ public: * @tc.desc: Device State Change of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnDeviceStateChange(const std::string &pkgName, const DmDeviceState &state, + virtual void OnDeviceStateChange(const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info) = 0; /** diff --git a/services/service/include/ipc/lite/ipc_server_listener.h b/services/service/include/ipc/lite/ipc_server_listener.h index f6dfcb6af..33dbb53ae 100644 --- a/services/service/include/ipc/lite/ipc_server_listener.h +++ b/services/service/include/ipc/lite/ipc_server_listener.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -18,6 +18,7 @@ #include +#include "dm_device_info.h" #include "ipc_req.h" #include "ipc_rsp.h" #include "ipc_server_listenermgr.h" @@ -38,18 +39,11 @@ public: int32_t SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); /** - * @tc.name: IpcServerListener::SendAll - * @tc.desc: Send All of the Ipc Server Listener - * @tc.type: FUNC - */ - int32_t SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); - - /** - * @tc.name: IpcServerListener::GetAllPkgName + * @tc.name: IpcServerListener::GetAllProcessInfo * @tc.desc: Get All PkgName from stub * @tc.type: FUNC */ - std::vector GetAllPkgName(); + std::vector GetAllProcessInfo(); private: void CommonSvcToIdentity(CommonSvcId *svcId, SvcIdentity *identity); diff --git a/services/service/include/ipc/standard/ipc_server_listener.h b/services/service/include/ipc/standard/ipc_server_listener.h index 4a19b1e57..ebd8e55a2 100644 --- a/services/service/include/ipc/standard/ipc_server_listener.h +++ b/services/service/include/ipc/standard/ipc_server_listener.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -18,6 +18,7 @@ #include +#include "dm_device_info.h" #include "ipc_req.h" #include "ipc_rsp.h" @@ -37,18 +38,11 @@ public: int32_t SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); /** - * @tc.name: IpcServerListener::SendAll - * @tc.desc: Send All of the Ipc Server Listener - * @tc.type: FUNC - */ - int32_t SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); - - /** - * @tc.name: IpcServerListener::GetAllPkgName + * @tc.name: IpcServerListener::GetAllProcessInfo * @tc.desc: Get All PkgName from stub * @tc.type: FUNC */ - std::vector GetAllPkgName(); + std::vector GetAllProcessInfo(); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/include/ipc/standard/ipc_server_stub.h b/services/service/include/ipc/standard/ipc_server_stub.h index 6c3f819f2..84c3cc734 100644 --- a/services/service/include/ipc/standard/ipc_server_stub.h +++ b/services/service/include/ipc/standard/ipc_server_stub.h @@ -30,6 +30,7 @@ #include "system_ability.h" #include "account_boot_listener.h" +#include "dm_device_info.h" #include "dm_single_instance.h" namespace OHOS { @@ -86,14 +87,14 @@ public: * @tc.desc: Register DeviceManager Listener of the IpcServerStub * @tc.type: FUNC */ - int32_t RegisterDeviceManagerListener(std::string &pkgName, sptr listener); + int32_t RegisterDeviceManagerListener(const ProcessInfo &processInfo, sptr listener); /** * @tc.name: IpcServerStub::UnRegisterDeviceManagerListener * @tc.desc: UnRegister DeviceManager Listener of the IpcServerStub * @tc.type: FUNC */ - int32_t UnRegisterDeviceManagerListener(std::string &pkgName); + int32_t UnRegisterDeviceManagerListener(const ProcessInfo &processInfo); /** * @tc.name: IpcServerStub::QueryServiceState @@ -103,32 +104,25 @@ public: ServiceRunningState QueryServiceState() const; /** - * @tc.name: IpcServerStub::SendALL - * @tc.desc: SendALL of the IpcServerStub - * @tc.type: FUNC - */ - int32_t SendALL(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); - - /** - * @tc.name: IpcServerStub::GetAllPkgName + * @tc.name: IpcServerStub::GetAllProcessInfo * @tc.desc: Get All PkgName from dmListener_ * @tc.type: FUNC */ - std::vector GetAllPkgName(); + std::vector GetAllProcessInfo(); /** * @tc.name: IpcServerStub::GetDmListener * @tc.desc: Get DmListener of the IpcServerStub * @tc.type: FUNC */ - const sptr GetDmListener(std::string pkgName) const; + const sptr GetDmListener(ProcessInfo processInfo) const; /** * @tc.name: IpcServerStub::GetDmListenerPkgName * @tc.desc: Get DmListener PkgName of the IpcServerStub * @tc.type: FUNC */ - const std::string GetDmListenerPkgName(const wptr &remote) const; + const ProcessInfo GetDmListenerPkgName(const wptr &remote) const; /** * @tc.name: IpcServerStub::Dump @@ -160,8 +154,8 @@ private: bool registerToService_; ServiceRunningState state_; mutable std::mutex listenerLock_; - std::map> appRecipient_; - std::map> dmListener_; + std::map> appRecipient_; + std::map> dmListener_; std::shared_ptr accountBootListener_; }; } // namespace DistributedHardware diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 9f37dbb56..bfbe8dc3f 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1935,11 +1935,11 @@ void DeviceManagerService::HandleDeviceTrustedChange(const std::string &msg) return; } -void DeviceManagerService::ClearDiscoveryCache(const std::string &pkgName) +void DeviceManagerService::ClearDiscoveryCache(const ProcessInfo &processInfo) { - LOGI("PkgName %{public}s.", pkgName.c_str()); + LOGI("PkgName %{public}s.", processInfo.pkgName.c_str()); CHECK_NULL_VOID(discoveryMgr_); - discoveryMgr_->ClearDiscoveryCache(pkgName); + discoveryMgr_->ClearDiscoveryCache(processInfo); } void DeviceManagerService::HandleDeviceScreenStatusChange(DmDeviceInfo &deviceInfo) diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index 51deca390..ee6c91e62 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -46,7 +46,7 @@ namespace OHOS { namespace DistributedHardware { std::mutex DeviceManagerServiceListener::alreadyOnlinePkgNameLock_; -std::unordered_map DeviceManagerServiceListener::alreadyOnlinePkgName_ = {}; +std::unordered_map DeviceManagerServiceListener::alreadyOnlinePkgName_ = {}; void DeviceManagerServiceListener::ConvertDeviceInfoToDeviceBasicInfo(const std::string &pkgName, const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo) { @@ -77,11 +77,12 @@ void DeviceManagerServiceListener::ConvertDeviceInfoToDeviceBasicInfo(const std: } void DeviceManagerServiceListener::SetDeviceInfo(std::shared_ptr pReq, - const std::string &pkgName, const DmDeviceState &state, const DmDeviceInfo &deviceInfo, + const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &deviceInfo, const DmDeviceBasicInfo &deviceBasicInfo) { LOGD("DeviceManagerServiceListener::SetDeviceInfo"); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); + pReq->SetProcessInfo(processInfo); pReq->SetDeviceState(state); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::string appId = ""; @@ -110,35 +111,29 @@ void DeviceManagerServiceListener::SetDeviceInfo(std::shared_ptrSetDeviceBasicInfo(deviceBasicInfo); } -std::string DeviceManagerServiceListener::ComposeOnlineKey(const std::string &pkgName, const std::string &devId) -{ - return pkgName + "_" + devId; -} - void DeviceManagerServiceListener::ProcessDeviceStateChange(const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo) { LOGI("In"); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - std::vector PkgNameVec = ipcServerListener_.GetAllPkgName();//todo + std::vector processInfoVec = ipcServerListener_.GetAllProcessInfo(); if (state == DEVICE_STATE_OFFLINE) { - RemoveOnlinePkgName(info);//todo + RemoveOnlinePkgName(info); for (const auto &it : PkgNameVec) { SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); } } if (state == DEVICE_STATE_ONLINE) { - for (const auto &it : PkgNameVec) { - std::string notifyKey = ComposeOnlineKey(it, std::string(info.deviceId)); + for (const auto &it : processInfoVec) { DmDeviceState notifyState = state; { std::lock_guard autoLock(alreadyOnlinePkgNameLock_); - if (alreadyOnlinePkgName_.find(notifyKey) != alreadyOnlinePkgName_.end()) { + if (alreadyOnlinePkgName_.find(it) != alreadyOnlinePkgName_.end()) { notifyState = DmDeviceState::DEVICE_INFO_CHANGED; } else { - alreadyOnlinePkgName_[notifyKey] = info; + alreadyOnlinePkgName_[it] = info; } } SetDeviceInfo(pReq, it, notifyState, info, deviceBasicInfo); @@ -146,14 +141,14 @@ void DeviceManagerServiceListener::ProcessDeviceStateChange(const DmDeviceState } } if (state == DEVICE_INFO_READY || state == DEVICE_INFO_CHANGED) { - for (const auto &it : PkgNameVec) { + for (const auto &it : processInfoVec) { SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); } } } -void DeviceManagerServiceListener::ProcessAppStateChange(const std::string &pkgName, const DmDeviceState &state, +void DeviceManagerServiceListener::ProcessAppStateChange(const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo) { LOGI("In"); @@ -200,16 +195,16 @@ void DeviceManagerServiceListener::ProcessAppStateChange(const std::string &pkgN } } -void DeviceManagerServiceListener::OnDeviceStateChange(const std::string &pkgName, const DmDeviceState &state, +void DeviceManagerServiceListener::OnDeviceStateChange(const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info) { LOGI("OnDeviceStateChange, state = %{public}d", state); DmDeviceBasicInfo deviceBasicInfo; - ConvertDeviceInfoToDeviceBasicInfo(pkgName, info, deviceBasicInfo); - if (pkgName == std::string(DM_PKG_NAME)) {//todo + ConvertDeviceInfoToDeviceBasicInfo(processInfo.pkgName, info, deviceBasicInfo); + if (processInfo.pkgName == std::string(DM_PKG_NAME)) { ProcessDeviceStateChange(state, info, deviceBasicInfo); } else { - ProcessAppStateChange(pkgName, state, info, deviceBasicInfo); + ProcessAppStateChange(processInfo, state, info, deviceBasicInfo); } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) KVAdapterManager::GetInstance().DeleteAgedEntry(); @@ -485,7 +480,7 @@ void DeviceManagerServiceListener::OnDeviceTrustChange(const std::string &udid, GetAnonyString(uuid).c_str(), authForm); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - std::vector PkgNameVec = ipcServerListener_.GetAllPkgName(); + std::vector PkgNameVec = ipcServerListener_.GetAllProcessInfo(); for (const auto &it : PkgNameVec) { pReq->SetPkgName(it); pReq->SetUdid(udid); @@ -520,7 +515,7 @@ void DeviceManagerServiceListener::OnDeviceScreenStateChange(const std::string & if (pkgName == std::string(DM_PKG_NAME)) { std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - std::vector PkgNameVec = ipcServerListener_.GetAllPkgName(); + std::vector PkgNameVec = ipcServerListener_.GetAllProcessInfo(); for (const auto &it : PkgNameVec) { SetDeviceScreenInfo(pReq, it, devInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_SCREEN_STATE_NOTIFY, pReq, pRsp); @@ -562,7 +557,7 @@ void DeviceManagerServiceListener::OnCredentialAuthStatus(const std::string &pkg pReq->SetDeviceTypeId(deviceTypeId); pReq->SetErrCode(errcode); if (pkgName == std::string(DM_PKG_NAME)) { - std::vector PkgNameVec = ipcServerListener_.GetAllPkgName(); + std::vector PkgNameVec = ipcServerListener_.GetAllProcessInfo(); for (const auto &it : PkgNameVec) { pReq->SetPkgName(it); ipcServerListener_.SendRequest(SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY, pReq, pRsp); diff --git a/services/service/src/discovery/discovery_manager.cpp b/services/service/src/discovery/discovery_manager.cpp index 285337a8f..1dd70df98 100644 --- a/services/service/src/discovery/discovery_manager.cpp +++ b/services/service/src/discovery/discovery_manager.cpp @@ -585,13 +585,13 @@ bool DiscoveryManager::CloseCommonDependencyObj() } #endif -void DiscoveryManager::ClearDiscoveryCache(const std::string &pkgName) +void DiscoveryManager::ClearDiscoveryCache(const ProcessInfo &processInfo) { - LOGI("PkgName %{public}s.", pkgName.c_str()); + LOGI("PkgName %{public}s.", processInfo.pkgName.c_str()); uint16_t subscribeId = 0; { std::lock_guard autoLock(locks_); - if (pkgNameSet_.find(pkgName) != pkgNameSet_.end()) { + if (pkgNameSet_.find(pkgName) != pkgNameSet_.end()) { //todo 发现待修改 LOGI("Erase pkgname %{public}s from pkgNameSet.", pkgName.c_str()); pkgNameSet_.erase(pkgName); } diff --git a/services/service/src/ipc/lite/ipc_server_listener.cpp b/services/service/src/ipc/lite/ipc_server_listener.cpp index 954372559..e4df32736 100644 --- a/services/service/src/ipc/lite/ipc_server_listener.cpp +++ b/services/service/src/ipc/lite/ipc_server_listener.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -66,40 +66,16 @@ int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr return DM_OK; } -int32_t IpcServerListener::SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) +std::vector IpcServerListener::GetAllProcessInfo() { + std::vector processInfoVec; const std::map &listenerMap = IpcServerListenermgr::GetInstance().GetAllListeners(); for (const auto &kv : listenerMap) { - SvcIdentity svc; - IpcIo io; - uint8_t data[MAX_DM_IPC_LEN] = {0}; - std::string pkgName = kv.first; - - req->SetPkgName(pkgName); - if (IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, io, data, MAX_DM_IPC_LEN) != DM_OK) { - LOGE("SetRequest failed cmdCode:%{public}d", cmdCode); - continue; - } - CommonSvcId svcId = kv.second; - CommonSvcToIdentity(&svcId, &svc); - MessageOption option; - MessageOptionInit(&option); - option.flags = TF_OP_ASYNC; - if (::SendRequest(svc, cmdCode, &io, nullptr, option, nullptr) != DM_OK) { - LOGI("SendRequest failed cmdCode:%{public}d", cmdCode); - } - } - return DM_OK; -} - -std::vector IpcServerListener::GetAllPkgName() -{ - std::vector pkgNameList; - const std::map &listenerMap = IpcServerListenermgr::GetInstance().GetAllListeners(); - for (const auto &kv : listenerMap) { - pkgNameList.push_back(kv.first); + ProcessInfo processInfo; + processInfo.pkgName = kv.first; + processInfoVec.push_back(processInfo); } - return pkgNameList; + return processInfoVec; } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/ipc/standard/ipc_cmd_parser.cpp b/services/service/src/ipc/standard/ipc_cmd_parser.cpp index 64b21766b..f622c072e 100644 --- a/services/service/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/standard/ipc_cmd_parser.cpp @@ -43,6 +43,7 @@ #include "ipc_notify_pin_holder_event_req.h" #include "ipc_server_client_proxy.h" #include "ipc_server_stub.h" +#include "multiple_user_connector.h" #include "nlohmann/json.hpp" @@ -419,8 +420,11 @@ ON_IPC_CMD(REGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParcel OHOS::HiviewDFX::XCollie::GetInstance().CancelTimer(id); return ERR_DM_POINT_NULL; } + ProcessInfo processInfo; + MultipleUserConnector::GetTokenIdAndUserId(processInfo.tokenId, processInfo.userId); + processInfo.pkgName = pkgName; DeviceManagerService::GetInstance().RegisterCallerAppId(pkgName); - int32_t result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, callback); + int32_t result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, callback); if (!reply.WriteInt32(result)) { LOGE("write result failed"); OHOS::HiviewDFX::XCollie::GetInstance().CancelTimer(id); @@ -433,8 +437,11 @@ ON_IPC_CMD(REGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParcel ON_IPC_CMD(UNREGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParcel &reply) { std::string pkgName = data.ReadString(); + ProcessInfo processInfo; + MultipleUserConnector::GetTokenIdAndUserId(processInfo.tokenId, processInfo.userId); + processInfo.pkgName = pkgName; DeviceManagerService::GetInstance().UnRegisterCallerAppId(pkgName); - int32_t result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + int32_t result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); if (!reply.WriteInt32(result)) { LOGE("write result failed"); return ERR_DM_IPC_WRITE_FAILED; diff --git a/services/service/src/ipc/standard/ipc_server_listener.cpp b/services/service/src/ipc/standard/ipc_server_listener.cpp index a9dc4c9f4..2fa0b8ab6 100644 --- a/services/service/src/ipc/standard/ipc_server_listener.cpp +++ b/services/service/src/ipc/standard/ipc_server_listener.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -31,12 +31,12 @@ int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr LOGE("IpcServerListener::SendRequest cmdCode param invalid!"); return ERR_DM_UNSUPPORTED_IPC_COMMAND; } - std::string pkgName = req->GetPkgName(); - if (pkgName.empty()) { + ProcessInfo processInfo = req->GetProcessInfo(); + if (processInfo.pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - sptr listener = IpcServerStub::GetInstance().GetDmListener(pkgName); + sptr listener = IpcServerStub::GetInstance().GetDmListener(processInfo); if (listener == nullptr) { LOGI("cannot get listener for package:%{public}s.", pkgName.c_str()); return ERR_DM_POINT_NULL; @@ -44,23 +44,9 @@ int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr return listener->SendCmd(cmdCode, req, rsp); } -std::vector IpcServerListener::GetAllPkgName() +std::vector IpcServerListener::GetAllProcessInfo() { - return IpcServerStub::GetInstance().GetAllPkgName(); -} - -int32_t IpcServerListener::SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) -{ - if (cmdCode < 0 || cmdCode >= IPC_MSG_BUTT) { - LOGE("IpcServerListener::SendAll cmdCode param invalid!"); - return ERR_DM_UNSUPPORTED_IPC_COMMAND; - } - int32_t ret = IpcServerStub::GetInstance().SendALL(cmdCode, req, rsp); - if (ret != DM_OK) { - LOGE("IpcServerListener::SendAll failed!"); - return ret; - } - return DM_OK; + return IpcServerStub::GetInstance().GetAllProcessInfo(); } } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/ipc/standard/ipc_server_stub.cpp b/services/service/src/ipc/standard/ipc_server_stub.cpp index 0ad5e7f8f..c29d4d4ac 100644 --- a/services/service/src/ipc/standard/ipc_server_stub.cpp +++ b/services/service/src/ipc/standard/ipc_server_stub.cpp @@ -33,6 +33,7 @@ #include "device_manager_ipc_interface_code.h" #include "device_manager_service.h" #include "dm_constants.h" +#include "dm_device_info.h" #include "dm_log.h" #include "multiple_user_connector.h" @@ -201,28 +202,29 @@ ServiceRunningState IpcServerStub::QueryServiceState() const return state_; } -int32_t IpcServerStub::RegisterDeviceManagerListener(std::string &pkgName, sptr listener) +int32_t IpcServerStub::RegisterDeviceManagerListener(const ProcessInfo &processInfo, sptr listener) { - if (pkgName.empty() || listener == nullptr) { + if (processInfo.pkgName.empty() || listener == nullptr) { LOGE("RegisterDeviceManagerListener error: input parameter invalid."); return ERR_DM_POINT_NULL; } - LOGI("Register device manager listener for package name: %{public}s", pkgName.c_str()); + LOGI("Register device manager listener for package name: %{public}s, tokenId: %{public}u", + processInfo.pkgName.c_str(), processInfo.tokenId); std::lock_guard autoLock(listenerLock_); - auto iter = dmListener_.find(pkgName); + auto iter = dmListener_.find(processInfo); if (iter != dmListener_.end()) { LOGI("Listener already exists"); - auto recipientIter = appRecipient_.find(pkgName); + auto recipientIter = appRecipient_.find(processInfo); if (recipientIter == appRecipient_.end()) { LOGI("AppRecipient not exists"); - dmListener_.erase(pkgName); + dmListener_.erase(processInfo); } else { auto listener = iter->second; auto appRecipient = recipientIter->second; listener->AsObject()->RemoveDeathRecipient(appRecipient); - appRecipient_.erase(pkgName); - dmListener_.erase(pkgName); + appRecipient_.erase(processInfo); + dmListener_.erase(processInfo); } } @@ -230,90 +232,74 @@ int32_t IpcServerStub::RegisterDeviceManagerListener(std::string &pkgName, sptr< if (!listener->AsObject()->AddDeathRecipient(appRecipient)) { LOGE("AddDeathRecipient Failed"); } - dmListener_[pkgName] = listener; - appRecipient_[pkgName] = appRecipient; + dmListener_[processInfo] = listener; + appRecipient_[processInfo] = appRecipient; LOGI("Register listener complete."); return DM_OK; } -int32_t IpcServerStub::UnRegisterDeviceManagerListener(std::string &pkgName) +int32_t IpcServerStub::UnRegisterDeviceManagerListener(const ProcessInfo &processInfo) { - if (pkgName.empty()) { + if (processInfo.pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("IpcServerStub::UnRegisterDeviceManagerListener In, pkgName: %{public}s", pkgName.c_str()); + LOGI("IpcServerStub::UnRegisterDeviceManagerListener In, pkgName: %{public}s", processInfo.pkgName.c_str()); std::lock_guard autoLock(listenerLock_); - auto listenerIter = dmListener_.find(pkgName); + auto listenerIter = dmListener_.find(processInfo); if (listenerIter == dmListener_.end()) { LOGI("Listener not exists"); return DM_OK; } - auto recipientIter = appRecipient_.find(pkgName); + auto recipientIter = appRecipient_.find(processInfo); if (recipientIter == appRecipient_.end()) { LOGI("AppRecipient not exists"); - dmListener_.erase(pkgName); + dmListener_.erase(processInfo); return DM_OK; } auto listener = listenerIter->second; auto appRecipient = recipientIter->second; listener->AsObject()->RemoveDeathRecipient(appRecipient); - appRecipient_.erase(pkgName); - dmListener_.erase(pkgName); + appRecipient_.erase(processInfo); + dmListener_.erase(processInfo); return DM_OK; } -int32_t IpcServerStub::SendALL(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) +std::vector IpcServerStub::GetAllProcessInfo() { + std::vector processInfoVec; std::lock_guard autoLock(listenerLock_); for (const auto &iter : dmListener_) { - auto pkgName = iter.first; - auto listener = iter.second; - req->SetPkgName(pkgName); - if (listener == nullptr) { - LOGE("IpcServerStub::SendALL, listener is nullptr, pkgName : %{public}s.", pkgName.c_str()); - continue; - } - listener->SendCmd(cmdCode, req, rsp); - } - return DM_OK; -} - -std::vector IpcServerStub::GetAllPkgName() -{ - std::vector PkgNameVec; - std::lock_guard autoLock(listenerLock_); - for (const auto &iter : dmListener_) { - PkgNameVec.push_back(iter.first); + processInfoVec.push_back(iter.first); } - return PkgNameVec; + return processInfoVec; } -const sptr IpcServerStub::GetDmListener(std::string pkgName) const +const sptr IpcServerStub::GetDmListener(ProcessInfo processInfo) const { - if (pkgName.empty()) { + if (processInfo.pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return nullptr; } std::lock_guard autoLock(listenerLock_); - auto iter = dmListener_.find(pkgName); + auto iter = dmListener_.find(processInfo); if (iter == dmListener_.end()) { return nullptr; } return iter->second; } -const std::string IpcServerStub::GetDmListenerPkgName(const wptr &remote) const +const ProcessInfo IpcServerStub::GetDmListenerPkgName(const wptr &remote) const { - std::string pkgName = ""; + ProcessInfo processInfo; std::lock_guard autoLock(listenerLock_); for (const auto &iter : dmListener_) { if ((iter.second)->AsObject() == remote.promote()) { - pkgName = iter.first; + processInfo = iter.first; break; } } - return pkgName; + return processInfo; } int32_t IpcServerStub::Dump(int32_t fd, const std::vector& args) @@ -340,10 +326,10 @@ int32_t IpcServerStub::Dump(int32_t fd, const std::vector& args) void AppDeathRecipient::OnRemoteDied(const wptr &remote) { - std::string pkgName = IpcServerStub::GetInstance().GetDmListenerPkgName(remote); - LOGI("AppDeathRecipient: OnRemoteDied for %{public}s", pkgName.c_str()); - IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); - DeviceManagerService::GetInstance().ClearDiscoveryCache(pkgName); + ProcessInfo processInfo = IpcServerStub::GetInstance().GetDmListenerPkgName(remote); + LOGI("AppDeathRecipient: OnRemoteDied for %{public}s", processInfo.pkgName.c_str()); + IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); + DeviceManagerService::GetInstance().ClearDiscoveryCache(processInfo); } } // namespace DistributedHardware } // namespace OHOS diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index 3e2038dc2..20594b841 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -451,27 +451,27 @@ HWTEST_F(DeviceProfileConnectorTest, SyncAclByBindType_001, testing::ext::TestSi EXPECT_EQ(ret.empty(), true); } -HWTEST_F(DeviceProfileConnectorTest, GetPkgNameFromAcl_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, GetProcessInfoFromAcl_001, testing::ext::TestSize.Level0) { std::string localDeviceId = "localDeviceId"; std::string targetDeviceId = "targetDeviceId"; - auto ret = DeviceProfileConnector::GetInstance().GetPkgNameFromAcl(localDeviceId, targetDeviceId); + auto ret = DeviceProfileConnector::GetInstance().GetProcessInfoFromAcl(localDeviceId, targetDeviceId); EXPECT_EQ(ret.empty(), true); } -HWTEST_F(DeviceProfileConnectorTest, GetPkgNameFromAcl_002, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, GetProcessInfoFromAcl_002, testing::ext::TestSize.Level0) { std::string localDeviceId = "123456"; std::string targetDeviceId = "deviceId"; - auto ret = DeviceProfileConnector::GetInstance().GetPkgNameFromAcl(localDeviceId, targetDeviceId); + auto ret = DeviceProfileConnector::GetInstance().GetProcessInfoFromAcl(localDeviceId, targetDeviceId); EXPECT_EQ(ret.empty(), true); } -HWTEST_F(DeviceProfileConnectorTest, GetPkgNameFromAcl_003, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, GetProcessInfoFromAcl_003, testing::ext::TestSize.Level0) { std::string localDeviceId = "deviceId"; std::string targetDeviceId = "deviceId"; - auto ret = DeviceProfileConnector::GetInstance().GetPkgNameFromAcl(localDeviceId, targetDeviceId); + auto ret = DeviceProfileConnector::GetInstance().GetProcessInfoFromAcl(localDeviceId, targetDeviceId); EXPECT_EQ(ret.empty(), false); } diff --git a/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp b/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp index 1d9b2bb50..e4d7e8c31 100644 --- a/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp +++ b/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp @@ -57,7 +57,7 @@ void DeviceProfileConnectorFuzzTest(const uint8_t* data, size_t size) DeviceProfileConnector::GetInstance().CheckBindType(trustDeviceId, requestDeviceId); DeviceProfileConnector::GetInstance().GetBindTypeByPkgName(pkgName, requestDeviceId, trustUdid); - DeviceProfileConnector::GetInstance().GetPkgNameFromAcl(localDeviceId, targetDeviceId); + DeviceProfileConnector::GetInstance().GetProcessInfoFromAcl(localDeviceId, targetDeviceId); DeviceProfileConnector::GetInstance().GetOfflineParamFromAcl(trustDeviceId, requestDeviceId); DeviceProfileConnector::GetInstance().PutAccessControlList(aclInfo, dmAccesser, dmAccessee); DeviceProfileConnector::GetInstance().DeleteAccessControlList(pkgName, localDeviceId, requestDeviceId, bindLevel); diff --git a/test/servicesfuzztest/ipcserverlistener_fuzzer/ipc_server_listener_fuzzer.cpp b/test/servicesfuzztest/ipcserverlistener_fuzzer/ipc_server_listener_fuzzer.cpp index 6e531a287..b7c8de713 100644 --- a/test/servicesfuzztest/ipcserverlistener_fuzzer/ipc_server_listener_fuzzer.cpp +++ b/test/servicesfuzztest/ipcserverlistener_fuzzer/ipc_server_listener_fuzzer.cpp @@ -37,7 +37,6 @@ void IpcServerListenerFuzzTest(const uint8_t* data, size_t size) std::shared_ptr ipcServerListener = std::make_shared(); ipcServerListener->SendRequest(cmdCode, req, rsp); - ipcServerListener->SendAll(cmdCode, req, rsp); } } } diff --git a/test/servicesfuzztest/ipcserverstub_fuzzer/ipc_server_stub_fuzzer.cpp b/test/servicesfuzztest/ipcserverstub_fuzzer/ipc_server_stub_fuzzer.cpp index 3f134f4d0..7d1666c72 100644 --- a/test/servicesfuzztest/ipcserverstub_fuzzer/ipc_server_stub_fuzzer.cpp +++ b/test/servicesfuzztest/ipcserverstub_fuzzer/ipc_server_stub_fuzzer.cpp @@ -52,9 +52,11 @@ void IpcServerStubFuzzTest(const uint8_t* data, size_t size) IpcServerStub::GetInstance().Init(); IpcServerStub::GetInstance().OnRemoteRequest(code, data1, reply, option); IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); - IpcServerStub::GetInstance().GetDmListener(pkgName); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + IpcServerStub::GetInstance().GetDmListener(processInfo); IpcServerStub::GetInstance().SendCmd(code, req, rsp); - IpcServerStub::GetInstance().GetAllPkgName(); + IpcServerStub::GetInstance().GetAllProcessInfo(); IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); } } diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index db40dd891..860d53862 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -2282,9 +2282,10 @@ HWTEST_F(DeviceManagerServiceTest, SendServiceUnBindBroadCast_001, testing::ext: HWTEST_F(DeviceManagerServiceTest, ClearDiscoveryCache_001, testing::ext::TestSize.Level0) { - std::string pkgName = "pkgName001"; + ProcessInfo processInfo; + processInfo.pkgName = "pkgName001"; DeviceManagerService::GetInstance().InitDMServiceListener(); - DeviceManagerService::GetInstance().ClearDiscoveryCache(pkgName); + DeviceManagerService::GetInstance().ClearDiscoveryCache(processInfo); EXPECT_NE(DeviceManagerService::GetInstance().discoveryMgr_, nullptr); DeviceManagerService::GetInstance().UninitDMServiceListener(); } diff --git a/test/unittest/UTTest_device_manager_service_listener.cpp b/test/unittest/UTTest_device_manager_service_listener.cpp index 77a8944df..c8d1de00c 100644 --- a/test/unittest/UTTest_device_manager_service_listener.cpp +++ b/test/unittest/UTTest_device_manager_service_listener.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022-2023 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -19,6 +19,7 @@ #include "dm_anonymous.h" #include "dm_constants.h" +#include "dm_device_info.h" #include "dm_log.h" #include "ipc_notify_auth_result_req.h" #include "ipc_notify_device_found_req.h" @@ -55,14 +56,17 @@ namespace { HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceStateChange_001, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; + ProcessInfo processInfo; + processInfo.pkgName = "com.ohos.helloworld"; + processInfo.userId = 100; + processInfo.tokenId = 123456; DmDeviceState state = DEVICE_STATE_ONLINE; DmDeviceInfo info = { .deviceId = "asdad", .deviceName = "asda", .deviceTypeId = 1, }; - listener_->OnDeviceStateChange(pkgName, state, info); + listener_->OnDeviceStateChange(processInfo, state, info); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), false); } @@ -76,14 +80,17 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceStateChange_001, testing::ext HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceStateChange_002, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "ohos.distributedhardware.devicemanager"; + ProcessInfo processInfo; + processInfo.pkgName = "ohos.distributedhardware.devicemanager"; + processInfo.userId = 100; + processInfo.tokenId = 123456; DmDeviceState state = DEVICE_STATE_OFFLINE; DmDeviceInfo info = { .deviceId = "asdad", .deviceName = "asda", .deviceTypeId = 1, }; - listener_->OnDeviceStateChange(pkgName, state, info); + listener_->OnDeviceStateChange(processInfo, state, info); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } diff --git a/test/unittest/UTTest_dm_pin_holder.h b/test/unittest/UTTest_dm_pin_holder.h index 1434de194..1de806249 100644 --- a/test/unittest/UTTest_dm_pin_holder.h +++ b/test/unittest/UTTest_dm_pin_holder.h @@ -23,6 +23,7 @@ #include #include "mock/mock_ipc_client_proxy.h" #include "device_manager.h" +#include "dm_device_info.h" #include "dm_single_instance.h" #include "idevice_manager_service_listener.h" @@ -60,9 +61,10 @@ public: { } - void OnDeviceStateChange(const std::string &pkgName, const DmDeviceState &state, const DmDeviceInfo &info) override + void OnDeviceStateChange(const ProcessInfo &processInfo, const DmDeviceState &state, + const DmDeviceInfo &info) override { - (void)pkgName; + (void)processInfo; (void)state; (void)info; } diff --git a/test/unittest/UTTest_ipc_server_listener.cpp b/test/unittest/UTTest_ipc_server_listener.cpp index 60d60f42f..fb83d8974 100644 --- a/test/unittest/UTTest_ipc_server_listener.cpp +++ b/test/unittest/UTTest_ipc_server_listener.cpp @@ -279,87 +279,14 @@ HWTEST_F(IpcServerListenerTest, SendRequest_007, testing::ext::TestSize.Level0) } /** - * @tc.name: SendAll_001 - * @tc.desc: 1. set cmdCode -1 - * set req not null - * set rsp not null - * check ret is ERR_DM_UNSUPPORTED_IPC_COMMAND - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(IpcServerListenerTest, SendAll_001, testing::ext::TestSize.Level0) -{ - // set cmdCode not null - int32_t cmdCode = -1; - // set req not null - std::shared_ptr req = std::make_shared(); - // set rsp not null - std::shared_ptr rsp = std::make_shared(); - std::shared_ptr ipcServerListener = std::make_shared(); - int ret = ipcServerListener->SendAll(cmdCode, req, rsp); - // check ret is ERR_DM_UNSUPPORTED_IPC_COMMAND - ASSERT_EQ(ret, ERR_DM_UNSUPPORTED_IPC_COMMAND); -} - -/** - * @tc.name: SendAll_002 - * @tc.desc: 1. set cmdCode 999 - * set req not null - * set rsp not null - * check ret is ERR_DM_UNSUPPORTED_IPC_COMMAND - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(IpcServerListenerTest, SendAll_002, testing::ext::TestSize.Level0) -{ - // set cmdCode not null - int32_t cmdCode = 999; - // set req not null - std::shared_ptr req = std::make_shared(); - // set rsp not null - std::shared_ptr rsp = std::make_shared(); - std::shared_ptr ipcServerListener = std::make_shared(); - int ret = ipcServerListener->SendAll(cmdCode, req, rsp); - // check ret is ERR_DM_UNSUPPORTED_IPC_COMMAND - ASSERT_EQ(ret, ERR_DM_UNSUPPORTED_IPC_COMMAND); -} - -/** - * @tc.name: SendAll_003 - * @tc.desc: 1. set cmdCode SERVER_DEVICE_STATE_NOTIFY - * set req not null - * set rsp not null - * check ret is DM_OK - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(IpcServerListenerTest, SendAll_003, testing::ext::TestSize.Level0) -{ - // set cmdCode not null - int32_t cmdCode = SERVER_DEVICE_STATE_NOTIFY; - // set req not null - std::shared_ptr req = std::make_shared(); - // set rsp not null - std::shared_ptr rsp = std::make_shared(); - std::shared_ptr ipcServerListener = std::make_shared(); - std::string pkgName = "com.ohos.test"; - sptr remoteObject = sptr(new IpcClientStub()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); - IpcServerStub::GetInstance().dmListener_.clear(); - int ret = ipcServerListener->SendAll(cmdCode, req, rsp); - // check ret is DM_OK - ASSERT_EQ(ret, DM_OK); -} - -/** - * @tc.name: GetAllPkgName_001 + * @tc.name: GetAllProcessInfo_001 * @tc.type: FUNC */ -HWTEST_F(IpcServerListenerTest, GetAllPkgName_001, testing::ext::TestSize.Level0) +HWTEST_F(IpcServerListenerTest, GetAllProcessInfo_001, testing::ext::TestSize.Level0) { std::shared_ptr ipcServerListener = std::make_shared(); - std::vector pkgName = ipcServerListener->GetAllPkgName(); - ASSERT_NE(pkgName.empty(), false); + std::vector processInfo = ipcServerListener->GetAllProcessInfo(); + ASSERT_NE(processInfo.empty(), false); } } // namespace } // namespace DistributedHardware diff --git a/test/unittest/UTTest_ipc_server_stub.cpp b/test/unittest/UTTest_ipc_server_stub.cpp index 2bbbecb96..593feaf57 100644 --- a/test/unittest/UTTest_ipc_server_stub.cpp +++ b/test/unittest/UTTest_ipc_server_stub.cpp @@ -486,10 +486,12 @@ HWTEST_F(IpcServerStubTest, GetDmListenerPkgName_001, testing::ext::TestSize.Lev { sptr remote(new IpcClientStub()); std::string pkgName = "com.ohos.GetDmListenerPkgName_001"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; sptr listener = sptr(new IpcClientStub()); - IpcServerStub::GetInstance().dmListener_[pkgName] = listener; - std::string ret = IpcServerStub::GetInstance().GetDmListenerPkgName(remote); - EXPECT_TRUE(ret.empty() || (ret == pkgName)); + IpcServerStub::GetInstance().dmListener_[processInfo] = listener; + ProcessInfo ret = IpcServerStub::GetInstance().GetDmListenerPkgName(remote); + EXPECT_TRUE(ret == nullptr || (ret == processInfo)); IpcServerStub::GetInstance().dmListener_.clear(); } @@ -504,10 +506,11 @@ HWTEST_F(IpcServerStubTest, GetDmListenerPkgName_001, testing::ext::TestSize.Lev HWTEST_F(IpcServerStubTest, GetDmListener_001, testing::ext::TestSize.Level0) { // 1. Set pkgName is com.ohos.test - std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = "com.ohos.test"; sptr ret = nullptr; // 2. Call IpcServerStub UnRegisterDeviceManagerListener - ret = IpcServerStub::GetInstance().GetDmListener(pkgName); + ret = IpcServerStub::GetInstance().GetDmListener(processInfo); // 3. check ret is DM_OK ASSERT_EQ(ret, nullptr); } @@ -524,6 +527,8 @@ HWTEST_F(IpcServerStubTest, GetDmListener_002, testing::ext::TestSize.Level0) { // 1. Set pkgName is com.ohos.test std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; int result = 0; sptr listener = sptr(new IpcClientStub()); // 2. Call IpcServerStub RegisterDeviceManagerListener with param @@ -532,7 +537,7 @@ HWTEST_F(IpcServerStubTest, GetDmListener_002, testing::ext::TestSize.Level0) ASSERT_EQ(result, DM_OK); sptr ret = nullptr; // 2. Call IpcServerStub UnRegisterDeviceManagerListener - ret = IpcServerStub::GetInstance().GetDmListener(pkgName); + ret = IpcServerStub::GetInstance().GetDmListener(processInfo); // 3. check ret is DM_OK ASSERT_NE(ret, nullptr); } @@ -557,8 +562,9 @@ HWTEST_F(IpcServerStubTest, GetDmListener_003, testing::ext::TestSize.Level0) ASSERT_EQ(result, DM_OK); sptr ret = nullptr; // 2. Call IpcServerStub UnRegisterDeviceManagerListener - std::string testPkgName = "test"; - ret = IpcServerStub::GetInstance().GetDmListener(testPkgName); + ProcessInfo processInfo; + processInfo.pkgName = "test"; + ret = IpcServerStub::GetInstance().GetDmListener(processInfo); // 3. check ret is DM_OK ASSERT_EQ(ret, nullptr); } @@ -583,7 +589,9 @@ HWTEST_F(IpcServerStubTest, GetDmListener_004, testing::ext::TestSize.Level0) ASSERT_EQ(result, ERR_DM_POINT_NULL); sptr ret = nullptr; // 2. Call IpcServerStub UnRegisterDeviceManagerListener - ret = IpcServerStub::GetInstance().GetDmListener(pkgName); + ProcessInfo processInfo; + processInfo.pkgName = ""; + ret = IpcServerStub::GetInstance().GetDmListener(processInfo); // 3. check ret is nullptr ASSERT_EQ(ret, nullptr); } @@ -608,7 +616,9 @@ HWTEST_F(IpcServerStubTest, GetDmListener_005, testing::ext::TestSize.Level0) ASSERT_EQ(result, ERR_DM_POINT_NULL); sptr ret = nullptr; // 2. Call IpcServerStub UnRegisterDeviceManagerListener - ret = IpcServerStub::GetInstance().GetDmListener(pkgName); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + ret = IpcServerStub::GetInstance().GetDmListener(processInfo); // 3. check ret is nullptr ASSERT_EQ(ret, nullptr); } @@ -677,14 +687,14 @@ HWTEST_F(IpcServerStubTest, OnAddSystemAbility_002, testing::ext::TestSize.Level } /** - * @tc.name: GetAllPkgName_001 + * @tc.name: GetAllProcessInfo_001 * @tc.type: FUNC */ -HWTEST_F(IpcServerStubTest, GetAllPkgName_001, testing::ext::TestSize.Level0) +HWTEST_F(IpcServerStubTest, GetAllProcessInfo_001, testing::ext::TestSize.Level0) { - std::vector pkgName; - pkgName = IpcServerStub::GetInstance().GetAllPkgName(); - ASSERT_EQ(pkgName.empty(), false); + std::vector processInfo; + processInfo = IpcServerStub::GetInstance().GetAllProcessInfo(); + ASSERT_EQ(processInfo.empty(), false); } /** diff --git a/test/unittest/mock/ipc_server_listener.cpp b/test/unittest/mock/ipc_server_listener.cpp index 0c70d88ae..4db0579fd 100644 --- a/test/unittest/mock/ipc_server_listener.cpp +++ b/test/unittest/mock/ipc_server_listener.cpp @@ -22,13 +22,5 @@ int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr req_ = req; return 0; } - -int32_t IpcServerListener::SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) -{ - (void)cmdCode; - req_ = req; - std::cout << req_->GetPkgName() << "\n"; - return 0; -} } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/mock/ipc_server_listener.h b/test/unittest/mock/ipc_server_listener.h index b3c8e04b9..d13d77a6c 100644 --- a/test/unittest/mock/ipc_server_listener.h +++ b/test/unittest/mock/ipc_server_listener.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2022 Huawei Device Co., Ltd. + * Copyright (c) 2022-2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -18,6 +18,7 @@ #include #include +#include "dm_device_info.h" #include "ipc_req.h" #include "ipc_rsp.h" @@ -35,18 +36,13 @@ public: * @tc.type: FUNC */ int32_t SendRequest(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); + /** - * @tc.name: IpcServerListener::SendAll - * @tc.desc: Ipc server listener send messages - * @tc.type: FUNC - */ - int32_t SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp); - /** - * @tc.name: IpcServerListener::GetAllPkgName + * @tc.name: IpcServerListener::GetAllProcessInfo * @tc.desc: Get All PkgName from stub * @tc.type: FUNC */ - std::vector GetAllPkgName(); + std::vector GetAllProcessInfo(); std::shared_ptr req_; }; } // namespace DistributedHardware -- Gitee From 259fb0743fe0ce561ff1b434c78b0a4af99a9863 Mon Sep 17 00:00:00 2001 From: hwzhangchuang Date: Sat, 2 Nov 2024 16:13:36 +0800 Subject: [PATCH 08/27] add user switch func Signed-off-by: hwzhangchuang --- .../include/multiple_user_connector.h | 12 +++++-- .../src/deviceprofile_connector.cpp | 1 + .../src/multiple_user_connector.cpp | 17 ++++++++++ .../include/device_manager_service_impl.h | 2 +- .../src/device_manager_service_impl.cpp | 22 ++++++++++--- .../service/include/device_manager_service.h | 10 ++++-- .../dm_account_common_event.h | 14 +++++++- .../service/src/device_manager_service.cpp | 28 +++++++++------- .../dm_account_common_event.cpp | 32 ++++++++++++------- 9 files changed, 104 insertions(+), 34 deletions(-) diff --git a/commondependency/include/multiple_user_connector.h b/commondependency/include/multiple_user_connector.h index a1d0ba13d..278b4dcc3 100644 --- a/commondependency/include/multiple_user_connector.h +++ b/commondependency/include/multiple_user_connector.h @@ -47,11 +47,19 @@ public: /** * @tc.name: MultipleUserConnector::GetOhosAccountId - * @tc.desc: Get Current AccountId of the Multiple User Connector + * @tc.desc: Get Current AccountId of current user * @tc.type: FUNC */ static std::string GetOhosAccountId(void); - + + /** + * @brief Get the Ohos Account Id By Userid + * + * @param userId the user id in which account login + * @return std::string the account id + */ + static std::string GetOhosAccountIdByUserid(int32_t userId); + /** * @tc.name: MultipleUserConnector::SetSwitchOldAccountId * @tc.desc: Set Switch Old UserId of the Multiple User Connector diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index 2b750aae9..bfe102b94 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -913,6 +913,7 @@ int32_t DeviceProfileConnector::HandleAccountLogoutEvent(int32_t remoteUserId, c GetAnonyString(localUdid).c_str()); std::vector profiles = GetAccessControlProfile(); int32_t bindType = DM_INVALIED_BINDTYPE; + //TODO: 根据对端退账号的userid清理acl for (const auto &item : profiles) { if (item.GetTrustDeviceId() != remoteUdid) { continue; diff --git a/commondependency/src/multiple_user_connector.cpp b/commondependency/src/multiple_user_connector.cpp index 691cd7f90..bbe556e20 100644 --- a/commondependency/src/multiple_user_connector.cpp +++ b/commondependency/src/multiple_user_connector.cpp @@ -70,6 +70,23 @@ std::string MultipleUserConnector::GetOhosAccountId(void) #endif } +std::string MultipleUserConnector::GetOhosAccountIdByUserid(int32_t userId) +{ +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) + return ""; +#elif OS_ACCOUNT_PART_EXISTS + OhosAccountInfo accountInfo; + ErrCode ret = OhosAccountKits::GetInstance().GetOhosAccountInfoByUserId(userId, accountInfo); + if (ret != 0 || accountInfo.uid_ == "") { + LOGE("GetOhosAccountId error ret: %{public}d", ret); + return ""; + } + return accountInfo.uid_; +#else + return ""; +#endif +} + std::string MultipleUserConnector::GetOhosAccountName(void) { #if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 72c6c12fc..6b67aac46 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -147,7 +147,7 @@ private: void HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId); void HandleUserRemoved(int32_t preUserId); DmAuthForm ConvertBindTypeToAuthForm(int32_t bindType); - void HandleUserSwitched(int32_t switchUserId); + void HandleUserSwitched(int32_t currentUserId, int32_t beforeUserId); private: std::shared_ptr authMgr_; diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 18fb5c548..545bfd393 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -692,12 +692,22 @@ void DeviceManagerServiceImpl::HandleUserRemoved(int32_t preUserId) hiChainConnector_->DeleteAllGroup(preUserId); } -void DeviceManagerServiceImpl::HandleUserSwitched(int32_t switchUserId) +void DeviceManagerServiceImpl::HandleUserSwitched(int32_t currentUserId, int32_t beforeUserId) { - LOGI("switchUserId: %{public}d.", switchUserId); - DeviceProfileConnector::GetInstance().DeleteAclForUserRemoved(switchUserId); - CHECK_NULL_VOID(hiChainConnector_); - hiChainConnector_->DeleteP2PGroup(switchUserId); + LOGI("currentUserId: %{public}d, beforeUserId: %{public}d", switchUserId, beforeUserId); + //DeviceProfileConnector::GetInstance().DeleteAclForUserRemoved(switchUserId); + //CHECK_NULL_VOID(hiChainConnector_); + //hiChainConnector_->DeleteP2PGroup(switchUserId); + std::string curUserAccountId = MultipleUserConnector::GetOhosAccountIdByUserId(currentUserId); + std::string befUserAccountId = MultipleUserConnector::GetOhosAccountIdByUserId(beforeUserId); + + //TODO1: ѯDPŹϵ + + //TODO2: olduseridĿŹϵstatusΪ0 + + //TODO3: newuseridĿŹϵstatusΪ1 + + //TODO4: DPŹϵ } void DeviceManagerServiceImpl::ScreenCommonEventCallback(std::string commonEventType) @@ -761,11 +771,13 @@ void DeviceManagerServiceImpl::HandleAccountLogoutEvent(int32_t remoteUserId, co return; } CHECK_NULL_VOID(authMgr_); + //TODO: ݶԶ˺ŵuseridȺ authMgr_->DeleteGroup(DM_PKG_NAME, remoteUdid); CHECK_NULL_VOID(listener_); std::string uuid = ""; SoftbusCache::GetInstance().GetUuidByUdid(remoteUdid, uuid); listener_->OnDeviceTrustChange(remoteUdid, uuid, ConvertBindTypeToAuthForm(bindType)); + //TODOϱ߼߸Ӧļ } DmAuthForm DeviceManagerServiceImpl::ConvertBindTypeToAuthForm(int32_t bindType) diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index 3490e79ee..cffc8ec64 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -218,7 +218,7 @@ private: #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) void SubscribeAccountCommonEvent(); - void AccountCommonEventCallback(int32_t userId, const std::string commonEventType); + void AccountCommonEventCallback(const std::string commonEventType, int32_t currentUserId, int32_t beforeUserId); void SubscribeScreenLockEvent(); void ScreenCommonEventCallback(std::string commonEventType); void ConvertUdidHashToAnoyDeviceId(DmDeviceInfo &deviceInfo); @@ -226,7 +226,13 @@ private: int32_t GetUdidHashByAnoyDeviceId(const std::string &anoyDeviceId, std::string &udidHash); void HandleAccountLogout(int32_t userId, const std::string &accountId); void HandleUserRemoved(int32_t preUserId); - void HandleUserSwitched(int32_t switchUserId); + /** + * @brief process the user switch + * + * @param currentUserId the user id which switched to foreground. + * @param beforeUserId the user id which switched to backend. + */ + void HandleUserSwitched(int32_t currentUserId, int32_t beforeUserId); #if defined(SUPPORT_BLUETOOTH) || defined(SUPPORT_WIFI) void SubscribePublishCommonEvent(); void QueryDependsSwitchState(); diff --git a/services/service/include/publishcommonevent/dm_account_common_event.h b/services/service/include/publishcommonevent/dm_account_common_event.h index b0a9e6878..640bf206f 100644 --- a/services/service/include/publishcommonevent/dm_account_common_event.h +++ b/services/service/include/publishcommonevent/dm_account_common_event.h @@ -33,7 +33,19 @@ namespace DistributedHardware { using OHOS::EventFwk::CommonEventData; using OHOS::EventFwk::CommonEventSubscriber; using OHOS::EventFwk::CommonEventSubscribeInfo; -using AccountEventCallback = std::function; +/** + * @brief account event callback define, fun(event_type, current userid, before userid) + * first param, accont event + * second param, the current userid + * third param, the userid before. + * first param | second param | third param + * ------------------------------------------ + * COMMON_EVENT_USER_SWITCHED | switch target user id | the user id before switch + * COMMON_EVENT_USER_REMOVED | -1 | the user id removed + * COMMON_EVENT_HWID_LOGOUT | logout in witch user id | logout in witch user id + * COMMON_EVENT_HWID_LOGIN | login in witch user id | login in witch user id + */ +using AccountEventCallback = std::function; class DmAccountEventSubscriber : public CommonEventSubscriber { public: diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index bfbe8dc3f..f67c20c1a 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1600,8 +1600,8 @@ void DeviceManagerService::SubscribeAccountCommonEvent() if (accountCommonEventManager_ == nullptr) { accountCommonEventManager_ = std::make_shared(); } - AccountEventCallback callback = [=](const auto &arg1, const auto &arg2) { - this->AccountCommonEventCallback(arg1, arg2); + AccountEventCallback callback = [=](const auto &eventType, const auto ¤tUserId, const auto &beforeUserId) { + this->AccountCommonEventCallback(eventType, currentUserId, beforeUserId); }; std::vector AccountCommonEventVec; AccountCommonEventVec.emplace_back(CommonEventSupport::COMMON_EVENT_USER_SWITCHED); @@ -1629,20 +1629,26 @@ void DeviceManagerService::SubscribeScreenLockEvent() return; } -void DeviceManagerService::AccountCommonEventCallback(int32_t userId, const std::string commonEventType) +void DeviceManagerService::AccountCommonEventCallback(const std::string commonEventType, int32_t currentUserId, + int32_t beforeUserId) { - LOGI("CommonEventType: %{public}s, userId: %{public}d", commonEventType.c_str(), userId); + LOGI("CommonEventType: %{public}s, currentUserId: %{public}d, beforeUserId: %{public}d", commonEventType.c_str(), + currentUserId, beforeUserId); if (commonEventType == CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { if (MultipleUserConnector::GetSwitchOldUserId() > 0 && - (userId != MultipleUserConnector::GetSwitchOldUserId())) { + (currentUserId != MultipleUserConnector::GetSwitchOldUserId())) { HandleUserSwitched(MultipleUserConnector::GetSwitchOldUserId()); } - MultipleUserConnector::SetSwitchOldUserId(userId); + MultipleUserConnector::SetSwitchOldUserId(currentUserId); MultipleUserConnector::SetSwitchOldAccountId(MultipleUserConnector::GetOhosAccountId()); MultipleUserConnector::SetSwitchOldAccountName(MultipleUserConnector::GetOhosAccountName()); if (IsDMServiceAdapterLoad()) { - dmServiceImplExt_->AccountUserSwitched(userId, MultipleUserConnector::GetOhosAccountId()); + dmServiceImplExt_->AccountUserSwitched(currentUserId, MultipleUserConnector::GetOhosAccountId()); } + + //TODO: лbeforeUserId߼ + + //TODO: лcurrentUserId߼ߣNOҪûߣܱ߼ߣ } else if (commonEventType == CommonEventSupport::COMMON_EVENT_HWID_LOGIN) { MultipleUserConnector::SetSwitchOldAccountId(MultipleUserConnector::GetOhosAccountId()); MultipleUserConnector::SetSwitchOldAccountName(MultipleUserConnector::GetOhosAccountName()); @@ -1650,7 +1656,7 @@ void DeviceManagerService::AccountCommonEventCallback(int32_t userId, const std: HandleAccountLogout(MultipleUserConnector::GetCurrentAccountUserID(), MultipleUserConnector::GetSwitchOldAccountId()); } else if (commonEventType == CommonEventSupport::COMMON_EVENT_USER_REMOVED) { - HandleUserRemoved(userId); + HandleUserRemoved(beforeUserId); } else { LOGE("Invalied account common event."); } @@ -1687,11 +1693,11 @@ void DeviceManagerService::HandleAccountLogout(int32_t userId, const std::string } } -void DeviceManagerService::HandleUserSwitched(int32_t switchUserId) +void DeviceManagerService::HandleUserSwitched(int32_t currentUserId, int32_t beforeUserId) { - LOGI("switchUserId: %{public}d.", switchUserId); + LOGI("currentUserId: %{public}d. beforeUserId: %{public}d", currentUserId, beforeUserId); if (IsDMServiceImplReady()) { - dmServiceImpl_->HandleUserSwitched(switchUserId); + dmServiceImpl_->HandleUserSwitched(currentUserId, beforeUserId); } } diff --git a/services/service/src/publishcommonevent/dm_account_common_event.cpp b/services/service/src/publishcommonevent/dm_account_common_event.cpp index 50ca53d73..cdbc822d2 100644 --- a/services/service/src/publishcommonevent/dm_account_common_event.cpp +++ b/services/service/src/publishcommonevent/dm_account_common_event.cpp @@ -136,27 +136,35 @@ bool DmAccountCommonEventManager::UnsubscribeAccountCommonEvent() void DmAccountEventSubscriber::OnReceiveEvent(const CommonEventData &data) { std::string receiveEvent = data.GetWant().GetAction(); - LOGI("Received account event: %{public}s", receiveEvent.c_str()); - int32_t userId = data.GetCode(); - bool accountValiedEvent = false; - if (receiveEvent == EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED || - receiveEvent == EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED) { - userId = data.GetCode(); - accountValiedEvent = true; + int32_t currentUserId = -1; + int32_t beforeUserId = -1; + bool accountValidEvent = false; + + if (receiveEvent == EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { + currentUserId = data.GetCode(); + beforeUserId = std::atoi(data.GetWant().GetStringParam("oldId").c_str()); + accountValidEvent = true; + } + if (receiveEvent == EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED) { + beforeUserId = data.GetCode(); + accountValidEvent = true; } if (receiveEvent == EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT || receiveEvent == EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGIN) { - userId = data.GetWant().GetIntParam("userId", 0); - accountValiedEvent = true; + currentUserId = data.GetWant().GetIntParam("userId", 0); + beforeUserId = currentUserId; + accountValidEvent = true; } - if (userId <= 0 || !accountValiedEvent) { + LOGI("Received account event: %{public}s, currentUserId: %{public}d, beforeUserId: %{public}d", + receiveEvent.c_str(), currentUserId, beforeUserId); + if (!accountValidEvent) { LOGE("Invalied account type event."); return; } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - ffrt::submit([=]() { callback_(userId, receiveEvent); }); + ffrt::submit([=]() { callback_(receiveEvent, currentUserId, beforeUserId); }); #else - std::thread dealThread([=]() { callback_(userId, receiveEvent); }); + std::thread dealThread([=]() { callback_(receiveEvent, currentUserId, beforeUserId); }); int32_t ret = pthread_setname_np(dealThread.native_handle(), DEAL_THREAD); if (ret != DM_OK) { LOGE("dealThread setname failed."); -- Gitee From bfc2b4b1f2d93cbcee55dbb2dfb63e794294e360 Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Mon, 4 Nov 2024 09:44:38 +0800 Subject: [PATCH 09/27] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E7=BC=96=E8=AF=91?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/deviceprofile_connector.h | 5 +- .../include/multiple_user_connector.h | 2 +- .../src/deviceprofile_connector.cpp | 18 ++++--- .../src/multiple_user_connector.cpp | 5 +- .../dependency/softbus/softbus_connector.h | 6 +-- .../device_manager_service_impl_lite.h | 2 +- .../src/authentication/dm_auth_manager.cpp | 32 ++++++++---- .../dependency/softbus/softbus_connector.cpp | 4 +- .../src/device_manager_service_impl.cpp | 18 +++---- .../src/device_manager_service_impl_lite.cpp | 3 +- .../devicestate/dm_device_state_manager.cpp | 22 ++++---- .../include/device_manager_service_listener.h | 2 +- .../include/discovery/discovery_manager.h | 2 +- .../include/idevice_manager_service_impl.h | 2 +- .../service/src/device_manager_service.cpp | 8 +-- .../src/device_manager_service_listener.cpp | 52 ++++++++++--------- .../src/discovery/discovery_manager.cpp | 4 +- .../src/ipc/standard/ipc_cmd_parser.cpp | 8 ++- .../src/ipc/standard/ipc_server_listener.cpp | 2 +- .../src/ipc/standard/ipc_server_stub.cpp | 3 +- utils/include/appInfo/lite/app_manager.h | 1 + utils/include/appInfo/standard/app_manager.h | 1 + utils/src/appInfo/lite/app_manager.cpp | 10 +++- utils/src/appInfo/standard/app_manager.cpp | 2 +- 24 files changed, 122 insertions(+), 92 deletions(-) diff --git a/commondependency/include/deviceprofile_connector.h b/commondependency/include/deviceprofile_connector.h index 6c79d6af8..9db34515e 100644 --- a/commondependency/include/deviceprofile_connector.h +++ b/commondependency/include/deviceprofile_connector.h @@ -78,7 +78,7 @@ typedef struct DmAccessee { typedef struct DmOfflineParam { uint32_t bindType; - std::vector processVec; + std::vector processVec; int32_t leftAclNumber; } DmOfflineParam; @@ -110,7 +110,8 @@ public: void DeleteAclForUserRemoved(int32_t userId); DmOfflineParam DeleteAccessControlList(const std::string &pkgName, const std::string &localDeviceId, const std::string &remoteDeviceId, int32_t bindLevel); - std::vector GetProcessInfoFromAcl(std::string &localDeviceId, std::string &targetDeviceId); + std::vector GetProcessInfoFromAcl(std::string &localDeviceId, + std::string &targetDeviceId); bool CheckIdenticalAccount(int32_t userId, const std::string &accountId); bool CheckSrcDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId); bool CheckSinkDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId); diff --git a/commondependency/include/multiple_user_connector.h b/commondependency/include/multiple_user_connector.h index 278b4dcc3..e5331623b 100644 --- a/commondependency/include/multiple_user_connector.h +++ b/commondependency/include/multiple_user_connector.h @@ -97,7 +97,7 @@ public: static void GetSelfTokenIdAndUserId(uint32_t &tokenId, int32_t &userId); static void GetTokenIdAndUserId(uint32_t &tokenId, int32_t &userId); static std::string GetOhosAccountIdByUserId(int32_t userId); - static int32_t GetForegroundUsers(std::vector userVec); + static int32_t GetForegroundUsers(std::vector &userVec); static int32_t GetForegroundUser(void); private: diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index bfe102b94..8393b3af3 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -362,14 +362,14 @@ std::vector DeviceProfileConnector::SyncAclByBindType(std::string pkgNa return bindType; } -std::vector DeviceProfileConnector::GetProcessInfoFromAcl(std::string &localDeviceId, - std::string &targetDeviceId) +std::vector DeviceProfileConnector::GetProcessInfoFromAcl( + std::string &localDeviceId, std::string &targetDeviceId) { LOGI("Start."); std::vector profiles = GetAccessControlProfileByUserId(MultipleUserConnector::GetForegroundUser()); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); - std::vector processInfoVec; + std::vector processInfoVec; for (auto &item : profiles) { if (item.GetTrustDeviceId() != targetDeviceId || item.GetStatus() != ACTIVE) { continue; @@ -378,7 +378,7 @@ std::vector DeviceProfileConnector::GetProcessInfoFromAcl(std::stri item.GetAccessee().GetAccesseeDeviceId() == targetDeviceId) || (item.GetAccesser().GetAccesserDeviceId() == targetDeviceId && item.GetAccessee().GetAccesseeDeviceId() == localDeviceId)) { - ProcessInfo processInfo; + OHOS::DistributedHardware::ProcessInfo processInfo; processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); processInfo.userId = item.GetAccesser().GetAccesserUserId(); processInfo.tokenId = item.GetAccesser().GetAccesserTokenId(); @@ -410,17 +410,21 @@ DmOfflineParam DeviceProfileConnector::GetOfflineParamFromAcl(std::string trustD priority = DEVICE_PEER_TO_PEER_TYPE; } else if (item.GetBindLevel() == DEVICE && item.GetAuthenticationType() == ALLOW_AUTH_ONCE) { priority = DEVICE_PEER_TO_PEER_TYPE; - ProcessInfo processInfo; + OHOS::DistributedHardware::ProcessInfo processInfo; processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); processInfo.userId = item.GetAccesser().GetAccesserUserId(); processInfo.tokenId = item.GetAccesser().GetAccesserTokenId(); - offlineParam.pkgNameVec.push_back(processInfo); + offlineParam.processVec.push_back(processInfo); } else if ((item.GetAccesser().GetAccesserDeviceId() == requestDeviceId && item.GetAccessee().GetAccesseeDeviceId() == trustDeviceId) || (item.GetAccesser().GetAccesserDeviceId() == trustDeviceId && item.GetAccessee().GetAccesseeDeviceId() == requestDeviceId)) { priority = APP_PEER_TO_PEER_TYPE; - offlineParam.pkgNameVec.push_back(item.GetAccesser().GetAccesserBundleName()); + OHOS::DistributedHardware::ProcessInfo processInfo; + processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.userId = item.GetAccesser().GetAccesserUserId(); + processInfo.tokenId = item.GetAccesser().GetAccesserTokenId(); + offlineParam.processVec.push_back(processInfo); } if (priority > offlineParam.bindType) { offlineParam.bindType = priority; diff --git a/commondependency/src/multiple_user_connector.cpp b/commondependency/src/multiple_user_connector.cpp index bbe556e20..5ae02fec0 100644 --- a/commondependency/src/multiple_user_connector.cpp +++ b/commondependency/src/multiple_user_connector.cpp @@ -15,6 +15,7 @@ #include "multiple_user_connector.h" +#include "dm_constants.h" #include "dm_log.h" #include "ipc_skeleton.h" #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) @@ -132,9 +133,9 @@ void MultipleUserConnector::GetTokenIdAndUserId(uint32_t &tokenId, int32_t &user #if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) return; #elif OS_ACCOUNT_PART_EXISTS - ErrCode ret = OsAccountManager::GetOsAccountLocalldFromUid(uid, userId); + ErrCode ret = OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId); if (ret != 0) { - LOGE("GetOsAccountLocalldFromUid error ret: %{public}d", ret); + LOGE("GetOsAccountLocalIdFromUid error ret: %{public}d", ret); return; } return; diff --git a/services/implementation/include/dependency/softbus/softbus_connector.h b/services/implementation/include/dependency/softbus/softbus_connector.h index 6ccdf0f40..8991eeb90 100644 --- a/services/implementation/include/dependency/softbus/softbus_connector.h +++ b/services/implementation/include/dependency/softbus/softbus_connector.h @@ -145,8 +145,8 @@ public: void HandleDeviceOffline(std::string deviceId); void SetProcessInfo(ProcessInfo processInfo); bool CheckIsOnline(const std::string &targetDeviceId); - void SetPkgNameVec(std::vector processInfoVec); - std::vector GetProcessInfo(); + void SetProcessInfoVec(std::vector processInfoVec); + std::vector GetProcessInfo(); void ClearProcessInfo(); DmDeviceInfo GetDeviceInfoByDeviceId(const std::string &deviceId); void DeleteOffLineTimer(std::string &udidHash); @@ -176,7 +176,7 @@ private: std::shared_ptr deviceStateManagerCallback_; static std::queue discoveryDeviceIdQueue_; static std::unordered_map deviceUdidMap_; - static std::vector processInfoVec_; + static std::vector processInfoVec_; static std::mutex discoveryCallbackMutex_; static std::mutex discoveryDeviceInfoMutex_; static std::mutex deviceUdidLocks_; diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index 18d643c3d..e6b954f9f 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -135,7 +135,7 @@ public: void HandleIdentAccountLogout(const std::string &udid, int32_t userId, const std::string &accountId); void HandleUserRemoved(int32_t preUserId); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); - void HandleUserSwitched(int32_t switchUserId); + void HandleUserSwitched(int32_t currentUserId, int32_t beforeUserId); int32_t StopAuthenticateDevice(const std::string &pkgName); void HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode); int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId); diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 1e551e75f..3c14707b6 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -352,13 +352,17 @@ int32_t DmAuthManager::DeleteAcl(const std::string &pkgName, const std::string & } if (bindLevel == APP && offlineParam.leftAclNumber != 0) { LOGI("The pkgName unbind app-level type leftAclNumber not zero."); - softbusConnector_->SetProcessInfo(pkgName);//todo + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + softbusConnector_->SetProcessInfo(processInfo);//todo softbusConnector_->HandleDeviceOffline(remoteUdid); return DM_OK; } if (bindLevel == APP && offlineParam.leftAclNumber == 0) { LOGI("The pkgName unbind app-level type leftAclNumber is zero."); - softbusConnector_->SetProcessInfo(pkgName);//todo + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + softbusConnector_->SetProcessInfo(processInfo);//todo hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); return DM_OK; } @@ -1948,7 +1952,9 @@ void DmAuthManager::SrcAuthDeviceFinish() authResponseContext_->haveCredential)) { if ((authResponseContext_->bindLevel == APP || authResponseContext_->bindLevel == SERVICE) && !authResponseContext_->isIdenticalAccount && !authResponseContext_->hostPkgName.empty()) { - softbusConnector_->SetProcessInfo(authResponseContext_->hostPkgName);//todo + ProcessInfo processInfo; + processInfo.pkgName = authResponseContext_->hostPkgName; + softbusConnector_->SetProcessInfo(processInfo);//todo } softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK)); @@ -1962,7 +1968,9 @@ void DmAuthManager::SrcAuthDeviceFinish() authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT); if ((authResponseContext_->bindLevel == APP || authResponseContext_->bindLevel == SERVICE) && !authResponseContext_->isIdenticalAccount && !authResponseContext_->hostPkgName.empty()) { - softbusConnector_->SetProcessInfo(authResponseContext_->hostPkgName);//todo + ProcessInfo processInfo; + processInfo.pkgName = authResponseContext_->hostPkgName; + softbusConnector_->SetProcessInfo(processInfo);//todo } softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); authRequestState_->TransitionTo(std::make_shared()); @@ -1991,7 +1999,9 @@ void DmAuthManager::SinkAuthDeviceFinish() } if (authResponseContext_->isOnline) { LOGI("The device is online."); - softbusConnector_->SetProcessInfo(authResponseContext_->hostPkgName);//todo + ProcessInfo processInfo; + processInfo.pkgName = authResponseContext_->hostPkgName; + softbusConnector_->SetProcessInfo(processInfo);//todo softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); } } @@ -2116,9 +2126,9 @@ void DmAuthManager::ProcRespNegotiateExt(const int32_t &sessionId) MultipleUserConnector::SetSwitchOldAccountId(authResponseContext_->localAccountId); MultipleUserConnector::SetSwitchOldUserId(authResponseContext_->localUserId); authResponseContext_->isIdenticalAccount = false; - if (authResponseContext_->localAccountId == accountId && accountId != "ohosAnonymousUid") { - authResponseContext_->isIdenticalAccount = true; - } + // if (authResponseContext_->localAccountId == accountId && accountId != "ohosAnonymousUid") {//todo + // authResponseContext_->isIdenticalAccount = true; + // } authResponseContext_->remoteAccountId = authResponseContext_->localAccountId; authResponseContext_->remoteUserId = authResponseContext_->localUserId; char localDeviceId[DEVICE_UUID_LENGTH] = {0}; @@ -2509,8 +2519,8 @@ std::string DmAuthManager::GetBundleName(nlohmann::json &jsonObject) if (!jsonObject.is_discarded() && IsString(jsonObject, BUNDLE_NAME_KEY)) { return jsonObject[BUNDLE_NAME_KEY].get(); } - bool isSystemSA; - std::string bundleName + bool isSystemSA = false; + std::string bundleName; AppManager::GetInstance().GetCallerName(isSystemSA, bundleName); return bundleName; } @@ -2527,7 +2537,7 @@ int32_t DmAuthManager::GetBinderInfo() authResponseContext_->localUserId = userVec[0]; authResponseContext_->localAccountId = MultipleUserConnector::GetOhosAccountIdByUserId(authResponseContext_->localUserId); - if (authResponseContext_->bundleName.isEmpty()) { + if (authResponseContext_->bundleName.empty()) { return DM_OK; } ret = AppManager::GetInstance(). diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index 8600ad671..36096955f 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -48,7 +48,7 @@ std::map> SoftbusConnect std::map> SoftbusConnector::publishCallbackMap_ = {}; std::queue SoftbusConnector::discoveryDeviceIdQueue_ = {}; std::unordered_map SoftbusConnector::deviceUdidMap_ = {}; -std::vector SoftbusConnector::processInfoVec_ = {}; +std::vector SoftbusConnector::processInfoVec_ = {}; std::mutex SoftbusConnector::discoveryCallbackMutex_; std::mutex SoftbusConnector::discoveryDeviceInfoMutex_; std::mutex SoftbusConnector::deviceUdidLocks_; @@ -684,7 +684,7 @@ void SoftbusConnector::SetProcessInfoVec(std::vector processInfoVec processInfoVec_ = processInfoVec; } -std::vector SoftbusConnector::GetProcessInfo() +std::vector SoftbusConnector::GetProcessInfo() { LOGI("In"); std::lock_guard lock(processInfoVecMutex_); diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 545bfd393..5b4beefd0 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -225,7 +225,7 @@ void DeviceManagerServiceImpl::HandleOffline(DmDeviceState devState, DmDeviceInf deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); } else if (offlineParam.bindType == APP_PEER_TO_PEER_TYPE) { LOGI("The offline device is app-level bind type."); - softbusConnector_->SetProcessVec(offlineParam.processVec); + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); } if (offlineParam.leftAclNumber == 0) { @@ -694,20 +694,20 @@ void DeviceManagerServiceImpl::HandleUserRemoved(int32_t preUserId) void DeviceManagerServiceImpl::HandleUserSwitched(int32_t currentUserId, int32_t beforeUserId) { - LOGI("currentUserId: %{public}d, beforeUserId: %{public}d", switchUserId, beforeUserId); + LOGI("currentUserId: %{public}d, beforeUserId: %{public}d", currentUserId, beforeUserId); //DeviceProfileConnector::GetInstance().DeleteAclForUserRemoved(switchUserId); //CHECK_NULL_VOID(hiChainConnector_); //hiChainConnector_->DeleteP2PGroup(switchUserId); std::string curUserAccountId = MultipleUserConnector::GetOhosAccountIdByUserId(currentUserId); std::string befUserAccountId = MultipleUserConnector::GetOhosAccountIdByUserId(beforeUserId); - //TODO1: ѯDPŹϵ + //TODO1: ��ѯDP���Ź�ϵ - //TODO2: olduseridĿŹϵstatusΪ0 + //TODO2: ��olduserid�Ŀ��Ź�ϵstatus����Ϊ0 - //TODO3: newuseridĿŹϵstatusΪ1 + //TODO3: ��newuserid�Ŀ��Ź�ϵstatus����Ϊ1 - //TODO4: DPŹϵ + //TODO4: ����DP���Ź�ϵ } void DeviceManagerServiceImpl::ScreenCommonEventCallback(std::string commonEventType) @@ -771,13 +771,13 @@ void DeviceManagerServiceImpl::HandleAccountLogoutEvent(int32_t remoteUserId, co return; } CHECK_NULL_VOID(authMgr_); - //TODO: ݶԶ˺ŵuseridȺ + //TODO: ���ݶԶ����˺ŵ�userid����Ⱥ�� authMgr_->DeleteGroup(DM_PKG_NAME, remoteUdid); CHECK_NULL_VOID(listener_); std::string uuid = ""; SoftbusCache::GetInstance().GetUuidByUdid(remoteUdid, uuid); listener_->OnDeviceTrustChange(remoteUdid, uuid, ConvertBindTypeToAuthForm(bindType)); - //TODOϱ߼߸Ӧļ + //TODO���ϱ��߼������߸���Ӧ�ļ����� } DmAuthForm DeviceManagerServiceImpl::ConvertBindTypeToAuthForm(int32_t bindType) @@ -851,7 +851,7 @@ void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devI return; } else if (bindType == IDENTICAL_ACCOUNT_TYPE || bindType == DEVICE_PEER_TO_PEER_TYPE || bindType == DEVICE_ACROSS_ACCOUNT_TYPE) { - softbusConnector_->ClearPkgName(); + softbusConnector_->ClearProcessInfo(); LOGI("networkId: %{public}s", GetAnonyString(devInfo.networkId).c_str()); } else if (bindType == APP_PEER_TO_PEER_TYPE || bindType == APP_ACROSS_ACCOUNT_TYPE) { std::vector processInfoVec = diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index 5528bd9cf..46ed922ce 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -513,9 +513,10 @@ void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devI return; } -void DeviceManagerServiceImpl::HandleUserSwitched(int32_t switchUserId) +void DeviceManagerServiceImpl::HandleUserSwitched(int32_t currentUserId, int32_t beforeUserId) { (void)switchUserId; + (void)beforeUserId; return; } diff --git a/services/implementation/src/devicestate/dm_device_state_manager.cpp b/services/implementation/src/devicestate/dm_device_state_manager.cpp index 86d42fa58..86141a46c 100644 --- a/services/implementation/src/devicestate/dm_device_state_manager.cpp +++ b/services/implementation/src/devicestate/dm_device_state_manager.cpp @@ -111,7 +111,7 @@ void DmDeviceStateManager::OnDeviceOnline(std::string deviceId, int32_t authForm } } ProcessDeviceStateChange(DEVICE_STATE_ONLINE, devInfo); - softbusConnector_->ClearPkgName(); + softbusConnector_->ClearProcessInfo(); } void DmDeviceStateManager::OnDeviceOffline(std::string deviceId) @@ -127,7 +127,7 @@ void DmDeviceStateManager::OnDeviceOffline(std::string deviceId) devInfo = stateDeviceInfos_[deviceId]; } ProcessDeviceStateChange(DEVICE_STATE_OFFLINE, devInfo); - softbusConnector_->ClearPkgName(); + softbusConnector_->ClearProcessInfo(); } void DmDeviceStateManager::HandleDeviceStatusChange(DmDeviceState devState, DmDeviceInfo &devInfo) @@ -140,7 +140,7 @@ void DmDeviceStateManager::HandleDeviceStatusChange(DmDeviceState devState, DmDe SaveOnlineDeviceInfo(devInfo); DmDistributedHardwareLoad::GetInstance().LoadDistributedHardwareFwk(); ProcessDeviceStateChange(devState, devInfo); - softbusConnector_->ClearPkgName(); + softbusConnector_->ClearProcessInfo(); break; case DEVICE_STATE_OFFLINE: StartOffLineTimer(devInfo); @@ -151,12 +151,12 @@ void DmDeviceStateManager::HandleDeviceStatusChange(DmDeviceState devState, DmDe softbusConnector_->EraseUdidFromMap(udid); } ProcessDeviceStateChange(devState, devInfo); - softbusConnector_->ClearPkgName(); + softbusConnector_->ClearProcessInfo(); break; case DEVICE_INFO_CHANGED: ChangeDeviceInfo(devInfo); ProcessDeviceStateChange(devState, devInfo); - softbusConnector_->ClearPkgName(); + softbusConnector_->ClearProcessInfo(); break; default: LOGE("HandleDeviceStatusChange error, unknown device state = %{public}d", devState); @@ -520,16 +520,16 @@ void DmDeviceStateManager::HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) LOGE("failed, ptr is null."); return; } - std::vector pkgName = softbusConnector_->GetPkgName();//todo - LOGI("pkgName size: %{public}zu", pkgName.size()); - if (pkgName.size() == 0) { + std::vector processInfo = softbusConnector_->GetProcessInfo();//todo + LOGI("pkgName size: %{public}zu", processInfo.size()); + if (processInfo.size() == 0) { listener_->OnDeviceScreenStateChange(std::string(DM_PKG_NAME), devInfo); } else { - for (auto item : pkgName) { - listener_->OnDeviceScreenStateChange(item, devInfo); + for (auto item : processInfo) { + listener_->OnDeviceScreenStateChange(item.pkgName, devInfo); } } - softbusConnector_->ClearPkgName(); + softbusConnector_->ClearProcessInfo(); } void DmDeviceStateManager::HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index 5c8b63c80..bb2b31e03 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -98,7 +98,7 @@ private: #if !defined(__LITEOS_M__) IpcServerListener ipcServerListener_; static std::mutex alreadyOnlinePkgNameLock_; - static std::unordered_map alreadyOnlinePkgName_; + static std::map alreadyOnlinePkgName_; #endif }; } // namespace DistributedHardware diff --git a/services/service/include/discovery/discovery_manager.h b/services/service/include/discovery/discovery_manager.h index ce7ab495e..04c5deef3 100644 --- a/services/service/include/discovery/discovery_manager.h +++ b/services/service/include/discovery/discovery_manager.h @@ -71,7 +71,7 @@ public: static bool IsCommonDependencyReady(); static bool CloseCommonDependencyObj(); #endif - void ClearDiscoveryCache(const ProcessInfo &processInfo); + void ClearDiscoveryCache(const std::string &pkgName); private: void StartDiscoveryTimer(const std::string &pkgName); diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index 79e0d6753..ba9ce25a8 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -271,7 +271,7 @@ public: virtual void HandleIdentAccountLogout(const std::string &udid, int32_t userId, const std::string &accountId) = 0; virtual void HandleUserRemoved(int32_t preUserId) = 0; virtual void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) = 0; - virtual void HandleUserSwitched(int32_t switchUserId) = 0; + virtual void HandleUserSwitched(int32_t currentUserId, int32_t beforeUserId) = 0; virtual int32_t StopAuthenticateDevice(const std::string &pkgName) = 0; virtual void HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) = 0; virtual int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId) = 0; diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index f67c20c1a..46b17245a 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1637,7 +1637,7 @@ void DeviceManagerService::AccountCommonEventCallback(const std::string commonEv if (commonEventType == CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { if (MultipleUserConnector::GetSwitchOldUserId() > 0 && (currentUserId != MultipleUserConnector::GetSwitchOldUserId())) { - HandleUserSwitched(MultipleUserConnector::GetSwitchOldUserId()); + HandleUserSwitched(currentUserId, MultipleUserConnector::GetSwitchOldUserId()); } MultipleUserConnector::SetSwitchOldUserId(currentUserId); MultipleUserConnector::SetSwitchOldAccountId(MultipleUserConnector::GetOhosAccountId()); @@ -1646,9 +1646,9 @@ void DeviceManagerService::AccountCommonEventCallback(const std::string commonEv dmServiceImplExt_->AccountUserSwitched(currentUserId, MultipleUserConnector::GetOhosAccountId()); } - //TODO: лbeforeUserId߼ + //TODO: �����л���beforeUserId�����߼����� - //TODO: лcurrentUserId߼ߣNOҪûߣܱ߼ߣ + //TODO: �����л���currentUserId�����߼����ߣ�NO����Ҫ���������û����������ߣ����ܱ��߼����ߣ� } else if (commonEventType == CommonEventSupport::COMMON_EVENT_HWID_LOGIN) { MultipleUserConnector::SetSwitchOldAccountId(MultipleUserConnector::GetOhosAccountId()); MultipleUserConnector::SetSwitchOldAccountName(MultipleUserConnector::GetOhosAccountName()); @@ -1945,7 +1945,7 @@ void DeviceManagerService::ClearDiscoveryCache(const ProcessInfo &processInfo) { LOGI("PkgName %{public}s.", processInfo.pkgName.c_str()); CHECK_NULL_VOID(discoveryMgr_); - discoveryMgr_->ClearDiscoveryCache(processInfo); + discoveryMgr_->ClearDiscoveryCache(processInfo.pkgName); } void DeviceManagerService::HandleDeviceScreenStatusChange(DmDeviceInfo &deviceInfo) diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index ee6c91e62..2262571cf 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -46,7 +46,7 @@ namespace OHOS { namespace DistributedHardware { std::mutex DeviceManagerServiceListener::alreadyOnlinePkgNameLock_; -std::unordered_map DeviceManagerServiceListener::alreadyOnlinePkgName_ = {}; +std::map DeviceManagerServiceListener::alreadyOnlinePkgName_ = {}; void DeviceManagerServiceListener::ConvertDeviceInfoToDeviceBasicInfo(const std::string &pkgName, const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo) { @@ -86,13 +86,13 @@ void DeviceManagerServiceListener::SetDeviceInfo(std::shared_ptrSetDeviceState(state); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::string appId = ""; - if (AppManager::GetInstance().GetAppIdByPkgName(pkgName, appId) != DM_OK) {//todo + if (AppManager::GetInstance().GetAppIdByPkgName(processInfo.pkgName, appId) != DM_OK) {//todo pReq->SetDeviceInfo(deviceInfo); pReq->SetDeviceBasicInfo(deviceBasicInfo); return; } DmDeviceInfo dmDeviceInfo = deviceInfo; - ConvertUdidHashToAnoyAndSave(pkgName, dmDeviceInfo); + ConvertUdidHashToAnoyAndSave(processInfo.pkgName, dmDeviceInfo); DmDeviceBasicInfo dmDeviceBasicInfo = deviceBasicInfo; if (memset_s(dmDeviceBasicInfo.deviceId, DM_MAX_DEVICE_ID_LEN, 0, DM_MAX_DEVICE_ID_LEN) != DM_OK) { LOGE("ConvertNodeBasicInfoToDmDevice memset failed."); @@ -120,7 +120,7 @@ void DeviceManagerServiceListener::ProcessDeviceStateChange(const DmDeviceState std::vector processInfoVec = ipcServerListener_.GetAllProcessInfo(); if (state == DEVICE_STATE_OFFLINE) { RemoveOnlinePkgName(info); - for (const auto &it : PkgNameVec) { + for (const auto &it : processInfoVec) { SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); } @@ -155,18 +155,19 @@ void DeviceManagerServiceListener::ProcessAppStateChange(const ProcessInfo &proc std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); std::unordered_set notifyPkgnames = PermissionManager::GetInstance().GetSystemSA(); - notifyPkgnames.insert(pkgName); + notifyPkgnames.insert(processInfo.pkgName); if (state == DEVICE_STATE_ONLINE) { for (const auto &it : notifyPkgnames) { - std::string notifyKey = it + "_" + info.deviceId; + ProcessInfo processInfo; + processInfo.pkgName = it; { std::lock_guard autoLock(alreadyOnlinePkgNameLock_); - if (alreadyOnlinePkgName_.find(notifyKey) != alreadyOnlinePkgName_.end()) { + if (alreadyOnlinePkgName_.find(processInfo) != alreadyOnlinePkgName_.end()) { continue; } - alreadyOnlinePkgName_[notifyKey] = info; + alreadyOnlinePkgName_[processInfo] = info; } - SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); + SetDeviceInfo(pReq, processInfo, state, info, deviceBasicInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); } } @@ -174,23 +175,24 @@ void DeviceManagerServiceListener::ProcessAppStateChange(const ProcessInfo &proc if (!SoftbusCache::GetInstance().CheckIsOnline(std::string(info.deviceId))) { RemoveOnlinePkgName(info); for (const auto &it : notifyPkgnames) { - SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); + ProcessInfo processInfo; + processInfo.pkgName = it; + SetDeviceInfo(pReq, processInfo, state, info, deviceBasicInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); } } else { - std::string notifyKey = pkgName + "_" + info.deviceId; { std::lock_guard autoLock(alreadyOnlinePkgNameLock_); - if (alreadyOnlinePkgName_.find(notifyKey) != alreadyOnlinePkgName_.end()) { - alreadyOnlinePkgName_.erase(notifyKey); + if (alreadyOnlinePkgName_.find(processInfo) != alreadyOnlinePkgName_.end()) { + alreadyOnlinePkgName_.erase(processInfo); } } - SetDeviceInfo(pReq, pkgName, state, info, deviceBasicInfo); + SetDeviceInfo(pReq, processInfo, state, info, deviceBasicInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); } } if (state == DEVICE_INFO_READY || state == DEVICE_INFO_CHANGED) { - SetDeviceInfo(pReq, pkgName, state, info, deviceBasicInfo); + SetDeviceInfo(pReq, processInfo, state, info, deviceBasicInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); } } @@ -480,9 +482,9 @@ void DeviceManagerServiceListener::OnDeviceTrustChange(const std::string &udid, GetAnonyString(uuid).c_str(), authForm); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - std::vector PkgNameVec = ipcServerListener_.GetAllProcessInfo(); - for (const auto &it : PkgNameVec) { - pReq->SetPkgName(it); + std::vector processInfoVec = ipcServerListener_.GetAllProcessInfo(); + for (const auto &it : processInfoVec) { + pReq->SetPkgName(it.pkgName); pReq->SetUdid(udid); pReq->SetUuid(uuid); pReq->SetAuthForm(authForm); @@ -515,9 +517,9 @@ void DeviceManagerServiceListener::OnDeviceScreenStateChange(const std::string & if (pkgName == std::string(DM_PKG_NAME)) { std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - std::vector PkgNameVec = ipcServerListener_.GetAllProcessInfo(); - for (const auto &it : PkgNameVec) { - SetDeviceScreenInfo(pReq, it, devInfo); + std::vector processInfoVec = ipcServerListener_.GetAllProcessInfo(); + for (const auto &it : processInfoVec) { + SetDeviceScreenInfo(pReq, it.pkgName, devInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_SCREEN_STATE_NOTIFY, pReq, pRsp); } } else { @@ -557,9 +559,9 @@ void DeviceManagerServiceListener::OnCredentialAuthStatus(const std::string &pkg pReq->SetDeviceTypeId(deviceTypeId); pReq->SetErrCode(errcode); if (pkgName == std::string(DM_PKG_NAME)) { - std::vector PkgNameVec = ipcServerListener_.GetAllProcessInfo(); - for (const auto &it : PkgNameVec) { - pReq->SetPkgName(it); + std::vector processInfoVec = ipcServerListener_.GetAllProcessInfo(); + for (const auto &it : processInfoVec) { + pReq->SetPkgName(it.pkgName); ipcServerListener_.SendRequest(SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY, pReq, pRsp); } } else { @@ -572,7 +574,7 @@ void DeviceManagerServiceListener::OnAppUnintall(const std::string &pkgName) { std::lock_guard autoLock(alreadyOnlinePkgNameLock_); for (auto it = alreadyOnlinePkgName_.begin(); it != alreadyOnlinePkgName_.end();) { - if (it->first.find(pkgName) == 0) { + if (it->first.pkgName.find(pkgName) == 0) { it = alreadyOnlinePkgName_.erase(it); } else { ++it; diff --git a/services/service/src/discovery/discovery_manager.cpp b/services/service/src/discovery/discovery_manager.cpp index 1dd70df98..8fbf9044d 100644 --- a/services/service/src/discovery/discovery_manager.cpp +++ b/services/service/src/discovery/discovery_manager.cpp @@ -585,9 +585,9 @@ bool DiscoveryManager::CloseCommonDependencyObj() } #endif -void DiscoveryManager::ClearDiscoveryCache(const ProcessInfo &processInfo) +void DiscoveryManager::ClearDiscoveryCache(const std::string &pkgName) { - LOGI("PkgName %{public}s.", processInfo.pkgName.c_str()); + LOGI("PkgName %{public}s.", pkgName.c_str()); uint16_t subscribeId = 0; { std::lock_guard autoLock(locks_); diff --git a/services/service/src/ipc/standard/ipc_cmd_parser.cpp b/services/service/src/ipc/standard/ipc_cmd_parser.cpp index f622c072e..e3dc7b57c 100644 --- a/services/service/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/standard/ipc_cmd_parser.cpp @@ -421,7 +421,9 @@ ON_IPC_CMD(REGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParcel return ERR_DM_POINT_NULL; } ProcessInfo processInfo; - MultipleUserConnector::GetTokenIdAndUserId(processInfo.tokenId, processInfo.userId); + uint32_t tokenId; + MultipleUserConnector::GetTokenIdAndUserId(tokenId, processInfo.userId); + processInfo.tokenId = tokenId; processInfo.pkgName = pkgName; DeviceManagerService::GetInstance().RegisterCallerAppId(pkgName); int32_t result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, callback); @@ -438,8 +440,10 @@ ON_IPC_CMD(UNREGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParce { std::string pkgName = data.ReadString(); ProcessInfo processInfo; - MultipleUserConnector::GetTokenIdAndUserId(processInfo.tokenId, processInfo.userId); + uint32_t tokenId; + MultipleUserConnector::GetTokenIdAndUserId(tokenId, processInfo.userId); processInfo.pkgName = pkgName; + processInfo.tokenId = tokenId; DeviceManagerService::GetInstance().UnRegisterCallerAppId(pkgName); int32_t result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); if (!reply.WriteInt32(result)) { diff --git a/services/service/src/ipc/standard/ipc_server_listener.cpp b/services/service/src/ipc/standard/ipc_server_listener.cpp index 2fa0b8ab6..7a692d6cb 100644 --- a/services/service/src/ipc/standard/ipc_server_listener.cpp +++ b/services/service/src/ipc/standard/ipc_server_listener.cpp @@ -38,7 +38,7 @@ int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr } sptr listener = IpcServerStub::GetInstance().GetDmListener(processInfo); if (listener == nullptr) { - LOGI("cannot get listener for package:%{public}s.", pkgName.c_str()); + LOGI("cannot get listener for package:%{public}s.", processInfo.pkgName.c_str()); return ERR_DM_POINT_NULL; } return listener->SendCmd(cmdCode, req, rsp); diff --git a/services/service/src/ipc/standard/ipc_server_stub.cpp b/services/service/src/ipc/standard/ipc_server_stub.cpp index c29d4d4ac..ce10a362a 100644 --- a/services/service/src/ipc/standard/ipc_server_stub.cpp +++ b/services/service/src/ipc/standard/ipc_server_stub.cpp @@ -209,8 +209,7 @@ int32_t IpcServerStub::RegisterDeviceManagerListener(const ProcessInfo &processI return ERR_DM_POINT_NULL; } - LOGI("Register device manager listener for package name: %{public}s, tokenId: %{public}u", - processInfo.pkgName.c_str(), processInfo.tokenId); + LOGI("Register device manager listener for package name: %{public}s", processInfo.pkgName.c_str()); std::lock_guard autoLock(listenerLock_); auto iter = dmListener_.find(processInfo); if (iter != dmListener_.end()) { diff --git a/utils/include/appInfo/lite/app_manager.h b/utils/include/appInfo/lite/app_manager.h index fc69459bc..dc6b24018 100644 --- a/utils/include/appInfo/lite/app_manager.h +++ b/utils/include/appInfo/lite/app_manager.h @@ -30,6 +30,7 @@ public: void UnRegisterCallerAppId(const std::string &pkgName); int32_t GetAppIdByPkgName(const std::string &pkgName, std::string &appId); bool IsSystemSA(); + int32_t GetCallerName(bool isSystemSA, std::string &callerName); int32_t GetNativeTokenIdByName(std::string &processName, int64_t tokenId); int32_t GetHapTokenIdByName(int32_t userId, std::string &bundleName, int32_t instIndex, int64_t tokenId); }; diff --git a/utils/include/appInfo/standard/app_manager.h b/utils/include/appInfo/standard/app_manager.h index 5bb9d3b7a..828e5b123 100644 --- a/utils/include/appInfo/standard/app_manager.h +++ b/utils/include/appInfo/standard/app_manager.h @@ -36,6 +36,7 @@ public: void UnRegisterCallerAppId(const std::string &pkgName); int32_t GetAppIdByPkgName(const std::string &pkgName, std::string &appId); bool IsSystemSA(); + int32_t GetCallerName(bool isSystemSA, std::string &callerName); int32_t GetNativeTokenIdByName(std::string &processName, int64_t tokenId); int32_t GetHapTokenIdByName(int32_t userId, std::string &bundleName, int32_t instIndex, int64_t tokenId); private: diff --git a/utils/src/appInfo/lite/app_manager.cpp b/utils/src/appInfo/lite/app_manager.cpp index d79b82535..40e89b598 100644 --- a/utils/src/appInfo/lite/app_manager.cpp +++ b/utils/src/appInfo/lite/app_manager.cpp @@ -47,14 +47,20 @@ bool AppManager::IsSystemSA() return true; } -int32_t GetNativeTokenIdByName(std::string &processName, int64_t tokenId) +int32_t AppManager::GetCallerName(bool isSystemSA, std::string &callerName) +{ + (void)isSystemSA; + (void)callerName; + return DM_OK; +} +int32_t AppManager::GetNativeTokenIdByName(std::string &processName, int64_t tokenId) { (void)processName; (void)tokenId; return DM_OK; } -int32_t GetHapTokenIdByName(int32_t userId, std::string &bundleName, int32_t instIndex, int64_t tokenId) +int32_t AppManager::GetHapTokenIdByName(int32_t userId, std::string &bundleName, int32_t instIndex, int64_t tokenId) { (void)userId; (void)bundleName; diff --git a/utils/src/appInfo/standard/app_manager.cpp b/utils/src/appInfo/standard/app_manager.cpp index be0c78d93..3bb47c8fb 100644 --- a/utils/src/appInfo/standard/app_manager.cpp +++ b/utils/src/appInfo/standard/app_manager.cpp @@ -197,7 +197,7 @@ int32_t AppManager::GetNativeTokenIdByName(std::string &processName, int64_t tok int32_t AppManager::GetHapTokenIdByName(int32_t userId, std::string &bundleName, int32_t instIndex, int64_t tokenId) { - AccessTokenIDEx hapTokenId = AccessTokenInfoManager::GetInstance().GetHapTokenId(userId, bundleName, instIndex); + auto hapTokenId = AccessTokenKit::GetHapTokenID(userId, bundleName, instIndex); if (hapTokenId == 0) { LOGE("GetHapTokenId failed."); return ERR_DM_FAILED; -- Gitee From d7795c6e493946540254a6ba8e2cb2aed10c34ac Mon Sep 17 00:00:00 2001 From: hwzhangchuang Date: Tue, 5 Nov 2024 14:05:37 +0800 Subject: [PATCH 10/27] t --- .../include/deviceprofile_connector.h | 1 + .../include/multiple_user_connector.h | 3 +-- .../src/deviceprofile_connector.cpp | 23 +++++++++++++++++++ .../src/multiple_user_connector.cpp | 21 ++--------------- 4 files changed, 27 insertions(+), 21 deletions(-) diff --git a/commondependency/include/deviceprofile_connector.h b/commondependency/include/deviceprofile_connector.h index 9db34515e..7c5dd0722 100644 --- a/commondependency/include/deviceprofile_connector.h +++ b/commondependency/include/deviceprofile_connector.h @@ -128,6 +128,7 @@ public: void DeleteAccessControlList(const std::string &udid); int32_t GetBindLevel(const std::string &pkgName, const std::string &localUdid, const std::string &udid, uint64_t &tokenId); + std::map GetDeviceIdAndBindType(int32_t userId, const std::string &localUdid); std::map GetDeviceIdAndBindType(int32_t userId, const std::string &accountId, const std::string &localUdid); int32_t HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, diff --git a/commondependency/include/multiple_user_connector.h b/commondependency/include/multiple_user_connector.h index e5331623b..e42ac7b56 100644 --- a/commondependency/include/multiple_user_connector.h +++ b/commondependency/include/multiple_user_connector.h @@ -58,7 +58,7 @@ public: * @param userId the user id in which account login * @return std::string the account id */ - static std::string GetOhosAccountIdByUserid(int32_t userId); + static std::string GetOhosAccountIdByUserId(int32_t userId); /** * @tc.name: MultipleUserConnector::SetSwitchOldAccountId @@ -96,7 +96,6 @@ public: static std::string GetSwitchOldAccountName(void); static void GetSelfTokenIdAndUserId(uint32_t &tokenId, int32_t &userId); static void GetTokenIdAndUserId(uint32_t &tokenId, int32_t &userId); - static std::string GetOhosAccountIdByUserId(int32_t userId); static int32_t GetForegroundUsers(std::vector &userVec); static int32_t GetForegroundUser(void); diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index 8393b3af3..65628d345 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -873,6 +873,29 @@ int32_t DeviceProfileConnector::GetBindLevel(const std::string &pkgName, const s return bindLevel; } +std::map DeviceProfileConnector::GetDeviceIdAndBindType(int32_t userId, + const std::string &localUdid) +{ + LOGI("userId %{public}d", userId); + std::vector profiles = GetAccessControlProfileByUserId(userId); + std::map deviceIdMap; + for (const auto &item : profiles) { + if (item.GetAccesser().GetAccesserUserId() == userId && + item.GetAccesser().GetAccesserDeviceId() == localUdid) { + LOGI("Get Device Bind type localUdid %{public}s is src.", GetAnonyString(localUdid).c_str()); + UpdateBindType(item.GetTrustDeviceId(), item.GetBindType(), deviceIdMap); + continue; + } + if (item.GetAccessee().GetAccesseeUserId() == userId && + item.GetAccessee().GetAccesseeDeviceId() == localUdid) { + LOGI("Get Device Bind type localUdid %{public}s is sink.", GetAnonyString(localUdid).c_str()); + UpdateBindType(item.GetTrustDeviceId(), item.GetBindType(), deviceIdMap); + continue; + } + } + return deviceIdMap; +} + std::map DeviceProfileConnector::GetDeviceIdAndBindType(int32_t userId, const std::string &accountId, const std::string &localUdid) { diff --git a/commondependency/src/multiple_user_connector.cpp b/commondependency/src/multiple_user_connector.cpp index 5ae02fec0..8390a3b39 100644 --- a/commondependency/src/multiple_user_connector.cpp +++ b/commondependency/src/multiple_user_connector.cpp @@ -71,7 +71,7 @@ std::string MultipleUserConnector::GetOhosAccountId(void) #endif } -std::string MultipleUserConnector::GetOhosAccountIdByUserid(int32_t userId) +std::string MultipleUserConnector::GetOhosAccountIdByUserId(int32_t userId) { #if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) return ""; @@ -79,7 +79,7 @@ std::string MultipleUserConnector::GetOhosAccountIdByUserid(int32_t userId) OhosAccountInfo accountInfo; ErrCode ret = OhosAccountKits::GetInstance().GetOhosAccountInfoByUserId(userId, accountInfo); if (ret != 0 || accountInfo.uid_ == "") { - LOGE("GetOhosAccountId error ret: %{public}d", ret); + LOGE("error ret: %{public}d", ret); return ""; } return accountInfo.uid_; @@ -180,23 +180,6 @@ std::string MultipleUserConnector::GetSwitchOldAccountName(void) return accountName_; } -std::string MultipleUserConnector::GetOhosAccountIdByUserId(int32_t userId) -{ -#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) - return ""; -#elif OS_ACCOUNT_PART_EXISTS - OhosAccountInfo accountInfo; - ErrCode ret = OhosAccountKits::GetInstance().GetOhosAccountInfoByUserId(userId, accountInfo); - if (ret != 0 || accountInfo.uid_ == "") { - LOGE("error ret: %{public}d", ret); - return ""; - } - return accountInfo.uid_; -#else - return ""; -#endif -} - int32_t MultipleUserConnector::GetForegroundUsers(std::vector &userVec) { #if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) -- Gitee From d7850cdfabe4e1dd8f888e40a3f2fceda6c46fa7 Mon Sep 17 00:00:00 2001 From: hwzhangchuang Date: Tue, 5 Nov 2024 14:06:20 +0800 Subject: [PATCH 11/27] add user foreground broadcast Signed-off-by: hwzhangchuang --- common/include/dm_anonymous.h | 27 +++++ common/src/dm_anonymous.cpp | 18 +++ .../include/device_manager_service_impl.h | 9 ++ .../src/device_manager_service_impl.cpp | 31 ++++-- .../service/include/device_manager_service.h | 4 + .../include/idevice_manager_service_impl.h | 3 + .../relationship_sync_mgr.h | 12 +- .../service/src/device_manager_service.cpp | 71 +++++++++++- .../relationship_sync_mgr.cpp | 104 +++++++++++++++++- 9 files changed, 262 insertions(+), 17 deletions(-) diff --git a/common/include/dm_anonymous.h b/common/include/dm_anonymous.h index 292a3049c..920722427 100644 --- a/common/include/dm_anonymous.h +++ b/common/include/dm_anonymous.h @@ -26,7 +26,9 @@ namespace OHOS { namespace DistributedHardware { std::string GetAnonyString(const std::string &value); +std::string GetAnonyStringList(const std::vector &values); std::string GetAnonyInt32(const int32_t value); +std::string GetAnonyInt32List(const std::vector &values); bool IsNumberString(const std::string &inputString); bool IsString(const nlohmann::json &jsonObj, const std::string &key); bool IsInt32(const nlohmann::json &jsonObj, const std::string &key); @@ -43,6 +45,31 @@ int64_t StringToInt64(const std::string &str, int32_t base); void VersionSplitToInt(const std::string &str, const char split, std::vector &numVec); bool CompareVecNum(const std::vector &srcVecNum, const std::vector &sinkVecNum); bool CompareVersion(const std::string &remoteVersion, const std::string &oldVersion); + +template +std::string GetAnonyInteger(const T value) +{ + std::string tempString = std::to_string(value); + size_t length = tempString.length(); + if (length == 0x01) { + tempString[0] = '*'; + return tempString; + } + for (size_t i = 1; i < length - 1; i++) { + tempString[i] = '*'; + } + return tempString; +} + +template +std::string GetAnonyIntegerList(const std::vector &values) +{ + std::string temp = ""; + for (auto const &v : values) { + temp += GetAnonyInteger(v) + ", "; + } + return temp; +} } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_ANONYMOUS_H diff --git a/common/src/dm_anonymous.cpp b/common/src/dm_anonymous.cpp index 6bfd22004..fca41ecad 100644 --- a/common/src/dm_anonymous.cpp +++ b/common/src/dm_anonymous.cpp @@ -50,6 +50,15 @@ std::string GetAnonyString(const std::string &value) return res; } +std::string GetAnonyStringList(const std::vector &values) +{ + std::string temp = ""; + for (auto const &v : values) { + temp += GetAnonyString(v) + ", "; + } + return temp; +} + std::string GetAnonyInt32(const int32_t value) { std::string tempString = std::to_string(value); @@ -64,6 +73,15 @@ std::string GetAnonyInt32(const int32_t value) return tempString; } +std::string GetAnonyInt32List(const std::vector &values) +{ + std::string temp = ""; + for (auto const &v : values) { + temp += GetAnonyInt32(v) + ", "; + } + return temp; +} + bool IsNumberString(const std::string &inputString) { LOGI("IsNumberString for DeviceManagerNapi"); diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 6b67aac46..f10435f6a 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -133,6 +133,14 @@ public: int32_t StopAuthenticateDevice(const std::string &pkgName); void HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode); int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId); + /** + * @brief process the foreground userid sync broadcast. + * + * @param remoteUserIds the remote device foreground userids. + * @param remoteUdid the remote device udid. + * @param isNeedRsp true for need send back local foreground userids, false for not need send back. + */ + void HandleSyncForegroundUserIdEvent(const std::vector &remoteUserIds, const std::string &remoteUdid); private: int32_t PraseNotifyEventJson(const std::string &event, nlohmann::json &jsonObject); @@ -140,6 +148,7 @@ private: void HandleOffline(DmDeviceState devState, DmDeviceInfo &devInfo); void HandleOnline(DmDeviceState devState, DmDeviceInfo &devInfo); void PutIdenticalAccountToAcl(std::string requestDeviceId, std::string trustDeviceId); + std::map GetDeviceIdAndBindType(int32_t userId); std::map GetDeviceIdAndBindType(int32_t userId, const std::string &accountId); void HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, const std::string &remoteUdid); diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 5b4beefd0..e39f7c315 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -701,13 +701,13 @@ void DeviceManagerServiceImpl::HandleUserSwitched(int32_t currentUserId, int32_t std::string curUserAccountId = MultipleUserConnector::GetOhosAccountIdByUserId(currentUserId); std::string befUserAccountId = MultipleUserConnector::GetOhosAccountIdByUserId(beforeUserId); - //TODO1: ��ѯDP���Ź�ϵ + //TODO1: 查询DP可信关系 - //TODO2: ��olduserid�Ŀ��Ź�ϵstatus����Ϊ0 + //TODO2: 将olduserid的可信关系status设置为0 - //TODO3: ��newuserid�Ŀ��Ź�ϵstatus����Ϊ1 + //TODO3: 将newuserid的可信关系status设置为1 - //TODO4: ����DP���Ź�ϵ + //TODO4: 更新DP可信关系 } void DeviceManagerServiceImpl::ScreenCommonEventCallback(std::string commonEventType) @@ -749,6 +749,14 @@ int32_t DeviceManagerServiceImpl::GetBindLevel(const std::string &pkgName, const return DeviceProfileConnector::GetInstance().GetBindLevel(pkgName, localUdid, udid, tokenId); } +std::map DeviceManagerServiceImpl::GetDeviceIdAndBindType(int32_t userId) +{ + char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localUdidTemp); + return DeviceProfileConnector::GetInstance().GetDeviceIdAndBindType(userId, localUdid); +} + std::map DeviceManagerServiceImpl::GetDeviceIdAndBindType(int32_t userId, const std::string &accountId) { @@ -771,13 +779,13 @@ void DeviceManagerServiceImpl::HandleAccountLogoutEvent(int32_t remoteUserId, co return; } CHECK_NULL_VOID(authMgr_); - //TODO: ���ݶԶ����˺ŵ�userid����Ⱥ�� + //TODO: 根据对端退账号的userid清理群组 authMgr_->DeleteGroup(DM_PKG_NAME, remoteUdid); CHECK_NULL_VOID(listener_); std::string uuid = ""; SoftbusCache::GetInstance().GetUuidByUdid(remoteUdid, uuid); listener_->OnDeviceTrustChange(remoteUdid, uuid, ConvertBindTypeToAuthForm(bindType)); - //TODO���ϱ��߼������߸���Ӧ�ļ����� + //TODO:上报逻辑上下线给对应的监听者 } DmAuthForm DeviceManagerServiceImpl::ConvertBindTypeToAuthForm(int32_t bindType) @@ -823,10 +831,19 @@ void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const return; } CHECK_NULL_VOID(softbusConnector_); - softbusConnector_->SetProcessInfo(pkgName);//todo + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + softbusConnector_->SetProcessInfo(processInfo);//todo softbusConnector_->HandleDeviceOffline(remoteUdid); } +void DeviceManagerServiceImpl::HandleSyncForegroundUserIdEvent(const std::vector &remoteUserIds, + const std::string &remoteUdid) +{ + LOGI("receive remote foreground userids: %{public}s, remote udid: %{public}s", + GetAnonyIntegerList(remoteUserIds).c_str(), GetAnonyString(remoteUdid).c_str()); +} + void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) { LOGI("In"); diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index cffc8ec64..b31a3b844 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -215,6 +215,10 @@ private: void SendServiceUnBindBroadCast(const std::vector &peerUdids, int32_t userId, uint64_t tokenId); void SendAccountLogoutBroadCast(const std::vector &peerUdids, const std::string &accountId, const std::string &accountName, int32_t userId); + void SendForegroundUserIdsBroadCast(const std::vector &peerUdids, + const std::vector &userIds); + void HandleForegroundUserIdsBroadCast(const std::vector &remoteUserIds, + const std::string &remoteUdid, bool isNeedResponse); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) void SubscribeAccountCommonEvent(); diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index ba9ce25a8..ec9eb5e26 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -261,6 +261,7 @@ public: virtual int32_t CheckAccessControl(const DmAccessCaller &caller, const std::string &srcUdid, const DmAccessCallee &callee, const std::string &sinkUdid) = 0; virtual void HandleDeviceNotTrust(const std::string &udid) = 0; + virtual std::map GetDeviceIdAndBindType(int32_t userId) = 0; virtual std::map GetDeviceIdAndBindType(int32_t userId, const std::string &accountId) = 0; virtual void HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, const std::string &remoteUdid) = 0; @@ -275,6 +276,8 @@ public: virtual int32_t StopAuthenticateDevice(const std::string &pkgName) = 0; virtual void HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) = 0; virtual int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId) = 0; + virtual void HandleSyncForegroundUserIdEvent(const std::vector &remoteUserIds, + const std::string &remoteUdid) = 0; }; using CreateDMServiceFuncPtr = IDeviceManagerServiceImpl *(*)(void); diff --git a/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h b/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h index 10156b19d..08de2fae2 100644 --- a/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h +++ b/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h @@ -22,6 +22,7 @@ #include "dm_single_instance.h" namespace OHOS { namespace DistributedHardware { +const uint32_t MAX_FOREGROUND_USER_ID_NUM = 5; enum class RelationShipChangeType : uint32_t { ACCOUNT_LOGOUT = 0, DEVICE_UNBIND = 1, @@ -29,7 +30,8 @@ enum class RelationShipChangeType : uint32_t { SERVICE_UNBIND = 3, DEL_USER = 4, APP_UNINSTALL = 5, - TYPE_MAX = 6 + SYNC_FOREGROUND_USERID = 6, + TYPE_MAX = 7 }; struct RelationShipChangeMsg { @@ -37,9 +39,15 @@ struct RelationShipChangeMsg { uint32_t userId; std::string accountId; uint64_t tokenId; + // The broadcast need send to these devices with the udids std::vector peerUdids; + // The broadcast from which device with the udid. std::string peerUdid; std::string accountName; + // true: request, false: response + bool syncUserIdFlag; + // The foreground userid list + std::vector foregroundUserIds; explicit RelationShipChangeMsg(); bool ToBroadcastPayLoad(uint8_t *&msg, uint32_t &len) const; @@ -50,11 +58,13 @@ struct RelationShipChangeMsg { void ToAccountLogoutPayLoad(uint8_t *&msg, uint32_t &len) const; void ToDeviceUnbindPayLoad(uint8_t *&msg, uint32_t &len) const; void ToAppUnbindPayLoad(uint8_t *&msg, uint32_t &len) const; + void ToSyncForegroundUserId(uint8_t *&msg, uint32_t &len) const; cJSON *ToArrayJson() const; bool FromAccountLogoutPayLoad(const cJSON *payloadJson); bool FromDeviceUnbindPayLoad(const cJSON *payloadJson); bool FromAppUnbindPayLoad(const cJSON *payloadJson); + bool FromSyncForegroundUserId(const cJSON *payloadJson); std::string ToJson() const; bool FromJson(const std::string &msgJson); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 46b17245a..ca6b09e59 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1637,7 +1637,7 @@ void DeviceManagerService::AccountCommonEventCallback(const std::string commonEv if (commonEventType == CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { if (MultipleUserConnector::GetSwitchOldUserId() > 0 && (currentUserId != MultipleUserConnector::GetSwitchOldUserId())) { - HandleUserSwitched(currentUserId, MultipleUserConnector::GetSwitchOldUserId()); + HandleUserSwitched(currentUserId, beforeUserId); } MultipleUserConnector::SetSwitchOldUserId(currentUserId); MultipleUserConnector::SetSwitchOldAccountId(MultipleUserConnector::GetOhosAccountId()); @@ -1646,9 +1646,9 @@ void DeviceManagerService::AccountCommonEventCallback(const std::string commonEv dmServiceImplExt_->AccountUserSwitched(currentUserId, MultipleUserConnector::GetOhosAccountId()); } - //TODO: �����л���beforeUserId�����߼����� + //TODO: 根据切换的beforeUserId,报逻辑下线 - //TODO: �����л���currentUserId�����߼����ߣ�NO����Ҫ���������û����������ߣ����ܱ��߼����ߣ� + //TODO: 根据切换的currentUserId,报逻辑上线(NO,需要总线在新用户下重新上线,才能报逻辑上线) } else if (commonEventType == CommonEventSupport::COMMON_EVENT_HWID_LOGIN) { MultipleUserConnector::SetSwitchOldAccountId(MultipleUserConnector::GetOhosAccountId()); MultipleUserConnector::SetSwitchOldAccountName(MultipleUserConnector::GetOhosAccountName()); @@ -1696,6 +1696,22 @@ void DeviceManagerService::HandleAccountLogout(int32_t userId, const std::string void DeviceManagerService::HandleUserSwitched(int32_t currentUserId, int32_t beforeUserId) { LOGI("currentUserId: %{public}d. beforeUserId: %{public}d", currentUserId, beforeUserId); + std::map deviceMap; + std::vector peerUdids; + deviceMap = dmServiceImpl_->GetDeviceIdAndBindType(beforeUserId); + for (const auto &item : deviceMap) { + peerUdids.emplace_back(item.first); + } + if (!peerUdids.empty()) { + std::vector userVec; + int32_t ret = MultipleUserConnector::GetForegroundUsers(userVec); + if (ret != DM_OK || userVec.empty()) { + LOGE("Get foreground userids failed, ret: %{public}d", ret); + } else { + LOGE("Send local forground userids"); + SendForegroundUserIdsBroadCast(peerUdids, userVec); + } + } if (IsDMServiceImplReady()) { dmServiceImpl_->HandleUserSwitched(currentUserId, beforeUserId); } @@ -1725,6 +1741,51 @@ void DeviceManagerService::SendAccountLogoutBroadCast(const std::vectorSendAclChangedBroadcast(broadCastMsg); } +void DeviceManagerService::SendForegroundUserIdsBroadCast(const std::vector &peerUdids, + const std::vector &userIds) +{ + LOGI("peerUdids: %{public}s, foreground userids: %{public}s", GetAnonyStringList(peerUdids).c_str(), + GetAnonyInt32List(userIds).c_str()); + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::SYNC_FOREGROUND_USERID; + msg.peerUdids = peerUdids; + msg.syncUserIdFlag = true; + for (const auto userId : userIds) { + msg.foregroundUserIds.push_back(static_cast(userId)); + } + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + CHECK_NULL_VOID(softbusListener_); + softbusListener_->SendAclChangedBroadcast(broadCastMsg); +} + +void DeviceManagerService::HandleForegroundUserIdsBroadCast(const std::vector &remoteUserIds, + const std::string &remoteUdid, bool isNeedResponse) +{ + if (isNeedResponse) { + std::vector userVec; + int32_t ret = MultipleUserConnector::GetForegroundUsers(userVec); + if (ret != DM_OK || userVec.empty()) { + LOGE("Get Forground users failed, ret: %{public}d", ret); + } else { + LOGE("Send back local foreground userids: %{public}s", GetAnonyInt32List(userVec).c_str()); + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::SYNC_FOREGROUND_USERID; + msg.peerUdids.push_back(remoteUdid); + msg.syncUserIdFlag = false; + for (const auto userId : userVec) { + msg.foregroundUserIds.push_back(static_cast(userId)); + } + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + CHECK_NULL_VOID(softbusListener_); + softbusListener_->SendAclChangedBroadcast(broadCastMsg); + } + } + + if (IsDMServiceImplReady()) { + dmServiceImpl_->HandleSyncForegroundUserIdEvent(remoteUserIds, remoteUdid); + } +} + void DeviceManagerService::ScreenCommonEventCallback(std::string commonEventType) { if (!IsDMImplSoLoaded()) { @@ -1934,6 +1995,10 @@ void DeviceManagerService::HandleDeviceTrustedChange(const std::string &msg) dmServiceImpl_->HandleAppUnBindEvent(relationShipMsg.userId, relationShipMsg.peerUdid, static_cast(relationShipMsg.tokenId)); break; + case RelationShipChangeType::SYNC_FOREGROUND_USERID: + dmServiceImpl_->HandleSyncForegroundUserIdEvent(relationShipMsg.foregroundUserIds, + relationShipMsg.peerUdid); + break; default: LOGI("Dm have not this event type."); break; diff --git a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp index 494e959a8..3ff53063c 100644 --- a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp +++ b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp @@ -44,6 +44,9 @@ namespace { const int32_t APP_UNBIND_PAYLOAD_LEN = 6; const int32_t USERID_PAYLOAD_LEN = 2; const int32_t ACCOUNTID_PAYLOAD_LEN = 6; + const int32_t SYNC_FOREGROUND_USERID_PAYLOAD_MAX_LEN = 11; + const int32_t SYNC_FOREGROUND_USERID_PAYLOAD_MIN_LEN = 3; + const int32_t USERID_BYTES = 2; const int32_t BIT_PER_BYTES = 8; const int32_t INVALIED_PAYLOAD_SIZE = 12; @@ -51,10 +54,15 @@ namespace { const char * const MSG_VALUE = "VALUE"; const char * const MSG_PEER_UDID = "PEER_UDID"; const char * const MSG_ACCOUNTID = "ACCOUNTID"; + + // The userid len info cost 7 bits. + const int32_t FOREGROUND_USERID_LEN_BITS = 7; + const uint16_t FOREGROUND_USERID_LEN_0B = 0b01111111; } RelationShipChangeMsg::RelationShipChangeMsg() : type(RelationShipChangeType::TYPE_MAX), - userId(UINT32_MAX), accountId(""), tokenId(UINT64_MAX), peerUdid("") + userId(UINT32_MAX), accountId(""), tokenId(UINT64_MAX), peerUdids({}), peerUdid(""), accountName(""), + syncUserIdFlag(false), foregroundUserIds({}) { } @@ -79,6 +87,10 @@ bool RelationShipChangeMsg::ToBroadcastPayLoad(uint8_t *&msg, uint32_t &len) con ToAppUnbindPayLoad(msg, len); ret = true; break; + case RelationShipChangeType::SYNC_FOREGROUND_USERID: + ToSyncForegroundUserId(msg, len); + ret = true; + break; default: LOGE("RelationShipChange type invalid"); break; @@ -104,6 +116,9 @@ bool RelationShipChangeMsg::FromBroadcastPayLoad(const cJSON *payloadJson, Relat case RelationShipChangeType::APP_UNBIND: ret = FromAppUnbindPayLoad(payloadJson); break; + case RelationShipChangeType::SYNC_FOREGROUND_USERID: + ret = FromSyncForegroundUserId(payloadJson); + break; default: LOGE("RelationShipChange type invalid"); break; @@ -130,6 +145,10 @@ bool RelationShipChangeMsg::IsValid() const // current NOT support ret = false; break; + case RelationShipChangeType::SYNC_FOREGROUND_USERID: + ret = (!foregroundUserIds.empty() && + (static_cast(foregroundUserIds.size()) <= MAX_FOREGROUND_USER_ID_NUM)); + break; case RelationShipChangeType::TYPE_MAX: ret = false; break; @@ -143,14 +162,15 @@ bool RelationShipChangeMsg::IsValid() const bool RelationShipChangeMsg::IsChangeTypeValid() { return (type == RelationShipChangeType::ACCOUNT_LOGOUT) || (type == RelationShipChangeType::DEVICE_UNBIND) || - (type == RelationShipChangeType::APP_UNBIND); + (type == RelationShipChangeType::APP_UNBIND) || (type == RelationShipChangeType::SYNC_FOREGROUND_USERID); } bool RelationShipChangeMsg::IsChangeTypeValid(uint32_t type) { return (type == (uint32_t)RelationShipChangeType::ACCOUNT_LOGOUT) || (type == (uint32_t)RelationShipChangeType::DEVICE_UNBIND) || - (type == (uint32_t)RelationShipChangeType::APP_UNBIND); + (type == (uint32_t)RelationShipChangeType::APP_UNBIND) || + (type == (uint32_t)RelationShipChangeType::SYNC_FOREGROUND_USERID); } void RelationShipChangeMsg::ToAccountLogoutPayLoad(uint8_t *&msg, uint32_t &len) const @@ -189,6 +209,31 @@ void RelationShipChangeMsg::ToAppUnbindPayLoad(uint8_t *&msg, uint32_t &len) con len = APP_UNBIND_PAYLOAD_LEN; } +void RelationShipChangeMsg::ToSyncForegroundUserId(uint8_t *&msg, uint32_t &len) const +{ + uint32_t foregroundUserIdNum = static_cast(foregroundUserIds.size()); + if (foregroundUserIdNum > MAX_FOREGROUND_USER_ID_NUM) { + LOGE("foregroundUserIdNum too big, %{public}u", foregroundUserIdNum); + return; + } + + len = foregroundUserIdNum * USERID_BYTES + 1; + msg = new uint8_t[len](); + if (syncUserIdFlag) { + msg[0] |= 0x1 << FOREGROUND_USERID_LEN_BITS; + } else { + msg[0] |= 0x0 << FOREGROUND_USERID_LEN_BITS; + } + + msg[0] |= foregroundUserIdNum; + + for (int32_t idx = 1; idx < len;) { + msg[idx] |= foregroundUserIds[idx - 1]; + msg[idx + 1] |= foregroundUserIds[idx - 1] >> BIT_PER_BYTES; + idx += 2; + } +} + bool RelationShipChangeMsg::FromAccountLogoutPayLoad(const cJSON *payloadJson) { if (payloadJson == NULL) { @@ -196,7 +241,7 @@ bool RelationShipChangeMsg::FromAccountLogoutPayLoad(const cJSON *payloadJson) return false; } int32_t arraySize = cJSON_GetArraySize(payloadJson); - if (arraySize < ACCOUNT_LOGOUT_PAYLOAD_LEN || arraySize > INVALIED_PAYLOAD_SIZE) { + if (arraySize < ACCOUNT_LOGOUT_PAYLOAD_LEN || arraySize >= INVALIED_PAYLOAD_SIZE) { LOGE("Payload invalied,the size is %{public}d.", arraySize); return false; } @@ -226,7 +271,7 @@ bool RelationShipChangeMsg::FromDeviceUnbindPayLoad(const cJSON *payloadJson) return false; } int32_t arraySize = cJSON_GetArraySize(payloadJson); - if (arraySize < ACCOUNT_LOGOUT_PAYLOAD_LEN || arraySize > INVALIED_PAYLOAD_SIZE) { + if (arraySize < ACCOUNT_LOGOUT_PAYLOAD_LEN || arraySize >= INVALIED_PAYLOAD_SIZE) { LOGE("Payload invalied,the size is %{public}d.", arraySize); return false; } @@ -248,7 +293,7 @@ bool RelationShipChangeMsg::FromAppUnbindPayLoad(const cJSON *payloadJson) return false; } int32_t arraySize = cJSON_GetArraySize(payloadJson); - if (arraySize < ACCOUNT_LOGOUT_PAYLOAD_LEN || arraySize > INVALIED_PAYLOAD_SIZE) { + if (arraySize < ACCOUNT_LOGOUT_PAYLOAD_LEN || arraySize >= INVALIED_PAYLOAD_SIZE) { LOGE("Payload invalied,the size is %{public}d.", arraySize); return false; } @@ -271,6 +316,53 @@ bool RelationShipChangeMsg::FromAppUnbindPayLoad(const cJSON *payloadJson) return true; } +bool RelationShipChangeMsg::FromSyncForegroundUserId(const cJSON *payloadJson) +{ + if (payloadJson == NULL) { + LOGE("SyncForegroundUserId payloadJson is null."); + return false; + } + + int32_t arraySize = cJSON_GetArraySize(payloadJson); + if (arraySize < SYNC_FOREGROUND_USERID_PAYLOAD_MIN_LEN || arraySize > SYNC_FOREGROUND_USERID_PAYLOAD_MAX_LEN) { + LOGE("Payload invalied, the size is %{public}d.", arraySize); + return false; + } + + cJSON *payloadItem = cJSON_GetArrayItem(payloadJson, 0); + CHECK_NULL_RETURN(payloadItem, false); + uint32_t userIdNum = 0; + if (cJSON_IsNumber(payloadItem)) { + this->syncUserIdFlag = (((static_cast(payloadItem->valueint)) >> FOREGROUND_USERID_LEN_BITS) == 0x1); + userIdNum = ((static_cast(payloadItem->valueint)) & FOREGROUND_USERID_LEN_0B); + } + + int32_t effectiveLen = userIdNum * USERID_BYTES + 1; + if (effectiveLen > arraySize) { + LOGE("payload userIdNum invalid, userIdNum: %{public}u, arraySize: %{public}d", userIdNum, arraySize); + return false; + } + + uint16_t tempUserId = 0; + for (int32_t idx = 1; idx < effectiveLen; idx++) { + cJSON *payloadItem = cJSON_GetArrayItem(payloadJson, idx); + CHECK_NULL_RETURN(payloadItem, false); + if (!cJSON_IsNumber(payloadItem)) { + LOGE("Payload invalid, user id not integer"); + return false; + } + if ((idx - 1) % USERID_BYTES == 0) { + tempUserId |= (static_cast(payloadItem->valueint)); + } + if ((idx - 1) % USERID_BYTES == 1) { + tempUserId |= (static_cast(payloadItem->valueint)) << BIT_PER_BYTES; + this->foregroundUserIds.push_back(tempUserId); + tempUserId = 0; + } + } + return true; +} + cJSON *RelationShipChangeMsg::ToArrayJson() const { uint8_t *payload = nullptr; -- Gitee From 654917b0840aeacc3b494305478c3edecb7c39f3 Mon Sep 17 00:00:00 2001 From: hwzhangchuang Date: Tue, 5 Nov 2024 14:13:13 +0800 Subject: [PATCH 12/27] modify bug Signed-off-by: hwzhangchuang --- services/service/src/device_manager_service.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index ca6b09e59..8fd93a9a2 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1996,8 +1996,8 @@ void DeviceManagerService::HandleDeviceTrustedChange(const std::string &msg) static_cast(relationShipMsg.tokenId)); break; case RelationShipChangeType::SYNC_FOREGROUND_USERID: - dmServiceImpl_->HandleSyncForegroundUserIdEvent(relationShipMsg.foregroundUserIds, - relationShipMsg.peerUdid); + HandleForegroundUserIdsBroadCast(relationShipMsg.foregroundUserIds, + relationShipMsg.peerUdid, relationShipMsg.syncUserIdFlag); break; default: LOGI("Dm have not this event type."); -- Gitee From 3bcedac0b24f871ce982162b86292b4e4b5ffd3f Mon Sep 17 00:00:00 2001 From: hwzhangchuang Date: Tue, 5 Nov 2024 14:20:21 +0800 Subject: [PATCH 13/27] modify letter problem Signed-off-by: hwzhangchuang --- .../relationship_sync_mgr.cpp | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp index 3ff53063c..5c32cbcec 100644 --- a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp +++ b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp @@ -47,7 +47,7 @@ namespace { const int32_t SYNC_FOREGROUND_USERID_PAYLOAD_MAX_LEN = 11; const int32_t SYNC_FOREGROUND_USERID_PAYLOAD_MIN_LEN = 3; const int32_t USERID_BYTES = 2; - const int32_t BIT_PER_BYTES = 8; + const int32_t BITS_PER_BYTE = 8; const int32_t INVALIED_PAYLOAD_SIZE = 12; const char * const MSG_TYPE = "TYPE"; @@ -57,7 +57,7 @@ namespace { // The userid len info cost 7 bits. const int32_t FOREGROUND_USERID_LEN_BITS = 7; - const uint16_t FOREGROUND_USERID_LEN_0B = 0b01111111; + const uint16_t FOREGROUND_USERID_LEN_MASK = 0b01111111; } RelationShipChangeMsg::RelationShipChangeMsg() : type(RelationShipChangeType::TYPE_MAX), @@ -177,7 +177,7 @@ void RelationShipChangeMsg::ToAccountLogoutPayLoad(uint8_t *&msg, uint32_t &len) { msg = new uint8_t[ACCOUNT_LOGOUT_PAYLOAD_LEN](); for (int i = 0; i < USERID_PAYLOAD_LEN; i++) { - msg[i] |= (userId >> (i * BIT_PER_BYTES)) & 0xFF; + msg[i] |= (userId >> (i * BITS_PER_BYTE)) & 0xFF; } for (int j = USERID_PAYLOAD_LEN; j < ACCOUNT_LOGOUT_PAYLOAD_LEN; j++) { @@ -190,7 +190,7 @@ void RelationShipChangeMsg::ToDeviceUnbindPayLoad(uint8_t *&msg, uint32_t &len) { msg = new uint8_t[DEVICE_UNBIND_PAYLOAD_LEN](); for (int i = 0; i < USERID_PAYLOAD_LEN; i++) { - msg[i] |= (userId >> (i * BIT_PER_BYTES)) & 0xFF; + msg[i] |= (userId >> (i * BITS_PER_BYTE)) & 0xFF; } len = DEVICE_UNBIND_PAYLOAD_LEN; } @@ -199,11 +199,11 @@ void RelationShipChangeMsg::ToAppUnbindPayLoad(uint8_t *&msg, uint32_t &len) con { msg = new uint8_t[APP_UNBIND_PAYLOAD_LEN](); for (int i = 0; i < USERID_PAYLOAD_LEN; i++) { - msg[i] |= (userId >> (i * BIT_PER_BYTES)) & 0xFF; + msg[i] |= (userId >> (i * BITS_PER_BYTE)) & 0xFF; } for (int i = USERID_PAYLOAD_LEN; i < APP_UNBIND_PAYLOAD_LEN; i++) { - msg[i] |= (tokenId >> ((i - USERID_PAYLOAD_LEN) * BIT_PER_BYTES)) & 0xFF; + msg[i] |= (tokenId >> ((i - USERID_PAYLOAD_LEN) * BITS_PER_BYTE)) & 0xFF; } len = APP_UNBIND_PAYLOAD_LEN; @@ -229,7 +229,7 @@ void RelationShipChangeMsg::ToSyncForegroundUserId(uint8_t *&msg, uint32_t &len) for (int32_t idx = 1; idx < len;) { msg[idx] |= foregroundUserIds[idx - 1]; - msg[idx + 1] |= foregroundUserIds[idx - 1] >> BIT_PER_BYTES; + msg[idx + 1] |= foregroundUserIds[idx - 1] >> BITS_PER_BYTE; idx += 2; } } @@ -250,7 +250,7 @@ bool RelationShipChangeMsg::FromAccountLogoutPayLoad(const cJSON *payloadJson) cJSON *payloadItem = cJSON_GetArrayItem(payloadJson, i); CHECK_NULL_RETURN(payloadItem, false); if (cJSON_IsNumber(payloadItem)) { - userId |= (static_cast(payloadItem->valueint)) << (i * BIT_PER_BYTES); + userId |= (static_cast(payloadItem->valueint)) << (i * BITS_PER_BYTE); } } accountId = ""; @@ -280,7 +280,7 @@ bool RelationShipChangeMsg::FromDeviceUnbindPayLoad(const cJSON *payloadJson) cJSON *payloadItem = cJSON_GetArrayItem(payloadJson, i); CHECK_NULL_RETURN(payloadItem, false); if (cJSON_IsNumber(payloadItem)) { - userId |= (static_cast(payloadItem->valueint)) << (i * BIT_PER_BYTES); + userId |= (static_cast(payloadItem->valueint)) << (i * BITS_PER_BYTE); } } return true; @@ -302,7 +302,7 @@ bool RelationShipChangeMsg::FromAppUnbindPayLoad(const cJSON *payloadJson) cJSON *payloadItem = cJSON_GetArrayItem(payloadJson, i); CHECK_NULL_RETURN(payloadItem, false); if (cJSON_IsNumber(payloadItem)) { - userId |= (static_cast(payloadItem->valueint)) << (i * BIT_PER_BYTES); + userId |= (static_cast(payloadItem->valueint)) << (i * BITS_PER_BYTE); } } tokenId = 0; @@ -310,7 +310,7 @@ bool RelationShipChangeMsg::FromAppUnbindPayLoad(const cJSON *payloadJson) cJSON *payloadItem = cJSON_GetArrayItem(payloadJson, j); CHECK_NULL_RETURN(payloadItem, false); if (cJSON_IsNumber(payloadItem)) { - tokenId |= (static_cast(payloadItem->valueint)) << ((j - USERID_PAYLOAD_LEN) * BIT_PER_BYTES); + tokenId |= (static_cast(payloadItem->valueint)) << ((j - USERID_PAYLOAD_LEN) * BITS_PER_BYTE); } } return true; @@ -334,7 +334,7 @@ bool RelationShipChangeMsg::FromSyncForegroundUserId(const cJSON *payloadJson) uint32_t userIdNum = 0; if (cJSON_IsNumber(payloadItem)) { this->syncUserIdFlag = (((static_cast(payloadItem->valueint)) >> FOREGROUND_USERID_LEN_BITS) == 0x1); - userIdNum = ((static_cast(payloadItem->valueint)) & FOREGROUND_USERID_LEN_0B); + userIdNum = ((static_cast(payloadItem->valueint)) & FOREGROUND_USERID_LEN_MASK); } int32_t effectiveLen = userIdNum * USERID_BYTES + 1; @@ -355,7 +355,7 @@ bool RelationShipChangeMsg::FromSyncForegroundUserId(const cJSON *payloadJson) tempUserId |= (static_cast(payloadItem->valueint)); } if ((idx - 1) % USERID_BYTES == 1) { - tempUserId |= (static_cast(payloadItem->valueint)) << BIT_PER_BYTES; + tempUserId |= (static_cast(payloadItem->valueint)) << BITS_PER_BYTE; this->foregroundUserIds.push_back(tempUserId); tempUserId = 0; } -- Gitee From 9979b26b6766fbd27c3b76ce51feb9e02e1dc25c Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Mon, 4 Nov 2024 09:44:38 +0800 Subject: [PATCH 14/27] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E7=BC=96=E8=AF=91?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/deviceprofile_connector.h | 9 ++- .../include/multiple_user_connector.h | 2 +- .../src/deviceprofile_connector.cpp | 45 +++++++---- .../src/multiple_user_connector.cpp | 5 +- .../src/notify/device_manager_notify.cpp | 8 +- .../dependency/softbus/softbus_connector.h | 6 +- .../device_manager_service_impl_lite.h | 2 +- .../src/authentication/dm_auth_manager.cpp | 50 +++++++----- .../dependency/softbus/softbus_connector.cpp | 4 +- .../src/device_manager_service_impl.cpp | 24 +++--- .../src/device_manager_service_impl_lite.cpp | 3 +- .../devicestate/dm_device_state_manager.cpp | 24 +++--- .../include/device_manager_service_listener.h | 7 +- .../include/discovery/discovery_manager.h | 2 +- .../include/idevice_manager_service_impl.h | 2 +- .../idevice_manager_service_listener.h | 2 +- .../service/src/device_manager_service.cpp | 12 +-- .../src/device_manager_service_listener.cpp | 78 +++++++++++-------- .../src/discovery/discovery_manager.cpp | 4 +- .../src/ipc/standard/ipc_cmd_parser.cpp | 8 +- .../src/ipc/standard/ipc_server_listener.cpp | 2 +- .../src/ipc/standard/ipc_server_stub.cpp | 3 +- .../UTTest_dm_deviceprofile_connector.cpp | 5 +- test/unittest/UTTest_dm_pin_holder.h | 4 +- utils/include/appInfo/lite/app_manager.h | 1 + utils/include/appInfo/standard/app_manager.h | 1 + utils/src/appInfo/lite/app_manager.cpp | 10 ++- utils/src/appInfo/standard/app_manager.cpp | 2 +- 28 files changed, 193 insertions(+), 132 deletions(-) diff --git a/commondependency/include/deviceprofile_connector.h b/commondependency/include/deviceprofile_connector.h index 6c79d6af8..18b950185 100644 --- a/commondependency/include/deviceprofile_connector.h +++ b/commondependency/include/deviceprofile_connector.h @@ -78,7 +78,7 @@ typedef struct DmAccessee { typedef struct DmOfflineParam { uint32_t bindType; - std::vector processVec; + std::vector processVec; int32_t leftAclNumber; } DmOfflineParam; @@ -110,7 +110,8 @@ public: void DeleteAclForUserRemoved(int32_t userId); DmOfflineParam DeleteAccessControlList(const std::string &pkgName, const std::string &localDeviceId, const std::string &remoteDeviceId, int32_t bindLevel); - std::vector GetProcessInfoFromAcl(std::string &localDeviceId, std::string &targetDeviceId); + std::vector GetProcessInfoFromAcl(std::string &localDeviceId, + std::string &targetDeviceId); bool CheckIdenticalAccount(int32_t userId, const std::string &accountId); bool CheckSrcDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId); bool CheckSinkDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId); @@ -132,8 +133,8 @@ public: int32_t HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, const std::string &remoteUdid, const std::string &localUdid); int32_t HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, const std::string &localUdid); - std::string HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId, - const std::string &localUdid); + OHOS::DistributedHardware::ProcessInfo HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, + int32_t tokenId, const std::string &localUdid); std::vector GetAllAccessControlProfile(); void DeleteAccessControlById(int64_t accessControlId); diff --git a/commondependency/include/multiple_user_connector.h b/commondependency/include/multiple_user_connector.h index 278b4dcc3..e5331623b 100644 --- a/commondependency/include/multiple_user_connector.h +++ b/commondependency/include/multiple_user_connector.h @@ -97,7 +97,7 @@ public: static void GetSelfTokenIdAndUserId(uint32_t &tokenId, int32_t &userId); static void GetTokenIdAndUserId(uint32_t &tokenId, int32_t &userId); static std::string GetOhosAccountIdByUserId(int32_t userId); - static int32_t GetForegroundUsers(std::vector userVec); + static int32_t GetForegroundUsers(std::vector &userVec); static int32_t GetForegroundUser(void); private: diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index bfe102b94..38a81df10 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -362,14 +362,14 @@ std::vector DeviceProfileConnector::SyncAclByBindType(std::string pkgNa return bindType; } -std::vector DeviceProfileConnector::GetProcessInfoFromAcl(std::string &localDeviceId, - std::string &targetDeviceId) +std::vector DeviceProfileConnector::GetProcessInfoFromAcl( + std::string &localDeviceId, std::string &targetDeviceId) { LOGI("Start."); std::vector profiles = GetAccessControlProfileByUserId(MultipleUserConnector::GetForegroundUser()); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); - std::vector processInfoVec; + std::vector processInfoVec; for (auto &item : profiles) { if (item.GetTrustDeviceId() != targetDeviceId || item.GetStatus() != ACTIVE) { continue; @@ -378,7 +378,7 @@ std::vector DeviceProfileConnector::GetProcessInfoFromAcl(std::stri item.GetAccessee().GetAccesseeDeviceId() == targetDeviceId) || (item.GetAccesser().GetAccesserDeviceId() == targetDeviceId && item.GetAccessee().GetAccesseeDeviceId() == localDeviceId)) { - ProcessInfo processInfo; + OHOS::DistributedHardware::ProcessInfo processInfo; processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); processInfo.userId = item.GetAccesser().GetAccesserUserId(); processInfo.tokenId = item.GetAccesser().GetAccesserTokenId(); @@ -410,17 +410,21 @@ DmOfflineParam DeviceProfileConnector::GetOfflineParamFromAcl(std::string trustD priority = DEVICE_PEER_TO_PEER_TYPE; } else if (item.GetBindLevel() == DEVICE && item.GetAuthenticationType() == ALLOW_AUTH_ONCE) { priority = DEVICE_PEER_TO_PEER_TYPE; - ProcessInfo processInfo; + OHOS::DistributedHardware::ProcessInfo processInfo; processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); processInfo.userId = item.GetAccesser().GetAccesserUserId(); processInfo.tokenId = item.GetAccesser().GetAccesserTokenId(); - offlineParam.pkgNameVec.push_back(processInfo); + offlineParam.processVec.push_back(processInfo); } else if ((item.GetAccesser().GetAccesserDeviceId() == requestDeviceId && item.GetAccessee().GetAccesseeDeviceId() == trustDeviceId) || (item.GetAccesser().GetAccesserDeviceId() == trustDeviceId && item.GetAccessee().GetAccesseeDeviceId() == requestDeviceId)) { priority = APP_PEER_TO_PEER_TYPE; - offlineParam.pkgNameVec.push_back(item.GetAccesser().GetAccesserBundleName()); + OHOS::DistributedHardware::ProcessInfo processInfo; + processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.userId = item.GetAccesser().GetAccesserUserId(); + processInfo.tokenId = item.GetAccesser().GetAccesserTokenId(); + offlineParam.processVec.push_back(processInfo); } if (priority > offlineParam.bindType) { offlineParam.bindType = priority; @@ -512,7 +516,7 @@ DmOfflineParam DeviceProfileConnector::DeleteAccessControlList(const std::string LOGE("Invalied bindlevel."); return offlineParam; } - std::vector profiles = GetAccessControlProfile(); + std::vector profiles = GetAccessControlProfile();//todo if (profiles.empty()) { LOGE("Acl is empty."); return offlineParam; @@ -550,6 +554,10 @@ void DeviceProfileConnector::DeleteAppBindLevel(DmOfflineParam &offlineParam, co DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); deleteNums++; offlineParam.bindType = APP; + ProcessInfo processInfo; + processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.userId = item.GetAccesser().GetAccesserUserId(); + offlineParam.processVec.push_back(processInfo); LOGI("Src delete acl pkgName %{public}s, bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", pkgName.c_str(), item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); @@ -561,6 +569,10 @@ void DeviceProfileConnector::DeleteAppBindLevel(DmOfflineParam &offlineParam, co DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); deleteNums++; offlineParam.bindType = APP; + ProcessInfo processInfo; + processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); + processInfo.userId = item.GetAccessee().GetAccesseeUserId(); + offlineParam.processVec.push_back(processInfo); LOGI("Sink delete acl pkgName %{public}s, bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", pkgName.c_str(), item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); @@ -838,12 +850,12 @@ int32_t DeviceProfileConnector::CheckIsSameAccount(const DmAccessCaller &caller, return ERR_DM_FAILED; } -int32_t DeviceProfileConnector::GetBindLevel(const std::string &pkgName, const std::string &localUdid, +int32_t DeviceProfileConnector::GetBindLevel(const std::string &pkgName, const std::string &localUdid,//todo const std::string &udid, uint64_t &tokenId) { LOGI("pkgName %{public}s, tokenId %{public}" PRId64", udid %{public}s.", pkgName.c_str(), tokenId, GetAnonyString(udid).c_str()); - std::vector profiles = GetAccessControlProfile(); + std::vector profiles = GetAccessControlProfile();//todo int32_t bindLevel = INVALIED_TYPE; for (auto &item : profiles) { if (item.GetTrustDeviceId() != udid) { @@ -957,13 +969,14 @@ int32_t DeviceProfileConnector::HandleDevUnBindEvent(int32_t remoteUserId, const return bindType; } -std::string DeviceProfileConnector::HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, - int32_t tokenId, const std::string &localUdid) +OHOS::DistributedHardware::ProcessInfo DeviceProfileConnector::HandleAppUnBindEvent(int32_t remoteUserId, + const std::string &remoteUdid, int32_t tokenId, const std::string &localUdid) { LOGI("RemoteUserId %{public}d, remoteUdid %{public}s, tokenId %{public}d, localUdid %{public}s.", remoteUserId, GetAnonyString(remoteUdid).c_str(), tokenId, GetAnonyString(localUdid).c_str()); std::vector profiles = GetAccessControlProfile(); std::string pkgName = ""; + ProcessInfo processInfo; for (const auto &item : profiles) { if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || item.GetBindLevel() != APP) { @@ -975,7 +988,9 @@ std::string DeviceProfileConnector::HandleAppUnBindEvent(int32_t remoteUserId, c item.GetAccessee().GetAccesseeDeviceId() == localUdid) { LOGI("Src device unbind."); DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); - pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); + processInfo.userId = item.GetAccessee().GetAccesseeUserId(); + processInfo.tokenId = item.GetAccessee().GetAccesseeTokenId(); continue; } if (item.GetAccessee().GetAccesseeUserId() == remoteUserId && @@ -984,7 +999,9 @@ std::string DeviceProfileConnector::HandleAppUnBindEvent(int32_t remoteUserId, c item.GetAccesser().GetAccesserDeviceId() == localUdid) { LOGI("Sink device unbind."); DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); - pkgName = item.GetAccessee().GetAccesseeBundleName(); + processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.userId = item.GetAccesser().GetAccesserUserId(); + processInfo.tokenId = item.GetAccesser().GetAccesserTokenId(); continue; } } diff --git a/commondependency/src/multiple_user_connector.cpp b/commondependency/src/multiple_user_connector.cpp index bbe556e20..5ae02fec0 100644 --- a/commondependency/src/multiple_user_connector.cpp +++ b/commondependency/src/multiple_user_connector.cpp @@ -15,6 +15,7 @@ #include "multiple_user_connector.h" +#include "dm_constants.h" #include "dm_log.h" #include "ipc_skeleton.h" #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) @@ -132,9 +133,9 @@ void MultipleUserConnector::GetTokenIdAndUserId(uint32_t &tokenId, int32_t &user #if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) return; #elif OS_ACCOUNT_PART_EXISTS - ErrCode ret = OsAccountManager::GetOsAccountLocalldFromUid(uid, userId); + ErrCode ret = OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId); if (ret != 0) { - LOGE("GetOsAccountLocalldFromUid error ret: %{public}d", ret); + LOGE("GetOsAccountLocalIdFromUid error ret: %{public}d", ret); return; } return; diff --git a/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp index ef741b46a..93a06ad7a 100644 --- a/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp +++ b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp @@ -261,7 +261,7 @@ void DeviceManagerNotify::OnRemoteDied() } } -void DeviceManagerNotify::OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &deviceInfo)//todo +void DeviceManagerNotify::OnDeviceOnline(const std::string &pkgName, const DmDeviceInfo &deviceInfo) { if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); @@ -293,7 +293,7 @@ void DeviceManagerNotify::OnDeviceOnline(const std::string &pkgName, const DmDev #endif } -void DeviceManagerNotify::OnDeviceOnline(const std::string &pkgName, const DmDeviceBasicInfo &deviceBasicInfo)//todo +void DeviceManagerNotify::OnDeviceOnline(const std::string &pkgName, const DmDeviceBasicInfo &deviceBasicInfo) { if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); @@ -325,7 +325,7 @@ void DeviceManagerNotify::OnDeviceOnline(const std::string &pkgName, const DmDev #endif } -void DeviceManagerNotify::OnDeviceOffline(const std::string &pkgName, const DmDeviceInfo &deviceInfo)//todo +void DeviceManagerNotify::OnDeviceOffline(const std::string &pkgName, const DmDeviceInfo &deviceInfo) { if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); @@ -357,7 +357,7 @@ void DeviceManagerNotify::OnDeviceOffline(const std::string &pkgName, const DmDe #endif } -void DeviceManagerNotify::OnDeviceOffline(const std::string &pkgName, const DmDeviceBasicInfo &deviceBasicInfo)//todo +void DeviceManagerNotify::OnDeviceOffline(const std::string &pkgName, const DmDeviceBasicInfo &deviceBasicInfo) { if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); diff --git a/services/implementation/include/dependency/softbus/softbus_connector.h b/services/implementation/include/dependency/softbus/softbus_connector.h index 6ccdf0f40..8991eeb90 100644 --- a/services/implementation/include/dependency/softbus/softbus_connector.h +++ b/services/implementation/include/dependency/softbus/softbus_connector.h @@ -145,8 +145,8 @@ public: void HandleDeviceOffline(std::string deviceId); void SetProcessInfo(ProcessInfo processInfo); bool CheckIsOnline(const std::string &targetDeviceId); - void SetPkgNameVec(std::vector processInfoVec); - std::vector GetProcessInfo(); + void SetProcessInfoVec(std::vector processInfoVec); + std::vector GetProcessInfo(); void ClearProcessInfo(); DmDeviceInfo GetDeviceInfoByDeviceId(const std::string &deviceId); void DeleteOffLineTimer(std::string &udidHash); @@ -176,7 +176,7 @@ private: std::shared_ptr deviceStateManagerCallback_; static std::queue discoveryDeviceIdQueue_; static std::unordered_map deviceUdidMap_; - static std::vector processInfoVec_; + static std::vector processInfoVec_; static std::mutex discoveryCallbackMutex_; static std::mutex discoveryDeviceInfoMutex_; static std::mutex deviceUdidLocks_; diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index 18d643c3d..e6b954f9f 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -135,7 +135,7 @@ public: void HandleIdentAccountLogout(const std::string &udid, int32_t userId, const std::string &accountId); void HandleUserRemoved(int32_t preUserId); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); - void HandleUserSwitched(int32_t switchUserId); + void HandleUserSwitched(int32_t currentUserId, int32_t beforeUserId); int32_t StopAuthenticateDevice(const std::string &pkgName); void HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode); int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId); diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 1e551e75f..d0900eb6b 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -350,17 +350,21 @@ int32_t DmAuthManager::DeleteAcl(const std::string &pkgName, const std::string & LOGE("Acl not contain the pkgname bind data."); return ERR_DM_FAILED; } - if (bindLevel == APP && offlineParam.leftAclNumber != 0) { - LOGI("The pkgName unbind app-level type leftAclNumber not zero."); - softbusConnector_->SetProcessInfo(pkgName);//todo - softbusConnector_->HandleDeviceOffline(remoteUdid); - return DM_OK; - } - if (bindLevel == APP && offlineParam.leftAclNumber == 0) { - LOGI("The pkgName unbind app-level type leftAclNumber is zero."); - softbusConnector_->SetProcessInfo(pkgName);//todo - hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); - return DM_OK; + if (bindLevel == APP) { + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + if (offlineParam.leftAclNumber != 0) { + LOGI("The pkgName unbind app-level type leftAclNumber not zero."); + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); + softbusConnector_->HandleDeviceOffline(remoteUdid); + return DM_OK; + } + if (offlineParam.leftAclNumber == 0) { + LOGI("The pkgName unbind app-level type leftAclNumber is zero."); + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); + return DM_OK; + } } if (bindLevel == DEVICE && offlineParam.leftAclNumber != 0) { LOGI("Unbind deivce-level, retain identical account bind type."); @@ -1948,7 +1952,10 @@ void DmAuthManager::SrcAuthDeviceFinish() authResponseContext_->haveCredential)) { if ((authResponseContext_->bindLevel == APP || authResponseContext_->bindLevel == SERVICE) && !authResponseContext_->isIdenticalAccount && !authResponseContext_->hostPkgName.empty()) { - softbusConnector_->SetProcessInfo(authResponseContext_->hostPkgName);//todo + ProcessInfo processInfo; + processInfo.pkgName = authResponseContext_->hostPkgName; + processInfo.userId = authResponseContext_->localUserId; + softbusConnector_->SetProcessInfo(processInfo); } softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK)); @@ -1962,7 +1969,10 @@ void DmAuthManager::SrcAuthDeviceFinish() authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT); if ((authResponseContext_->bindLevel == APP || authResponseContext_->bindLevel == SERVICE) && !authResponseContext_->isIdenticalAccount && !authResponseContext_->hostPkgName.empty()) { - softbusConnector_->SetProcessInfo(authResponseContext_->hostPkgName);//todo + ProcessInfo processInfo; + processInfo.pkgName = authResponseContext_->hostPkgName; + processInfo.userId = authResponseContext_->localUserId; + softbusConnector_->SetProcessInfo(processInfo); } softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); authRequestState_->TransitionTo(std::make_shared()); @@ -1991,7 +2001,10 @@ void DmAuthManager::SinkAuthDeviceFinish() } if (authResponseContext_->isOnline) { LOGI("The device is online."); - softbusConnector_->SetProcessInfo(authResponseContext_->hostPkgName);//todo + ProcessInfo processInfo; + processInfo.pkgName = authResponseContext_->hostPkgName; + processInfo.userId = authResponseContext_->localUserId; + softbusConnector_->SetProcessInfo(processInfo); softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); } } @@ -2116,7 +2129,8 @@ void DmAuthManager::ProcRespNegotiateExt(const int32_t &sessionId) MultipleUserConnector::SetSwitchOldAccountId(authResponseContext_->localAccountId); MultipleUserConnector::SetSwitchOldUserId(authResponseContext_->localUserId); authResponseContext_->isIdenticalAccount = false; - if (authResponseContext_->localAccountId == accountId && accountId != "ohosAnonymousUid") { + if (authResponseContext_->localAccountId == authRequestContext_->localAccountId && + authRequestContext_->localAccountId != "ohosAnonymousUid") { authResponseContext_->isIdenticalAccount = true; } authResponseContext_->remoteAccountId = authResponseContext_->localAccountId; @@ -2509,8 +2523,8 @@ std::string DmAuthManager::GetBundleName(nlohmann::json &jsonObject) if (!jsonObject.is_discarded() && IsString(jsonObject, BUNDLE_NAME_KEY)) { return jsonObject[BUNDLE_NAME_KEY].get(); } - bool isSystemSA; - std::string bundleName + bool isSystemSA = false; + std::string bundleName; AppManager::GetInstance().GetCallerName(isSystemSA, bundleName); return bundleName; } @@ -2527,7 +2541,7 @@ int32_t DmAuthManager::GetBinderInfo() authResponseContext_->localUserId = userVec[0]; authResponseContext_->localAccountId = MultipleUserConnector::GetOhosAccountIdByUserId(authResponseContext_->localUserId); - if (authResponseContext_->bundleName.isEmpty()) { + if (authResponseContext_->bundleName.empty()) { return DM_OK; } ret = AppManager::GetInstance(). diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index 8600ad671..36096955f 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -48,7 +48,7 @@ std::map> SoftbusConnect std::map> SoftbusConnector::publishCallbackMap_ = {}; std::queue SoftbusConnector::discoveryDeviceIdQueue_ = {}; std::unordered_map SoftbusConnector::deviceUdidMap_ = {}; -std::vector SoftbusConnector::processInfoVec_ = {}; +std::vector SoftbusConnector::processInfoVec_ = {}; std::mutex SoftbusConnector::discoveryCallbackMutex_; std::mutex SoftbusConnector::discoveryDeviceInfoMutex_; std::mutex SoftbusConnector::deviceUdidLocks_; @@ -684,7 +684,7 @@ void SoftbusConnector::SetProcessInfoVec(std::vector processInfoVec processInfoVec_ = processInfoVec; } -std::vector SoftbusConnector::GetProcessInfo() +std::vector SoftbusConnector::GetProcessInfo() { LOGI("In"); std::lock_guard lock(processInfoVecMutex_); diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 545bfd393..01730834e 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -225,7 +225,7 @@ void DeviceManagerServiceImpl::HandleOffline(DmDeviceState devState, DmDeviceInf deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); } else if (offlineParam.bindType == APP_PEER_TO_PEER_TYPE) { LOGI("The offline device is app-level bind type."); - softbusConnector_->SetProcessVec(offlineParam.processVec); + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); } if (offlineParam.leftAclNumber == 0) { @@ -694,20 +694,20 @@ void DeviceManagerServiceImpl::HandleUserRemoved(int32_t preUserId) void DeviceManagerServiceImpl::HandleUserSwitched(int32_t currentUserId, int32_t beforeUserId) { - LOGI("currentUserId: %{public}d, beforeUserId: %{public}d", switchUserId, beforeUserId); + LOGI("currentUserId: %{public}d, beforeUserId: %{public}d", currentUserId, beforeUserId); //DeviceProfileConnector::GetInstance().DeleteAclForUserRemoved(switchUserId); //CHECK_NULL_VOID(hiChainConnector_); //hiChainConnector_->DeleteP2PGroup(switchUserId); std::string curUserAccountId = MultipleUserConnector::GetOhosAccountIdByUserId(currentUserId); std::string befUserAccountId = MultipleUserConnector::GetOhosAccountIdByUserId(beforeUserId); - //TODO1: ѯDPŹϵ + //TODO1: ��ѯDP���Ź�ϵ - //TODO2: olduseridĿŹϵstatusΪ0 + //TODO2: ��olduserid�Ŀ��Ź�ϵstatus����Ϊ0 - //TODO3: newuseridĿŹϵstatusΪ1 + //TODO3: ��newuserid�Ŀ��Ź�ϵstatus����Ϊ1 - //TODO4: DPŹϵ + //TODO4: ����DP���Ź�ϵ } void DeviceManagerServiceImpl::ScreenCommonEventCallback(std::string commonEventType) @@ -771,13 +771,13 @@ void DeviceManagerServiceImpl::HandleAccountLogoutEvent(int32_t remoteUserId, co return; } CHECK_NULL_VOID(authMgr_); - //TODO: ݶԶ˺ŵuseridȺ + //TODO: ���ݶԶ����˺ŵ�userid����Ⱥ�� authMgr_->DeleteGroup(DM_PKG_NAME, remoteUdid); CHECK_NULL_VOID(listener_); std::string uuid = ""; SoftbusCache::GetInstance().GetUuidByUdid(remoteUdid, uuid); listener_->OnDeviceTrustChange(remoteUdid, uuid, ConvertBindTypeToAuthForm(bindType)); - //TODOϱ߼߸Ӧļ + //TODO���ϱ��߼������߸���Ӧ�ļ����� } DmAuthForm DeviceManagerServiceImpl::ConvertBindTypeToAuthForm(int32_t bindType) @@ -816,14 +816,14 @@ void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); std::string localUdid = std::string(localUdidTemp); - std::string pkgName = + ProcessInfo processInfo = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid); - if (pkgName.empty()) { + if (processInfo.pkgName.empty()) { LOGE("Pkgname is empty."); return; } CHECK_NULL_VOID(softbusConnector_); - softbusConnector_->SetProcessInfo(pkgName);//todo + softbusConnector_->SetProcessInfo(processInfo); softbusConnector_->HandleDeviceOffline(remoteUdid); } @@ -851,7 +851,7 @@ void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devI return; } else if (bindType == IDENTICAL_ACCOUNT_TYPE || bindType == DEVICE_PEER_TO_PEER_TYPE || bindType == DEVICE_ACROSS_ACCOUNT_TYPE) { - softbusConnector_->ClearPkgName(); + softbusConnector_->ClearProcessInfo(); LOGI("networkId: %{public}s", GetAnonyString(devInfo.networkId).c_str()); } else if (bindType == APP_PEER_TO_PEER_TYPE || bindType == APP_ACROSS_ACCOUNT_TYPE) { std::vector processInfoVec = diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index 5528bd9cf..46ed922ce 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -513,9 +513,10 @@ void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devI return; } -void DeviceManagerServiceImpl::HandleUserSwitched(int32_t switchUserId) +void DeviceManagerServiceImpl::HandleUserSwitched(int32_t currentUserId, int32_t beforeUserId) { (void)switchUserId; + (void)beforeUserId; return; } diff --git a/services/implementation/src/devicestate/dm_device_state_manager.cpp b/services/implementation/src/devicestate/dm_device_state_manager.cpp index 86d42fa58..5c89d934d 100644 --- a/services/implementation/src/devicestate/dm_device_state_manager.cpp +++ b/services/implementation/src/devicestate/dm_device_state_manager.cpp @@ -111,7 +111,7 @@ void DmDeviceStateManager::OnDeviceOnline(std::string deviceId, int32_t authForm } } ProcessDeviceStateChange(DEVICE_STATE_ONLINE, devInfo); - softbusConnector_->ClearPkgName(); + softbusConnector_->ClearProcessInfo(); } void DmDeviceStateManager::OnDeviceOffline(std::string deviceId) @@ -127,7 +127,7 @@ void DmDeviceStateManager::OnDeviceOffline(std::string deviceId) devInfo = stateDeviceInfos_[deviceId]; } ProcessDeviceStateChange(DEVICE_STATE_OFFLINE, devInfo); - softbusConnector_->ClearPkgName(); + softbusConnector_->ClearProcessInfo(); } void DmDeviceStateManager::HandleDeviceStatusChange(DmDeviceState devState, DmDeviceInfo &devInfo) @@ -140,7 +140,7 @@ void DmDeviceStateManager::HandleDeviceStatusChange(DmDeviceState devState, DmDe SaveOnlineDeviceInfo(devInfo); DmDistributedHardwareLoad::GetInstance().LoadDistributedHardwareFwk(); ProcessDeviceStateChange(devState, devInfo); - softbusConnector_->ClearPkgName(); + softbusConnector_->ClearProcessInfo(); break; case DEVICE_STATE_OFFLINE: StartOffLineTimer(devInfo); @@ -151,12 +151,12 @@ void DmDeviceStateManager::HandleDeviceStatusChange(DmDeviceState devState, DmDe softbusConnector_->EraseUdidFromMap(udid); } ProcessDeviceStateChange(devState, devInfo); - softbusConnector_->ClearPkgName(); + softbusConnector_->ClearProcessInfo(); break; case DEVICE_INFO_CHANGED: ChangeDeviceInfo(devInfo); ProcessDeviceStateChange(devState, devInfo); - softbusConnector_->ClearPkgName(); + softbusConnector_->ClearProcessInfo(); break; default: LOGE("HandleDeviceStatusChange error, unknown device state = %{public}d", devState); @@ -520,16 +520,18 @@ void DmDeviceStateManager::HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) LOGE("failed, ptr is null."); return; } - std::vector pkgName = softbusConnector_->GetPkgName();//todo - LOGI("pkgName size: %{public}zu", pkgName.size()); - if (pkgName.size() == 0) { - listener_->OnDeviceScreenStateChange(std::string(DM_PKG_NAME), devInfo); + std::vector processInfos = softbusConnector_->GetProcessInfo(); + LOGI("process size: %{public}zu", processInfos.size()); + if (processInfos.size() == 0) { + ProcessInfo processInfo; + ProcessInfo.pkgName = std::string(DM_PKG_NAME); + listener_->OnDeviceScreenStateChange(ProcessInfo, devInfo); } else { - for (auto item : pkgName) { + for (auto item : processInfos) { listener_->OnDeviceScreenStateChange(item, devInfo); } } - softbusConnector_->ClearPkgName(); + softbusConnector_->ClearProcessInfo(); } void DmDeviceStateManager::HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index 5c8b63c80..16cc8605b 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -73,7 +73,7 @@ public: void OnPinHolderEvent(const std::string &pkgName, DmPinHolderEvent event, int32_t result, const std::string &content) override; void OnDeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm) override; - void OnDeviceScreenStateChange(const std::string &pkgName, DmDeviceInfo &devInfo) override; + void OnDeviceScreenStateChange(const ProcessInfo &processInfo, DmDeviceInfo &devInfo) override; void OnCredentialAuthStatus(const std::string &pkgName, uint16_t deviceTypeId, int32_t errcode) override; void OnAppUnintall(const std::string &pkgName) override; @@ -86,7 +86,7 @@ private: const DmDeviceBasicInfo &deviceBasicInfo); void ProcessAppStateChange(const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); - void SetDeviceScreenInfo(std::shared_ptr pReq, const std::string &pkgName, + void SetDeviceScreenInfo(std::shared_ptr pReq, const ProcessInfo &processInfo, const DmDeviceInfo &deviceInfo); void RemoveOnlinePkgName(const DmDeviceInfo &info); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) @@ -94,11 +94,12 @@ private: int32_t ConvertUdidHashToAnoyDeviceId(const std::string &pkgName, const std::string &udidHash, std::string &anoyDeviceId); #endif + void GetNotifyProcessInfos(const ProcessInfo &processInfo, std::set &processInfoSet); private: #if !defined(__LITEOS_M__) IpcServerListener ipcServerListener_; static std::mutex alreadyOnlinePkgNameLock_; - static std::unordered_map alreadyOnlinePkgName_; + static std::map alreadyOnlinePkgName_; #endif }; } // namespace DistributedHardware diff --git a/services/service/include/discovery/discovery_manager.h b/services/service/include/discovery/discovery_manager.h index ce7ab495e..04c5deef3 100644 --- a/services/service/include/discovery/discovery_manager.h +++ b/services/service/include/discovery/discovery_manager.h @@ -71,7 +71,7 @@ public: static bool IsCommonDependencyReady(); static bool CloseCommonDependencyObj(); #endif - void ClearDiscoveryCache(const ProcessInfo &processInfo); + void ClearDiscoveryCache(const std::string &pkgName); private: void StartDiscoveryTimer(const std::string &pkgName); diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index 79e0d6753..ba9ce25a8 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -271,7 +271,7 @@ public: virtual void HandleIdentAccountLogout(const std::string &udid, int32_t userId, const std::string &accountId) = 0; virtual void HandleUserRemoved(int32_t preUserId) = 0; virtual void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) = 0; - virtual void HandleUserSwitched(int32_t switchUserId) = 0; + virtual void HandleUserSwitched(int32_t currentUserId, int32_t beforeUserId) = 0; virtual int32_t StopAuthenticateDevice(const std::string &pkgName) = 0; virtual void HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) = 0; virtual int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId) = 0; diff --git a/services/service/include/idevice_manager_service_listener.h b/services/service/include/idevice_manager_service_listener.h index e52280475..0abbf2bb8 100644 --- a/services/service/include/idevice_manager_service_listener.h +++ b/services/service/include/idevice_manager_service_listener.h @@ -157,7 +157,7 @@ public: * @tc.desc: Device Screen State Change of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnDeviceScreenStateChange(const std::string &pkgName, DmDeviceInfo &devInfo) = 0; + virtual void OnDeviceScreenStateChange(const ProcessInfo &processInfo, DmDeviceInfo &devInfo) = 0; /** * @tc.name: IDeviceManagerServiceListener::OnCredentialAuthStatus diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index f67c20c1a..bf763ec1f 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -571,7 +571,7 @@ int32_t DeviceManagerService::UnAuthenticateDevice(const std::string &pkgName, c return ERR_DM_NOT_INIT; } uint64_t tokenId = 0; - int32_t bindLevel = dmServiceImpl_->GetBindLevel(pkgName, std::string(localUdid), udid, tokenId); + int32_t bindLevel = dmServiceImpl_->GetBindLevel(pkgName, std::string(localUdid), udid, tokenId);//todo LOGI("UnAuthenticateDevice get bindlevel %{public}d.", bindLevel); if (bindLevel == INVALIED_BIND_LEVEL) { LOGE("UnAuthenticateDevice failed, Acl not contain the bindLevel %{public}d.", bindLevel); @@ -678,7 +678,7 @@ int32_t DeviceManagerService::UnBindDevice(const std::string &pkgName, const std char localUdid[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localUdid, DEVICE_UUID_LENGTH); uint64_t tokenId = 0; - int32_t bindLevel = dmServiceImpl_->GetBindLevel(pkgName, std::string(localUdid), udid, tokenId); + int32_t bindLevel = dmServiceImpl_->GetBindLevel(pkgName, std::string(localUdid), udid, tokenId);//todo LOGI("UnAuthenticateDevice get bindlevel %{public}d.", bindLevel); if (bindLevel == INVALIED_BIND_LEVEL) { LOGE("UnAuthenticateDevice failed, Acl not contain the bindLevel %{public}d.", bindLevel); @@ -1637,7 +1637,7 @@ void DeviceManagerService::AccountCommonEventCallback(const std::string commonEv if (commonEventType == CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { if (MultipleUserConnector::GetSwitchOldUserId() > 0 && (currentUserId != MultipleUserConnector::GetSwitchOldUserId())) { - HandleUserSwitched(MultipleUserConnector::GetSwitchOldUserId()); + HandleUserSwitched(currentUserId, MultipleUserConnector::GetSwitchOldUserId()); } MultipleUserConnector::SetSwitchOldUserId(currentUserId); MultipleUserConnector::SetSwitchOldAccountId(MultipleUserConnector::GetOhosAccountId()); @@ -1646,9 +1646,9 @@ void DeviceManagerService::AccountCommonEventCallback(const std::string commonEv dmServiceImplExt_->AccountUserSwitched(currentUserId, MultipleUserConnector::GetOhosAccountId()); } - //TODO: лbeforeUserId߼ + //TODO: �����л���beforeUserId�����߼����� - //TODO: лcurrentUserId߼ߣNOҪûߣܱ߼ߣ + //TODO: �����л���currentUserId�����߼����ߣ�NO����Ҫ���������û����������ߣ����ܱ��߼����ߣ� } else if (commonEventType == CommonEventSupport::COMMON_EVENT_HWID_LOGIN) { MultipleUserConnector::SetSwitchOldAccountId(MultipleUserConnector::GetOhosAccountId()); MultipleUserConnector::SetSwitchOldAccountName(MultipleUserConnector::GetOhosAccountName()); @@ -1945,7 +1945,7 @@ void DeviceManagerService::ClearDiscoveryCache(const ProcessInfo &processInfo) { LOGI("PkgName %{public}s.", processInfo.pkgName.c_str()); CHECK_NULL_VOID(discoveryMgr_); - discoveryMgr_->ClearDiscoveryCache(processInfo); + discoveryMgr_->ClearDiscoveryCache(processInfo.pkgName); } void DeviceManagerService::HandleDeviceScreenStatusChange(DmDeviceInfo &deviceInfo) diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index ee6c91e62..3c2a8366c 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -46,7 +46,7 @@ namespace OHOS { namespace DistributedHardware { std::mutex DeviceManagerServiceListener::alreadyOnlinePkgNameLock_; -std::unordered_map DeviceManagerServiceListener::alreadyOnlinePkgName_ = {}; +std::map DeviceManagerServiceListener::alreadyOnlinePkgName_ = {}; void DeviceManagerServiceListener::ConvertDeviceInfoToDeviceBasicInfo(const std::string &pkgName, const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo) { @@ -86,13 +86,13 @@ void DeviceManagerServiceListener::SetDeviceInfo(std::shared_ptrSetDeviceState(state); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::string appId = ""; - if (AppManager::GetInstance().GetAppIdByPkgName(pkgName, appId) != DM_OK) {//todo + if (AppManager::GetInstance().GetAppIdByPkgName(processInfo.pkgName, appId) != DM_OK) { pReq->SetDeviceInfo(deviceInfo); pReq->SetDeviceBasicInfo(deviceBasicInfo); return; } DmDeviceInfo dmDeviceInfo = deviceInfo; - ConvertUdidHashToAnoyAndSave(pkgName, dmDeviceInfo); + ConvertUdidHashToAnoyAndSave(processInfo.pkgName, dmDeviceInfo); DmDeviceBasicInfo dmDeviceBasicInfo = deviceBasicInfo; if (memset_s(dmDeviceBasicInfo.deviceId, DM_MAX_DEVICE_ID_LEN, 0, DM_MAX_DEVICE_ID_LEN) != DM_OK) { LOGE("ConvertNodeBasicInfoToDmDevice memset failed."); @@ -120,7 +120,7 @@ void DeviceManagerServiceListener::ProcessDeviceStateChange(const DmDeviceState std::vector processInfoVec = ipcServerListener_.GetAllProcessInfo(); if (state == DEVICE_STATE_OFFLINE) { RemoveOnlinePkgName(info); - for (const auto &it : PkgNameVec) { + for (const auto &it : processInfoVec) { SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); } @@ -154,17 +154,16 @@ void DeviceManagerServiceListener::ProcessAppStateChange(const ProcessInfo &proc LOGI("In"); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - std::unordered_set notifyPkgnames = PermissionManager::GetInstance().GetSystemSA(); - notifyPkgnames.insert(pkgName); + std::set processInfoSet; + GetNotifyProcessInfos(processInfo, processInfoSet); if (state == DEVICE_STATE_ONLINE) { - for (const auto &it : notifyPkgnames) { - std::string notifyKey = it + "_" + info.deviceId; + for (const auto &it : processInfoSet) { { std::lock_guard autoLock(alreadyOnlinePkgNameLock_); - if (alreadyOnlinePkgName_.find(notifyKey) != alreadyOnlinePkgName_.end()) { + if (alreadyOnlinePkgName_.find(it) != alreadyOnlinePkgName_.end()) { continue; } - alreadyOnlinePkgName_[notifyKey] = info; + alreadyOnlinePkgName_[it] = info; } SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); @@ -173,24 +172,23 @@ void DeviceManagerServiceListener::ProcessAppStateChange(const ProcessInfo &proc if (state == DEVICE_STATE_OFFLINE) { if (!SoftbusCache::GetInstance().CheckIsOnline(std::string(info.deviceId))) { RemoveOnlinePkgName(info); - for (const auto &it : notifyPkgnames) { + for (const auto &it : processInfoSet) { SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); } } else { - std::string notifyKey = pkgName + "_" + info.deviceId; { std::lock_guard autoLock(alreadyOnlinePkgNameLock_); - if (alreadyOnlinePkgName_.find(notifyKey) != alreadyOnlinePkgName_.end()) { - alreadyOnlinePkgName_.erase(notifyKey); + if (alreadyOnlinePkgName_.find(processInfo) != alreadyOnlinePkgName_.end()) { + alreadyOnlinePkgName_.erase(processInfo); } } - SetDeviceInfo(pReq, pkgName, state, info, deviceBasicInfo); + SetDeviceInfo(pReq, processInfo, state, info, deviceBasicInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); } } if (state == DEVICE_INFO_READY || state == DEVICE_INFO_CHANGED) { - SetDeviceInfo(pReq, pkgName, state, info, deviceBasicInfo); + SetDeviceInfo(pReq, processInfo, state, info, deviceBasicInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); } } @@ -480,9 +478,9 @@ void DeviceManagerServiceListener::OnDeviceTrustChange(const std::string &udid, GetAnonyString(uuid).c_str(), authForm); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - std::vector PkgNameVec = ipcServerListener_.GetAllProcessInfo(); - for (const auto &it : PkgNameVec) { - pReq->SetPkgName(it); + std::vector processInfoVec = ipcServerListener_.GetAllProcessInfo(); + for (const auto &it : processInfoVec) { + pReq->SetPkgName(it.pkgName); pReq->SetUdid(udid); pReq->SetUuid(uuid); pReq->SetAuthForm(authForm); @@ -491,10 +489,11 @@ void DeviceManagerServiceListener::OnDeviceTrustChange(const std::string &udid, } void DeviceManagerServiceListener::SetDeviceScreenInfo(std::shared_ptr pReq, - const std::string &pkgName, const DmDeviceInfo &deviceInfo) + const ProcessInfo &processInfo, const DmDeviceInfo &deviceInfo) { LOGI("In"); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); + pReq->SetProcessInfo(processInfo); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::string appId = ""; if (AppManager::GetInstance().GetAppIdByPkgName(pkgName, appId) != DM_OK) { @@ -509,23 +508,23 @@ void DeviceManagerServiceListener::SetDeviceScreenInfo(std::shared_ptrSetDeviceInfo(deviceInfo); } -void DeviceManagerServiceListener::OnDeviceScreenStateChange(const std::string &pkgName, DmDeviceInfo &devInfo) +void DeviceManagerServiceListener::OnDeviceScreenStateChange(const ProcessInfo &processInfo, DmDeviceInfo &devInfo) { - LOGI("In, pkgName = %{public}s", pkgName.c_str()); - if (pkgName == std::string(DM_PKG_NAME)) { + LOGI("In, pkgName = %{public}s", processInfo.pkgName.c_str()); + if (processInfo.pkgName == std::string(DM_PKG_NAME)) { std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - std::vector PkgNameVec = ipcServerListener_.GetAllProcessInfo(); - for (const auto &it : PkgNameVec) { + std::vector processInfoVec = ipcServerListener_.GetAllProcessInfo(); + for (const auto &it : processInfoVec) { SetDeviceScreenInfo(pReq, it, devInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_SCREEN_STATE_NOTIFY, pReq, pRsp); } } else { std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - std::unordered_set notifyPkgnames = PermissionManager::GetInstance().GetSystemSA(); - notifyPkgnames.insert(pkgName); - for (const auto &it : notifyPkgnames) { + std::set processInfoSet; + GetNotifyProcessInfos(processInfo, processInfoSet); + for (const auto &it : processInfoSet) { SetDeviceScreenInfo(pReq, it, devInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_SCREEN_STATE_NOTIFY, pReq, pRsp); } @@ -557,9 +556,9 @@ void DeviceManagerServiceListener::OnCredentialAuthStatus(const std::string &pkg pReq->SetDeviceTypeId(deviceTypeId); pReq->SetErrCode(errcode); if (pkgName == std::string(DM_PKG_NAME)) { - std::vector PkgNameVec = ipcServerListener_.GetAllProcessInfo(); - for (const auto &it : PkgNameVec) { - pReq->SetPkgName(it); + std::vector processInfoVec = ipcServerListener_.GetAllProcessInfo(); + for (const auto &it : processInfoVec) { + pReq->SetPkgName(it.pkgName); ipcServerListener_.SendRequest(SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY, pReq, pRsp); } } else { @@ -572,12 +571,25 @@ void DeviceManagerServiceListener::OnAppUnintall(const std::string &pkgName) { std::lock_guard autoLock(alreadyOnlinePkgNameLock_); for (auto it = alreadyOnlinePkgName_.begin(); it != alreadyOnlinePkgName_.end();) { - if (it->first.find(pkgName) == 0) { + if (it->first.pkgName.find(pkgName) == 0) { it = alreadyOnlinePkgName_.erase(it); } else { ++it; } } } + +void DeviceManagerServiceListener::GetNotifyProcessInfos(const ProcessInfo &processInfo, + std::set &processInfoSet) +{ + std::unordered_set notifyPkgnames = PermissionManager::GetInstance().GetSystemSA(); + for (const auto &it : notifyPkgnames) { + ProcessInfo processInfo; + processInfo.pkgName = it; + processInfo.userId = 0; + processInfoSet.push_back(processInfo); + } + processInfoSet.push_back(processInfo); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/discovery/discovery_manager.cpp b/services/service/src/discovery/discovery_manager.cpp index 1dd70df98..8fbf9044d 100644 --- a/services/service/src/discovery/discovery_manager.cpp +++ b/services/service/src/discovery/discovery_manager.cpp @@ -585,9 +585,9 @@ bool DiscoveryManager::CloseCommonDependencyObj() } #endif -void DiscoveryManager::ClearDiscoveryCache(const ProcessInfo &processInfo) +void DiscoveryManager::ClearDiscoveryCache(const std::string &pkgName) { - LOGI("PkgName %{public}s.", processInfo.pkgName.c_str()); + LOGI("PkgName %{public}s.", pkgName.c_str()); uint16_t subscribeId = 0; { std::lock_guard autoLock(locks_); diff --git a/services/service/src/ipc/standard/ipc_cmd_parser.cpp b/services/service/src/ipc/standard/ipc_cmd_parser.cpp index f622c072e..e3dc7b57c 100644 --- a/services/service/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/standard/ipc_cmd_parser.cpp @@ -421,7 +421,9 @@ ON_IPC_CMD(REGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParcel return ERR_DM_POINT_NULL; } ProcessInfo processInfo; - MultipleUserConnector::GetTokenIdAndUserId(processInfo.tokenId, processInfo.userId); + uint32_t tokenId; + MultipleUserConnector::GetTokenIdAndUserId(tokenId, processInfo.userId); + processInfo.tokenId = tokenId; processInfo.pkgName = pkgName; DeviceManagerService::GetInstance().RegisterCallerAppId(pkgName); int32_t result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, callback); @@ -438,8 +440,10 @@ ON_IPC_CMD(UNREGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParce { std::string pkgName = data.ReadString(); ProcessInfo processInfo; - MultipleUserConnector::GetTokenIdAndUserId(processInfo.tokenId, processInfo.userId); + uint32_t tokenId; + MultipleUserConnector::GetTokenIdAndUserId(tokenId, processInfo.userId); processInfo.pkgName = pkgName; + processInfo.tokenId = tokenId; DeviceManagerService::GetInstance().UnRegisterCallerAppId(pkgName); int32_t result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); if (!reply.WriteInt32(result)) { diff --git a/services/service/src/ipc/standard/ipc_server_listener.cpp b/services/service/src/ipc/standard/ipc_server_listener.cpp index 2fa0b8ab6..7a692d6cb 100644 --- a/services/service/src/ipc/standard/ipc_server_listener.cpp +++ b/services/service/src/ipc/standard/ipc_server_listener.cpp @@ -38,7 +38,7 @@ int32_t IpcServerListener::SendRequest(int32_t cmdCode, std::shared_ptr } sptr listener = IpcServerStub::GetInstance().GetDmListener(processInfo); if (listener == nullptr) { - LOGI("cannot get listener for package:%{public}s.", pkgName.c_str()); + LOGI("cannot get listener for package:%{public}s.", processInfo.pkgName.c_str()); return ERR_DM_POINT_NULL; } return listener->SendCmd(cmdCode, req, rsp); diff --git a/services/service/src/ipc/standard/ipc_server_stub.cpp b/services/service/src/ipc/standard/ipc_server_stub.cpp index c29d4d4ac..ce10a362a 100644 --- a/services/service/src/ipc/standard/ipc_server_stub.cpp +++ b/services/service/src/ipc/standard/ipc_server_stub.cpp @@ -209,8 +209,7 @@ int32_t IpcServerStub::RegisterDeviceManagerListener(const ProcessInfo &processI return ERR_DM_POINT_NULL; } - LOGI("Register device manager listener for package name: %{public}s, tokenId: %{public}u", - processInfo.pkgName.c_str(), processInfo.tokenId); + LOGI("Register device manager listener for package name: %{public}s", processInfo.pkgName.c_str()); std::lock_guard autoLock(listenerLock_); auto iter = dmListener_.find(processInfo); if (iter != dmListener_.end()) { diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index 20594b841..8f9fd3a26 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -16,6 +16,7 @@ #include "UTTest_dm_deviceprofile_connector.h" #include "dm_constants.h" +#include "dm_device_info.h" #include "deviceprofile_connector.h" namespace OHOS { @@ -791,10 +792,10 @@ HWTEST_F(DeviceProfileConnectorTest, HandleAppUnBindEvent_001, testing::ext::Tes std::string remoteUdid = "remoteDeviceId"; std::string localUdid = "localDeviceId"; std::string pkgName = ""; - std::string res = ""; + ProcessInfo res = ""; res = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid); - EXPECT_EQ(pkgName, res); + EXPECT_EQ(pkgName, res.pkgName); } HWTEST_F(DeviceProfileConnectorTest, SingleUserProcess_001, testing::ext::TestSize.Level0) diff --git a/test/unittest/UTTest_dm_pin_holder.h b/test/unittest/UTTest_dm_pin_holder.h index 1de806249..8cd1e8eca 100644 --- a/test/unittest/UTTest_dm_pin_holder.h +++ b/test/unittest/UTTest_dm_pin_holder.h @@ -189,9 +189,9 @@ public: (void)authForm; } - void OnDeviceScreenStateChange(const std::string &pkgName, DmDeviceInfo &devInfo) override + void OnDeviceScreenStateChange(const ProcessInfo &processInfo, DmDeviceInfo &devInfo) override { - (void)pkgName; + (void)processInfo; (void)devInfo; } diff --git a/utils/include/appInfo/lite/app_manager.h b/utils/include/appInfo/lite/app_manager.h index fc69459bc..dc6b24018 100644 --- a/utils/include/appInfo/lite/app_manager.h +++ b/utils/include/appInfo/lite/app_manager.h @@ -30,6 +30,7 @@ public: void UnRegisterCallerAppId(const std::string &pkgName); int32_t GetAppIdByPkgName(const std::string &pkgName, std::string &appId); bool IsSystemSA(); + int32_t GetCallerName(bool isSystemSA, std::string &callerName); int32_t GetNativeTokenIdByName(std::string &processName, int64_t tokenId); int32_t GetHapTokenIdByName(int32_t userId, std::string &bundleName, int32_t instIndex, int64_t tokenId); }; diff --git a/utils/include/appInfo/standard/app_manager.h b/utils/include/appInfo/standard/app_manager.h index 5bb9d3b7a..828e5b123 100644 --- a/utils/include/appInfo/standard/app_manager.h +++ b/utils/include/appInfo/standard/app_manager.h @@ -36,6 +36,7 @@ public: void UnRegisterCallerAppId(const std::string &pkgName); int32_t GetAppIdByPkgName(const std::string &pkgName, std::string &appId); bool IsSystemSA(); + int32_t GetCallerName(bool isSystemSA, std::string &callerName); int32_t GetNativeTokenIdByName(std::string &processName, int64_t tokenId); int32_t GetHapTokenIdByName(int32_t userId, std::string &bundleName, int32_t instIndex, int64_t tokenId); private: diff --git a/utils/src/appInfo/lite/app_manager.cpp b/utils/src/appInfo/lite/app_manager.cpp index d79b82535..40e89b598 100644 --- a/utils/src/appInfo/lite/app_manager.cpp +++ b/utils/src/appInfo/lite/app_manager.cpp @@ -47,14 +47,20 @@ bool AppManager::IsSystemSA() return true; } -int32_t GetNativeTokenIdByName(std::string &processName, int64_t tokenId) +int32_t AppManager::GetCallerName(bool isSystemSA, std::string &callerName) +{ + (void)isSystemSA; + (void)callerName; + return DM_OK; +} +int32_t AppManager::GetNativeTokenIdByName(std::string &processName, int64_t tokenId) { (void)processName; (void)tokenId; return DM_OK; } -int32_t GetHapTokenIdByName(int32_t userId, std::string &bundleName, int32_t instIndex, int64_t tokenId) +int32_t AppManager::GetHapTokenIdByName(int32_t userId, std::string &bundleName, int32_t instIndex, int64_t tokenId) { (void)userId; (void)bundleName; diff --git a/utils/src/appInfo/standard/app_manager.cpp b/utils/src/appInfo/standard/app_manager.cpp index be0c78d93..3bb47c8fb 100644 --- a/utils/src/appInfo/standard/app_manager.cpp +++ b/utils/src/appInfo/standard/app_manager.cpp @@ -197,7 +197,7 @@ int32_t AppManager::GetNativeTokenIdByName(std::string &processName, int64_t tok int32_t AppManager::GetHapTokenIdByName(int32_t userId, std::string &bundleName, int32_t instIndex, int64_t tokenId) { - AccessTokenIDEx hapTokenId = AccessTokenInfoManager::GetInstance().GetHapTokenId(userId, bundleName, instIndex); + auto hapTokenId = AccessTokenKit::GetHapTokenID(userId, bundleName, instIndex); if (hapTokenId == 0) { LOGE("GetHapTokenId failed."); return ERR_DM_FAILED; -- Gitee From 52535c0245ea01531b445fc6b206ab660ef379bc Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Tue, 5 Nov 2024 21:59:13 +0800 Subject: [PATCH 15/27] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E7=BB=91=E5=AE=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/deviceprofile_connector.h | 1 + .../include/multiple_user_connector.h | 2 +- .../src/deviceprofile_connector.cpp | 52 ++++++-- .../src/multiple_user_connector.cpp | 18 +-- .../src/authentication/dm_auth_manager.cpp | 25 ++-- .../src/device_manager_service_impl.cpp | 24 ++-- .../service/src/device_manager_service.cpp | 11 +- .../service/src/softbus/softbus_listener.cpp | 2 +- .../UTTest_dm_auth_manager_first.cpp | 16 +-- .../UTTest_dm_deviceprofile_connector.cpp | 11 +- .../ipc_server_stub_fuzzer.cpp | 9 +- .../softbus_connector_common_fuzzer.cpp | 4 +- .../UTTest_softbus_connector.cpp | 40 ++++--- .../UTTest_device_manager_service.cpp | 11 +- .../UTTest_device_manager_service_impl.cpp | 2 +- .../UTTest_device_manager_service_two.cpp | 5 +- .../UTTest_ipc_server_client_proxy.cpp | 16 ++- test/unittest/UTTest_ipc_server_listener.cpp | 22 +++- test/unittest/UTTest_ipc_server_stub.cpp | 113 +++++++++--------- 19 files changed, 209 insertions(+), 175 deletions(-) diff --git a/commondependency/include/deviceprofile_connector.h b/commondependency/include/deviceprofile_connector.h index e9edccda8..b4b1b4f74 100644 --- a/commondependency/include/deviceprofile_connector.h +++ b/commondependency/include/deviceprofile_connector.h @@ -138,6 +138,7 @@ public: int32_t tokenId, const std::string &localUdid); std::vector GetAllAccessControlProfile(); void DeleteAccessControlById(int64_t accessControlId); + int32_t HandleUserSwitched(const std::string &localUdid, int32_t currentUserId, int32_t beforeUserId); private: int32_t HandleDmAuthForm(DistributedDeviceProfile::AccessControlProfile profiles, DmDiscoveryInfo discoveryInfo); diff --git a/commondependency/include/multiple_user_connector.h b/commondependency/include/multiple_user_connector.h index e42ac7b56..94219d6db 100644 --- a/commondependency/include/multiple_user_connector.h +++ b/commondependency/include/multiple_user_connector.h @@ -94,7 +94,7 @@ public: * @tc.type: FUNC */ static std::string GetSwitchOldAccountName(void); - static void GetSelfTokenIdAndUserId(uint32_t &tokenId, int32_t &userId); + static void GetTokenIdAndForegroundUserId(uint32_t &tokenId, int32_t &userId); static void GetTokenIdAndUserId(uint32_t &tokenId, int32_t &userId); static int32_t GetForegroundUsers(std::vector &userVec); static int32_t GetForegroundUser(void); diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index 3a0e98e17..b6def759a 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -225,7 +225,8 @@ std::vector DeviceProfileConnector::GetBindTypeByPkgName(std::string pk std::string trustUdid) { LOGI("Start."); - std::vector profiles = GetAccessControlProfile(); + std::vector profiles = + GetAccessControlProfileByUserId(MultipleUserConnector::GetForegroundUser()); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); std::vector bindTypeVec; for (auto &item : profiles) { @@ -340,7 +341,8 @@ void DeviceProfileConnector::ProcessBindType(AccessControlProfile profiles, DmDi std::vector DeviceProfileConnector::SyncAclByBindType(std::string pkgName, std::vector bindTypeVec, std::string localDeviceId, std::string targetDeviceId) { - std::vector profiles = GetAccessControlProfile(); + std::vector profiles = + GetAccessControlProfileByUserId(MultipleUserConnector::GetForegroundUser()); LOGI("AccessControlProfile size is %{public}zu", profiles.size()); std::vector sinkBindType; std::vector bindType; @@ -516,7 +518,7 @@ DmOfflineParam DeviceProfileConnector::DeleteAccessControlList(const std::string LOGE("Invalied bindlevel."); return offlineParam; } - std::vector profiles = GetAccessControlProfile();//todo + std::vector profiles = GetAccessControlProfile(); if (profiles.empty()) { LOGE("Acl is empty."); return offlineParam; @@ -850,12 +852,12 @@ int32_t DeviceProfileConnector::CheckIsSameAccount(const DmAccessCaller &caller, return ERR_DM_FAILED; } -int32_t DeviceProfileConnector::GetBindLevel(const std::string &pkgName, const std::string &localUdid,//todo +int32_t DeviceProfileConnector::GetBindLevel(const std::string &pkgName, const std::string &localUdid, const std::string &udid, uint64_t &tokenId) { LOGI("pkgName %{public}s, tokenId %{public}" PRId64", udid %{public}s.", pkgName.c_str(), tokenId, GetAnonyString(udid).c_str()); - std::vector profiles = GetAccessControlProfile();//todo + std::vector profiles = GetAccessControlProfile(); int32_t bindLevel = INVALIED_TYPE; for (auto &item : profiles) { if (item.GetTrustDeviceId() != udid) { @@ -946,13 +948,20 @@ int32_t DeviceProfileConnector::HandleAccountLogoutEvent(int32_t remoteUserId, c LOGI("RemoteUserId %{public}d, remoteAccountHash %{public}s, remoteUdid %{public}s, localUdid %{public}s.", remoteUserId, GetAnonyString(remoteAccountHash).c_str(), GetAnonyString(remoteUdid).c_str(), GetAnonyString(localUdid).c_str()); - std::vector profiles = GetAccessControlProfile(); + std::vector profiles = GetAccessControlProfileByUserId(remoteUserId); int32_t bindType = DM_INVALIED_BINDTYPE; - //TODO: 根据对端退账号的userid清理acl for (const auto &item : profiles) { if (item.GetTrustDeviceId() != remoteUdid) { continue; } + if (item.GetAccesser().GetAccesserDeviceId() == remoteUdid + && item.GetAccesser().GetAccesserUserId() != remoteUserId) { + continue; + } + if (item.GetAccessee().GetAccesseeDeviceId() == remoteUdid + && item.GetAccessee().GetAccesseeUserId() != remoteUserId) { + continue; + } DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); bindType = DM_IDENTICAL_ACCOUNT; } @@ -1044,6 +1053,35 @@ void DeviceProfileConnector::DeleteAccessControlById(int64_t accessControlId) DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(accessControlId); } +int32_t DeviceProfileConnector::HandleUserSwitched(const std::string &localUdid, int32_t currentUserId, + int32_t beforeUserId) +{ + LOGI("Start."); + std::vector profiles = GetAccessControlProfileByUserId(beforeUserId); + LOGI("to inactive ACL size is %{public}zu", profiles.size()); + for (auto &item : profiles) { + if ((item.GetAccesser().GetAccesserUserId() == beforeUserId && + item.GetAccesser().GetAccesserDeviceId() == localUdid) || + (item.GetAccessee().GetAccesseeUserId() == beforeUserId && + item.GetAccessee().GetAccesseeDeviceId() == localUdid)) { + item.SetStatus(INACTIVE); + DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); + } + } + profiles = GetAccessControlProfileByUserId(currentUserId); + LOGI("to active ACL size is %{public}zu", profiles.size()); + for (auto &item : profiles) { + if ((item.GetAccesser().GetAccesserUserId() == beforeUserId && + item.GetAccesser().GetAccesserDeviceId() == localUdid) || + (item.GetAccessee().GetAccesseeUserId() == beforeUserId && + item.GetAccessee().GetAccesseeDeviceId() == localUdid)) { + item.SetStatus(ACTIVE); + DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); + } + } + return DM_OK; +} + IDeviceProfileConnector *CreateDpConnectorInstance() { return &DeviceProfileConnector::GetInstance(); diff --git a/commondependency/src/multiple_user_connector.cpp b/commondependency/src/multiple_user_connector.cpp index 8390a3b39..1b9f45f93 100644 --- a/commondependency/src/multiple_user_connector.cpp +++ b/commondependency/src/multiple_user_connector.cpp @@ -108,31 +108,19 @@ std::string MultipleUserConnector::GetOhosAccountName(void) #endif } -void MultipleUserConnector::GetSelfTokenIdAndUserId(uint32_t &tokenId, int32_t &userId) +void MultipleUserConnector::GetTokenIdAndForegroundUserId(uint32_t &tokenId, int32_t &userId) { - int32_t uid = OHOS::IPCSkeleton::GetCallingUid(); tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); -#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) - return; -#elif OS_ACCOUNT_PART_EXISTS - ErrCode ret = OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId); - if (ret != 0) { - LOGE("GetOsAccountLocalIdFromUid error ret: %{public}d", ret); - return; - } - return; -#else // OS_ACCOUNT_PART_EXISTS - return; -#endif + userId = GetForegroundUser(); } void MultipleUserConnector::GetTokenIdAndUserId(uint32_t &tokenId, int32_t &userId) { - int32_t uid = OHOS::IPCSkeleton::GetCallingUid(); tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); #if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) return; #elif OS_ACCOUNT_PART_EXISTS + int32_t uid = OHOS::IPCSkeleton::GetCallingUid(); ErrCode ret = OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId); if (ret != 0) { LOGE("GetOsAccountLocalIdFromUid error ret: %{public}d", ret); diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index d0900eb6b..24af783be 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -201,7 +201,9 @@ void DmAuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, authRequestContext_->deviceId = deviceId; authRequestContext_->addr = deviceId; authRequestContext_->dmVersion = DM_VERSION_5_0_2; - authRequestContext_->localUserId = 100;//todo + uint32_t tokenId; + MultipleUserConnector::GetTokenIdAndForegroundUserId(tokenId, authRequestContext_->localUserId); + authRequestContext_->tokenId = static_cast(tokenId); authRequestContext_->localAccountId = MultipleUserConnector::GetOhosAccountIdByUserId(authRequestContext_->localUserId); MultipleUserConnector::SetSwitchOldAccountId(authRequestContext_->localAccountId); @@ -223,9 +225,6 @@ void DmAuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, if (IsString(jsonObject, APP_THUMBNAIL)) { authRequestContext_->appThumbnail = jsonObject[APP_THUMBNAIL].get(); } - if (IsString(jsonObject, TAG_TOKENID)) { - authRequestContext_->tokenId = StringToInt64(jsonObject[TAG_TOKENID].get(), STRTOLL_BASE_10); - } if (IsInt32(jsonObject, TAG_BIND_LEVEL)) { authRequestContext_->bindLevel = jsonObject[TAG_BIND_LEVEL].get(); } @@ -353,6 +352,7 @@ int32_t DmAuthManager::DeleteAcl(const std::string &pkgName, const std::string & if (bindLevel == APP) { ProcessInfo processInfo; processInfo.pkgName = pkgName; + processInfo.userId = MultipleUserConnector::GetForegroundUser(); if (offlineParam.leftAclNumber != 0) { LOGI("The pkgName unbind app-level type leftAclNumber not zero."); softbusConnector_->SetProcessInfoVec(offlineParam.processVec); @@ -2532,19 +2532,16 @@ std::string DmAuthManager::GetBundleName(nlohmann::json &jsonObject) int32_t DmAuthManager::GetBinderInfo() { CHECK_NULL_RETURN(authResponseContext_, ERR_DM_POINT_NULL); - std::vector userVec; - int32_t ret = MultipleUserConnector::GetForegroundUsers(userVec); - if (ret != DM_OK || userVec.size() == 0) { - LOGE("get userid error ret: %{public}d.", ret); - return ERR_DM_FAILED; - } - authResponseContext_->localUserId = userVec[0]; - authResponseContext_->localAccountId = - MultipleUserConnector::GetOhosAccountIdByUserId(authResponseContext_->localUserId); if (authResponseContext_->bundleName.empty()) { + authResponseContext_->localUserId = MultipleUserConnector::GetCurrentAccountUserID(); + authResponseContext_->localAccountId = MultipleUserConnector::GetOhosAccountId(); + authResponseContext_->tokenId = authResponseContext_->remoteTokenId; return DM_OK; } - ret = AppManager::GetInstance(). + authResponseContext_->localUserId = MultipleUserConnector::GetForegroundUser(); + authResponseContext_->localAccountId = + MultipleUserConnector::GetOhosAccountIdByUserId(authResponseContext_->localUserId); + int32_t ret = AppManager::GetInstance(). GetNativeTokenIdByName(authResponseContext_->bundleName, authResponseContext_->tokenId); if (ret == DM_OK) { return DM_OK; diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 273688de6..15cabbdf6 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -694,20 +694,12 @@ void DeviceManagerServiceImpl::HandleUserRemoved(int32_t preUserId) void DeviceManagerServiceImpl::HandleUserSwitched(int32_t currentUserId, int32_t beforeUserId) { - LOGI("currentUserId: %{public}d, beforeUserId: %{public}d", currentUserId, beforeUserId); - //DeviceProfileConnector::GetInstance().DeleteAclForUserRemoved(switchUserId); - //CHECK_NULL_VOID(hiChainConnector_); - //hiChainConnector_->DeleteP2PGroup(switchUserId); - std::string curUserAccountId = MultipleUserConnector::GetOhosAccountIdByUserId(currentUserId); - std::string befUserAccountId = MultipleUserConnector::GetOhosAccountIdByUserId(beforeUserId); - - //TODO1: ��ѯDP���Ź�ϵ - - //TODO2: ��olduserid�Ŀ��Ź�ϵstatus����Ϊ0 - - //TODO3: ��newuserid�Ŀ��Ź�ϵstatus����Ϊ1 - - //TODO4: ����DP���Ź�ϵ + LOGI("currentUserId: %{public}s, beforeUserId: %{public}s", GetAnonyInt32(currentUserId).c_str(), + GetAnonyInt32(beforeUserId).c_str()); + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string localUdid = static_cast(localDeviceId); + DeviceProfileConnector::GetInstance().HandleUserSwitched(localUdid, currentUserId, beforeUserId); } void DeviceManagerServiceImpl::ScreenCommonEventCallback(std::string commonEventType) @@ -779,13 +771,13 @@ void DeviceManagerServiceImpl::HandleAccountLogoutEvent(int32_t remoteUserId, co return; } CHECK_NULL_VOID(authMgr_); - //TODO: ���ݶԶ����˺ŵ�userid����Ⱥ�� + //TODO: 根据对端退账号的userid清理群组 authMgr_->DeleteGroup(DM_PKG_NAME, remoteUdid); CHECK_NULL_VOID(listener_); std::string uuid = ""; SoftbusCache::GetInstance().GetUuidByUdid(remoteUdid, uuid); listener_->OnDeviceTrustChange(remoteUdid, uuid, ConvertBindTypeToAuthForm(bindType)); - //TODO���ϱ��߼������߸���Ӧ�ļ����� + //TODO:上报逻辑上下线给对应的监听者 } DmAuthForm DeviceManagerServiceImpl::ConvertBindTypeToAuthForm(int32_t bindType) diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index afc0bfe2c..a419a4a51 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -260,7 +260,7 @@ int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, c } uint32_t tokenId = 0; int32_t userId = -1; - MultipleUserConnector::GetSelfTokenIdAndUserId(tokenId, userId); + MultipleUserConnector::GetTokenIdAndForegroundUserId(tokenId, userId); if (userId == -1 || tokenId == -1) { LOGE("userId or tokenId acquire fail!"); return ERR_DM_INPUT_PARA_INVALID; @@ -571,7 +571,7 @@ int32_t DeviceManagerService::UnAuthenticateDevice(const std::string &pkgName, c return ERR_DM_NOT_INIT; } uint64_t tokenId = 0; - int32_t bindLevel = dmServiceImpl_->GetBindLevel(pkgName, std::string(localUdid), udid, tokenId);//todo + int32_t bindLevel = dmServiceImpl_->GetBindLevel(pkgName, std::string(localUdid), udid, tokenId); LOGI("UnAuthenticateDevice get bindlevel %{public}d.", bindLevel); if (bindLevel == INVALIED_BIND_LEVEL) { LOGE("UnAuthenticateDevice failed, Acl not contain the bindLevel %{public}d.", bindLevel); @@ -678,7 +678,7 @@ int32_t DeviceManagerService::UnBindDevice(const std::string &pkgName, const std char localUdid[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localUdid, DEVICE_UUID_LENGTH); uint64_t tokenId = 0; - int32_t bindLevel = dmServiceImpl_->GetBindLevel(pkgName, std::string(localUdid), udid, tokenId);//todo + int32_t bindLevel = dmServiceImpl_->GetBindLevel(pkgName, std::string(localUdid), udid, tokenId); LOGI("UnAuthenticateDevice get bindlevel %{public}d.", bindLevel); if (bindLevel == INVALIED_BIND_LEVEL) { LOGE("UnAuthenticateDevice failed, Acl not contain the bindLevel %{public}d.", bindLevel); @@ -1646,9 +1646,8 @@ void DeviceManagerService::AccountCommonEventCallback(const std::string commonEv dmServiceImplExt_->AccountUserSwitched(currentUserId, MultipleUserConnector::GetOhosAccountId()); } - //TODO: �����л���beforeUserId�����߼����� - - //TODO: �����л���currentUserId�����߼����ߣ�NO����Ҫ���������û����������ߣ����ܱ��߼����ߣ� + //TODO: 根据切换的beforeUserId,报逻辑下线 + //TODO: 根据切换的currentUserId,报逻辑上线(NO,需要总线在新用户下重新上线,才能报逻辑上线) } else if (commonEventType == CommonEventSupport::COMMON_EVENT_HWID_LOGIN) { MultipleUserConnector::SetSwitchOldAccountId(MultipleUserConnector::GetOhosAccountId()); MultipleUserConnector::SetSwitchOldAccountName(MultipleUserConnector::GetOhosAccountName()); diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index 1bdcc4ebc..b06255e35 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -121,7 +121,7 @@ static INodeStateCb softbusNodeStateCb_ = { .onLocalNetworkIdChanged = SoftbusListener::OnLocalDevInfoChange, .onNodeDeviceTrustedChange = SoftbusListener::OnDeviceTrustedChange, .onNodeStatusChanged = SoftbusListener::OnDeviceScreenStatusChanged, - .onHichainProofException = SoftbusListener::OnCredentialAuthStatus, + //.onHichainProofException = SoftbusListener::OnCredentialAuthStatus, }; static IRefreshCallback softbusRefreshCallback_ = { diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index 57f0ca81b..c0e6a625c 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -777,40 +777,40 @@ HWTEST_F(DmAuthManagerTest, SrcAuthDeviceFinish001, testing::ext::TestSize.Level authManager_->authResponseContext_->hostPkgName = "hostPkgName"; authManager_->softbusConnector_->deviceStateManagerCallback_ = std::make_shared(); authManager_->SrcAuthDeviceFinish(); - EXPECT_TRUE(authManager_->softbusConnector_->pkgNameVec_.size() > 0); + EXPECT_TRUE(authManager_->softbusConnector_->processInfoVec_.size() > 0); authManager_->authResponseContext_->confirmOperation = USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; authManager_->authResponseContext_->hostPkgName = ""; authManager_->SrcAuthDeviceFinish(); - EXPECT_TRUE(authManager_->softbusConnector_->pkgNameVec_.size() > 0); + EXPECT_TRUE(authManager_->softbusConnector_->processInfoVec_.size() > 0); authManager_->authResponseContext_->isIdenticalAccount = true; authManager_->SrcAuthDeviceFinish(); - EXPECT_TRUE(authManager_->softbusConnector_->pkgNameVec_.size() > 0); + EXPECT_TRUE(authManager_->softbusConnector_->processInfoVec_.size() > 0); authManager_->authResponseContext_->bindLevel = SERVICE; authManager_->SrcAuthDeviceFinish(); - EXPECT_TRUE(authManager_->softbusConnector_->pkgNameVec_.size() > 0); + EXPECT_TRUE(authManager_->softbusConnector_->processInfoVec_.size() > 0); authManager_->authResponseContext_->haveCredential = false; authManager_->authResponseContext_->bindLevel = APP; authManager_->authResponseContext_->isIdenticalAccount = false; authManager_->authResponseContext_->hostPkgName = "hostPkgName"; authManager_->SrcAuthDeviceFinish(); - EXPECT_TRUE(authManager_->softbusConnector_->pkgNameVec_.size() > 0); + EXPECT_TRUE(authManager_->softbusConnector_->processInfoVec_.size() > 0); authManager_->authResponseContext_->hostPkgName = ""; authManager_->SrcAuthDeviceFinish(); - EXPECT_TRUE(authManager_->softbusConnector_->pkgNameVec_.size() > 0); + EXPECT_TRUE(authManager_->softbusConnector_->processInfoVec_.size() > 0); authManager_->authResponseContext_->bindLevel = SERVICE; authManager_->authResponseContext_->isIdenticalAccount = true; authManager_->SrcAuthDeviceFinish(); - EXPECT_TRUE(authManager_->softbusConnector_->pkgNameVec_.size() > 0); + EXPECT_TRUE(authManager_->softbusConnector_->processInfoVec_.size() > 0); authManager_->authResponseContext_->confirmOperation = USER_OPERATION_TYPE_DONE_PINCODE_INPUT; authManager_->SrcAuthDeviceFinish(); - EXPECT_TRUE(authManager_->softbusConnector_->pkgNameVec_.size() > 0); + EXPECT_TRUE(authManager_->softbusConnector_->processInfoVec_.size() > 0); } HWTEST_F(DmAuthManagerTest, SrcAuthDeviceFinish002, testing::ext::TestSize.Level0) diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index 8f9fd3a26..6fb2e5905 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -47,7 +47,8 @@ HWTEST_F(DeviceProfileConnectorTest, GetAppTrustDeviceList_001, testing::ext::Te { std::string pkgName; std::string deviceId = "deviceId"; - auto ret = DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgName, deviceId); + int32_t userId = 100; + auto ret = DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgName, deviceId, userId); EXPECT_EQ(ret.empty(), true); } @@ -55,7 +56,8 @@ HWTEST_F(DeviceProfileConnectorTest, GetAppTrustDeviceList_002, testing::ext::Te { std::string pkgName = "bundleName"; std::string deviceId = "deviceId"; - auto ret = DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgName, deviceId); + int32_t userId = 100; + auto ret = DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgName, deviceId, userId); EXPECT_EQ(ret.empty(), true); } @@ -792,9 +794,8 @@ HWTEST_F(DeviceProfileConnectorTest, HandleAppUnBindEvent_001, testing::ext::Tes std::string remoteUdid = "remoteDeviceId"; std::string localUdid = "localDeviceId"; std::string pkgName = ""; - ProcessInfo res = ""; - - res = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid); + ProcessInfo res + = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid); EXPECT_EQ(pkgName, res.pkgName); } diff --git a/test/servicesfuzztest/ipcserverstub_fuzzer/ipc_server_stub_fuzzer.cpp b/test/servicesfuzztest/ipcserverstub_fuzzer/ipc_server_stub_fuzzer.cpp index 7d1666c72..b4d6047b6 100644 --- a/test/servicesfuzztest/ipcserverstub_fuzzer/ipc_server_stub_fuzzer.cpp +++ b/test/servicesfuzztest/ipcserverstub_fuzzer/ipc_server_stub_fuzzer.cpp @@ -48,16 +48,15 @@ void IpcServerStubFuzzTest(const uint8_t* data, size_t size) sptr listener = sptr(new IpcServerStub()); std::shared_ptr req = nullptr; std::shared_ptr rsp = std::make_shared(); - - IpcServerStub::GetInstance().Init(); - IpcServerStub::GetInstance().OnRemoteRequest(code, data1, reply, option); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); ProcessInfo processInfo; processInfo.pkgName = pkgName; + IpcServerStub::GetInstance().Init(); + IpcServerStub::GetInstance().OnRemoteRequest(code, data1, reply, option); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); IpcServerStub::GetInstance().GetDmListener(processInfo); IpcServerStub::GetInstance().SendCmd(code, req, rsp); IpcServerStub::GetInstance().GetAllProcessInfo(); - IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); } } } diff --git a/test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.cpp b/test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.cpp index 2d666504d..caa6d47cf 100644 --- a/test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.cpp +++ b/test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.cpp @@ -38,7 +38,9 @@ void SoftBusConnectorCommonFuzzTest(const uint8_t* data, size_t size) softbusConnector->GetDeviceUdidHashByUdid(str); softbusConnector->EraseUdidFromMap(str); softbusConnector->GetNetworkIdByDeviceId(str); - softbusConnector->SetPkgName(str); + ProcessInfo processInfo; + processInfo.pkgName = str; + softbusConnector->SetProcessInfo(processInfo); softbusConnector->CheckIsOnline(str); softbusConnector->GetDeviceInfoByDeviceId(str); } diff --git a/test/softbusunittest/UTTest_softbus_connector.cpp b/test/softbusunittest/UTTest_softbus_connector.cpp index 8c467dd65..92c14664b 100644 --- a/test/softbusunittest/UTTest_softbus_connector.cpp +++ b/test/softbusunittest/UTTest_softbus_connector.cpp @@ -812,14 +812,16 @@ HWTEST_F(SoftbusConnectorTest, AddMemberToDiscoverMap_002, testing::ext::TestSiz * @tc.name: SetPkgName_001 * @tc.type: FUNC */ -HWTEST_F(SoftbusConnectorTest, SetPkgName_001, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusConnectorTest, SetProcessInfo_001, testing::ext::TestSize.Level0) { std::string pkgName = "pkgName"; - std::vector pkgNameVec; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + std::vector processInfoVec; std::shared_ptr softbusConnector = std::make_shared(); - softbusConnector->SetPkgNameVec(pkgNameVec); - softbusConnector->SetPkgName(pkgName); - EXPECT_EQ(softbusConnector->pkgNameVec_.empty(), false); + softbusConnector->SetProcessInfoVec(processInfoVec); + softbusConnector->SetProcessInfo(processInfo); + EXPECT_EQ(softbusConnector->processInfoVec_.empty(), false); } /** @@ -870,25 +872,25 @@ HWTEST_F(SoftbusConnectorTest, GetNetworkIdByDeviceId_001, testing::ext::TestSiz } /** - * @tc.name: SetPkgNameVec_001 + * @tc.name: SetProcessInfoVec_001 * @tc.type: FUNC */ -HWTEST_F(SoftbusConnectorTest, SetPkgNameVec_001, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusConnectorTest, SetProcessInfoVec_001, testing::ext::TestSize.Level0) { - std::vector pkgNameVec; + std::vector processInfoVec; std::shared_ptr softbusConnector = std::make_shared(); - softbusConnector->SetPkgNameVec(pkgNameVec); - EXPECT_EQ(pkgNameVec.empty(), true); + softbusConnector->SetProcessInfoVec(processInfoVec); + EXPECT_EQ(processInfoVec.empty(), true); } /** * @tc.name: GetPkgName_001 * @tc.type: FUNC */ -HWTEST_F(SoftbusConnectorTest, GetPkgName_001, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusConnectorTest, GetProcessInfo_001, testing::ext::TestSize.Level0) { std::shared_ptr softbusConnector = std::make_shared(); - auto ret = softbusConnector->GetPkgName(); + auto ret = softbusConnector->GetProcessInfo(); EXPECT_EQ(ret.empty(), true); } @@ -896,11 +898,11 @@ HWTEST_F(SoftbusConnectorTest, GetPkgName_001, testing::ext::TestSize.Level0) * @tc.name: ClearPkgName_001 * @tc.type: FUNC */ -HWTEST_F(SoftbusConnectorTest, ClearPkgName_001, testing::ext::TestSize.Level0) +HWTEST_F(SoftbusConnectorTest, ClearProcessInfo_001, testing::ext::TestSize.Level0) { std::shared_ptr softbusConnector = std::make_shared(); - softbusConnector->ClearPkgName(); - EXPECT_EQ(softbusConnector->pkgNameVec_.empty(), true); + softbusConnector->ClearProcessInfo(); + EXPECT_EQ(softbusConnector->processInfoVec_.empty(), true); } /** @@ -914,7 +916,7 @@ HWTEST_F(SoftbusConnectorTest, HandleDeviceOnline_001, testing::ext::TestSize.Le std::shared_ptr callback = std::make_shared(); softbusConnector->RegisterSoftbusStateCallback(callback); softbusConnector->HandleDeviceOnline(deviceId, DmAuthForm::ACROSS_ACCOUNT); - EXPECT_EQ(softbusConnector->pkgNameVec_.empty(), true); + EXPECT_EQ(softbusConnector->processInfoVec_.empty(), true); } /** @@ -928,7 +930,7 @@ HWTEST_F(SoftbusConnectorTest, HandleDeviceOffline_001, testing::ext::TestSize.L std::shared_ptr callback = std::make_shared(); softbusConnector->RegisterSoftbusStateCallback(callback); softbusConnector->HandleDeviceOffline(deviceId); - EXPECT_EQ(softbusConnector->pkgNameVec_.empty(), true); + EXPECT_EQ(softbusConnector->processInfoVec_.empty(), true); } /** @@ -940,7 +942,7 @@ HWTEST_F(SoftbusConnectorTest, CheckIsOnline_001, testing::ext::TestSize.Level0) std::string targetDeviceId = "targetDeviceId"; std::shared_ptr softbusConnector = std::make_shared(); softbusConnector->CheckIsOnline(targetDeviceId); - EXPECT_EQ(softbusConnector->pkgNameVec_.empty(), true); + EXPECT_EQ(softbusConnector->processInfoVec_.empty(), true); } /** @@ -968,7 +970,7 @@ HWTEST_F(SoftbusConnectorTest, ConvertNodeBasicInfoToDmDevice_001, testing::ext: DmDeviceInfo dmDeviceInfo; std::shared_ptr softbusConnector = std::make_shared(); softbusConnector->ConvertNodeBasicInfoToDmDevice(nodeBasicInfo, dmDeviceInfo); - EXPECT_EQ(softbusConnector->pkgNameVec_.empty(), true); + EXPECT_EQ(softbusConnector->processInfoVec_.empty(), true); } } // namespace } // namespace DistributedHardware diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index 860d53862..a2a03fe49 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -326,20 +326,21 @@ HWTEST_F(DeviceManagerServiceTest, UnPublishDeviceDiscovery_004, testing::ext::T std::string pkgName = "com.ohos.test003"; int32_t publishId = 1; int32_t userId = 23; + int32_t userId1 = 101; std::string accountId = "hello123"; int32_t preUserId = 3; std::vector peerUdids; std::string accountName = "openharmony123"; std::string commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED; - DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, userId1); commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGIN; - DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, userId1); commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT; - DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, userId1); commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED; - DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, userId1); commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_BOOT_COMPLETED; - DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, userId1); DeviceManagerService::GetInstance().HandleAccountLogout(userId, accountId); DeviceManagerService::GetInstance().HandleUserRemoved(preUserId); DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 5042479b1..610bea99d 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -1333,7 +1333,7 @@ HWTEST_F(DeviceManagerServiceImplTest, GetAppTrustDeviceIdList_003, testing::ext if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); } - auto ret = deviceManagerServiceImpl_->GetAppTrustDeviceIdList(pkgname); + auto ret = deviceManagerServiceImpl_->GetAppTrustDeviceIdList(pkgname, 0); EXPECT_EQ(ret.empty(), true); } diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index e24249309..9f1ac7520 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -244,10 +244,11 @@ HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_202, testing::ext::TestSiz HWTEST_F(DeviceManagerServiceTest, InitAccountInfo_201, testing::ext::TestSize.Level0) { int32_t userId = 100; + int32_t userId1 = 101; std::string commonEventType = "usual.event.USER_SWITCHED"; - DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, userId1); commonEventType = "common.event.HWID_LOGIN"; - DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, userId1); int32_t ret = DeviceManagerService::GetInstance().InitAccountInfo(); EXPECT_EQ(ret, DM_OK); } diff --git a/test/unittest/UTTest_ipc_server_client_proxy.cpp b/test/unittest/UTTest_ipc_server_client_proxy.cpp index d987321e3..46b1c3f5e 100644 --- a/test/unittest/UTTest_ipc_server_client_proxy.cpp +++ b/test/unittest/UTTest_ipc_server_client_proxy.cpp @@ -100,7 +100,9 @@ HWTEST_F(IpcServerClientProxyTest, SendCmd_002, testing::ext::TestSize.Level0) DmDeviceInfo deviceInfo; // 2. set remoteObject not nullptr sptr remoteObject = sptr(new IpcClientStub()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); // set req not null @@ -140,7 +142,9 @@ HWTEST_F(IpcServerClientProxyTest, SendCmd_003, testing::ext::TestSize.Level0) DmDeviceInfo dmDeviceInfo; // 2. set remoteObject not nullptr sptr remoteObject = sptr(new IpcClientStub()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); // set req not null @@ -180,7 +184,9 @@ HWTEST_F(IpcServerClientProxyTest, SendCmd_004, testing::ext::TestSize.Level0) int32_t result = 1; // 2. set remoteObject not nullptr sptr remoteObject = sptr(new IpcClientStub()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); // set req not null @@ -220,7 +226,9 @@ HWTEST_F(IpcServerClientProxyTest, SendCmd_005, testing::ext::TestSize.Level0) int32_t result = 1; // 2. set remoteObject not nullptr sptr remoteObject = sptr(new IpcClientStub()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); // set req not null diff --git a/test/unittest/UTTest_ipc_server_listener.cpp b/test/unittest/UTTest_ipc_server_listener.cpp index fb83d8974..eaafad6c5 100644 --- a/test/unittest/UTTest_ipc_server_listener.cpp +++ b/test/unittest/UTTest_ipc_server_listener.cpp @@ -131,7 +131,9 @@ HWTEST_F(IpcServerListenerTest, SendRequest_003, testing::ext::TestSize.Level0) std::string pkgName = "com.ohos.test"; // 2. set remoteObject not nullptr sptr remoteObject = sptr(new IpcClientStub()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); // set req not null std::shared_ptr req = std::make_shared(); // set rsp not null @@ -165,7 +167,9 @@ HWTEST_F(IpcServerListenerTest, SendRequest_004, testing::ext::TestSize.Level0) // 2. set remoteObject nullptr sptr remoteObject = sptr(new IpcClientStub()); remoteObject = nullptr; - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); // set req not null std::shared_ptr req = std::make_shared(); // set rsp not null @@ -176,7 +180,7 @@ HWTEST_F(IpcServerListenerTest, SendRequest_004, testing::ext::TestSize.Level0) int ret = ipcServerListener->SendRequest(cmdCode, req, rsp); // 4. check ret is ERR_DM_INPUT_PARA_INVALID ASSERT_EQ(ret, ERR_DM_UNSUPPORTED_IPC_COMMAND); - IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); } /** @@ -199,7 +203,9 @@ HWTEST_F(IpcServerListenerTest, SendRequest_005, testing::ext::TestSize.Level0) std::string pkgName = "com.ohos.test"; // 2. set remoteObject nullptr sptr remoteObject = sptr(new IpcClientStub()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); // set req not null std::shared_ptr req = std::make_shared(); // set rsp not null @@ -232,7 +238,9 @@ HWTEST_F(IpcServerListenerTest, SendRequest_006, testing::ext::TestSize.Level0) std::string pkgName = "com.ohos.test"; // 2. set remoteObject nullptr sptr remoteObject = sptr(new IpcClientStub()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); // set req not null std::shared_ptr req = std::make_shared(); // set rsp null @@ -265,7 +273,9 @@ HWTEST_F(IpcServerListenerTest, SendRequest_007, testing::ext::TestSize.Level0) std::string pkgName = "com.ohos.test"; // 2. set remoteObject nullptr sptr remoteObject = sptr(new IpcClientStub()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); // set req not null std::shared_ptr req = std::make_shared(); // set rsp null diff --git a/test/unittest/UTTest_ipc_server_stub.cpp b/test/unittest/UTTest_ipc_server_stub.cpp index 593feaf57..f0fec3f64 100644 --- a/test/unittest/UTTest_ipc_server_stub.cpp +++ b/test/unittest/UTTest_ipc_server_stub.cpp @@ -229,7 +229,9 @@ HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_001, testing::ext::Tes std::string pkgName = ""; int ret = 0; sptr listener = nullptr; - ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); ASSERT_EQ(ret, ERR_DM_POINT_NULL); } @@ -245,7 +247,9 @@ HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_002, testing::ext::Tes std::string pkgName = "com.ohos.test"; int ret = 0; sptr listener = sptr(new IpcClientStub()); - ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); ASSERT_EQ(ret, DM_OK); } @@ -261,7 +265,9 @@ HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_003, testing::ext::Tes std::string pkgName = ""; int ret = 0; sptr listener = sptr(new IpcClientStub()); - ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); ASSERT_EQ(ret, ERR_DM_POINT_NULL); } @@ -280,7 +286,9 @@ HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_004, testing::ext::Tes int ret = 0; sptr listener = sptr(new IpcClientStub()); // 2. Call IpcServerStub RegisterDeviceManagerListener with param - ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is DM_OK ASSERT_EQ(ret, DM_OK); } @@ -305,18 +313,20 @@ HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_005, testing::ext::Tes int result = 0; sptr listener = sptr(new IpcClientStub()); // 2. Call IpcServerStub RegisterDeviceManagerListener with param - ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is DM_OK ASSERT_EQ(ret, DM_OK); sptr listener2 = sptr(new IpcClientStub()); // 4. Call IpcServerStub RegisterDeviceManagerListener with same pkgName another listener - result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener2); + result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener2); // 5. check result is DM_OK ASSERT_EQ(result, DM_OK); sptr listener3 = sptr(new IpcClientStub()); // 6. earse pkgName for appRecipient_ - IpcServerStub::GetInstance().appRecipient_.erase(pkgName); - result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener3); + IpcServerStub::GetInstance().appRecipient_.erase(processInfo); + result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener3); // 7. check result is DM_OK ASSERT_EQ(result, DM_OK); } @@ -330,9 +340,9 @@ HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_005, testing::ext::Tes */ HWTEST_F(IpcServerStubTest, UnRegisterDeviceManagerListener_001, testing::ext::TestSize.Level0) { - std::string pkgName; + ProcessInfo processInfo; int ret = 0; - ret = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + ret = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -352,13 +362,15 @@ HWTEST_F(IpcServerStubTest, UnRegisterDeviceManagerListener_002, testing::ext::T std::string pkgName = "com.ohos.test"; int ret = 0; sptr listener = sptr(new IpcClientStub()); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; // 2. Call IpcServerStub RegisterDeviceManagerListener with param - ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is DM_OK ASSERT_EQ(ret, DM_OK); int result = 0; // 4. Call IpcServerStub UnRegisterDeviceManagerListener - result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); // 5. check ret is DM_OK ASSERT_EQ(result, DM_OK); } @@ -377,7 +389,9 @@ HWTEST_F(IpcServerStubTest, UnRegisterDeviceManagerListener_003, testing::ext::T std::string pkgName = "com.ohos.test"; int ret = 0; // 2. Call IpcServerStub UnRegisterDeviceManagerListener - ret = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + ret = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); // 3. check ret is DM_OK ASSERT_EQ(ret, DM_OK); } @@ -396,18 +410,20 @@ HWTEST_F(IpcServerStubTest, UnRegisterDeviceManagerListener_004, testing::ext::T { // 1. Set PkgName is com.ohos.test std::string pkgName = "com.ohos.test1"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; int ret = 0; sptr listener = sptr(new IpcClientStub()); // 2. Call IpcServerStub RegisterDeviceManagerListener with param - ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is DM_OK ASSERT_EQ(ret, DM_OK); int result = 0; // 4. Call IpcServerStub UnRegisterDeviceManagerListener - result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); // 5. check ret is DM_OK ASSERT_EQ(result, DM_OK); - sptr dmListener = IpcServerStub::GetInstance().dmListener_[pkgName]; + sptr dmListener = IpcServerStub::GetInstance().dmListener_[processInfo]; ASSERT_EQ(dmListener, nullptr); } @@ -430,49 +446,26 @@ HWTEST_F(IpcServerStubTest, UnRegisterDeviceManagerListener_005, testing::ext::T int ret = 0; sptr listener = sptr(new IpcClientStub()); // 2. Call IpcServerStub RegisterDeviceManagerListener with param - ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is DM_OK ASSERT_EQ(ret, DM_OK); int result = 0; // 4. Call IpcServerStub UnRegisterDeviceManagerListener std::string testPkgName = "com.test"; - result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(testPkgName); + ProcessInfo processInfo1; + processInfo1.pkgName = testPkgName; + result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo1); // 5. check ret is DM_OK ASSERT_EQ(result, DM_OK); - IpcServerStub::GetInstance().appRecipient_.erase(pkgName); + IpcServerStub::GetInstance().appRecipient_.erase(processInfo); // 6. Call IpcServerStub UnRegisterDeviceManagerListener - result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); // 7. check ret is DM_OK ASSERT_EQ(result, DM_OK); } -/** - * @tc.name: SendALL_001 - * @tc.desc: 1. Set PkgName1 is com.ohos.SendALL_001 - * 2. Set PkgName2 is com.ohos.SendALL_002 - * 3. Add listener1 (nullptr) to dmListener_ with key pkgName1 - * 4. Add listener2 to dmListener_ with key listener2 - * 5. Call IpcServerStub::SendALL with cmdCode, req, rsp - * 6. Check result is DM_OK - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(IpcServerStubTest, SendALL_001, testing::ext::TestSize.Level0) -{ - int32_t cmdCode = -1; - std::shared_ptr req = std::make_shared(); - std::shared_ptr rsp = std::make_shared(); - std::string pkgName1 = "com.ohos.SendALL_001"; - std::string pkgName2 = "com.ohos.SendALL_002"; - sptr listener1 = nullptr; - sptr listener2 = sptr(new IpcClientStub()); - IpcServerStub::GetInstance().dmListener_[pkgName1] = listener1; - IpcServerStub::GetInstance().dmListener_[pkgName2] = listener2; - int32_t result = IpcServerStub::GetInstance().SendALL(cmdCode, req, rsp); - ASSERT_EQ(result, DM_OK); - IpcServerStub::GetInstance().dmListener_.clear(); -} - /** * @tc.name: GetDmListenerPkgName_001 * @tc.desc: 1. Set pkgName is com.ohos.GetDmListenerPkgName_001 @@ -491,7 +484,7 @@ HWTEST_F(IpcServerStubTest, GetDmListenerPkgName_001, testing::ext::TestSize.Lev sptr listener = sptr(new IpcClientStub()); IpcServerStub::GetInstance().dmListener_[processInfo] = listener; ProcessInfo ret = IpcServerStub::GetInstance().GetDmListenerPkgName(remote); - EXPECT_TRUE(ret == nullptr || (ret == processInfo)); + EXPECT_TRUE(ret == processInfo); IpcServerStub::GetInstance().dmListener_.clear(); } @@ -532,7 +525,7 @@ HWTEST_F(IpcServerStubTest, GetDmListener_002, testing::ext::TestSize.Level0) int result = 0; sptr listener = sptr(new IpcClientStub()); // 2. Call IpcServerStub RegisterDeviceManagerListener with param - result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is DM_OK ASSERT_EQ(result, DM_OK); sptr ret = nullptr; @@ -557,14 +550,16 @@ HWTEST_F(IpcServerStubTest, GetDmListener_003, testing::ext::TestSize.Level0) int result = 0; sptr listener = sptr(new IpcClientStub()); // 2. Call IpcServerStub RegisterDeviceManagerListener with param - result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ProcessInfo processInfo; + processInfo.pkgName = "test"; + result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is DM_OK ASSERT_EQ(result, DM_OK); sptr ret = nullptr; // 2. Call IpcServerStub UnRegisterDeviceManagerListener - ProcessInfo processInfo; - processInfo.pkgName = "test"; - ret = IpcServerStub::GetInstance().GetDmListener(processInfo); + ProcessInfo processInfo1; + processInfo1.pkgName = "test"; + ret = IpcServerStub::GetInstance().GetDmListener(processInfo1); // 3. check ret is DM_OK ASSERT_EQ(ret, nullptr); } @@ -584,13 +579,13 @@ HWTEST_F(IpcServerStubTest, GetDmListener_004, testing::ext::TestSize.Level0) int result = 0; sptr listener = sptr(new IpcClientStub()); // 2. Call IpcServerStub RegisterDeviceManagerListener with param - result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ProcessInfo processInfo; + processInfo.pkgName = ""; + result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is ERR_DM_POINT_NULL ASSERT_EQ(result, ERR_DM_POINT_NULL); sptr ret = nullptr; // 2. Call IpcServerStub UnRegisterDeviceManagerListener - ProcessInfo processInfo; - processInfo.pkgName = ""; ret = IpcServerStub::GetInstance().GetDmListener(processInfo); // 3. check ret is nullptr ASSERT_EQ(ret, nullptr); @@ -608,16 +603,16 @@ HWTEST_F(IpcServerStubTest, GetDmListener_005, testing::ext::TestSize.Level0) { // 1. Set pkgName is null std::string pkgName = "com.test.ohos"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; int result = 0; sptr listener = nullptr; // 2. Call IpcServerStub RegisterDeviceManagerListener with param - result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is ERR_DM_POINT_NULL ASSERT_EQ(result, ERR_DM_POINT_NULL); sptr ret = nullptr; // 2. Call IpcServerStub UnRegisterDeviceManagerListener - ProcessInfo processInfo; - processInfo.pkgName = pkgName; ret = IpcServerStub::GetInstance().GetDmListener(processInfo); // 3. check ret is nullptr ASSERT_EQ(ret, nullptr); -- Gitee From 3cc01702424d5148d3cb7298e66b4f32d78a3551 Mon Sep 17 00:00:00 2001 From: hwzhangchuang Date: Wed, 6 Nov 2024 20:10:42 +0800 Subject: [PATCH 16/27] add delete user broadcast Signed-off-by: hwzhangchuang --- .../include/device_manager_service_impl.h | 1 + .../src/device_manager_service_impl.cpp | 6 ++ .../service/include/device_manager_service.h | 3 +- .../include/idevice_manager_service_impl.h | 1 + .../relationship_sync_mgr.h | 8 +- .../service/src/device_manager_service.cpp | 35 ++++++-- .../relationship_sync_mgr.cpp | 85 +++++++++++++++---- 7 files changed, 114 insertions(+), 25 deletions(-) diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index f10435f6a..c1218e2f6 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -155,6 +155,7 @@ private: void HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid); void HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId); void HandleUserRemoved(int32_t preUserId); + void HandleRemoteUserRemoved(int32_t preUserId, const std::string &remoteUdid); DmAuthForm ConvertBindTypeToAuthForm(int32_t bindType); void HandleUserSwitched(int32_t currentUserId, int32_t beforeUserId); diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 15cabbdf6..a4836fffe 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -692,6 +692,12 @@ void DeviceManagerServiceImpl::HandleUserRemoved(int32_t preUserId) hiChainConnector_->DeleteAllGroup(preUserId); } +void DeviceManagerServiceImpl::HandleRemoteUserRemoved(int32_t userId, const std::string &remoteUdid) +{ + LOGI("remoteUdid %{public}s, userId %{public}d", GetAnonyString(remoteUdid).c_str(), userId); + //TOOD: process remote device delete user +} + void DeviceManagerServiceImpl::HandleUserSwitched(int32_t currentUserId, int32_t beforeUserId) { LOGI("currentUserId: %{public}s, beforeUserId: %{public}s", GetAnonyInt32(currentUserId).c_str(), diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index b31a3b844..2b500027f 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -219,6 +219,7 @@ private: const std::vector &userIds); void HandleForegroundUserIdsBroadCast(const std::vector &remoteUserIds, const std::string &remoteUdid, bool isNeedResponse); + void SendUserRemovedBroadCast(const std::vector &peerUdids, int32_t userId); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) void SubscribeAccountCommonEvent(); @@ -229,7 +230,7 @@ private: int32_t ConvertUdidHashToAnoyDeviceId(const std::string &udidHash, std::string &anoyDeviceId); int32_t GetUdidHashByAnoyDeviceId(const std::string &anoyDeviceId, std::string &udidHash); void HandleAccountLogout(int32_t userId, const std::string &accountId); - void HandleUserRemoved(int32_t preUserId); + void HandleUserRemoved(int32_t removedUserId); /** * @brief process the user switch * diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index ec9eb5e26..74d154bf8 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -278,6 +278,7 @@ public: virtual int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId) = 0; virtual void HandleSyncForegroundUserIdEvent(const std::vector &remoteUserIds, const std::string &remoteUdid) = 0; + virtual void HandleRemoteUserRemoved(int32_t userId, const std::string &remoteUdid) = 0; }; using CreateDMServiceFuncPtr = IDeviceManagerServiceImpl *(*)(void); diff --git a/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h b/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h index 08de2fae2..fb8b3b3cf 100644 --- a/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h +++ b/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h @@ -58,13 +58,15 @@ struct RelationShipChangeMsg { void ToAccountLogoutPayLoad(uint8_t *&msg, uint32_t &len) const; void ToDeviceUnbindPayLoad(uint8_t *&msg, uint32_t &len) const; void ToAppUnbindPayLoad(uint8_t *&msg, uint32_t &len) const; - void ToSyncForegroundUserId(uint8_t *&msg, uint32_t &len) const; - cJSON *ToArrayJson() const; + void ToSyncForegroundUserIdPayLoad(uint8_t *&msg, uint32_t &len) const; + void ToDelUserPayLoad(uint8_t *&msg, uint32_t &len) const; + cJSON *ToPayLoadJson() const; bool FromAccountLogoutPayLoad(const cJSON *payloadJson); bool FromDeviceUnbindPayLoad(const cJSON *payloadJson); bool FromAppUnbindPayLoad(const cJSON *payloadJson); - bool FromSyncForegroundUserId(const cJSON *payloadJson); + bool FromSyncForegroundUserIdPayLoad(const cJSON *payloadJson); + bool FromDelUserPayLoad(const cJSON *payloadJson); std::string ToJson() const; bool FromJson(const std::string &msgJson); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index a419a4a51..94270bae8 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -261,7 +261,7 @@ int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, c uint32_t tokenId = 0; int32_t userId = -1; MultipleUserConnector::GetTokenIdAndForegroundUserId(tokenId, userId); - if (userId == -1 || tokenId == -1) { + if (userId == -1 || tokenId == 0) { LOGE("userId or tokenId acquire fail!"); return ERR_DM_INPUT_PARA_INVALID; } @@ -1637,7 +1637,7 @@ void DeviceManagerService::AccountCommonEventCallback(const std::string commonEv if (commonEventType == CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { if (MultipleUserConnector::GetSwitchOldUserId() > 0 && (currentUserId != MultipleUserConnector::GetSwitchOldUserId())) { - HandleUserSwitched(currentUserId, MultipleUserConnector::GetSwitchOldUserId()); + HandleUserSwitched(currentUserId, beforeUserId); } MultipleUserConnector::SetSwitchOldUserId(currentUserId); MultipleUserConnector::SetSwitchOldAccountId(MultipleUserConnector::GetOhosAccountId()); @@ -1716,14 +1716,36 @@ void DeviceManagerService::HandleUserSwitched(int32_t currentUserId, int32_t bef } } -void DeviceManagerService::HandleUserRemoved(int32_t preUserId) +void DeviceManagerService::HandleUserRemoved(int32_t removedUserId) { - LOGI("PreUserId %{public}d.", preUserId); + LOGI("PreUserId %{public}d.", removedUserId); + std::map deviceMap; + std::vector peerUdids; + deviceMap = dmServiceImpl_->GetDeviceIdAndBindType(removedUserId); + for (const auto &item : deviceMap) { + peerUdids.emplace_back(item.first); + } + if (!peerUdids.empty()) { + // Send UserId Removed broadcast + SendUserRemovedBroadCast(peerUdids, removedUserId); + } if (IsDMServiceImplReady()) { - dmServiceImpl_->HandleUserRemoved(preUserId); + dmServiceImpl_->HandleUserRemoved(removedUserId); } } +void DeviceManagerService::SendUserRemovedBroadCast(const std::vector &peerUdids, int32_t userId) +{ + LOGI("peerUdids: %{public}s, userId %{public}d.", GetAnonyStringList(peerUdids).c_str(), userId); + RelationShipChangeMsg msg; + msg.type = RelationShipChangeType::DEL_USER; + msg.userId = userId; + msg.peerUdids = peerUdids; + std::string broadCastMsg = ReleationShipSyncMgr::GetInstance().SyncTrustRelationShip(msg); + CHECK_NULL_VOID(softbusListener_); + softbusListener_->SendAclChangedBroadcast(broadCastMsg); +} + void DeviceManagerService::SendAccountLogoutBroadCast(const std::vector &peerUdids, const std::string &accountId, const std::string &accountName, int32_t userId) { @@ -1998,6 +2020,9 @@ void DeviceManagerService::HandleDeviceTrustedChange(const std::string &msg) HandleForegroundUserIdsBroadCast(relationShipMsg.foregroundUserIds, relationShipMsg.peerUdid, relationShipMsg.syncUserIdFlag); break; + case RelationShipChangeType::DEL_USER: + dmServiceImpl_->HandleRemoteUserRemoved(relationShipMsg.userId, relationShipMsg.peerUdid); + break; default: LOGI("Dm have not this event type."); break; diff --git a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp index 5c32cbcec..1d6d52216 100644 --- a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp +++ b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp @@ -25,23 +25,33 @@ namespace DistributedHardware { DM_IMPLEMENT_SINGLE_INSTANCE(ReleationShipSyncMgr); namespace { /** - * @brief account logout payload length 8 + * @brief account logout payload length 8 bytes * | 2 bytes | 6 bytes | * | userid lower 2 bytes | account id first 6 bytes | */ const int32_t ACCOUNT_LOGOUT_PAYLOAD_LEN = 8; /** - * @brief device unbind payload length 2 + * @brief device unbind payload length 2 bytes * | 2 bytes | * | userid lower 2 bytes | */ const int32_t DEVICE_UNBIND_PAYLOAD_LEN = 2; /** - * @brief app unbind payload length 6 + * @brief app unbind payload length 6 bytes * | 2 bytes | 4 bytes | * | userid lower 2 bytes | token id lower 4 bytes | */ const int32_t APP_UNBIND_PAYLOAD_LEN = 6; + /** + * @brief delete user payload length 2 bytes + * | 2 bytes | + * | userid lower 2 bytes | + */ + const int32_t DEL_USER_PAYLOAD_LEN = 2; + /** + * @brief the userid payload cost 2 bytes. + * + */ const int32_t USERID_PAYLOAD_LEN = 2; const int32_t ACCOUNTID_PAYLOAD_LEN = 6; const int32_t SYNC_FOREGROUND_USERID_PAYLOAD_MAX_LEN = 11; @@ -88,7 +98,11 @@ bool RelationShipChangeMsg::ToBroadcastPayLoad(uint8_t *&msg, uint32_t &len) con ret = true; break; case RelationShipChangeType::SYNC_FOREGROUND_USERID: - ToSyncForegroundUserId(msg, len); + ToSyncForegroundUserIdPayLoad(msg, len); + ret = true; + break; + case RelationShipChangeType::DEL_USER: + ToDelUserPayLoad(msg, len); ret = true; break; default: @@ -117,7 +131,10 @@ bool RelationShipChangeMsg::FromBroadcastPayLoad(const cJSON *payloadJson, Relat ret = FromAppUnbindPayLoad(payloadJson); break; case RelationShipChangeType::SYNC_FOREGROUND_USERID: - ret = FromSyncForegroundUserId(payloadJson); + ret = FromSyncForegroundUserIdPayLoad(payloadJson); + break; + case RelationShipChangeType::DEL_USER: + ret = FromDelUserPayLoad(payloadJson); break; default: LOGE("RelationShipChange type invalid"); @@ -139,8 +156,10 @@ bool RelationShipChangeMsg::IsValid() const case RelationShipChangeType::APP_UNBIND: ret = (userId != UINT32_MAX && tokenId != UINT64_MAX); break; - case RelationShipChangeType::SERVICE_UNBIND: case RelationShipChangeType::DEL_USER: + ret = (userId != UINT32_MAX); + break; + case RelationShipChangeType::SERVICE_UNBIND: case RelationShipChangeType::APP_UNINSTALL: // current NOT support ret = false; @@ -162,7 +181,8 @@ bool RelationShipChangeMsg::IsValid() const bool RelationShipChangeMsg::IsChangeTypeValid() { return (type == RelationShipChangeType::ACCOUNT_LOGOUT) || (type == RelationShipChangeType::DEVICE_UNBIND) || - (type == RelationShipChangeType::APP_UNBIND) || (type == RelationShipChangeType::SYNC_FOREGROUND_USERID); + (type == RelationShipChangeType::APP_UNBIND) || (type == RelationShipChangeType::SYNC_FOREGROUND_USERID) || + (type == RelationShipChangeType::DEL_USER); } bool RelationShipChangeMsg::IsChangeTypeValid(uint32_t type) @@ -170,7 +190,8 @@ bool RelationShipChangeMsg::IsChangeTypeValid(uint32_t type) return (type == (uint32_t)RelationShipChangeType::ACCOUNT_LOGOUT) || (type == (uint32_t)RelationShipChangeType::DEVICE_UNBIND) || (type == (uint32_t)RelationShipChangeType::APP_UNBIND) || - (type == (uint32_t)RelationShipChangeType::SYNC_FOREGROUND_USERID); + (type == (uint32_t)RelationShipChangeType::SYNC_FOREGROUND_USERID) || + (type == (uint32_t)RelationShipChangeType::DEL_USER); } void RelationShipChangeMsg::ToAccountLogoutPayLoad(uint8_t *&msg, uint32_t &len) const @@ -209,7 +230,7 @@ void RelationShipChangeMsg::ToAppUnbindPayLoad(uint8_t *&msg, uint32_t &len) con len = APP_UNBIND_PAYLOAD_LEN; } -void RelationShipChangeMsg::ToSyncForegroundUserId(uint8_t *&msg, uint32_t &len) const +void RelationShipChangeMsg::ToSyncForegroundUserIdPayLoad(uint8_t *&msg, uint32_t &len) const { uint32_t foregroundUserIdNum = static_cast(foregroundUserIds.size()); if (foregroundUserIdNum > MAX_FOREGROUND_USER_ID_NUM) { @@ -227,13 +248,22 @@ void RelationShipChangeMsg::ToSyncForegroundUserId(uint8_t *&msg, uint32_t &len) msg[0] |= foregroundUserIdNum; - for (int32_t idx = 1; idx < len;) { - msg[idx] |= foregroundUserIds[idx - 1]; - msg[idx + 1] |= foregroundUserIds[idx - 1] >> BITS_PER_BYTE; + for (uint32_t idx = 1; idx < len;) { + msg[idx] |= foregroundUserIds[idx - 1] & 0xFF; + msg[idx + 1] |= (foregroundUserIds[idx - 1] >> BITS_PER_BYTE) & 0xFF; idx += 2; } } +void RelationShipChangeMsg::ToDelUserPayLoad(uint8_t *&msg, uint32_t &len) const +{ + len = DEL_USER_PAYLOAD_LEN; + msg = new uint8_t[len](); + for (int i = 0; i < USERID_PAYLOAD_LEN; i++) { + msg[i] |= (userId >> (i * BITS_PER_BYTE)) & 0xFF; + } +} + bool RelationShipChangeMsg::FromAccountLogoutPayLoad(const cJSON *payloadJson) { if (payloadJson == NULL) { @@ -316,7 +346,7 @@ bool RelationShipChangeMsg::FromAppUnbindPayLoad(const cJSON *payloadJson) return true; } -bool RelationShipChangeMsg::FromSyncForegroundUserId(const cJSON *payloadJson) +bool RelationShipChangeMsg::FromSyncForegroundUserIdPayLoad(const cJSON *payloadJson) { if (payloadJson == NULL) { LOGE("SyncForegroundUserId payloadJson is null."); @@ -325,7 +355,7 @@ bool RelationShipChangeMsg::FromSyncForegroundUserId(const cJSON *payloadJson) int32_t arraySize = cJSON_GetArraySize(payloadJson); if (arraySize < SYNC_FOREGROUND_USERID_PAYLOAD_MIN_LEN || arraySize > SYNC_FOREGROUND_USERID_PAYLOAD_MAX_LEN) { - LOGE("Payload invalied, the size is %{public}d.", arraySize); + LOGE("Payload invalid, the size is %{public}d.", arraySize); return false; } @@ -363,7 +393,30 @@ bool RelationShipChangeMsg::FromSyncForegroundUserId(const cJSON *payloadJson) return true; } -cJSON *RelationShipChangeMsg::ToArrayJson() const +bool RelationShipChangeMsg::FromDelUserPayLoad(const cJSON *payloadJson) +{ + if (payloadJson == NULL) { + LOGE("FromDelUserPayLoad payloadJson is null."); + return false; + } + + int32_t arraySize = cJSON_GetArraySize(payloadJson); + if (arraySize < DEL_USER_PAYLOAD_LEN) { + LOGE("Payload invalid, the size is %{public}d.", arraySize); + return false; + } + this->userId = 0; + for (uint32_t i = 0; i < USERID_PAYLOAD_LEN; i++) { + cJSON *payloadItem = cJSON_GetArrayItem(payloadJson, i); + CHECK_NULL_RETURN(payloadItem, false); + if (cJSON_IsNumber(payloadItem)) { + userId |= (static_cast(payloadItem->valueint)) << (i * BITS_PER_BYTE); + } + } + return true; +} + +cJSON *RelationShipChangeMsg::ToPayLoadJson() const { uint8_t *payload = nullptr; uint32_t len = 0; @@ -396,7 +449,7 @@ std::string RelationShipChangeMsg::ToJson() const return ""; } cJSON_AddNumberToObject(msg, MSG_TYPE, (uint32_t)type); - cJSON *arrayObj = ToArrayJson(); + cJSON *arrayObj = ToPayLoadJson(); if (arrayObj == nullptr) { LOGE("ArrayObj is nullptr."); cJSON_Delete(msg); -- Gitee From 1acdc9f83d74582f32c390c8b9bc797fb26e9625 Mon Sep 17 00:00:00 2001 From: hwzhangchuang Date: Wed, 6 Nov 2024 20:15:50 +0800 Subject: [PATCH 17/27] modify letter problem Signed-off-by: hwzhangchuang --- .../service/src/relationshipsyncmgr/relationship_sync_mgr.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp index 1d6d52216..94e5a033a 100644 --- a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp +++ b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp @@ -410,7 +410,7 @@ bool RelationShipChangeMsg::FromDelUserPayLoad(const cJSON *payloadJson) cJSON *payloadItem = cJSON_GetArrayItem(payloadJson, i); CHECK_NULL_RETURN(payloadItem, false); if (cJSON_IsNumber(payloadItem)) { - userId |= (static_cast(payloadItem->valueint)) << (i * BITS_PER_BYTE); + this->userId |= (static_cast(payloadItem->valueint)) << (i * BITS_PER_BYTE); } } return true; -- Gitee From 56af1f3eede32316d04a1ae55dc536a5fb8c48e8 Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Wed, 6 Nov 2024 22:16:05 +0800 Subject: [PATCH 18/27] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E7=BB=91=E5=AE=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication/dm_auth_manager.cpp | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 24af783be..50f4b6674 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -2123,18 +2123,18 @@ void DmAuthManager::ProcRespNegotiateExt(const int32_t &sessionId) { LOGI("DmAuthManager::ProcRespNegotiateExt start."); remoteDeviceId_ = authResponseContext_->localDeviceId; + authResponseContext_->remoteAccountId = authResponseContext_->localAccountId; + authResponseContext_->remoteUserId = authResponseContext_->localUserId; if (GetBinderInfo() != DM_OK) { authResponseContext_->reply = ERR_DM_GET_CALLER_DATA_FAILED; } MultipleUserConnector::SetSwitchOldAccountId(authResponseContext_->localAccountId); MultipleUserConnector::SetSwitchOldUserId(authResponseContext_->localUserId); authResponseContext_->isIdenticalAccount = false; - if (authResponseContext_->localAccountId == authRequestContext_->localAccountId && - authRequestContext_->localAccountId != "ohosAnonymousUid") { + if (authResponseContext_->localAccountId == authResponseContext_->remoteAccountId && + authResponseContext_->localAccountId != "ohosAnonymousUid") { authResponseContext_->isIdenticalAccount = true; } - authResponseContext_->remoteAccountId = authResponseContext_->localAccountId; - authResponseContext_->remoteUserId = authResponseContext_->localUserId; char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); authResponseContext_->deviceId = authResponseContext_->localDeviceId; @@ -2530,7 +2530,7 @@ std::string DmAuthManager::GetBundleName(nlohmann::json &jsonObject) } int32_t DmAuthManager::GetBinderInfo() -{ +{ CHECK_NULL_RETURN(authResponseContext_, ERR_DM_POINT_NULL); if (authResponseContext_->bundleName.empty()) { authResponseContext_->localUserId = MultipleUserConnector::GetCurrentAccountUserID(); @@ -2548,6 +2548,9 @@ int32_t DmAuthManager::GetBinderInfo() } ret = AppManager::GetInstance().GetHapTokenIdByName(authResponseContext_->localUserId, authResponseContext_->bundleName, 0, authResponseContext_->tokenId); + if (ret != DM_OK) { + authResponseContext_->tokenId = authResponseContext_->remoteTokenId; + } return ret; } } // namespace DistributedHardware -- Gitee From 9769a02f8c7860ce66aa1f5685d18d7c409393c6 Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Thu, 7 Nov 2024 01:19:36 +0800 Subject: [PATCH 19/27] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=8F=91=E7=8E=B0?= =?UTF-8?q?=E5=9B=9E=E8=B0=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- .../device_manager_ipc_interface_code.h | 3 - common/include/dm_anonymous.h | 3 +- .../ipc/model/ipc_start_discover_req.h | 73 ----- .../ipc/model/ipc_start_discovery_req.h | 74 ----- .../ipc/model/ipc_stop_discovery_req.h | 54 ---- common/src/dm_anonymous.cpp | 14 + .../include/deviceprofile_connector.h | 5 +- .../include/multiple_user_connector.h | 2 +- .../src/deviceprofile_connector.cpp | 88 +++--- .../src/multiple_user_connector.cpp | 6 +- .../native_cpp/include/device_manager_impl.h | 6 +- .../native_cpp/include/dm_device_info.h | 16 +- .../native_cpp/src/device_manager_impl.cpp | 295 +++++++----------- .../src/ipc/lite/ipc_cmd_parser.cpp | 20 -- .../src/ipc/standard/ipc_cmd_parser.cpp | 83 ----- .../src/notify/device_manager_notify.cpp | 108 ++++--- .../authentication/auth_ui_state_manager.h | 2 +- .../include/authentication/dm_auth_manager.h | 8 +- .../credential/dm_credential_manager.h | 5 +- .../include/device_manager_service_impl.h | 11 +- .../device_manager_service_impl_lite.h | 2 + .../devicestate/dm_device_state_manager.h | 1 - .../authentication/auth_ui_state_manager.cpp | 26 +- .../src/authentication/dm_auth_manager.cpp | 62 ++-- .../src/credential/dm_credential_manager.cpp | 26 +- .../src/device_manager_service_impl.cpp | 36 ++- .../src/device_manager_service_impl_lite.cpp | 9 +- .../devicestate/dm_device_state_manager.cpp | 43 +-- .../src/discovery/dm_discovery_manager.cpp | 8 - .../service/include/device_manager_service.h | 8 - .../include/device_manager_service_listener.h | 33 +- .../include/discovery/discovery_manager.h | 13 +- .../idevice_manager_service_listener.h | 35 +-- .../include/ipc/lite/ipc_server_listener.h | 1 + .../ipc/standard/ipc_server_listener.h | 3 +- .../include/ipc/standard/ipc_server_stub.h | 5 + .../permission/lite/permission_manager.h | 3 +- .../permission/standard/permission_manager.h | 3 +- .../service/include/pinholder/pin_holder.h | 2 +- .../service/src/device_manager_service.cpp | 68 +--- .../src/device_manager_service_listener.cpp | 155 +++++---- .../src/discovery/discovery_manager.cpp | 130 ++++++-- .../service/src/ipc/lite/ipc_cmd_parser.cpp | 21 -- .../src/ipc/lite/ipc_server_listener.cpp | 5 + .../src/ipc/standard/ipc_cmd_parser.cpp | 56 +--- .../src/ipc/standard/ipc_server_listener.cpp | 5 + .../src/ipc/standard/ipc_server_stub.cpp | 28 +- .../permission/lite/permission_manager.cpp | 10 +- .../standard/permission_manager.cpp | 18 +- services/service/src/pinholder/pin_holder.cpp | 82 ++--- .../authenticate_device_fuzzer.cpp | 2 +- .../UTTest_discovery_manager.cpp | 2 +- .../UTTest_dm_auth_manager_first.cpp | 1 - .../UTTest_dm_credential_manager.h | 2 +- .../UTTest_dm_device_state_manager.cpp | 8 - .../UTTest_dm_deviceprofile_connector.cpp | 11 +- .../UTTest_permission_manager.cpp | 28 +- .../device_manager_service_fuzzer.cpp | 3 - .../ipc_cmd_register_fuzzer.cpp | 2 - .../ipc_server_stub_fuzzer.cpp | 5 +- .../softbus_connector_common_fuzzer.cpp | 3 - .../UTTest_softbus_connector.cpp | 4 +- test/unittest/UTTest_device_manager_impl.cpp | 2 - .../UTTest_device_manager_impl_three.cpp | 5 - .../UTTest_device_manager_impl_two.cpp | 4 +- .../UTTest_device_manager_service.cpp | 151 +-------- .../UTTest_device_manager_service_impl.cpp | 2 +- ...UTTest_device_manager_service_listener.cpp | 111 ++++--- .../UTTest_device_manager_service_two.cpp | 18 +- test/unittest/UTTest_dm_pin_holder.cpp | 32 +- test/unittest/UTTest_dm_pin_holder.h | 63 ++-- .../UTTest_ipc_client_server_proxy.cpp | 2 - .../unittest/UTTest_ipc_cmd_parser_client.cpp | 8 - .../UTTest_ipc_cmd_parser_service.cpp | 58 ---- test/unittest/UTTest_ipc_cmd_register.cpp | 68 ---- .../UTTest_ipc_server_client_proxy.cpp | 20 +- test/unittest/UTTest_ipc_server_listener.cpp | 25 +- test/unittest/UTTest_ipc_server_stub.cpp | 57 ++-- test/unittest/mock/ipc_server_listener.h | 2 + 79 files changed, 915 insertions(+), 1557 deletions(-) delete mode 100644 common/include/ipc/model/ipc_start_discover_req.h delete mode 100644 common/include/ipc/model/ipc_start_discovery_req.h delete mode 100644 common/include/ipc/model/ipc_stop_discovery_req.h diff --git a/common/include/device_manager_ipc_interface_code.h b/common/include/device_manager_ipc_interface_code.h index 82f3b6251..087a5a1f1 100644 --- a/common/include/device_manager_ipc_interface_code.h +++ b/common/include/device_manager_ipc_interface_code.h @@ -29,9 +29,6 @@ enum DMIpcCmdInterfaceCode { GET_UDID_BY_NETWORK, GET_UUID_BY_NETWORK, GET_NETWORKTYPE_BY_NETWORK, - START_DEVICE_DISCOVER, - START_DEVICE_DISCOVERY, - STOP_DEVICE_DISCOVER, PUBLISH_DEVICE_DISCOVER, UNPUBLISH_DEVICE_DISCOVER, AUTHENTICATE_DEVICE, diff --git a/common/include/dm_anonymous.h b/common/include/dm_anonymous.h index 920722427..3a6d21396 100644 --- a/common/include/dm_anonymous.h +++ b/common/include/dm_anonymous.h @@ -45,7 +45,8 @@ int64_t StringToInt64(const std::string &str, int32_t base); void VersionSplitToInt(const std::string &str, const char split, std::vector &numVec); bool CompareVecNum(const std::vector &srcVecNum, const std::vector &sinkVecNum); bool CompareVersion(const std::string &remoteVersion, const std::string &oldVersion); - +std::string ComposeStr(const std::string &pkgName, uint16_t subscribeId); +std::string GetCallerPkgName(const std::string &pkgName); template std::string GetAnonyInteger(const T value) { diff --git a/common/include/ipc/model/ipc_start_discover_req.h b/common/include/ipc/model/ipc_start_discover_req.h deleted file mode 100644 index 863951cea..000000000 --- a/common/include/ipc/model/ipc_start_discover_req.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) 2023 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef OHOS_DM_IPC_START_DISCOVER_REQ_H -#define OHOS_DM_IPC_START_DISCOVER_REQ_H - -#include "ipc_req.h" - -namespace OHOS { -namespace DistributedHardware { -class IpcStartDevDiscoveryByIdReq : public IpcReq { - DECLARE_IPC_MODEL(IpcStartDevDiscoveryByIdReq); - -public: - /** - * @tc.name: IpcStartDiscoveryReq::GetSubscribeInfo - * @tc.desc: Ipc Start Discovery Request Get SubscribeInfo - * @tc.type: FUNC - */ - const uint16_t &GetSubscribeId() const - { - return subscribeId_; - } - - /** - * @tc.name: IpcStartDiscoveryReq::SetSubscribeInfo - * @tc.desc: Ipc Start Discovery Request Set SubscribeInfo - * @tc.type: FUNC - */ - void SetSubscribeId(const uint16_t &subscribeId) - { - subscribeId_ = subscribeId; - } - - /** - * @tc.name: IpcStartDiscoveryReq::GetExtra - * @tc.desc: Ipc Start Discovery Request Get Extra - * @tc.type: FUNC - */ - const std::string &GetFilterOption() const - { - return filterOptions_; - } - - /** - * @tc.name: IpcStartDiscoveryReq::SetExtra - * @tc.desc: Ipc Start Discovery Request Set Extra - * @tc.type: FUNC - */ - void SetFilterOption(const std::string &filterOptions) - { - filterOptions_ = filterOptions; - } - -private: - std::string filterOptions_; - uint16_t subscribeId_ { 0 }; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DM_IPC_START_DISCOVER_REQ_H diff --git a/common/include/ipc/model/ipc_start_discovery_req.h b/common/include/ipc/model/ipc_start_discovery_req.h deleted file mode 100644 index 421402c85..000000000 --- a/common/include/ipc/model/ipc_start_discovery_req.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - * 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 OHOS_DM_IPC_START_DISCOVERY_REQ_H -#define OHOS_DM_IPC_START_DISCOVERY_REQ_H - -#include "dm_subscribe_info.h" -#include "ipc_req.h" - -namespace OHOS { -namespace DistributedHardware { -class IpcStartDiscoveryReq : public IpcReq { - DECLARE_IPC_MODEL(IpcStartDiscoveryReq); - -public: - /** - * @tc.name: IpcStartDiscoveryReq::GetSubscribeInfo - * @tc.desc: Ipc Start Discovery Request Get SubscribeInfo - * @tc.type: FUNC - */ - const DmSubscribeInfo &GetSubscribeInfo() const - { - return subscribeInfo_; - } - - /** - * @tc.name: IpcStartDiscoveryReq::SetSubscribeInfo - * @tc.desc: Ipc Start Discovery Request Set SubscribeInfo - * @tc.type: FUNC - */ - void SetSubscribeInfo(const DmSubscribeInfo &subscribeInfo) - { - subscribeInfo_ = subscribeInfo; - } - - /** - * @tc.name: IpcStartDiscoveryReq::GetExtra - * @tc.desc: Ipc Start Discovery Request Get Extra - * @tc.type: FUNC - */ - const std::string &GetExtra() const - { - return extra_; - } - - /** - * @tc.name: IpcStartDiscoveryReq::SetExtra - * @tc.desc: Ipc Start Discovery Request Set Extra - * @tc.type: FUNC - */ - void SetExtra(const std::string &extra) - { - extra_ = extra; - } - -private: - std::string extra_; - DmSubscribeInfo subscribeInfo_; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DM_IPC_START_DISCOVERY_REQ_H diff --git a/common/include/ipc/model/ipc_stop_discovery_req.h b/common/include/ipc/model/ipc_stop_discovery_req.h deleted file mode 100644 index d5d2ae5ec..000000000 --- a/common/include/ipc/model/ipc_stop_discovery_req.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * 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 OHOS_DM_IPC_STOP_DISCOVERY_REQ_H -#define OHOS_DM_IPC_STOP_DISCOVERY_REQ_H - -#include - -#include "ipc_req.h" - -namespace OHOS { -namespace DistributedHardware { -class IpcStopDiscoveryReq : public IpcReq { - DECLARE_IPC_MODEL(IpcStopDiscoveryReq); - -public: - /** - * @tc.name: IpcStopDiscoveryReq::GetSubscribeId - * @tc.desc: Ipc stop discovery request get subscription id - * @tc.type: FUNC - */ - uint16_t GetSubscribeId() const - { - return subscribeId_; - } - - /** - * @tc.name: IpcStopDiscoveryReq::SetSubscribeId - * @tc.desc: Ipc stop discovery request set subscription id - * @tc.type: FUNC - */ - void SetSubscribeId(uint16_t subscribeId) - { - subscribeId_ = subscribeId; - } - -private: - uint16_t subscribeId_ { 0 }; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DM_IPC_STOP_DISCOVERY_REQ_H diff --git a/common/src/dm_anonymous.cpp b/common/src/dm_anonymous.cpp index fca41ecad..e370b32b0 100644 --- a/common/src/dm_anonymous.cpp +++ b/common/src/dm_anonymous.cpp @@ -283,5 +283,19 @@ bool CompareVersion(const std::string &remoteVersion, const std::string &oldVers VersionSplitToInt(oldVersion, '.', oldVersionVec); return CompareVecNum(remoteVersionVec, oldVersionVec); } + +std::string ComposeStr(const std::string &pkgName, uint16_t subscribeId) +{ + std::string strTemp = pkgName + "#" + std::to_string(subscribeId); + return strTemp; +} + +std::string GetCallerPkgName(const std::string &pkgName) +{ + std::istringstream stream(pkgName); + std::string item = ""; + getline(stream, item, '#'); + return item; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/commondependency/include/deviceprofile_connector.h b/commondependency/include/deviceprofile_connector.h index b4b1b4f74..570adb65f 100644 --- a/commondependency/include/deviceprofile_connector.h +++ b/commondependency/include/deviceprofile_connector.h @@ -45,6 +45,7 @@ constexpr uint32_t ACTIVE = 1; typedef struct DmDiscoveryInfo { std::string pkgname; std::string localDeviceId; + int32_t userId; std::string remoteDeviceIdHash; } DmDiscoveryInfo; @@ -95,7 +96,7 @@ class DeviceProfileConnector : public IDeviceProfileConnector { public: std::vector GetAccessControlProfile(); std::vector GetAccessControlProfileByUserId(int32_t userId); - uint32_t CheckBindType(std::string trustDeviceId, std::string requestDeviceId); + uint32_t CheckBindType(std::string peerUdid, std::string localUdid); int32_t PutAccessControlList(DmAclInfo aclInfo, DmAccesser dmAccesser, DmAccessee dmAccessee); int32_t UpdateAccessControlList(int32_t userId, std::string &oldAccountId, std::string &newAccountId); std::unordered_map GetAppTrustDeviceList(const std::string &pkgName, @@ -162,6 +163,8 @@ private: const std::vector &profiles, const std::string &localUdid, const std::string &remoteUdid); void UpdateBindType(const std::string &udid, int32_t bindType, std::map &deviceMap); + std::vector FilterAclProfileByUserId(const std::string &localUdid, + const std::string &remoteUdid, const std::vector &profiles); }; extern "C" IDeviceProfileConnector *CreateDpConnectorInstance(); diff --git a/commondependency/include/multiple_user_connector.h b/commondependency/include/multiple_user_connector.h index 94219d6db..f26f65898 100644 --- a/commondependency/include/multiple_user_connector.h +++ b/commondependency/include/multiple_user_connector.h @@ -95,7 +95,7 @@ public: */ static std::string GetSwitchOldAccountName(void); static void GetTokenIdAndForegroundUserId(uint32_t &tokenId, int32_t &userId); - static void GetTokenIdAndUserId(uint32_t &tokenId, int32_t &userId); + static void GetCallerUserId(int32_t &userId); static int32_t GetForegroundUsers(std::vector &userVec); static int32_t GetForegroundUser(void); diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index b6def759a..f422ec48a 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -87,18 +87,19 @@ std::unordered_map DeviceProfileConnector::GetAppTrustD int32_t DeviceProfileConnector::GetDeviceAclParam(DmDiscoveryInfo discoveryInfo, bool &isOnline, int32_t &authForm) { - std::vector profiles = GetAccessControlProfile(); - if (profiles.size() == 0) { - return DM_OK; - } + std::vector profiles = GetAccessControlProfileByUserId(discoveryInfo.userId); std::vector bindTypes; for (auto &item : profiles) { char deviceIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; if (Crypto::GetUdidHash(item.GetTrustDeviceId(), reinterpret_cast(deviceIdHash)) != DM_OK) { LOGE("get deviceIdHash by deviceId: %{public}s failed.", GetAnonyString(deviceIdHash).c_str()); - return ERR_DM_FAILED; + continue; } - if (static_cast(deviceIdHash) != discoveryInfo.remoteDeviceIdHash || item.GetStatus() != ACTIVE) { + if (static_cast(deviceIdHash) != discoveryInfo.remoteDeviceIdHash || + (discoveryInfo.localDeviceId == item.GetAccesser().GetAccesserDeviceId() && + discoveryInfo.userId != item.GetAccesser().GetAccesserUserId()) || + (discoveryInfo.localDeviceId == item.GetAccessee().GetAccesseeDeviceId() && + discoveryInfo.userId != item.GetAccessee().GetAccesseeUserId())) { continue; } int32_t bindType = HandleDmAuthForm(item, discoveryInfo); @@ -162,18 +163,17 @@ int32_t DeviceProfileConnector::HandleDmAuthForm(AccessControlProfile profiles, return DmAuthForm::INVALID_TYPE; } -uint32_t DeviceProfileConnector::CheckBindType(std::string trustDeviceId, std::string requestDeviceId) +uint32_t DeviceProfileConnector::CheckBindType(std::string peerUdid, std::string localUdid) { - LOGI("Start."); - std::vector profiles = - GetAccessControlProfileByUserId(MultipleUserConnector::GetForegroundUser()); - LOGI("AccessControlProfile size is %{public}zu", profiles.size()); + std::vector allProfiles = GetAllAccessControlProfile(); + std::vector filterProfiles = FilterAclProfileByUserId(localUdid, peerUdid, allProfiles); + LOGI("filterProfiles size is %{public}zu", filterProfiles.size()); uint32_t highestPriority = INVALIED_TYPE; - for (auto &item : profiles) { - if (trustDeviceId != item.GetTrustDeviceId() || item.GetStatus() != ACTIVE) { + for (auto &item : filterProfiles) { + if (peerUdid != item.GetTrustDeviceId() || item.GetStatus() != ACTIVE) { continue; } - uint32_t priority = static_cast(GetAuthForm(item, trustDeviceId, requestDeviceId)); + uint32_t priority = static_cast(GetAuthForm(item, peerUdid, localUdid)); if (priority > highestPriority) { highestPriority = priority; } @@ -195,22 +195,18 @@ int32_t DeviceProfileConnector::GetAuthForm(DistributedDeviceProfile::AccessCont case DM_POINT_TO_POINT: if (profiles.GetBindLevel() == DEVICE) { priority = DEVICE_PEER_TO_PEER_TYPE; - } else if (profiles.GetBindLevel() == APP && profiles.GetAccesser().GetAccesserDeviceId() == reqDev && - profiles.GetAccessee().GetAccesseeDeviceId() == trustDev) { + } else if (profiles.GetBindLevel() == APP) { priority = APP_PEER_TO_PEER_TYPE; - } else if (profiles.GetBindLevel() == APP && profiles.GetAccessee().GetAccesseeDeviceId() == reqDev && - profiles.GetAccesser().GetAccesserDeviceId() == trustDev) { + } else if (profiles.GetBindLevel() == APP) { priority = APP_PEER_TO_PEER_TYPE; } break; case DM_ACROSS_ACCOUNT: if (profiles.GetBindLevel() == DEVICE) { priority = DEVICE_ACROSS_ACCOUNT_TYPE; - } else if (profiles.GetBindLevel() == APP && profiles.GetAccesser().GetAccesserDeviceId() == reqDev && - profiles.GetAccessee().GetAccesseeDeviceId() == trustDev) { + } else if (profiles.GetBindLevel() == APP) { priority = APP_ACROSS_ACCOUNT_TYPE; - } else if (profiles.GetBindLevel() == APP && profiles.GetAccessee().GetAccesseeDeviceId() == reqDev && - profiles.GetAccesser().GetAccesserDeviceId() == trustDev) { + } else if (profiles.GetBindLevel() == APP) { priority = APP_ACROSS_ACCOUNT_TYPE; } break; @@ -367,25 +363,18 @@ std::vector DeviceProfileConnector::SyncAclByBindType(std::string pkgNa std::vector DeviceProfileConnector::GetProcessInfoFromAcl( std::string &localDeviceId, std::string &targetDeviceId) { - LOGI("Start."); - std::vector profiles = - GetAccessControlProfileByUserId(MultipleUserConnector::GetForegroundUser()); - LOGI("AccessControlProfile size is %{public}zu", profiles.size()); + std::vector allProfiles = GetAllAccessControlProfile(); + std::vector filterProfiles = FilterAclProfileByUserId(localDeviceId, + targetDeviceId, allProfiles); + LOGI("filterProfiles size is %{public}zu", filterProfiles.size()); std::vector processInfoVec; - for (auto &item : profiles) { + for (auto &item : filterProfiles) { if (item.GetTrustDeviceId() != targetDeviceId || item.GetStatus() != ACTIVE) { continue; } - if ((item.GetAccesser().GetAccesserDeviceId() == localDeviceId && - item.GetAccessee().GetAccesseeDeviceId() == targetDeviceId) || - (item.GetAccesser().GetAccesserDeviceId() == targetDeviceId && - item.GetAccessee().GetAccesseeDeviceId() == localDeviceId)) { - OHOS::DistributedHardware::ProcessInfo processInfo; - processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); - processInfo.userId = item.GetAccesser().GetAccesserUserId(); - processInfo.tokenId = item.GetAccesser().GetAccesserTokenId(); - processInfoVec.push_back(processInfo); - } + OHOS::DistributedHardware::ProcessInfo processInfo; + processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.userId = MultipleUserConnector::GetForegroundUser(); } return processInfoVec; } @@ -415,7 +404,6 @@ DmOfflineParam DeviceProfileConnector::GetOfflineParamFromAcl(std::string trustD OHOS::DistributedHardware::ProcessInfo processInfo; processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); processInfo.userId = item.GetAccesser().GetAccesserUserId(); - processInfo.tokenId = item.GetAccesser().GetAccesserTokenId(); offlineParam.processVec.push_back(processInfo); } else if ((item.GetAccesser().GetAccesserDeviceId() == requestDeviceId && item.GetAccessee().GetAccesseeDeviceId() == trustDeviceId) || @@ -425,7 +413,6 @@ DmOfflineParam DeviceProfileConnector::GetOfflineParamFromAcl(std::string trustD OHOS::DistributedHardware::ProcessInfo processInfo; processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); processInfo.userId = item.GetAccesser().GetAccesserUserId(); - processInfo.tokenId = item.GetAccesser().GetAccesserTokenId(); offlineParam.processVec.push_back(processInfo); } if (priority > offlineParam.bindType) { @@ -1021,7 +1008,6 @@ OHOS::DistributedHardware::ProcessInfo DeviceProfileConnector::HandleAppUnBindEv DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); processInfo.userId = item.GetAccessee().GetAccesseeUserId(); - processInfo.tokenId = item.GetAccessee().GetAccesseeTokenId(); continue; } if (item.GetAccessee().GetAccesseeUserId() == remoteUserId && @@ -1032,7 +1018,6 @@ OHOS::DistributedHardware::ProcessInfo DeviceProfileConnector::HandleAppUnBindEv DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); processInfo.userId = item.GetAccesser().GetAccesserUserId(); - processInfo.tokenId = item.GetAccesser().GetAccesserTokenId(); continue; } } @@ -1082,6 +1067,27 @@ int32_t DeviceProfileConnector::HandleUserSwitched(const std::string &localUdid, return DM_OK; } +std::vector DeviceProfileConnector::FilterAclProfileByUserId(const std::string &localUdid, + const std::string &remoteUdid, const std::vector &profiles) +{ + LOGI("localUdid %{public}s, remoteUdid %{public}s.", GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + std::vector profilesTemp; + int32_t userId = MultipleUserConnector::GetForegroundUser(); + for (const auto &item : profiles) { + if (item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccesser().GetAccesserUserId() == userId && + item.GetAccessee().GetAccesseeDeviceId() == remoteUdid) { + profilesTemp.push_back(item); + } else if (item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccessee().GetAccesseeUserId() == userId && + item.GetAccesser().GetAccesserDeviceId() == remoteUdid) { + profilesTemp.push_back(item); + } + } + return profilesTemp; +} + IDeviceProfileConnector *CreateDpConnectorInstance() { return &DeviceProfileConnector::GetInstance(); diff --git a/commondependency/src/multiple_user_connector.cpp b/commondependency/src/multiple_user_connector.cpp index 1b9f45f93..0fccd4c17 100644 --- a/commondependency/src/multiple_user_connector.cpp +++ b/commondependency/src/multiple_user_connector.cpp @@ -114,9 +114,8 @@ void MultipleUserConnector::GetTokenIdAndForegroundUserId(uint32_t &tokenId, int userId = GetForegroundUser(); } -void MultipleUserConnector::GetTokenIdAndUserId(uint32_t &tokenId, int32_t &userId) -{ - tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); +void MultipleUserConnector::GetCallerUserId(int32_t &userId) +{ #if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) return; #elif OS_ACCOUNT_PART_EXISTS @@ -124,7 +123,6 @@ void MultipleUserConnector::GetTokenIdAndUserId(uint32_t &tokenId, int32_t &user ErrCode ret = OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId); if (ret != 0) { LOGE("GetOsAccountLocalIdFromUid error ret: %{public}d", ret); - return; } return; #else // OS_ACCOUNT_PART_EXISTS diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h index ca18f9e29..7228d508e 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -409,7 +409,8 @@ private: DeviceManagerImpl(DeviceManagerImpl &&) = delete; DeviceManagerImpl &operator=(DeviceManagerImpl &&) = delete; - uint16_t AddDiscoveryCallback(const std::string &pkgName, std::shared_ptr callback); + uint16_t AddDiscoveryCallback(const std::string &pkgName, std::map &discoverParam, + std::shared_ptr callback); uint16_t RemoveDiscoveryCallback(const std::string &pkgName); int32_t AddPublishCallback(const std::string &pkgName); int32_t RemovePublishCallback(const std::string &pkgName); @@ -421,9 +422,6 @@ private: std::shared_ptr ipcClientProxy_ = std::make_shared(std::make_shared()); #endif - std::mutex subscribIdLock; - std::map subscribIdMap_; - std::mutex subMapLock; std::map pkgName2SubIdMap_; diff --git a/interfaces/inner_kits/native_cpp/include/dm_device_info.h b/interfaces/inner_kits/native_cpp/include/dm_device_info.h index 1ff016b40..73646703e 100644 --- a/interfaces/inner_kits/native_cpp/include/dm_device_info.h +++ b/interfaces/inner_kits/native_cpp/include/dm_device_info.h @@ -363,26 +363,18 @@ typedef struct DmAccessCallee { } DmAccessCallee; typedef struct ProcessInfo { - std::string udid; - int32_t userId = -1; - std::string accountId; - uint64_t tokenId = 0; + int32_t userId; std::string pkgName; bool operator==(const ProcessInfo &other) const { - return (udid == other.udid) && (userId == other.userId) && (accountId == other.accountId) && - (tokenId == other.tokenId) && (pkgName == other.pkgName); + return (userId == other.userId) && (pkgName == other.pkgName); } bool operator<(const ProcessInfo &other) const { - return (udid < other.udid) || - (udid == other.udid && userId < other.userId) || - (udid == other.udid && userId == other.userId && accountId < other.accountId) || - (udid == other.udid && userId == other.userId && accountId == other.accountId && tokenId < other.tokenId) || - (udid == other.udid && userId == other.userId && accountId == other.accountId && tokenId == other.tokenId && - pkgName < other.pkgName); + return (userId < other.userId) || + (userId == other.userId && pkgName < other.pkgName); } } ProcessInfo; } // namespace DistributedHardware diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index 9b163893a..3b777cd31 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -55,9 +55,6 @@ #include "ipc_set_credential_rsp.h" #include "ipc_set_useroperation_req.h" #include "ipc_skeleton.h" -#include "ipc_start_discovery_req.h" -#include "ipc_start_discover_req.h" -#include "ipc_stop_discovery_req.h" #include "ipc_unauthenticate_device_req.h" #include "ipc_unbind_device_req.h" #include "ipc_unpublish_req.h" @@ -455,35 +452,14 @@ int32_t DeviceManagerImpl::StartDeviceDiscovery(const std::string &pkgName, cons LOGE("DeviceManagerImpl::StartDeviceDiscovery error: Invalid para, pkgName: %{public}s", pkgName.c_str()); return ERR_DM_INPUT_PARA_INVALID; } - LOGI("Start, pkgName: %{public}s", pkgName.c_str()); - DmTraceStart(std::string(DM_HITRACE_START_DEVICE)); - DeviceManagerNotify::GetInstance().RegisterDiscoveryCallback(pkgName, subscribeInfo.subscribeId, callback); - - std::shared_ptr req = std::make_shared(); - std::shared_ptr rsp = std::make_shared(); - req->SetPkgName(pkgName); - req->SetExtra(extra); - req->SetSubscribeInfo(subscribeInfo); - int32_t ret = ipcClientProxy_->SendRequest(START_DEVICE_DISCOVER, req, rsp); - if (ret != DM_OK) { - LOGE("StartDeviceDiscovery error: Send Request failed ret: %{public}d", ret); - return ERR_DM_IPC_SEND_REQUEST_FAILED; - } - - ret = rsp->GetErrCode(); - if (ret != DM_OK) { - LOGE("StartDeviceDiscovery error: Failed with ret %{public}d", ret); - SysEventWrite(std::string(START_DEVICE_DISCOVERY_FAILED), DM_HISYEVENT_BEHAVIOR, - std::string(START_DEVICE_DISCOVERY_FAILED_MSG)); - return ret; - } - - DmTraceEnd(); - LOGI("Completed"); - SysEventWrite(std::string(START_DEVICE_DISCOVERY_SUCCESS), DM_HISYEVENT_BEHAVIOR, - std::string(START_DEVICE_DISCOVERY_SUCCESS_MSG)); - return DM_OK; + std::map discParam; + discParam.insert(std::pair(PARAM_KEY_SUBSCRIBE_ID, + std::to_string(subscribeInfo.subscribeId))); + discParam.insert(std::pair(PARAM_KEY_DISC_MEDIUM, std::to_string(subscribeInfo.medium))); + std::map filterOps; + filterOps.insert(std::pair(PARAM_KEY_FILTER_OPTIONS, extra)); + return StartDiscovering(pkgName, discParam, filterOps, callback); } int32_t DeviceManagerImpl::StartDeviceDiscovery(const std::string &pkgName, uint64_t tokenId, @@ -493,106 +469,115 @@ int32_t DeviceManagerImpl::StartDeviceDiscovery(const std::string &pkgName, uint LOGE("DeviceManagerImpl::StartDeviceDiscovery error: Invalid para, pkgName: %{public}s", pkgName.c_str()); return ERR_DM_INPUT_PARA_INVALID; } + std::map discParam; + discParam.insert(std::pair(PARAM_KEY_SUBSCRIBE_ID, std::to_string(tokenId))); + std::map filterOps; + filterOps.insert(std::pair(PARAM_KEY_FILTER_OPTIONS, filterOptions)); + return StartDiscovering(pkgName, discParam, filterOps, callback); +} - LOGI("Start, pkgName: %{public}s", pkgName.c_str()); - uint16_t subscribeId = 0; - { - std::lock_guard autoLock(subscribIdLock); - if (subscribIdMap_.find(tokenId) != subscribIdMap_.end()) { - return ERR_DM_DISCOVERY_REPEATED; - } - subscribeId = GenRandUint(0, DM_MAX_RANDOM); - subscribIdMap_[tokenId] = subscribeId; - } - DmTraceStart(std::string(DM_HITRACE_START_DEVICE)); - DeviceManagerNotify::GetInstance().RegisterDiscoveryCallback(pkgName, subscribeId, callback); - std::shared_ptr req = std::make_shared(); - std::shared_ptr rsp = std::make_shared(); - req->SetPkgName(pkgName); - req->SetFilterOption(filterOptions); - req->SetSubscribeId(subscribeId); - int32_t ret = ipcClientProxy_->SendRequest(START_DEVICE_DISCOVERY, req, rsp); - if (ret != DM_OK) { - LOGE("StartDeviceDiscovery error: Send Request failed ret: %{public}d", ret); - return ERR_DM_IPC_SEND_REQUEST_FAILED; - } - - ret = rsp->GetErrCode(); - if (ret != DM_OK) { - LOGE("StartDeviceDiscovery error: Failed with ret %{public}d", ret); - SysEventWrite(std::string(START_DEVICE_DISCOVERY_FAILED), DM_HISYEVENT_BEHAVIOR, - std::string(START_DEVICE_DISCOVERY_FAILED_MSG)); - return ret; +int32_t DeviceManagerImpl::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) +{ + if (pkgName.empty()) { + LOGE("DeviceManagerImpl::StopDeviceDiscovery Invalid parameter, pkgName is empty."); + return ERR_DM_INPUT_PARA_INVALID; } - - DmTraceEnd(); - LOGI("Completed"); - SysEventWrite(std::string(START_DEVICE_DISCOVERY_SUCCESS), DM_HISYEVENT_BEHAVIOR, - std::string(START_DEVICE_DISCOVERY_SUCCESS_MSG)); - return DM_OK; + std::map discParam; + discParam.insert(std::pair(PARAM_KEY_SUBSCRIBE_ID, std::to_string(subscribeId))); + return StopDiscovering(pkgName, discParam); } -int32_t DeviceManagerImpl::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) +int32_t DeviceManagerImpl::StopDeviceDiscovery(uint64_t tokenId, const std::string &pkgName) { if (pkgName.empty()) { LOGE("DeviceManagerImpl::StopDeviceDiscovery Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } + std::map discParam; + discParam.insert(std::pair(PARAM_KEY_SUBSCRIBE_ID, std::to_string(tokenId))); + return StopDiscovering(pkgName, discParam); +} + +int32_t DeviceManagerImpl::StartDiscovering(const std::string &pkgName, + std::map &discoverParam, const std::map &filterOptions, + std::shared_ptr callback) +{ + if (pkgName.empty() || callback == nullptr) { + LOGE("DeviceManagerImpl::StartDiscovering failed: input callback is null or pkgName is empty."); + return ERR_DM_INPUT_PARA_INVALID; + } LOGI("Start, pkgName: %{public}s", pkgName.c_str()); - std::shared_ptr req = std::make_shared(); + DmTraceStart(std::string(DM_HITRACE_START_DEVICE)); + + uint16_t subscribeId = AddDiscoveryCallback(pkgName, discoverParam, callback); + discoverParam.emplace(PARAM_KEY_SUBSCRIBE_ID, std::to_string(subscribeId)); + std::string discParaStr = ConvertMapToJsonString(discoverParam); + std::string filterOpStr = ConvertMapToJsonString(filterOptions); + + std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); - req->SetPkgName(pkgName); - req->SetSubscribeId(subscribeId); - int32_t ret = ipcClientProxy_->SendRequest(STOP_DEVICE_DISCOVER, req, rsp); + req->SetPkgName(ComposeStr(pkgName, subscribeId)); + req->SetFirstParam(discParaStr); + req->SetSecondParam(filterOpStr); + int32_t ret = ipcClientProxy_->SendRequest(START_DISCOVERING, req, rsp); if (ret != DM_OK) { - LOGE("StopDeviceDiscovery error: Send Request failed ret: %{public}d", ret); + LOGE("StartDiscovering error: Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } - ret = rsp->GetErrCode(); if (ret != DM_OK) { - LOGE("StopDeviceDiscovery error: Failed with ret %{public}d", ret); + LOGE("StartDiscovering error: Failed with ret %{public}d", ret); return ret; } - DeviceManagerNotify::GetInstance().UnRegisterDiscoveryCallback(pkgName, subscribeId); + DmTraceEnd(); LOGI("Completed"); + SysEventWrite(std::string(START_DEVICE_DISCOVERY_SUCCESS), DM_HISYEVENT_BEHAVIOR, + std::string(START_DEVICE_DISCOVERY_SUCCESS_MSG)); return DM_OK; } -int32_t DeviceManagerImpl::StopDeviceDiscovery(uint64_t tokenId, const std::string &pkgName) +int32_t DeviceManagerImpl::StopDiscovering(const std::string &pkgName, + std::map &discoverParam) { if (pkgName.empty()) { - LOGE("DeviceManagerImpl::StopDeviceDiscovery Invalid parameter, pkgName is empty."); + LOGE("DeviceManagerImpl::StopDiscovering failed: input pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } LOGI("Start, pkgName: %{public}s", pkgName.c_str()); - uint16_t subscribeId = 0; + uint16_t subscribeId = DM_INVALID_FLAG_ID; + if (discoverParam.find(PARAM_KEY_SUBSCRIBE_ID) != discoverParam.end()) { + subscribeId = std::atoi((discoverParam.find(PARAM_KEY_SUBSCRIBE_ID)->second).c_str()); + } + std::string discoveryFlag = ComposeStr(pkgName, subscribeId); { - std::lock_guard autoLock(subscribIdLock); - if (subscribIdMap_.find(tokenId) == subscribIdMap_.end()) { - return ERR_DM_STOP_DISCOVERY; + std::lock_guard autoLock(subMapLock); + if (pkgName2SubIdMap_.find(discoveryFlag) != pkgName2SubIdMap_.end()) { + subscribeId = pkgName2SubIdMap_[discoveryFlag]; } - subscribeId = subscribIdMap_[tokenId]; - subscribIdMap_.erase(tokenId); } - std::shared_ptr req = std::make_shared(); + if (subscribeId == DM_INVALID_FLAG_ID) { + LOGE("DeviceManagerImpl::StopDiscovering failed: cannot find pkgName in cache map."); + return ERR_DM_INPUT_PARA_INVALID; + } + discoverParam.emplace(PARAM_KEY_SUBSCRIBE_ID, std::to_string(subscribeId)); + std::string discParaStr = ConvertMapToJsonString(discoverParam); + + std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); - req->SetPkgName(pkgName); - req->SetSubscribeId(subscribeId); - int32_t ret = ipcClientProxy_->SendRequest(STOP_DEVICE_DISCOVER, req, rsp); + req->SetPkgName(discoveryFlag); + req->SetFirstParam(discParaStr); + int32_t ret = ipcClientProxy_->SendRequest(STOP_DISCOVERING, req, rsp); if (ret != DM_OK) { - LOGE("StopDeviceDiscovery error: Send Request failed ret: %{public}d", ret); + LOGE("StopDiscovering error: Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } - ret = rsp->GetErrCode(); if (ret != DM_OK) { - LOGE("StopDeviceDiscovery error: Failed with ret %{public}d", ret); + LOGE("StopDiscovering error: Failed with ret %{public}d", ret); return ret; } - - DeviceManagerNotify::GetInstance().UnRegisterDiscoveryCallback(pkgName, subscribeId); + RemoveDiscoveryCallback(discoveryFlag); LOGI("Completed"); return DM_OK; } @@ -1648,86 +1633,6 @@ int32_t DeviceManagerImpl::ExportAuthCode(std::string &authCode) return DM_OK; } -int32_t DeviceManagerImpl::StartDiscovering(const std::string &pkgName, - std::map &discoverParam, const std::map &filterOptions, - std::shared_ptr callback) -{ - if (pkgName.empty() || callback == nullptr) { - LOGE("DeviceManagerImpl::StartDiscovering failed: input callback is null or pkgName is empty."); - return ERR_DM_INPUT_PARA_INVALID; - } - LOGI("Start, pkgName: %{public}s", pkgName.c_str()); - DmTraceStart(std::string(DM_HITRACE_START_DEVICE)); - - uint16_t subscribeId = AddDiscoveryCallback(pkgName, callback); - discoverParam.emplace(PARAM_KEY_SUBSCRIBE_ID, std::to_string(subscribeId)); - std::string discParaStr = ConvertMapToJsonString(discoverParam); - std::string filterOpStr = ConvertMapToJsonString(filterOptions); - - std::shared_ptr req = std::make_shared(); - std::shared_ptr rsp = std::make_shared(); - req->SetPkgName(pkgName); - req->SetFirstParam(discParaStr); - req->SetSecondParam(filterOpStr); - int32_t ret = ipcClientProxy_->SendRequest(START_DISCOVERING, req, rsp); - if (ret != DM_OK) { - LOGE("StartDiscovering error: Send Request failed ret: %{public}d", ret); - return ERR_DM_IPC_SEND_REQUEST_FAILED; - } - ret = rsp->GetErrCode(); - if (ret != DM_OK) { - LOGE("StartDiscovering error: Failed with ret %{public}d", ret); - return ret; - } - - DmTraceEnd(); - LOGI("Completed"); - SysEventWrite(std::string(START_DEVICE_DISCOVERY_SUCCESS), DM_HISYEVENT_BEHAVIOR, - std::string(START_DEVICE_DISCOVERY_SUCCESS_MSG)); - return DM_OK; -} - -int32_t DeviceManagerImpl::StopDiscovering(const std::string &pkgName, - std::map &discoverParam) -{ - if (pkgName.empty()) { - LOGE("DeviceManagerImpl::StopDiscovering failed: input pkgName is empty."); - return ERR_DM_INPUT_PARA_INVALID; - } - LOGI("Start, pkgName: %{public}s", pkgName.c_str()); - uint16_t subscribeId = DM_INVALID_FLAG_ID; - { - std::lock_guard autoLock(subMapLock); - if (pkgName2SubIdMap_.find(pkgName) != pkgName2SubIdMap_.end()) { - subscribeId = pkgName2SubIdMap_[pkgName]; - } - } - if (subscribeId == DM_INVALID_FLAG_ID) { - LOGE("DeviceManagerImpl::StopDiscovering failed: cannot find pkgName in cache map."); - return ERR_DM_INPUT_PARA_INVALID; - } - discoverParam.emplace(PARAM_KEY_SUBSCRIBE_ID, std::to_string(subscribeId)); - std::string discParaStr = ConvertMapToJsonString(discoverParam); - - std::shared_ptr req = std::make_shared(); - std::shared_ptr rsp = std::make_shared(); - req->SetPkgName(pkgName); - req->SetFirstParam(discParaStr); - int32_t ret = ipcClientProxy_->SendRequest(STOP_DISCOVERING, req, rsp); - if (ret != DM_OK) { - LOGE("StopDiscovering error: Send Request failed ret: %{public}d", ret); - return ERR_DM_IPC_SEND_REQUEST_FAILED; - } - ret = rsp->GetErrCode(); - if (ret != DM_OK) { - LOGE("StopDiscovering error: Failed with ret %{public}d", ret); - return ret; - } - RemoveDiscoveryCallback(pkgName); - LOGI("Completed"); - return DM_OK; -} - int32_t DeviceManagerImpl::RegisterDiscoveryCallback(const std::string &pkgName, std::map &discoverParam, const std::map &filterOptions, std::shared_ptr callback) @@ -1737,15 +1642,14 @@ int32_t DeviceManagerImpl::RegisterDiscoveryCallback(const std::string &pkgName, return ERR_DM_INPUT_PARA_INVALID; } LOGI("Start, pkgName: %{public}s", pkgName.c_str()); - - uint16_t subscribeId = AddDiscoveryCallback(pkgName, callback); + uint16_t subscribeId = AddDiscoveryCallback(pkgName, discoverParam, callback); discoverParam.emplace(PARAM_KEY_SUBSCRIBE_ID, std::to_string(subscribeId)); std::string discParaStr = ConvertMapToJsonString(discoverParam); std::string filterOpStr = ConvertMapToJsonString(filterOptions); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); - req->SetPkgName(pkgName); + req->SetPkgName(ComposeStr(pkgName, subscribeId)); req->SetFirstParam(discParaStr); req->SetSecondParam(filterOpStr); int32_t ret = ipcClientProxy_->SendRequest(REGISTER_DISCOVERY_CALLBACK, req, rsp); @@ -1771,8 +1675,8 @@ int32_t DeviceManagerImpl::UnRegisterDiscoveryCallback(const std::string &pkgNam return ERR_DM_INPUT_PARA_INVALID; } LOGI("Start, pkgName: %{public}s", pkgName.c_str()); - - uint16_t subscribeId = RemoveDiscoveryCallback(pkgName); + std::string discoveryFlag = ComposeStr(pkgName, DM_INVALID_FLAG_ID); + uint16_t subscribeId = RemoveDiscoveryCallback(discoveryFlag); if (subscribeId == DM_INVALID_FLAG_ID) { DmRadarHelper::GetInstance().ReportDmBehavior( pkgName, "UnRegisterDiscoveryCallback", ERR_DM_INPUT_PARA_INVALID); @@ -1785,21 +1689,21 @@ int32_t DeviceManagerImpl::UnRegisterDiscoveryCallback(const std::string &pkgNam std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); - req->SetPkgName(pkgName); + req->SetPkgName(discoveryFlag); req->SetFirstParam(extraParaStr); int32_t ret = ipcClientProxy_->SendRequest(UNREGISTER_DISCOVERY_CALLBACK, req, rsp); if (ret != DM_OK) { - DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnRegisterDiscoveryCallback", ret); + DmRadarHelper::GetInstance().ReportDmBehavior(discoveryFlag, "UnRegisterDiscoveryCallback", ret); LOGE("UnRegisterDiscoveryCallback error: Send Request failed ret: %{public}d", ret); return ERR_DM_IPC_SEND_REQUEST_FAILED; } ret = rsp->GetErrCode(); if (ret != DM_OK) { - DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnRegisterDiscoveryCallback", ret); + DmRadarHelper::GetInstance().ReportDmBehavior(discoveryFlag, "UnRegisterDiscoveryCallback", ret); LOGE("UnRegisterDiscoveryCallback error: Failed with ret %{public}d", ret); return ret; } - DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "UnRegisterDiscoveryCallback", DM_OK); + DmRadarHelper::GetInstance().ReportDmBehavior(discoveryFlag, "UnRegisterDiscoveryCallback", DM_OK); LOGI("Completed"); return DM_OK; } @@ -1982,20 +1886,33 @@ int32_t DeviceManagerImpl::CheckAccessToTarget(uint64_t tokenId, const std::stri } uint16_t DeviceManagerImpl::AddDiscoveryCallback(const std::string &pkgName, - std::shared_ptr callback) + std::map &discoverParam, std::shared_ptr callback) { + if (discoverParam.empty() || callback == nullptr) { + LOGE("input param invalid."); + return DM_INVALID_FLAG_ID; + } uint16_t subscribeId = DM_INVALID_FLAG_ID; + if (discoverParam.find(PARAM_KEY_SUBSCRIBE_ID) != discoverParam.end()) { + subscribeId = std::atoi((discoverParam.find(PARAM_KEY_SUBSCRIBE_ID)->second).c_str()); + } + std::string discoveryFlag = ComposeStr(pkgName, subscribeId); { std::lock_guard autoLock(subMapLock); - if (pkgName2SubIdMap_.find(pkgName) != pkgName2SubIdMap_.end()) { - subscribeId = pkgName2SubIdMap_[pkgName]; - } else { - subscribeId = GenRandUint(DM_MIN_RANDOM, DM_MAX_RANDOM); - pkgName2SubIdMap_[pkgName] = subscribeId; + { + auto iter = pkgName2SubIdMap_.find(pkgName); + if (iter == pkgName2SubIdMap_.end() && subscribeId != DM_INVALID_FLAG_ID) { + pkgName2SubIdMap_[discoveryFlag] = subscribeId; + } else if (iter == pkgName2SubIdMap_.end() && subscribeId == DM_INVALID_FLAG_ID) { + subscribeId = GenRandUint(DM_MIN_RANDOM, DM_MAX_RANDOM); + pkgName2SubIdMap_[discoveryFlag] = subscribeId; + } else if (iter != pkgName2SubIdMap_.end()) { + subscribeId = pkgName2SubIdMap_[discoveryFlag]; + } } } - DeviceManagerNotify::GetInstance().RegisterDiscoveryCallback(pkgName, subscribeId, callback); - DmRadarHelper::GetInstance().ReportDmBehavior(pkgName, "AddDiscoveryCallback", DM_OK); + DeviceManagerNotify::GetInstance().RegisterDiscoveryCallback(discoveryFlag, subscribeId, callback); + DmRadarHelper::GetInstance().ReportDmBehavior(discoveryFlag, "AddDiscoveryCallback", DM_OK); return subscribeId; } diff --git a/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_cmd_parser.cpp b/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_cmd_parser.cpp index 248628c0d..abdb60dc3 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_cmd_parser.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_cmd_parser.cpp @@ -30,8 +30,6 @@ #include "ipc_register_listener_req.h" #include "ipc_set_credential_req.h" #include "ipc_set_credential_rsp.h" -#include "ipc_start_discover_req.h" -#include "ipc_stop_discovery_req.h" #include "securec.h" namespace OHOS { @@ -183,24 +181,6 @@ ON_IPC_READ_RESPONSE(START_DEVICE_DISCOVERY, IpcIo &reply, std::shared_ptr pBaseReq, IpcIo &request, uint8_t *buffer, - size_t buffLen) -{ - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); - std::string pkgName = pReq->GetPkgName(); - uint16_t subscribeId = pReq->GetSubscribeId(); - - IpcIoInit(&request, buffer, buffLen, 0); - WriteString(&request, pkgName.c_str()); - WriteUint16(&request, subscribeId); - return DM_OK; -} - -ON_IPC_READ_RESPONSE(STOP_DEVICE_DISCOVER, IpcIo &reply, std::shared_ptr pBaseRsp) -{ - return SetRspErrCode(reply, pBaseRsp); -} - ON_IPC_SET_REQUEST(REQUEST_CREDENTIAL, std::shared_ptr pBaseReq, IpcIo &request, uint8_t *buffer, size_t buffLen) { diff --git a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp index ce9976e29..5b374b6e1 100644 --- a/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp +++ b/interfaces/inner_kits/native_cpp/src/ipc/standard/ipc_cmd_parser.cpp @@ -48,9 +48,6 @@ #include "ipc_set_credential_req.h" #include "ipc_set_credential_rsp.h" #include "ipc_set_useroperation_req.h" -#include "ipc_start_discovery_req.h" -#include "ipc_start_discover_req.h" -#include "ipc_stop_discovery_req.h" #include "ipc_permission_req.h" #include "ipc_publish_req.h" #include "ipc_unbind_device_req.h" @@ -314,86 +311,6 @@ ON_IPC_READ_RESPONSE(GET_UUID_BY_NETWORK, MessageParcel &reply, std::shared_ptr< return DM_OK; } -ON_IPC_SET_REQUEST(START_DEVICE_DISCOVER, std::shared_ptr pBaseReq, MessageParcel &data) -{ - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); - std::string pkgName = pReq->GetPkgName(); - std::string extra = pReq->GetExtra(); - const DmSubscribeInfo dmSubscribeInfo = pReq->GetSubscribeInfo(); - if (!data.WriteString(pkgName)) { - LOGE("write pkgName failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - if (!data.WriteString(extra)) { - LOGE("write extra failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - if (!data.WriteRawData(&dmSubscribeInfo, sizeof(DmSubscribeInfo))) { - LOGE("write subscribe info failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - return DM_OK; -} - -ON_IPC_READ_RESPONSE(START_DEVICE_DISCOVER, MessageParcel &reply, std::shared_ptr pBaseRsp) -{ - pBaseRsp->SetErrCode(reply.ReadInt32()); - return DM_OK; -} - -ON_IPC_SET_REQUEST(START_DEVICE_DISCOVERY, std::shared_ptr pBaseReq, MessageParcel &data) -{ - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); - std::string pkgName = pReq->GetPkgName(); - std::string filterOption = pReq->GetFilterOption(); - const uint16_t subscribeId = pReq->GetSubscribeId(); - if (!data.WriteString(pkgName)) { - LOGE("write pkgName failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - if (!data.WriteString(filterOption)) { - LOGE("write filterOption failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - if (!data.WriteUint16(subscribeId)) { - LOGE("write subscribe id failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - return DM_OK; -} - -ON_IPC_READ_RESPONSE(START_DEVICE_DISCOVERY, MessageParcel &reply, std::shared_ptr pBaseRsp) -{ - pBaseRsp->SetErrCode(reply.ReadInt32()); - return DM_OK; -} - -ON_IPC_SET_REQUEST(STOP_DEVICE_DISCOVER, std::shared_ptr pBaseReq, MessageParcel &data) -{ - std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); - std::string pkgName = pReq->GetPkgName(); - uint16_t subscribeId = pReq->GetSubscribeId(); - if (!data.WriteString(pkgName)) { - LOGE("write pkgName failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - if (!data.WriteInt16((int16_t)subscribeId)) { - LOGE("write subscribeId failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - return DM_OK; -} - -ON_IPC_READ_RESPONSE(STOP_DEVICE_DISCOVER, MessageParcel &reply, std::shared_ptr pBaseRsp) -{ - if (pBaseRsp == nullptr) { - LOGE("pBaseRsp is null"); - return ERR_DM_FAILED; - } - pBaseRsp->SetErrCode(reply.ReadInt32()); - return DM_OK; -} - ON_IPC_SET_REQUEST(PUBLISH_DEVICE_DISCOVER, std::shared_ptr pBaseReq, MessageParcel &data) { std::shared_ptr pReq = std::static_pointer_cast(pBaseReq); diff --git a/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp index 93a06ad7a..fba6df1e4 100644 --- a/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp +++ b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp @@ -31,7 +31,7 @@ constexpr const char* DEVICEINFO_CHANGE = "deviceInfoChange"; constexpr const char* DEVICE_READY = "deviceReady"; constexpr const char* DEVICE_TRUST_CHANGE = "deviceTrustChange"; #endif - +const uint16_t DM_INVALID_FLAG_ID = 0; void DeviceManagerNotify::RegisterDeathRecipientCallback(const std::string &pkgName, std::shared_ptr dmInitCallback) { @@ -520,68 +520,66 @@ void DeviceManagerNotify::OnDeviceReady(const std::string &pkgName, const DmDevi void DeviceManagerNotify::OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, const DmDeviceInfo &deviceInfo) { + LOGD("pkgName:%{public}s, subscribeId:%{public}d.", + GetAnonyString(pkgName).c_str(), (int32_t)subscribeId); if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return; } - + std::string discNoSubscribeId = ComposeStr(pkgName, DM_INVALID_FLAG_ID); + std::string discWithSubscribeId = ComposeStr(pkgName, subscribeId); std::shared_ptr tempCbk; { std::lock_guard autoLock(lock_); - if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { - LOGE("DeviceManagerNotify::OnDeviceFound error, device discovery callback not register for" - "pkgName %{public}s.", pkgName.c_str()); - return; - } - std::map> &discoverCallMap = deviceDiscoveryCallbacks_[pkgName]; - auto iter = discoverCallMap.find(subscribeId); - if (iter == discoverCallMap.end()) { - LOGE("OnDeviceFound error, no register deviceDiscoveryCallback for subscribeId %{public}d.", - (int32_t)subscribeId); - return; + for (const auto &item : deviceDiscoveryCallbacks_) { + if (item.first != discNoSubscribeId && item.first != discWithSubscribeId) { + continue; + } + std::map> &discoverCallMap = + deviceDiscoveryCallbacks_[pkgName]; + auto iter = discoverCallMap.find(subscribeId); + if (iter != discoverCallMap.end()) { + tempCbk = iter->second; + } } - tempCbk = iter->second; } if (tempCbk == nullptr) { LOGE("OnDeviceFound error, registered device discovery callback is nullptr."); return; } - LOGD("Complete with devInfo, pkgName:%{public}s, subscribeId:%{public}d.", - GetAnonyString(pkgName).c_str(), (int32_t)subscribeId); tempCbk->OnDeviceFound(subscribeId, deviceInfo); } void DeviceManagerNotify::OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, const DmDeviceBasicInfo &deviceBasicInfo) { + LOGD("pkgName:%{public}s, subscribeId:%{public}d.", + GetAnonyString(pkgName).c_str(), (int32_t)subscribeId); if (pkgName.empty()) { LOGE("Invalid parameter, pkgName is empty."); return; } - + std::string discNoSubscribeId = ComposeStr(pkgName, DM_INVALID_FLAG_ID); + std::string discWithSubscribeId = ComposeStr(pkgName, subscribeId); std::shared_ptr tempCbk; { std::lock_guard autoLock(lock_); - if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { - LOGE("DeviceManagerNotify::OnDeviceFound error, device discovery callback not register for" - "pkgName %{public}s.", pkgName.c_str()); - return; - } - std::map> &discoverCallMap = deviceDiscoveryCallbacks_[pkgName]; - auto iter = discoverCallMap.find(subscribeId); - if (iter == discoverCallMap.end()) { - LOGE("OnDeviceFound error, no register deviceDiscoveryCallback for subscribeId %{public}d.", - (int32_t)subscribeId); - return; + for (const auto &item : deviceDiscoveryCallbacks_) { + if (item.first != discNoSubscribeId && item.first != discWithSubscribeId) { + continue; + } + std::map> &discoverCallMap = + deviceDiscoveryCallbacks_[pkgName]; + auto iter = discoverCallMap.find(subscribeId); + if (iter != discoverCallMap.end()) { + tempCbk = iter->second; + } } - tempCbk = iter->second; } if (tempCbk == nullptr) { LOGE("OnDeviceFound error, registered device discovery callback is nullptr."); return; } - LOGD("Complete with DmDeviceBasicInfo, pkgName:%{public}s, subscribeId:%{public}d.", - GetAnonyString(pkgName).c_str(), (int32_t)subscribeId); tempCbk->OnDeviceFound(subscribeId, deviceBasicInfo); } @@ -593,22 +591,22 @@ void DeviceManagerNotify::OnDiscoveryFailed(const std::string &pkgName, uint16_t } LOGI("DeviceManagerNotify::OnDiscoveryFailed in, pkgName:%{public}s, subscribeId %{public}d, failed" "reason %{public}d", pkgName.c_str(), (int32_t)subscribeId, failedReason); + std::string discNoSubscribeId = ComposeStr(pkgName, DM_INVALID_FLAG_ID); + std::string discWithSubscribeId = ComposeStr(pkgName, subscribeId); std::shared_ptr tempCbk; { std::lock_guard autoLock(lock_); - if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { - LOGE("DeviceManagerNotify::OnDiscoveryFailed error, device discovery callback not register for" - "pkgName %{public}s.", pkgName.c_str()); - return; - } - std::map> &discoverCallMap = deviceDiscoveryCallbacks_[pkgName]; - auto iter = discoverCallMap.find(subscribeId); - if (iter == discoverCallMap.end()) { - LOGE("OnDiscoveryFailed error, device discovery callback not register for subscribeId %{public}d.", - subscribeId); - return; + for (const auto &item : deviceDiscoveryCallbacks_) { + if (item.first != discNoSubscribeId && item.first != discWithSubscribeId) { + continue; + } + std::map> &discoverCallMap = + deviceDiscoveryCallbacks_[pkgName]; + auto iter = discoverCallMap.find(subscribeId); + if (iter != discoverCallMap.end()) { + tempCbk = iter->second; + } } - tempCbk = iter->second; } if (tempCbk == nullptr) { LOGE("OnDiscoveryFailed error, registered device discovery callback is nullptr."); @@ -624,22 +622,22 @@ void DeviceManagerNotify::OnDiscoverySuccess(const std::string &pkgName, uint16_ return; } LOGI("PkgName:%{public}s, subscribeId:%{public}d.", GetAnonyString(pkgName).c_str(), subscribeId); + std::string discNoSubscribeId = ComposeStr(pkgName, DM_INVALID_FLAG_ID); + std::string discWithSubscribeId = ComposeStr(pkgName, subscribeId); std::shared_ptr tempCbk; { std::lock_guard autoLock(lock_); - if (deviceDiscoveryCallbacks_.count(pkgName) == 0) { - LOGE("OnDiscoverySuccess error, device discovery callback not register for pkgName %{public}s.", - pkgName.c_str()); - return; - } - std::map> &discoverCallMap = deviceDiscoveryCallbacks_[pkgName]; - auto iter = discoverCallMap.find(subscribeId); - if (iter == discoverCallMap.end()) { - LOGE("OnDiscoverySuccess error, device discovery callback not register for subscribeId %{public}d.", - (int32_t)subscribeId); - return; + for (const auto &item : deviceDiscoveryCallbacks_) { + if (item.first != discNoSubscribeId && item.first != discWithSubscribeId) { + continue; + } + std::map> &discoverCallMap = + deviceDiscoveryCallbacks_[pkgName]; + auto iter = discoverCallMap.find(subscribeId); + if (iter != discoverCallMap.end()) { + tempCbk = iter->second; + } } - tempCbk = iter->second; } if (tempCbk == nullptr) { LOGE("OnDiscoverySuccess error, registered device discovery callback is nullptr."); diff --git a/services/implementation/include/authentication/auth_ui_state_manager.h b/services/implementation/include/authentication/auth_ui_state_manager.h index badf235d6..2a7bdbc6d 100644 --- a/services/implementation/include/authentication/auth_ui_state_manager.h +++ b/services/implementation/include/authentication/auth_ui_state_manager.h @@ -42,7 +42,7 @@ public: void UnRegisterUiStateCallback(const std::string pkgName); void UpdateUiState(const DmUiStateMsg msg); private: - std::set pkgSet_; + std::set pkgSet_; std::mutex pkgSetMutex_; std::shared_ptr listener_; }; diff --git a/services/implementation/include/authentication/dm_auth_manager.h b/services/implementation/include/authentication/dm_auth_manager.h index edf4e9d96..6c471abce 100644 --- a/services/implementation/include/authentication/dm_auth_manager.h +++ b/services/implementation/include/authentication/dm_auth_manager.h @@ -371,13 +371,6 @@ public: */ void HandleAuthenticateTimeout(std::string name); - /** - * @tc.name: DmAuthManager::CancelDisplay - * @tc.desc: Cancel Display of the DeviceManager Authenticate Manager - * @tc.type: FUNC - */ - void CancelDisplay(); - /** * @tc.name: DmAuthManager::GeneratePincode * @tc.desc: Generate Pincode of the DeviceManager Authenticate Manager @@ -571,6 +564,7 @@ private: std::string remoteVersion_ = ""; std::atomic authType_ = AUTH_TYPE_UNKNOW; std::string remoteUdidHash_ = ""; + ProcessInfo processInfo_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/include/credential/dm_credential_manager.h b/services/implementation/include/credential/dm_credential_manager.h index b20c09bfb..f30e282e9 100644 --- a/services/implementation/include/credential/dm_credential_manager.h +++ b/services/implementation/include/credential/dm_credential_manager.h @@ -95,7 +95,7 @@ public: int32_t DeleteCredential(const std::string &pkgName, const std::string &deleteInfo); /** - * @tc.name: HiChainConnector::OnCredentialResult + * @tc.name: HiChainConnector::OnGroupResult * @tc.desc: Credential Result of the DmCredential Manager * @tc.type: FUNC */ @@ -103,6 +103,7 @@ public: int32_t ImportRemoteCredentialExt(const std::string &credentialInfo); void OnGroupResultExt(int32_t action, const std::string &resultInfo); + void HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode); private: std::shared_ptr hiChainConnector_; @@ -110,7 +111,7 @@ private: std::vector credentialVec_; int64_t requestId_ = 0; std::mutex locks_; - std::string pkgName_; + ProcessInfo processInfo_; private: int32_t GetCredentialData(const std::string &credentialInfo, const CredentialData &inputCreData, nlohmann::json &jsonOutObj); diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index c1218e2f6..e8b435d6e 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -133,15 +133,8 @@ public: int32_t StopAuthenticateDevice(const std::string &pkgName); void HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode); int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId); - /** - * @brief process the foreground userid sync broadcast. - * - * @param remoteUserIds the remote device foreground userids. - * @param remoteUdid the remote device udid. - * @param isNeedRsp true for need send back local foreground userids, false for not need send back. - */ - void HandleSyncForegroundUserIdEvent(const std::vector &remoteUserIds, const std::string &remoteUdid); - + void HandleSyncForegroundUserIdEvent(const std::vector &remoteUserIds, + const std::string &remoteUdid); private: int32_t PraseNotifyEventJson(const std::string &event, nlohmann::json &jsonObject); std::string GetUdidHashByNetworkId(const std::string &networkId); diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index e6b954f9f..9d89973c5 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -139,6 +139,8 @@ public: int32_t StopAuthenticateDevice(const std::string &pkgName); void HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode); int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId); + void HandleSyncForegroundUserIdEvent(const std::vector &remoteUserIds, + const std::string &remoteUdid); private: std::string GetUdidHashByNetworkId(const std::string &networkId); diff --git a/services/implementation/include/devicestate/dm_device_state_manager.h b/services/implementation/include/devicestate/dm_device_state_manager.h index 68fb531a4..8e6806ef4 100644 --- a/services/implementation/include/devicestate/dm_device_state_manager.h +++ b/services/implementation/include/devicestate/dm_device_state_manager.h @@ -96,7 +96,6 @@ public: bool CheckIsOnline(const std::string &udid); void DeleteOffLineTimer(std::string udidHash); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); - void HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode); private: void StartEventThread(); void StopEventThread(); diff --git a/services/implementation/src/authentication/auth_ui_state_manager.cpp b/services/implementation/src/authentication/auth_ui_state_manager.cpp index ab4d5e415..d338980d7 100644 --- a/services/implementation/src/authentication/auth_ui_state_manager.cpp +++ b/services/implementation/src/authentication/auth_ui_state_manager.cpp @@ -16,7 +16,9 @@ #include "auth_ui_state_manager.h" #include "dm_log.h" #include "nlohmann/json.hpp" - +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "multiple_user_connector.h" +#endif namespace OHOS { namespace DistributedHardware { constexpr const char* UI_STATE_MSG = "uiStateMsg"; @@ -27,18 +29,28 @@ AuthUiStateManager::AuthUiStateManager(std::shared_ptr lock(pkgSetMutex_); - pkgSet_.emplace(pkgName); + pkgSet_.emplace(processInfo); } void AuthUiStateManager::UnRegisterUiStateCallback(const std::string pkgName) { + int32_t userId = -1; + MultipleUserConnector::GetCallerUserId(userId); + ProcessInfo processInfo; + processInfo.userId = userId; + processInfo.pkgName = pkgName; std::lock_guard lock(pkgSetMutex_); - if (pkgSet_.find(pkgName) == pkgSet_.end()) { - LOGE("AuthUiStateManager UnRegisterUiStateCallback pkgName is not exist."); + if (pkgSet_.find(processInfo) == pkgSet_.end()) { + LOGE("AuthUiStateManager UnRegisterUiStateCallback processInfo is not exist."); return; } - pkgSet_.erase(pkgName); + pkgSet_.erase(processInfo); } void AuthUiStateManager::UpdateUiState(const DmUiStateMsg msg) @@ -51,8 +63,8 @@ void AuthUiStateManager::UpdateUiState(const DmUiStateMsg msg) jsonObj[UI_STATE_MSG] = msg; std::string paramJson = jsonObj.dump(); std::lock_guard lock(pkgSetMutex_); - for (auto pkgName : pkgSet_) { - listener_->OnUiCall(pkgName, paramJson); + for (auto item : pkgSet_) { + listener_->OnUiCall(item, paramJson); } LOGI("AuthUiStateManager::UpdateUiState complete."); } diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 50f4b6674..d1bcb4c5c 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -42,6 +42,9 @@ #include "nlohmann/json.hpp" #include "parameter.h" #include "show_confirm.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "multiple_user_connector.h" +#endif namespace OHOS { namespace DistributedHardware { @@ -139,9 +142,9 @@ int32_t DmAuthManager::CheckAuthParamVaild(const std::string &pkgName, int32_t a if (!IsAuthTypeSupported(authType)) { LOGE("DmAuthManager::CheckAuthParamVaild authType %{public}d not support.", authType); - listener_->OnAuthResult(pkgName, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, ERR_DM_UNSUPPORTED_AUTH_TYPE); - listener_->OnBindResult(pkgName, peerTargetId_, ERR_DM_UNSUPPORTED_AUTH_TYPE, STATUS_DM_AUTH_DEFAULT, ""); + listener_->OnBindResult(processInfo_, peerTargetId_, ERR_DM_UNSUPPORTED_AUTH_TYPE, STATUS_DM_AUTH_DEFAULT, ""); return ERR_DM_UNSUPPORTED_AUTH_TYPE; } @@ -152,15 +155,17 @@ int32_t DmAuthManager::CheckAuthParamVaild(const std::string &pkgName, int32_t a if (!softbusConnector_->HaveDeviceInMap(deviceId)) { LOGE("CheckAuthParamVaild failed, the discoveryDeviceInfoMap_ not have this device."); - listener_->OnAuthResult(pkgName, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, ERR_DM_INPUT_PARA_INVALID); - listener_->OnBindResult(pkgName, peerTargetId_, ERR_DM_INPUT_PARA_INVALID, STATUS_DM_AUTH_DEFAULT, ""); + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, + ERR_DM_INPUT_PARA_INVALID); + listener_->OnBindResult(processInfo_, peerTargetId_, ERR_DM_INPUT_PARA_INVALID, STATUS_DM_AUTH_DEFAULT, ""); return ERR_DM_INPUT_PARA_INVALID; } if ((authType == AUTH_TYPE_IMPORT_AUTH_CODE) && (!IsAuthCodeReady(pkgName))) { LOGE("Auth code not exist."); - listener_->OnAuthResult(pkgName, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, ERR_DM_INPUT_PARA_INVALID); - listener_->OnBindResult(pkgName, peerTargetId_, ERR_DM_INPUT_PARA_INVALID, STATUS_DM_AUTH_DEFAULT, ""); + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, + ERR_DM_INPUT_PARA_INVALID); + listener_->OnBindResult(processInfo_, peerTargetId_, ERR_DM_INPUT_PARA_INVALID, STATUS_DM_AUTH_DEFAULT, ""); return ERR_DM_INPUT_PARA_INVALID; } return DM_OK; @@ -265,6 +270,10 @@ int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t au { LOGI("DmAuthManager::AuthenticateDevice start auth type %{public}d.", authType); SetAuthType(authType); + int32_t userId = -1; + MultipleUserConnector::GetCallerUserId(userId); + processInfo_.pkgName = pkgName; + processInfo_.userId = userId; int32_t ret = CheckAuthParamVaild(pkgName, authType, deviceId, extra); if (ret != DM_OK) { LOGE("DmAuthManager::AuthenticateDevice failed, param is invaild."); @@ -279,8 +288,8 @@ int32_t DmAuthManager::AuthenticateDevice(const std::string &pkgName, int32_t au if (authType == AUTH_TYPE_CRE) { LOGI("DmAuthManager::AuthenticateDevice for credential type, joinLNN directly."); softbusConnector_->JoinLnn(deviceId); - listener_->OnAuthResult(pkgName, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, DM_OK); - listener_->OnBindResult(pkgName, peerTargetId_, DM_OK, STATUS_DM_AUTH_DEFAULT, ""); + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, "", STATUS_DM_AUTH_DEFAULT, DM_OK); + listener_->OnBindResult(processInfo_, peerTargetId_, DM_OK, STATUS_DM_AUTH_DEFAULT, ""); return DM_OK; } InitAuthState(pkgName, authType, deviceId, extra); @@ -926,9 +935,9 @@ void DmAuthManager::ProcessAuthRequest(const int32_t &sessionId) softbusConnector_->GetSoftbusSession()->SendData(sessionId, msg); } - listener_->OnAuthResult(authResponseContext_->hostPkgName, peerTargetId_.deviceId, - authRequestContext_->token, STATUS_DM_SHOW_AUTHORIZE_UI, DM_OK); - listener_->OnBindResult(authResponseContext_->hostPkgName, peerTargetId_, DM_OK, STATUS_DM_SHOW_AUTHORIZE_UI, ""); + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, authRequestContext_->token, + STATUS_DM_SHOW_AUTHORIZE_UI, DM_OK); + listener_->OnBindResult(processInfo_, peerTargetId_, DM_OK, STATUS_DM_SHOW_AUTHORIZE_UI, ""); timer_->StartTimer(std::string(CONFIRM_TIMEOUT_TASK), GetTaskTimeout(CONFIRM_TIMEOUT_TASK, CONFIRM_TIMEOUT), [this] (std::string name) { DmAuthManager::HandleAuthenticateTimeout(name); @@ -969,8 +978,8 @@ void DmAuthManager::ProcessAuthRequestExt(const int32_t &sessionId) authResponseContext_->authed = !bindType.empty(); authResponseContext_->bindType = bindType; if (authResponseContext_->reply == ERR_DM_UNSUPPORTED_AUTH_TYPE) { - listener_->OnAuthResult(authResponseContext_->hostPkgName, peerTargetId_.deviceId, - authRequestContext_->token, AuthState::AUTH_REQUEST_NEGOTIATE_DONE, ERR_DM_UNSUPPORTED_AUTH_TYPE); + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, authRequestContext_->token, + AuthState::AUTH_REQUEST_NEGOTIATE_DONE, ERR_DM_UNSUPPORTED_AUTH_TYPE); authRequestState_->TransitionTo(std::make_shared()); return; } @@ -1000,9 +1009,9 @@ void DmAuthManager::ProcessAuthRequestExt(const int32_t &sessionId) for (auto msg : messageList) { softbusConnector_->GetSoftbusSession()->SendData(sessionId, msg); } - listener_->OnAuthResult(authResponseContext_->hostPkgName, peerTargetId_.deviceId, - authRequestContext_->token, STATUS_DM_SHOW_AUTHORIZE_UI, DM_OK); - listener_->OnBindResult(authResponseContext_->hostPkgName, peerTargetId_, DM_OK, STATUS_DM_SHOW_AUTHORIZE_UI, ""); + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, authRequestContext_->token, + STATUS_DM_SHOW_AUTHORIZE_UI, DM_OK); + listener_->OnBindResult(processInfo_, peerTargetId_, DM_OK, STATUS_DM_SHOW_AUTHORIZE_UI, ""); timer_->StartTimer(std::string(CONFIRM_TIMEOUT_TASK), GetTaskTimeout(CONFIRM_TIMEOUT_TASK, CONFIRM_TIMEOUT), [this] (std::string name) { DmAuthManager::HandleAuthenticateTimeout(name); @@ -1109,10 +1118,9 @@ void DmAuthManager::StartRespAuthProcess() GetTaskTimeout(SESSION_HEARTBEAT_TIMEOUT_TASK, SESSION_HEARTBEAT_TIMEOUT), [this] (std::string name) { DmAuthManager::HandleSessionHeartbeat(name); }); - listener_->OnAuthResult(authRequestContext_->hostPkgName, peerTargetId_.deviceId, + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, authRequestContext_->token, STATUS_DM_SHOW_PIN_INPUT_UI, DM_OK); - listener_->OnBindResult(authRequestContext_->hostPkgName, peerTargetId_, DM_OK, - STATUS_DM_SHOW_PIN_INPUT_UI, ""); + listener_->OnBindResult(processInfo_, peerTargetId_, DM_OK, STATUS_DM_SHOW_PIN_INPUT_UI, ""); authRequestState_->TransitionTo(std::make_shared()); } else { LOGE("do not accept"); @@ -1237,9 +1245,9 @@ void DmAuthManager::SrcAuthenticateFinish() authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT); } usleep(USLEEP_TIME_US_500000); // 500ms - listener_->OnAuthResult(authRequestContext_->hostPkgName, peerTargetId_.deviceId, - authRequestContext_->token, authResponseContext_->state, authRequestContext_->reason); - listener_->OnBindResult(authRequestContext_->hostPkgName, peerTargetId_, authRequestContext_->reason, + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, authRequestContext_->token, + authResponseContext_->state, authRequestContext_->reason); + listener_->OnBindResult(processInfo_, peerTargetId_, authRequestContext_->reason, authResponseContext_->state, GenerateBindResultContent()); softbusConnector_->GetSoftbusSession()->CloseAuthSession(authRequestContext_->sessionId); authRequestContext_ = nullptr; @@ -1281,16 +1289,6 @@ void DmAuthManager::AuthenticateFinish() LOGI("DmAuthManager::AuthenticateFinish complete"); } -void DmAuthManager::CancelDisplay() -{ - LOGI("DmAuthManager::CancelDisplay start"); - nlohmann::json jsonObj; - jsonObj[CANCEL_DISPLAY_KEY] = CANCEL_PIN_CODE_DISPLAY; - std::string paramJson = jsonObj.dump(); - std::string pkgName = "com.ohos.devicemanagerui"; - listener_->OnUiCall(pkgName, paramJson); -} - int32_t DmAuthManager::RegisterUiStateCallback(const std::string pkgName) { LOGI("DmAuthManager::RegisterUiStateCallback start"); diff --git a/services/implementation/src/credential/dm_credential_manager.cpp b/services/implementation/src/credential/dm_credential_manager.cpp index 043d2dd32..ce48bcc2c 100644 --- a/services/implementation/src/credential/dm_credential_manager.cpp +++ b/services/implementation/src/credential/dm_credential_manager.cpp @@ -20,7 +20,9 @@ #include "dm_log.h" #include "dm_random.h" #include "parameter.h" - +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "multiple_user_connector.h" +#endif namespace OHOS { namespace DistributedHardware { const int32_t LOCAL_CREDENTIAL_DEAL_TYPE = 1; @@ -123,7 +125,6 @@ int32_t DmCredentialManager::ImportCredential(const std::string &pkgName, const LOGE("credentialInfo not found by pkgName %{public}s", GetAnonyString(pkgName).c_str()); return ERR_DM_FAILED; } - pkgName_ = pkgName; nlohmann::json jsonObject = nlohmann::json::parse(credentialInfo, nullptr, false); if (jsonObject.is_discarded()) { LOGE("credentialInfo string not a json type."); @@ -213,7 +214,10 @@ int32_t DmCredentialManager::DeleteCredential(const std::string &pkgName, const LOGE("credentialInfo not found by pkgName %{public}s", GetAnonyString(pkgName).c_str()); return ERR_DM_FAILED; } - pkgName_ = pkgName; + int32_t callerUserId = -1; + MultipleUserConnector::GetCallerUserId(callerUserId); + processInfo_.pkgName = pkgName; + processInfo_.userId = callerUserId; nlohmann::json jsonObject = nlohmann::json::parse(deleteInfo, nullptr, false); if (jsonObject.is_discarded()) { LOGE("deleteInfo string not a json type."); @@ -247,7 +251,8 @@ int32_t DmCredentialManager::DeleteCredential(const std::string &pkgName, const void DmCredentialManager::OnGroupResultExt(int32_t action, const std::string &resultInfo) { LOGI("DmCredentialManager::OnGroupResultExt action %{public}d, resultInfo %{public}s.", action, resultInfo.c_str()); - listener_->OnCredentialResult(pkgName_, action, resultInfo); + CHECK_NULL_VOID(listener_); + listener_->OnCredentialResult(processInfo_, action, resultInfo); } void DmCredentialManager::OnGroupResult(int64_t requestId, int32_t action, @@ -257,7 +262,8 @@ void DmCredentialManager::OnGroupResult(int64_t requestId, int32_t action, if (requestId_ != requestId) { return; } - listener_->OnCredentialResult(pkgName_, action, resultInfo); + CHECK_NULL_VOID(listener_); + listener_->OnCredentialResult(processInfo_, action, resultInfo); } int32_t DmCredentialManager::RegisterCredentialCallback(const std::string &pkgName) @@ -266,9 +272,13 @@ int32_t DmCredentialManager::RegisterCredentialCallback(const std::string &pkgNa LOGE("DmCredentialManager::RegisterCredentialCallback input param is empty"); return ERR_DM_FAILED; } + int32_t userId = -1; + MultipleUserConnector::GetCallerUserId(userId); LOGI("DmCredentialManager::RegisterCredentialCallback pkgName = %{public}s", GetAnonyString(pkgName).c_str()); { std::lock_guard autoLock(locks_); + processInfo_.pkgName = pkgName; + processInfo_.userId = userId; credentialVec_.push_back(pkgName); } return hiChainConnector_->RegisterHiChainGroupCallback(std::shared_ptr(shared_from_this())); @@ -519,5 +529,11 @@ int32_t DmCredentialManager::DeleteRemoteCredential(const std::string &deleteInf } return DM_OK; } + +void DmCredentialManager::HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) +{ + CHECK_NULL_VOID(listener_); + listener_->OnCredentialAuthStatus(processInfo_, deviceTypeId, errcode); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index a4836fffe..d3f6630ee 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -252,31 +252,31 @@ void DeviceManagerServiceImpl::HandleOnline(DmDeviceState devState, DmDeviceInfo std::string requestDeviceId = std::string(localUdid); uint32_t bindType = DeviceProfileConnector::GetInstance().CheckBindType(trustDeviceId, requestDeviceId); LOGI("The online device bind type is %{public}d.", bindType); + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = MultipleUserConnector::GetForegroundUser(); if (bindType == INVALIED_TYPE && isCredentialType_.load()) { PutIdenticalAccountToAcl(requestDeviceId, trustDeviceId); devInfo.authForm = DmAuthForm::IDENTICAL_ACCOUNT; + isCredentialType_.store(false); + softbusConnector_->SetProcessInfo(processInfo); } else if (bindType == IDENTICAL_ACCOUNT_TYPE) { devInfo.authForm = DmAuthForm::IDENTICAL_ACCOUNT; + softbusConnector_->SetProcessInfo(processInfo); } else if (bindType == DEVICE_PEER_TO_PEER_TYPE) { devInfo.authForm = DmAuthForm::PEER_TO_PEER; + softbusConnector_->SetProcessInfo(processInfo); } else if (bindType == DEVICE_ACROSS_ACCOUNT_TYPE) { devInfo.authForm = DmAuthForm::ACROSS_ACCOUNT; + softbusConnector_->SetProcessInfo(processInfo); } else if (bindType == APP_PEER_TO_PEER_TYPE) { std::vector processInfoVec = DeviceProfileConnector::GetInstance().GetProcessInfoFromAcl(requestDeviceId, trustDeviceId); - if (processInfoVec.size() == 0) { - LOGI("The online device not need report pkgname"); - return; - } softbusConnector_->SetProcessInfoVec(processInfoVec); devInfo.authForm = DmAuthForm::PEER_TO_PEER; } else if (bindType == APP_ACROSS_ACCOUNT_TYPE) { std::vector processInfoVec = DeviceProfileConnector::GetInstance().GetProcessInfoFromAcl(requestDeviceId, trustDeviceId); - if (processInfoVec.size() == 0) { - LOGI("The online device not need report pkgname"); - return; - } softbusConnector_->SetProcessInfoVec(processInfoVec); devInfo.authForm = DmAuthForm::ACROSS_ACCOUNT; } @@ -300,6 +300,10 @@ void DeviceManagerServiceImpl::HandleDeviceStatusChange(DmDeviceState devState, LOGE("get deviceId: %{public}s failed", GetAnonyString(udiddHash).c_str()); return; } + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = MultipleUserConnector::GetForegroundUser(); + softbusConnector_->SetProcessInfo(processInfo); deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); } } @@ -488,7 +492,7 @@ int32_t DeviceManagerServiceImpl::RegisterUiStateCallback(const std::string &pkg int32_t DeviceManagerServiceImpl::UnRegisterUiStateCallback(const std::string &pkgName) { if (pkgName.empty()) { - LOGE("RegisterUiStateCallback failed, pkgName is empty"); + LOGE("UnRegisterUiStateCallback failed, pkgName is empty"); return ERR_DM_INPUT_PARA_INVALID; } if (authMgr_ == nullptr) { @@ -864,15 +868,13 @@ void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devI return; } else if (bindType == IDENTICAL_ACCOUNT_TYPE || bindType == DEVICE_PEER_TO_PEER_TYPE || bindType == DEVICE_ACROSS_ACCOUNT_TYPE) { - softbusConnector_->ClearProcessInfo(); - LOGI("networkId: %{public}s", GetAnonyString(devInfo.networkId).c_str()); + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = MultipleUserConnector::GetForegroundUser(); + softbusConnector_->SetProcessInfo(processInfo); } else if (bindType == APP_PEER_TO_PEER_TYPE || bindType == APP_ACROSS_ACCOUNT_TYPE) { std::vector processInfoVec = DeviceProfileConnector::GetInstance().GetProcessInfoFromAcl(requestDeviceId, trustDeviceId); - if (processInfoVec.size() == 0) { - LOGI("not need report pkgname"); - return; - } softbusConnector_->SetProcessInfoVec(processInfoVec); } deviceStateMgr_->HandleDeviceScreenStatusChange(devInfo); @@ -880,8 +882,8 @@ void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devI void DeviceManagerServiceImpl::HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) { - CHECK_NULL_VOID(deviceStateMgr_); - deviceStateMgr_->HandleCredentialAuthStatus(deviceTypeId, errcode); + CHECK_NULL_VOID(credentialMgr_); + credentialMgr_->HandleCredentialAuthStatus(deviceTypeId, errcode); } int32_t DeviceManagerServiceImpl::ProcessAppUnintall(const std::string &appId, int32_t accessTokenId) diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index 46ed922ce..24996f46d 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -533,13 +533,20 @@ void DeviceManagerServiceImpl::HandleCredentialAuthStatus(uint16_t deviceTypeId, return; } -int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId) +int32_t DeviceManagerServiceImpl::ProcessAppUnintall(const std::string &appId, int32_t accessTokenId) { (void)appId; (void)accessTokenId; return 0; } +void DeviceManagerServiceImpl::HandleSyncForegroundUserIdEvent(const std::vector &remoteUserIds, + const std::string &remoteUdid) +{ + (void)remoteUserIds; + (void)remoteUdid; +} + extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) { return new DeviceManagerServiceImpl; diff --git a/services/implementation/src/devicestate/dm_device_state_manager.cpp b/services/implementation/src/devicestate/dm_device_state_manager.cpp index 88d021b66..eaed6d51e 100644 --- a/services/implementation/src/devicestate/dm_device_state_manager.cpp +++ b/services/implementation/src/devicestate/dm_device_state_manager.cpp @@ -166,19 +166,11 @@ void DmDeviceStateManager::HandleDeviceStatusChange(DmDeviceState devState, DmDe void DmDeviceStateManager::ProcessDeviceStateChange(const DmDeviceState devState, const DmDeviceInfo &devInfo) { - if (softbusConnector_ == nullptr || listener_ == nullptr) { - LOGE("ProcessDeviceStateChange failed, callback_ptr is null."); - return; - } + CHECK_NULL_VOID(softbusConnector_); + CHECK_NULL_VOID(listener_); std::vector processInfoVec = softbusConnector_->GetProcessInfo(); - if (processInfoVec.size() == 0) { - ProcessInfo processInfo; - processInfo.pkgName = std::string(DM_PKG_NAME); - listener_->OnDeviceStateChange(processInfo, devState, devInfo); - } else { - for (auto item : processInfoVec) { - listener_->OnDeviceStateChange(item, devState, devInfo); - } + for (const auto &item : processInfoVec) { + listener_->OnDeviceStateChange(item, devState, devInfo); } } @@ -516,31 +508,14 @@ bool DmDeviceStateManager::CheckIsOnline(const std::string &udid) void DmDeviceStateManager::HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) { - if (softbusConnector_ == nullptr || listener_ == nullptr) { - LOGE("failed, ptr is null."); - return; - } + CHECK_NULL_VOID(softbusConnector_); + CHECK_NULL_VOID(listener_); std::vector processInfos = softbusConnector_->GetProcessInfo(); - LOGI("process size: %{public}zu", processInfos.size()); - if (processInfos.size() == 0) { - ProcessInfo processInfo; - processInfo.pkgName = std::string(DM_PKG_NAME); - listener_->OnDeviceScreenStateChange(processInfo, devInfo); - } else { - for (auto item : processInfos) { - listener_->OnDeviceScreenStateChange(item, devInfo); - } - } softbusConnector_->ClearProcessInfo(); -} - -void DmDeviceStateManager::HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) -{ - if (listener_ == nullptr) { - LOGE("Failed, listener_ is null."); - return; + LOGI("pkgName size: %{public}zu", processInfos.size()); + for (const auto &item : processInfos) { + listener_->OnDeviceScreenStateChange(item, devInfo); } - listener_->OnCredentialAuthStatus(std::string(DM_PKG_NAME), deviceTypeId, errcode); } } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/discovery/dm_discovery_manager.cpp b/services/implementation/src/discovery/dm_discovery_manager.cpp index 594b949f1..a9ccaee3a 100644 --- a/services/implementation/src/discovery/dm_discovery_manager.cpp +++ b/services/implementation/src/discovery/dm_discovery_manager.cpp @@ -160,9 +160,6 @@ void DmDiscoveryManager::OnDeviceFound(const std::string &pkgName, DmDeviceInfo info.authForm = DmAuthForm::INVALID_TYPE; GetAuthForm(localDeviceId, info.deviceId, filterPara.isTrusted, info.authForm); filterPara.authForm = info.authForm; - if (filter.IsValidDevice(discoveryContext.filterOp, discoveryContext.filters, filterPara)) { - listener_->OnDeviceFound(pkgName, discoveryContext.subscribeId, info); - } return; } @@ -223,9 +220,6 @@ void DmDiscoveryManager::OnDeviceFound(const std::string &pkgName, DmAuthForm authForm = DmAuthForm::INVALID_TYPE; GetAuthForm(localDeviceId, info.deviceId, filterPara.isTrusted, authForm); filterPara.authForm = authForm; - if (filter.IsValidDevice(discoveryContext.filterOp, discoveryContext.filters, filterPara)) { - listener_->OnDeviceFound(pkgName, discoveryContext.subscribeId, info); - } return; } @@ -248,7 +242,6 @@ void DmDiscoveryManager::OnDiscoveryFailed(const std::string &pkgName, int32_t s } } softbusConnector_->StopDiscovery(subscribeId); - listener_->OnDiscoveryFailed(pkgName, (uint32_t)subscribeId, failedReason); } void DmDiscoveryManager::OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId) @@ -258,7 +251,6 @@ void DmDiscoveryManager::OnDiscoverySuccess(const std::string &pkgName, int32_t std::lock_guard autoLock(locks_); discoveryContextMap_[pkgName].subscribeId = (uint32_t)subscribeId; } - listener_->OnDiscoverySuccess(pkgName, subscribeId); } void DmDiscoveryManager::HandleDiscoveryTimeout(std::string name) diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index 2b500027f..25141ceb1 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -76,14 +76,6 @@ public: int32_t GetUuidByNetworkId(const std::string &pkgName, const std::string &netWorkId, std::string &uuid); - int32_t StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, - const std::string &extra); - - int32_t StartDeviceDiscovery(const std::string &pkgName, const uint16_t subscribeInfo, - const std::string &filterOptions); - - int32_t StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId); - int32_t PublishDeviceDiscovery(const std::string &pkgName, const DmPublishInfo &publishInfo); int32_t UnPublishDeviceDiscovery(const std::string &pkgName, int32_t publishId); diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index 16cc8605b..97144f236 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -42,39 +42,37 @@ public: void OnDeviceStateChange(const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info) override; - void OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, const DmDeviceInfo &info) override; + void OnDeviceFound(const ProcessInfo &processInfo, uint16_t subscribeId, const DmDeviceInfo &info) override; - void OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, DmDeviceBasicInfo &info) override; + void OnDiscoveryFailed(const ProcessInfo &processInfo, uint16_t subscribeId, int32_t failedReason) override; - void OnDiscoveryFailed(const std::string &pkgName, uint16_t subscribeId, int32_t failedReason) override; - - void OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId) override; + void OnDiscoverySuccess(const ProcessInfo &processInfo, int32_t subscribeId) override; void OnPublishResult(const std::string &pkgName, int32_t publishId, int32_t publishResult) override; - void OnAuthResult(const std::string &pkgName, const std::string &deviceId, const std::string &token, int32_t status, - int32_t reason) override; + void OnAuthResult(const ProcessInfo &processInfo, const std::string &deviceId, const std::string &token, + int32_t status, int32_t reason) override; - void OnUiCall(std::string &pkgName, std::string ¶mJson) override; + void OnUiCall(const ProcessInfo &processInfo, std::string ¶mJson) override; - void OnCredentialResult(const std::string &pkgName, int32_t action, const std::string &resultInfo) override; + void OnCredentialResult(const ProcessInfo &processInfo, int32_t action, const std::string &resultInfo) override; - void OnBindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, + void OnBindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, int32_t status, std::string content) override; - void OnUnbindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, + void OnUnbindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, std::string content) override; - void OnPinHolderCreate(const std::string &pkgName, const std::string &deviceId, DmPinType pinType, + void OnPinHolderCreate(const ProcessInfo &processInfo, const std::string &deviceId, DmPinType pinType, const std::string &payload) override; - void OnPinHolderDestroy(const std::string &pkgName, DmPinType pinType, const std::string &payload) override; - void OnCreateResult(const std::string &pkgName, int32_t result) override; - void OnDestroyResult(const std::string &pkgName, int32_t result) override; - void OnPinHolderEvent(const std::string &pkgName, DmPinHolderEvent event, int32_t result, + void OnPinHolderDestroy(const ProcessInfo &processInfo, DmPinType pinType, const std::string &payload) override; + void OnCreateResult(const ProcessInfo &processInfo, int32_t result) override; + void OnDestroyResult(const ProcessInfo &processInfo, int32_t result) override; + void OnPinHolderEvent(const ProcessInfo &processInfo, DmPinHolderEvent event, int32_t result, const std::string &content) override; void OnDeviceTrustChange(const std::string &udid, const std::string &uuid, DmAuthForm authForm) override; void OnDeviceScreenStateChange(const ProcessInfo &processInfo, DmDeviceInfo &devInfo) override; - void OnCredentialAuthStatus(const std::string &pkgName, uint16_t deviceTypeId, int32_t errcode) override; + void OnCredentialAuthStatus(const ProcessInfo &processInfo, uint16_t deviceTypeId, int32_t errcode) override; void OnAppUnintall(const std::string &pkgName) override; private: @@ -95,6 +93,7 @@ private: std::string &anoyDeviceId); #endif void GetNotifyProcessInfos(const ProcessInfo &processInfo, std::set &processInfoSet); + std::vector GetNotifyProcessInfo(); private: #if !defined(__LITEOS_M__) IpcServerListener ipcServerListener_; diff --git a/services/service/include/discovery/discovery_manager.h b/services/service/include/discovery/discovery_manager.h index 04c5deef3..ddb542ab2 100644 --- a/services/service/include/discovery/discovery_manager.h +++ b/services/service/include/discovery/discovery_manager.h @@ -36,6 +36,11 @@ typedef struct DiscoveryContext { std::vector filters; } DiscoveryContext; +typedef struct MultiUserDiscovery { + std::string pkgName; + int32_t userId; +} MultiUserDiscovery; + typedef enum { PROXY_TRANSMISION = 0, PROXY_HEARTBEAT = 1, @@ -84,12 +89,16 @@ private: const std::string &searchJson); int32_t HandleDiscoveryQueue(const std::string &pkgName, uint16_t subscribeId, const std::map &filterOps); - int32_t GetDeviceAclParam(const std::string &pkgName, std::string deviceId, bool &isOnline, int32_t &authForm); + int32_t GetDeviceAclParam(const std::string &pkgName, int32_t userId, std::string deviceId, bool &isOnline, + int32_t &authForm); void ConfigDiscParam(const std::map &discoverParam, DmSubscribeInfo *dmSubInfo); bool CompareCapability(uint32_t capabilityType, const std::string &capabilityStr); void OnDeviceFound(const std::string &pkgName, const uint32_t capabilityType, const DmDeviceInfo &info, const DeviceFilterPara &filterPara); void UpdateInfoFreq(const std::map &discoverParam, DmSubscribeInfo &dmSubInfo); + std::string AddMultiUserIdentify(const std::string &pkgName); + std::string RemoveMultiUserIdentify(const std::string &pkgName); + void GetPkgNameAndUserId(const std::string &pkgName, std::string &callerPkgName, int32_t &userId); private: std::mutex locks_; @@ -104,6 +113,8 @@ private: std::set pkgNameSet_; std::map capabilityMap_; std::mutex capabilityMapLocks_; + std::mutex multiUserDiscLocks_; + std::map multiUserDiscMap_; #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) static bool isSoLoaded_; diff --git a/services/service/include/idevice_manager_service_listener.h b/services/service/include/idevice_manager_service_listener.h index 0abbf2bb8..bcb224a10 100644 --- a/services/service/include/idevice_manager_service_listener.h +++ b/services/service/include/idevice_manager_service_listener.h @@ -40,28 +40,21 @@ public: * @tc.desc: Device Found of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, const DmDeviceInfo &info) = 0; - - /** - * @tc.name: IDeviceManagerServiceListener::OnDeviceFound - * @tc.desc: Device Found of the DeviceManager Service Listener - * @tc.type: FUNC - */ - virtual void OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, DmDeviceBasicInfo &info) = 0; + virtual void OnDeviceFound(const ProcessInfo &processInfo, uint16_t subscribeId, const DmDeviceInfo &info) = 0; /** * @tc.name: IDeviceManagerServiceListener::OnDiscoveryFailed * @tc.desc: Discovery Failed of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnDiscoveryFailed(const std::string &pkgName, uint16_t subscribeId, int32_t failedReason) = 0; + virtual void OnDiscoveryFailed(const ProcessInfo &processInfo, uint16_t subscribeId, int32_t failedReason) = 0; /** * @tc.name: IDeviceManagerServiceListener::OnDiscoverySuccess * @tc.desc: Discovery Success of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId) = 0; + virtual void OnDiscoverySuccess(const ProcessInfo &processInfo, int32_t subscribeId) = 0; /** * @tc.name: IDeviceManagerServiceListener::OnPublishResult @@ -75,7 +68,7 @@ public: * @tc.desc: Auth Result of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnAuthResult(const std::string &pkgName, const std::string &deviceId, const std::string &token, + virtual void OnAuthResult(const ProcessInfo &processInfo, const std::string &deviceId, const std::string &token, int32_t status, int32_t reason) = 0; /** @@ -83,21 +76,21 @@ public: * @tc.desc: Fa Call of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnUiCall(std::string &pkgName, std::string ¶mJson) = 0; + virtual void OnUiCall(const ProcessInfo &processInfo, std::string ¶mJson) = 0; /** * @tc.name: IDeviceManagerServiceListener::OnCredentialResult * @tc.desc: Credential Result of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnCredentialResult(const std::string &pkgName, int32_t action, const std::string &resultInfo) = 0; + virtual void OnCredentialResult(const ProcessInfo &processInfo, int32_t action, const std::string &resultInfo) = 0; /** * @tc.name: IDeviceManagerServiceListener::OnBindResult * @tc.desc: Bind target Result of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnBindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, + virtual void OnBindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, int32_t status, std::string content) = 0; /** @@ -105,7 +98,7 @@ public: * @tc.desc: Unbind target Result of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnUnbindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, + virtual void OnUnbindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, std::string content) = 0; /** @@ -113,7 +106,7 @@ public: * @tc.desc: Unbind target Result of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnPinHolderCreate(const std::string &pkgName, const std::string &deviceId, DmPinType pinType, + virtual void OnPinHolderCreate(const ProcessInfo &processInfo, const std::string &deviceId, DmPinType pinType, const std::string &payload) = 0; /** @@ -121,28 +114,28 @@ public: * @tc.desc: Unbind target Result of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnPinHolderDestroy(const std::string &pkgName, DmPinType pinType, const std::string &payload) = 0; + virtual void OnPinHolderDestroy(const ProcessInfo &processInfo, DmPinType pinType, const std::string &payload) = 0; /** * @tc.name: IDeviceManagerServiceListener::OnCreateResult * @tc.desc: Create Pin Holder Result of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnCreateResult(const std::string &pkgName, int32_t result) = 0; + virtual void OnCreateResult(const ProcessInfo &processInfo, int32_t result) = 0; /** * @tc.name: IDeviceManagerServiceListener::OnDestroyResult * @tc.desc: Destroy Pin Holder Result of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnDestroyResult(const std::string &pkgName, int32_t result) = 0; + virtual void OnDestroyResult(const ProcessInfo &processInfo, int32_t result) = 0; /** * @tc.name: IDeviceManagerServiceListener::OnPinHolderEvent * @tc.desc: Pin Holder Event of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnPinHolderEvent(const std::string &pkgName, DmPinHolderEvent event, int32_t result, + virtual void OnPinHolderEvent(const ProcessInfo &processInfo, DmPinHolderEvent event, int32_t result, const std::string &content) = 0; /** @@ -164,7 +157,7 @@ public: * @tc.desc: Candidate Restrict Status Change of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnCredentialAuthStatus(const std::string &pkgName, uint16_t deviceTypeId, + virtual void OnCredentialAuthStatus(const ProcessInfo &processInfo, uint16_t deviceTypeId, int32_t errcode) = 0; virtual void OnAppUnintall(const std::string &pkgName) = 0; }; diff --git a/services/service/include/ipc/lite/ipc_server_listener.h b/services/service/include/ipc/lite/ipc_server_listener.h index 33dbb53ae..a4bf69daf 100644 --- a/services/service/include/ipc/lite/ipc_server_listener.h +++ b/services/service/include/ipc/lite/ipc_server_listener.h @@ -44,6 +44,7 @@ public: * @tc.type: FUNC */ std::vector GetAllProcessInfo(); + std::set GetSyatemSA(); private: void CommonSvcToIdentity(CommonSvcId *svcId, SvcIdentity *identity); diff --git a/services/service/include/ipc/standard/ipc_server_listener.h b/services/service/include/ipc/standard/ipc_server_listener.h index ebd8e55a2..af9761610 100644 --- a/services/service/include/ipc/standard/ipc_server_listener.h +++ b/services/service/include/ipc/standard/ipc_server_listener.h @@ -17,7 +17,7 @@ #define OHOS_DM_IPC_SERVER_LISTENER_H #include - +#include #include "dm_device_info.h" #include "ipc_req.h" #include "ipc_rsp.h" @@ -43,6 +43,7 @@ public: * @tc.type: FUNC */ std::vector GetAllProcessInfo(); + std::set GetSystemSA(); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/include/ipc/standard/ipc_server_stub.h b/services/service/include/ipc/standard/ipc_server_stub.h index 84c3cc734..ff6055c45 100644 --- a/services/service/include/ipc/standard/ipc_server_stub.h +++ b/services/service/include/ipc/standard/ipc_server_stub.h @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -144,11 +145,14 @@ public: * @tc.type: FUNC */ void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; + std::set GetSystemSA(); private: IpcServerStub(); ~IpcServerStub() override = default; bool Init(); + void AddSystemSA(const std::string &pkgName); + void RemoveSystemSA(const std::string &pkgName); private: bool registerToService_; @@ -157,6 +161,7 @@ private: std::map> appRecipient_; std::map> dmListener_; std::shared_ptr accountBootListener_; + std::set systemSA_; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/include/permission/lite/permission_manager.h b/services/service/include/permission/lite/permission_manager.h index 9d8d2cce5..0d506f71b 100644 --- a/services/service/include/permission/lite/permission_manager.h +++ b/services/service/include/permission/lite/permission_manager.h @@ -32,8 +32,9 @@ public: int32_t GetCallerProcessName(std::string &processName); bool CheckProcessNameValidOnAuthCode(const std::string &processName); bool CheckProcessNameValidOnPinHolder(const std::string &processName); + bool CheckWhiteListSystemSA(const std::string &pkgName); + std::unordered_set GetWhiteListSystemSA(); bool CheckSystemSA(const std::string &pkgName); - std::unordered_set GetSystemSA(); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/include/permission/standard/permission_manager.h b/services/service/include/permission/standard/permission_manager.h index b62f81ea5..b52b9ddba 100644 --- a/services/service/include/permission/standard/permission_manager.h +++ b/services/service/include/permission/standard/permission_manager.h @@ -33,8 +33,9 @@ public: int32_t GetCallerProcessName(std::string &processName); bool CheckProcessNameValidOnAuthCode(const std::string &processName); bool CheckProcessNameValidOnPinHolder(const std::string &processName); + bool CheckWhiteListSystemSA(const std::string &pkgName); + std::unordered_set GetWhiteListSystemSA(); bool CheckSystemSA(const std::string &pkgName); - std::unordered_set GetSystemSA(); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/include/pinholder/pin_holder.h b/services/service/include/pinholder/pin_holder.h index 75d999cd9..c31157cbd 100644 --- a/services/service/include/pinholder/pin_holder.h +++ b/services/service/include/pinholder/pin_holder.h @@ -75,7 +75,6 @@ private: std::shared_ptr session_ = nullptr; std::shared_ptr timer_ = nullptr; - std::string registerPkgName_ = ""; std::string remoteDeviceId_ = ""; std::string payload_ = ""; DmPinType pinType_ = NUMBER_PIN_CODE; @@ -85,6 +84,7 @@ private: bool isRemoteSupported_ = false; std::atomic isDestroy_ {false}; DestroyState destroyState_ = STATE_UNKNOW; + ProcessInfo processInfo_; }; } } diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 94270bae8..b1454f904 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -267,7 +267,7 @@ int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, c } if (!onlineDeviceList.empty() && IsDMServiceImplReady()) { std::unordered_map udidMap; - if (PermissionManager::GetInstance().CheckSystemSA(pkgName)) { + if (PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName)) { udidMap = dmServiceImpl_->GetAppTrustDeviceIdList(std::string(ALL_PKGNAME), userId); } else { udidMap = dmServiceImpl_->GetAppTrustDeviceIdList(pkgName, userId); @@ -411,72 +411,6 @@ int32_t DeviceManagerService::GetUuidByNetworkId(const std::string &pkgName, con return SoftbusListener::GetUuidByNetworkId(netWorkId.c_str(), uuid); } -int32_t DeviceManagerService::StartDeviceDiscovery(const std::string &pkgName, const DmSubscribeInfo &subscribeInfo, - const std::string &extra) -{ - if (!PermissionManager::GetInstance().CheckPermission()) { - LOGE("The caller: %{public}s does not have permission to call StartDeviceDiscovery.", pkgName.c_str()); - return ERR_DM_NO_PERMISSION; - } - LOGI("Begin for pkgName = %{public}s, extra = %{public}s", - pkgName.c_str(), extra.c_str()); - if (pkgName.empty()) { - LOGE("Invalid parameter, pkgName is empty."); - return ERR_DM_INPUT_PARA_INVALID; - } - - SoftbusListener::SetHostPkgName(pkgName); - std::map discParam; - discParam.insert(std::pair(PARAM_KEY_SUBSCRIBE_ID, - std::to_string(subscribeInfo.subscribeId))); - discParam.insert(std::pair(PARAM_KEY_DISC_MEDIUM, std::to_string(subscribeInfo.medium))); - - std::map filterOps; - filterOps.insert(std::pair(PARAM_KEY_FILTER_OPTIONS, extra)); - CHECK_NULL_RETURN(discoveryMgr_, ERR_DM_POINT_NULL); - return discoveryMgr_->StartDiscovering(pkgName, discParam, filterOps); -} - -int32_t DeviceManagerService::StartDeviceDiscovery(const std::string &pkgName, const uint16_t subscribeId, - const std::string &filterOptions) -{ - if (!PermissionManager::GetInstance().CheckNewPermission()) { - LOGE("The caller: %{public}s does not have permission to call StartDeviceDiscovery.", pkgName.c_str()); - return ERR_DM_NO_PERMISSION; - } - LOGI("Begin for pkgName = %{public}s, filterOptions = %{public}s, subscribeId = %{public}d", - pkgName.c_str(), filterOptions.c_str(), subscribeId); - if (pkgName.empty()) { - LOGE("Invalid parameter, pkgName is empty."); - return ERR_DM_INPUT_PARA_INVALID; - } - - SoftbusListener::SetHostPkgName(pkgName); - std::map discParam; - discParam.insert(std::pair(PARAM_KEY_SUBSCRIBE_ID, std::to_string(subscribeId))); - - std::map filterOps; - filterOps.insert(std::pair(PARAM_KEY_FILTER_OPTIONS, filterOptions)); - CHECK_NULL_RETURN(discoveryMgr_, ERR_DM_POINT_NULL); - return discoveryMgr_->StartDiscovering(pkgName, discParam, filterOps); -} - -int32_t DeviceManagerService::StopDeviceDiscovery(const std::string &pkgName, uint16_t subscribeId) -{ - if (!PermissionManager::GetInstance().CheckPermission() && - !PermissionManager::GetInstance().CheckNewPermission()) { - LOGE("The caller: %{public}s does not have permission to call StopDeviceDiscovery.", pkgName.c_str()); - return ERR_DM_NO_PERMISSION; - } - LOGI("Begin for pkgName = %{public}s", pkgName.c_str()); - if (pkgName.empty()) { - LOGE("Invalid parameter, pkgName is empty."); - return ERR_DM_INPUT_PARA_INVALID; - } - CHECK_NULL_RETURN(discoveryMgr_, ERR_DM_POINT_NULL); - return discoveryMgr_->StopDiscovering(pkgName, subscribeId); -} - int32_t DeviceManagerService::PublishDeviceDiscovery(const std::string &pkgName, const DmPublishInfo &publishInfo) { if (!PermissionManager::GetInstance().CheckPermission()) { diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index 757080743..5526b6d4d 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -39,6 +39,7 @@ #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) #include "datetime_ex.h" #include "kv_adapter_manager.h" +#include "multiple_user_connector.h" #endif #include "parameter.h" #include "permission_manager.h" @@ -117,7 +118,7 @@ void DeviceManagerServiceListener::ProcessDeviceStateChange(const DmDeviceState LOGI("In"); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - std::vector processInfoVec = ipcServerListener_.GetAllProcessInfo(); + std::vector processInfoVec = GetNotifyProcessInfo(); if (state == DEVICE_STATE_OFFLINE) { RemoveOnlinePkgName(info); for (const auto &it : processInfoVec) { @@ -209,54 +210,49 @@ void DeviceManagerServiceListener::OnDeviceStateChange(const ProcessInfo &proces #endif } -void DeviceManagerServiceListener::OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, +void DeviceManagerServiceListener::OnDeviceFound(const ProcessInfo &processInfo, uint16_t subscribeId, const DmDeviceInfo &info) { std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); DmDeviceInfo deviceInfo = info; #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) - ConvertUdidHashToAnoyAndSave(pkgName, deviceInfo); + ConvertUdidHashToAnoyAndSave(processInfo.pkgName, deviceInfo); #endif DmDeviceBasicInfo devBasicInfo; - ConvertDeviceInfoToDeviceBasicInfo(pkgName, deviceInfo, devBasicInfo); + ConvertDeviceInfoToDeviceBasicInfo(processInfo.pkgName, deviceInfo, devBasicInfo); pReq->SetDeviceBasicInfo(devBasicInfo); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetSubscribeId(subscribeId); pReq->SetDeviceInfo(deviceInfo); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_FOUND, pReq, pRsp); } -void DeviceManagerServiceListener::OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, - DmDeviceBasicInfo &info) -{ - (void)pkgName; - (void)subscribeId; - (void)info; -} - -void DeviceManagerServiceListener::OnDiscoveryFailed(const std::string &pkgName, uint16_t subscribeId, +void DeviceManagerServiceListener::OnDiscoveryFailed(const ProcessInfo &processInfo, uint16_t subscribeId, int32_t failedReason) { LOGI("DeviceManagerServiceListener::OnDiscoveryFailed"); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetSubscribeId(subscribeId); pReq->SetResult(failedReason); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_DISCOVER_FINISH, pReq, pRsp); } -void DeviceManagerServiceListener::OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId) +void DeviceManagerServiceListener::OnDiscoverySuccess(const ProcessInfo &processInfo, int32_t subscribeId) { LOGI("DeviceManagerServiceListener::OnDiscoverySuccess"); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetSubscribeId((uint16_t)subscribeId); pReq->SetResult(DM_OK); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_DISCOVER_FINISH, pReq, pRsp); } @@ -272,7 +268,7 @@ void DeviceManagerServiceListener::OnPublishResult(const std::string &pkgName, i ipcServerListener_.SendRequest(SERVER_PUBLISH_FINISH, pReq, pRsp); } -void DeviceManagerServiceListener::OnAuthResult(const std::string &pkgName, const std::string &deviceId, +void DeviceManagerServiceListener::OnAuthResult(const ProcessInfo &processInfo, const std::string &deviceId, const std::string &token, int32_t status, int32_t reason) { std::shared_ptr pReq = std::make_shared(); @@ -283,42 +279,45 @@ void DeviceManagerServiceListener::OnAuthResult(const std::string &pkgName, cons pReq->SetDeviceId(deviceId); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::string deviceIdTemp = ""; - if (ConvertUdidHashToAnoyDeviceId(pkgName, deviceId, deviceIdTemp) == DM_OK) { + if (ConvertUdidHashToAnoyDeviceId(processInfo.pkgName, deviceId, deviceIdTemp) == DM_OK) { pReq->SetDeviceId(deviceIdTemp); } #endif - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetToken(token); pReq->SetStatus(status); pReq->SetReason(reason); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_AUTH_RESULT, pReq, pRsp); } -void DeviceManagerServiceListener::OnUiCall(std::string &pkgName, std::string ¶mJson) +void DeviceManagerServiceListener::OnUiCall(const ProcessInfo &processInfo, std::string ¶mJson) { LOGI("OnUiCall in"); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetJsonParam(paramJson); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_FA_NOTIFY, pReq, pRsp); } -void DeviceManagerServiceListener::OnCredentialResult(const std::string &pkgName, int32_t action, +void DeviceManagerServiceListener::OnCredentialResult(const ProcessInfo &processInfo, int32_t action, const std::string &resultInfo) { - LOGI("call OnCredentialResult for %{public}s, action %{public}d", pkgName.c_str(), action); + LOGI("call OnCredentialResult for %{public}s, action %{public}d", processInfo.pkgName.c_str(), action); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetCredentialAction(action); pReq->SetCredentialResult(resultInfo); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_CREDENTIAL_RESULT, pReq, pRsp); } -void DeviceManagerServiceListener::OnBindResult(const std::string &pkgName, const PeerTargetId &targetId, +void DeviceManagerServiceListener::OnBindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, int32_t status, std::string content) { std::shared_ptr pReq = std::make_shared(); @@ -330,20 +329,21 @@ void DeviceManagerServiceListener::OnBindResult(const std::string &pkgName, cons #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::string deviceIdTemp = ""; DmKVValue kvValue; - if (ConvertUdidHashToAnoyDeviceId(pkgName, targetId.deviceId, deviceIdTemp) == DM_OK && + if (ConvertUdidHashToAnoyDeviceId(processInfo.pkgName, targetId.deviceId, deviceIdTemp) == DM_OK && KVAdapterManager::GetInstance().Get(deviceIdTemp, kvValue) == DM_OK) { returnTargetId.deviceId = deviceIdTemp; } #endif - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetPeerTargetId(returnTargetId); pReq->SetResult(result); pReq->SetStatus(status); pReq->SetContent(content); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(BIND_TARGET_RESULT, pReq, pRsp); } -void DeviceManagerServiceListener::OnUnbindResult(const std::string &pkgName, const PeerTargetId &targetId, +void DeviceManagerServiceListener::OnUnbindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, std::string content) { std::shared_ptr pReq = std::make_shared(); @@ -352,79 +352,85 @@ void DeviceManagerServiceListener::OnUnbindResult(const std::string &pkgName, co #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::string deviceIdTemp = ""; DmKVValue kvValue; - if (ConvertUdidHashToAnoyDeviceId(pkgName, targetId.deviceId, deviceIdTemp) == DM_OK && + if (ConvertUdidHashToAnoyDeviceId(processInfo.pkgName, targetId.deviceId, deviceIdTemp) == DM_OK && KVAdapterManager::GetInstance().Get(deviceIdTemp, kvValue) == DM_OK) { returnTargetId.deviceId = deviceIdTemp; } #endif - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetPeerTargetId(returnTargetId); pReq->SetResult(result); pReq->SetContent(content); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(UNBIND_TARGET_RESULT, pReq, pRsp); } -void DeviceManagerServiceListener::OnPinHolderCreate(const std::string &pkgName, const std::string &deviceId, +void DeviceManagerServiceListener::OnPinHolderCreate(const ProcessInfo &processInfo, const std::string &deviceId, DmPinType pinType, const std::string &payload) { - LOGI("DeviceManagerServiceListener::OnPinHolderCreate : %{public}s", pkgName.c_str()); + LOGI("DeviceManagerServiceListener::OnPinHolderCreate : %{public}s", processInfo.pkgName.c_str()); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetDeviceId(deviceId); pReq->SetPinType(pinType); pReq->SetPayload(payload); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_CREATE_PIN_HOLDER, pReq, pRsp); } -void DeviceManagerServiceListener::OnPinHolderDestroy(const std::string &pkgName, DmPinType pinType, +void DeviceManagerServiceListener::OnPinHolderDestroy(const ProcessInfo &processInfo, DmPinType pinType, const std::string &payload) { - LOGI("DeviceManagerServiceListener::OnPinHolderDestroy : %{public}s", pkgName.c_str()); + LOGI("DeviceManagerServiceListener::OnPinHolderDestroy : %{public}s", processInfo.pkgName.c_str()); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetPinType(pinType); pReq->SetPayload(payload); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_DESTROY_PIN_HOLDER, pReq, pRsp); } -void DeviceManagerServiceListener::OnCreateResult(const std::string &pkgName, int32_t result) +void DeviceManagerServiceListener::OnCreateResult(const ProcessInfo &processInfo, int32_t result) { LOGI("DeviceManagerServiceListener::OnCreateResult : %{public}d", result); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetResult(result); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_CREATE_PIN_HOLDER_RESULT, pReq, pRsp); } -void DeviceManagerServiceListener::OnDestroyResult(const std::string &pkgName, int32_t result) +void DeviceManagerServiceListener::OnDestroyResult(const ProcessInfo &processInfo, int32_t result) { LOGI("DeviceManagerServiceListener::OnDestroyResult : %{public}d", result); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetResult(result); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_DESTROY_PIN_HOLDER_RESULT, pReq, pRsp); } -void DeviceManagerServiceListener::OnPinHolderEvent(const std::string &pkgName, DmPinHolderEvent event, +void DeviceManagerServiceListener::OnPinHolderEvent(const ProcessInfo &processInfo, DmPinHolderEvent event, int32_t result, const std::string &content) { LOGI("OnPinHolderEvent pkgName: %{public}s, event: %{public}d, result: %{public}d", - pkgName.c_str(), event, result); + processInfo.pkgName.c_str(), event, result); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - pReq->SetPkgName(pkgName); + pReq->SetPkgName(processInfo.pkgName); pReq->SetPinHolderEvent(event); pReq->SetResult(result); pReq->SetContent(content); + pReq->SetProcessInfo(processInfo); ipcServerListener_.SendRequest(SERVER_ON_PIN_HOLDER_EVENT, pReq, pRsp); } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) @@ -478,12 +484,13 @@ void DeviceManagerServiceListener::OnDeviceTrustChange(const std::string &udid, GetAnonyString(uuid).c_str(), authForm); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - std::vector processInfoVec = ipcServerListener_.GetAllProcessInfo(); - for (const auto &it : processInfoVec) { - pReq->SetPkgName(it.pkgName); + std::vector processInfoVec = GetNotifyProcessInfo(); + for (const auto &item : processInfoVec) { + pReq->SetPkgName(item.pkgName); pReq->SetUdid(udid); pReq->SetUuid(uuid); pReq->SetAuthForm(authForm); + pReq->SetProcessInfo(item); ipcServerListener_.SendRequest(REMOTE_DEVICE_TRUST_CHANGE, pReq, pRsp); } } @@ -514,20 +521,24 @@ void DeviceManagerServiceListener::OnDeviceScreenStateChange(const ProcessInfo & if (processInfo.pkgName == std::string(DM_PKG_NAME)) { std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - std::vector processInfoVec = ipcServerListener_.GetAllProcessInfo(); - for (const auto &it : processInfoVec) { - SetDeviceScreenInfo(pReq, it, devInfo); + std::vector processInfoVec = GetNotifyProcessInfo(); + for (const auto &item : processInfoVec) { + SetDeviceScreenInfo(pReq, item, devInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_SCREEN_STATE_NOTIFY, pReq, pRsp); } } else { std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - std::set processInfoSet; - GetNotifyProcessInfos(processInfo, processInfoSet); - for (const auto &it : processInfoSet) { - SetDeviceScreenInfo(pReq, it, devInfo); + std::unordered_set notifyPkgnames = PermissionManager::GetInstance().GetWhiteListSystemSA(); + for (const auto &item : notifyPkgnames) { + ProcessInfo processInfo; + processInfo.pkgName = item; + processInfo.userId = 0; + SetDeviceScreenInfo(pReq, processInfo, devInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_SCREEN_STATE_NOTIFY, pReq, pRsp); } + SetDeviceScreenInfo(pReq, processInfo, devInfo); + ipcServerListener_.SendRequest(SERVER_DEVICE_SCREEN_STATE_NOTIFY, pReq, pRsp); } } @@ -546,25 +557,18 @@ void DeviceManagerServiceListener::RemoveOnlinePkgName(const DmDeviceInfo &info) } } -void DeviceManagerServiceListener::OnCredentialAuthStatus(const std::string &pkgName, +void DeviceManagerServiceListener::OnCredentialAuthStatus(const ProcessInfo &processInfo, uint16_t deviceTypeId, int32_t errcode) { - LOGI("In, pkgName = %{public}s", pkgName.c_str()); + LOGI("In, pkgName = %{public}s", processInfo.pkgName.c_str()); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); pReq->SetDeviceTypeId(deviceTypeId); pReq->SetErrCode(errcode); - if (pkgName == std::string(DM_PKG_NAME)) { - std::vector processInfoVec = ipcServerListener_.GetAllProcessInfo(); - for (const auto &it : processInfoVec) { - pReq->SetPkgName(it.pkgName); - ipcServerListener_.SendRequest(SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY, pReq, pRsp); - } - } else { - pReq->SetPkgName(pkgName); - ipcServerListener_.SendRequest(SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY, pReq, pRsp); - } + pReq->SetPkgName(processInfo.pkgName); + pReq->SetProcessInfo(processInfo); + ipcServerListener_.SendRequest(SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY, pReq, pRsp); } void DeviceManagerServiceListener::OnAppUnintall(const std::string &pkgName) @@ -582,7 +586,7 @@ void DeviceManagerServiceListener::OnAppUnintall(const std::string &pkgName) void DeviceManagerServiceListener::GetNotifyProcessInfos(const ProcessInfo &processInfo, std::set &processInfoSet) { - std::unordered_set notifyPkgnames = PermissionManager::GetInstance().GetSystemSA(); + std::unordered_set notifyPkgnames = PermissionManager::GetInstance().GetWhiteListSystemSA(); for (const auto &it : notifyPkgnames) { ProcessInfo processInfo; processInfo.pkgName = it; @@ -591,5 +595,22 @@ void DeviceManagerServiceListener::GetNotifyProcessInfos(const ProcessInfo &proc } processInfoSet.emplace(processInfo); } + +std::vector DeviceManagerServiceListener::GetNotifyProcessInfo() +{ + std::vector processInfos = ipcServerListener_.GetAllProcessInfo(); + std::set systemSA = ipcServerListener_.GetSystemSA(); + std::vector processInfosTemp; + for (auto item : processInfos) { + if (systemSA.find(item.pkgName) != systemSA.end()) { + item.userId = 0; + processInfosTemp.push_back(item); + } + if (item.userId == MultipleUserConnector::GetForegroundUser()) { + processInfosTemp.push_back(item); + } + } + return processInfosTemp; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/discovery/discovery_manager.cpp b/services/service/src/discovery/discovery_manager.cpp index 8fbf9044d..82d5e012a 100644 --- a/services/service/src/discovery/discovery_manager.cpp +++ b/services/service/src/discovery/discovery_manager.cpp @@ -23,6 +23,9 @@ #include "dm_anonymous.h" #include "dm_constants.h" #include "parameter.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "multiple_user_connector.h" +#endif namespace OHOS { namespace DistributedHardware { @@ -62,6 +65,7 @@ int32_t DiscoveryManager::EnableDiscoveryListener(const std::string &pkgName, LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } + std::string pkgNameTemp = AddMultiUserIdentify(pkgName); DmSubscribeInfo dmSubInfo; dmSubInfo.subscribeId = DM_INVALID_FLAG_ID; dmSubInfo.mode = DmDiscoverMode::DM_DISCOVER_MODE_PASSIVE; @@ -82,7 +86,7 @@ int32_t DiscoveryManager::EnableDiscoveryListener(const std::string &pkgName, dmSubInfo.subscribeId = std::atoi((discoverParam.find(PARAM_KEY_SUBSCRIBE_ID)->second).c_str()); { std::lock_guard autoLock(subIdMapLocks_); - pkgName2SubIdMap_[pkgName] = dmSubInfo.subscribeId; + pkgName2SubIdMap_[pkgNameTemp] = dmSubInfo.subscribeId; } } if (discoverParam.find(PARAM_KEY_DISC_CAPABILITY) != discoverParam.end()) { @@ -95,7 +99,7 @@ int32_t DiscoveryManager::EnableDiscoveryListener(const std::string &pkgName, LOGI("EnableDiscoveryListener capability = %{public}s,", std::string(dmSubInfo.capability).c_str()); { std::lock_guard capLock(capabilityMapLocks_); - capabilityMap_[pkgName] = std::string(dmSubInfo.capability); + capabilityMap_[pkgNameTemp] = std::string(dmSubInfo.capability); } int32_t ret = softbusListener_->RefreshSoftbusLNN(DM_PKG_NAME, dmSubInfo, LNN_DISC_CAPABILITY); @@ -103,7 +107,7 @@ int32_t DiscoveryManager::EnableDiscoveryListener(const std::string &pkgName, LOGE("EnableDiscoveryListener failed, softbus refresh lnn ret: %{public}d.", ret); return ret; } - softbusListener_->RegisterSoftbusLnnOpsCbk(pkgName, shared_from_this()); + softbusListener_->RegisterSoftbusLnnOpsCbk(pkgNameTemp, shared_from_this()); return DM_OK; } @@ -115,7 +119,7 @@ int32_t DiscoveryManager::DisableDiscoveryListener(const std::string &pkgName, LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } - + std::string pkgNameTemp = RemoveMultiUserIdentify(pkgName); if (extraParam.find(PARAM_KEY_META_TYPE) != extraParam.end()) { LOGI("DisableDiscoveryListener, input MetaType = %{public}s", (extraParam.find(PARAM_KEY_META_TYPE)->second).c_str()); @@ -125,16 +129,16 @@ int32_t DiscoveryManager::DisableDiscoveryListener(const std::string &pkgName, subscribeId = std::atoi((extraParam.find(PARAM_KEY_SUBSCRIBE_ID)->second).c_str()); { std::lock_guard autoLock(subIdMapLocks_); - pkgName2SubIdMap_.erase(pkgName); + pkgName2SubIdMap_.erase(pkgNameTemp); } } { std::lock_guard capLock(capabilityMapLocks_); - if (capabilityMap_.find(pkgName) != capabilityMap_.end()) { - capabilityMap_.erase(pkgName); + if (capabilityMap_.find(pkgNameTemp) != capabilityMap_.end()) { + capabilityMap_.erase(pkgNameTemp); } } - softbusListener_->UnRegisterSoftbusLnnOpsCbk(pkgName); + softbusListener_->UnRegisterSoftbusLnnOpsCbk(pkgNameTemp); return softbusListener_->StopRefreshSoftbusLNN(subscribeId); } @@ -146,9 +150,10 @@ int32_t DiscoveryManager::StartDiscovering(const std::string &pkgName, LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } + std::string pkgNameTemp = AddMultiUserIdentify(pkgName); DmSubscribeInfo dmSubInfo; ConfigDiscParam(discoverParam, &dmSubInfo); - if (HandleDiscoveryQueue(pkgName, dmSubInfo.subscribeId, filterOptions) != DM_OK) { + if (HandleDiscoveryQueue(pkgNameTemp, dmSubInfo.subscribeId, filterOptions) != DM_OK) { return ERR_DM_DISCOVERY_REPEATED; } @@ -158,17 +163,17 @@ int32_t DiscoveryManager::StartDiscovering(const std::string &pkgName, isStandardMetaNode = (metaType == MetaNodeType::PROXY_TRANSMISION); } - softbusListener_->RegisterSoftbusLnnOpsCbk(pkgName, shared_from_this()); - StartDiscoveryTimer(pkgName); + softbusListener_->RegisterSoftbusLnnOpsCbk(pkgNameTemp, shared_from_this()); + StartDiscoveryTimer(pkgNameTemp); auto it = filterOptions.find(PARAM_KEY_FILTER_OPTIONS); nlohmann::json jsonObject = nlohmann::json::parse(it->second, nullptr, false); if (!jsonObject.is_discarded() && jsonObject.contains(TYPE_MINE)) { - return StartDiscovering4MineLibary(pkgName, dmSubInfo, it->second); + return StartDiscovering4MineLibary(pkgNameTemp, dmSubInfo, it->second); } - int32_t ret = isStandardMetaNode ? StartDiscoveringNoMetaType(pkgName, dmSubInfo, discoverParam) : - StartDiscovering4MetaType(pkgName, dmSubInfo, discoverParam); + int32_t ret = isStandardMetaNode ? StartDiscoveringNoMetaType(pkgNameTemp, dmSubInfo, discoverParam) : + StartDiscovering4MetaType(pkgNameTemp, dmSubInfo, discoverParam); if (ret != DM_OK) { LOGE("StartDiscovering for meta node process failed, ret = %{public}d", ret); return ret; @@ -307,24 +312,25 @@ int32_t DiscoveryManager::StopDiscovering(const std::string &pkgName, uint16_t s LOGE("Invalid parameter, pkgName is empty."); return ERR_DM_INPUT_PARA_INVALID; } + std::string pkgNameTemp = RemoveMultiUserIdentify(pkgName); { std::lock_guard autoLock(locks_); - if (pkgNameSet_.find(pkgName) != pkgNameSet_.end()) { - pkgNameSet_.erase(pkgName); + if (pkgNameSet_.find(pkgNameTemp) != pkgNameSet_.end()) { + pkgNameSet_.erase(pkgNameTemp); } - if (discoveryContextMap_.find(pkgName) != discoveryContextMap_.end()) { - discoveryContextMap_.erase(pkgName); - timer_->DeleteTimer(pkgName); + if (discoveryContextMap_.find(pkgNameTemp) != discoveryContextMap_.end()) { + discoveryContextMap_.erase(pkgNameTemp); + timer_->DeleteTimer(pkgNameTemp); } } { std::lock_guard capLock(capabilityMapLocks_); - if (capabilityMap_.find(pkgName) != capabilityMap_.end()) { - capabilityMap_.erase(pkgName); + if (capabilityMap_.find(pkgNameTemp) != capabilityMap_.end()) { + capabilityMap_.erase(pkgNameTemp); } } - softbusListener_->UnRegisterSoftbusLnnOpsCbk(pkgName); + softbusListener_->UnRegisterSoftbusLnnOpsCbk(pkgNameTemp); #if (defined(MINE_HARMONY)) return mineSoftbusListener_->StopRefreshSoftbusLNN(subscribeId); #else @@ -334,12 +340,16 @@ int32_t DiscoveryManager::StopDiscovering(const std::string &pkgName, uint16_t s void DiscoveryManager::OnDeviceFound(const std::string &pkgName, const DmDeviceInfo &info, bool isOnline) { + int32_t userId = -1; + std::string callerPkgName = ""; + GetPkgNameAndUserId(pkgName, callerPkgName, userId); DeviceFilterPara filterPara; filterPara.isOnline = false; filterPara.range = info.range; filterPara.deviceType = info.deviceTypeId; std::string deviceIdHash = static_cast(info.deviceId); - if (isOnline && GetDeviceAclParam(pkgName, deviceIdHash, filterPara.isOnline, filterPara.authForm) != DM_OK) { + if (isOnline && GetDeviceAclParam(callerPkgName, userId, deviceIdHash, filterPara.isOnline, + filterPara.authForm) != DM_OK) { LOGE("The found device get online param failed."); } nlohmann::json jsonObject = nlohmann::json::parse(info.extraData, nullptr, false); @@ -358,6 +368,12 @@ void DiscoveryManager::OnDeviceFound(const std::string &pkgName, const DmDeviceI void DiscoveryManager::OnDeviceFound(const std::string &pkgName, const uint32_t capabilityType, const DmDeviceInfo &info, const DeviceFilterPara &filterPara) { + int32_t userId = -1; + std::string callerPkgName = ""; + GetPkgNameAndUserId(pkgName, callerPkgName, userId); + ProcessInfo processInfo; + processInfo.userId = userId; + processInfo.pkgName = callerPkgName; bool isIndiscoveryContextMap = false; DiscoveryContext discoveryContext; { @@ -382,7 +398,7 @@ void DiscoveryManager::OnDeviceFound(const std::string &pkgName, const uint32_t subscribeId = pkgName2SubIdMap_[pkgName]; } LOGD("OnDeviceFound, pkgName = %{public}s, cabability = %{public}d", pkgName.c_str(), capabilityType); - listener_->OnDeviceFound(pkgName, subscribeId, info); + listener_->OnDeviceFound(processInfo, subscribeId, info); return; } DiscoveryFilter filter; @@ -395,7 +411,7 @@ void DiscoveryManager::OnDeviceFound(const std::string &pkgName, const uint32_t } } LOGD("OnDeviceFound, pkgName = %{public}s, cabability = %{public}d", pkgName.c_str(), capabilityType); - listener_->OnDeviceFound(pkgName, discoveryContext.subscribeId, info); + listener_->OnDeviceFound(processInfo, discoveryContext.subscribeId, info); } } @@ -413,6 +429,12 @@ bool DiscoveryManager::CompareCapability(uint32_t capabilityType, const std::str void DiscoveryManager::OnDiscoveringResult(const std::string &pkgName, int32_t subscribeId, int32_t result) { LOGI("DiscoveryManager::OnDiscoveringResult, subscribeId = %{public}d, result = %{public}d.", subscribeId, result); + int32_t userId = -1; + std::string callerPkgName = ""; + GetPkgNameAndUserId(pkgName, callerPkgName, userId); + ProcessInfo processInfo; + processInfo.userId = userId; + processInfo.pkgName = callerPkgName; if (pkgName.empty() || (listener_ == nullptr)) { LOGE("DiscoveryManager::OnDiscoveringResult failed, IDeviceManagerServiceListener is null."); return; @@ -420,7 +442,7 @@ void DiscoveryManager::OnDiscoveringResult(const std::string &pkgName, int32_t s if (result == 0) { std::lock_guard autoLock(locks_); discoveryContextMap_[pkgName].subscribeId = (uint32_t)subscribeId; - listener_->OnDiscoverySuccess(pkgName, subscribeId); + listener_->OnDiscoverySuccess(processInfo, subscribeId); return; } { @@ -439,7 +461,7 @@ void DiscoveryManager::OnDiscoveringResult(const std::string &pkgName, int32_t s capabilityMap_.erase(pkgName); } } - listener_->OnDiscoveryFailed(pkgName, (uint32_t)subscribeId, result); + listener_->OnDiscoveryFailed(processInfo, (uint32_t)subscribeId, result); softbusListener_->StopRefreshSoftbusLNN(subscribeId); } @@ -513,7 +535,7 @@ void DiscoveryManager::UpdateInfoFreq( } } -int32_t DiscoveryManager::GetDeviceAclParam(const std::string &pkgName, std::string deviceId, +int32_t DiscoveryManager::GetDeviceAclParam(const std::string &pkgName, int32_t userId, std::string deviceId, bool &isOnline, int32_t &authForm) { #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) @@ -524,6 +546,7 @@ int32_t DiscoveryManager::GetDeviceAclParam(const std::string &pkgName, std::str discoveryInfo.pkgname = pkgName; discoveryInfo.localDeviceId = requestDeviceId; discoveryInfo.remoteDeviceIdHash = deviceId; + discoveryInfo.userId = userId; if (DiscoveryManager::IsCommonDependencyReady() && DiscoveryManager::GetCommonDependencyObj() != nullptr) { if (DiscoveryManager::GetCommonDependencyObj()->GetDeviceAclParam(discoveryInfo, isOnline, authForm) != DM_OK) { LOGE("GetDeviceAclParam failed."); @@ -619,5 +642,56 @@ void DiscoveryManager::ClearDiscoveryCache(const std::string &pkgName) CHECK_NULL_VOID(timer_); timer_->DeleteTimer(pkgName); } + +std::string DiscoveryManager::AddMultiUserIdentify(const std::string &pkgName) +{ + int32_t userId = -1; + MultipleUserConnector::GetCallerUserId(userId); + if (userId == -1) { + LOGE("Get caller userId failed."); + return pkgName; + } + MultiUserDiscovery multiUserDisc; + multiUserDisc.pkgName = pkgName; + multiUserDisc.userId = userId; + std::string pkgNameTemp = ComposeStr(pkgName, userId); + { + std::lock_guard autoLock(multiUserDiscLocks_); + multiUserDiscMap_[pkgNameTemp] = multiUserDisc; + } + return pkgNameTemp; +} + +std::string DiscoveryManager::RemoveMultiUserIdentify(const std::string &pkgName) +{ + int32_t userId = -1; + MultipleUserConnector::GetCallerUserId(userId); + if (userId == -1) { + LOGE("Get caller userId failed."); + return pkgName; + } + std::string pkgNameTemp = ComposeStr(pkgName, userId); + { + std::lock_guard autoLock(multiUserDiscLocks_); + if (multiUserDiscMap_.find(pkgNameTemp) != multiUserDiscMap_.end()) { + multiUserDiscMap_.erase(pkgNameTemp); + } + } + return pkgNameTemp; +} + +void DiscoveryManager::GetPkgNameAndUserId(const std::string &pkgName, std::string &callerPkgName, + int32_t &userId) +{ + { + std::lock_guard autoLock(multiUserDiscLocks_); + if (multiUserDiscMap_.find(pkgName) != multiUserDiscMap_.end()) { + callerPkgName = GetCallerPkgName(multiUserDiscMap_[pkgName].pkgName); + userId = multiUserDiscMap_[pkgName].userId; + return; + } + } + LOGE("find failed."); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/ipc/lite/ipc_cmd_parser.cpp b/services/service/src/ipc/lite/ipc_cmd_parser.cpp index 9154339c2..e6f3bd310 100644 --- a/services/service/src/ipc/lite/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/lite/ipc_cmd_parser.cpp @@ -159,27 +159,6 @@ ON_IPC_SERVER_CMD(GET_TRUST_DEVICE_LIST, IpcIo &req, IpcIo &reply) } } -ON_IPC_SERVER_CMD(START_DEVICE_DISCOVERY, IpcIo &req, IpcIo &reply) -{ - LOGI("StartDeviceDiscovery service listener."); - std::string pkgName = (const char *)ReadString(&req, nullptr); - std::string extra = (const char *)ReadString(&req, nullptr); - uint16_t subscribeId = 0; - ReadUint16(&req, &subscribeId); - int32_t ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeId, extra); - WriteInt32(&reply, ret); -} - -ON_IPC_SERVER_CMD(STOP_DEVICE_DISCOVER, IpcIo &req, IpcIo &reply) -{ - LOGI("StopDeviceDiscovery service listener."); - std::string pkgName = (const char *)ReadString(&req, nullptr); - uint16_t subscribeId = 0; - ReadUint16(&req, &subscribeId); - int32_t ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); - WriteInt32(&reply, ret); -} - ON_IPC_SERVER_CMD(REQUEST_CREDENTIAL, IpcIo &req, IpcIo &reply) { LOGI("request credential service listener."); diff --git a/services/service/src/ipc/lite/ipc_server_listener.cpp b/services/service/src/ipc/lite/ipc_server_listener.cpp index e4df32736..424dbb72f 100644 --- a/services/service/src/ipc/lite/ipc_server_listener.cpp +++ b/services/service/src/ipc/lite/ipc_server_listener.cpp @@ -77,5 +77,10 @@ std::vector IpcServerListener::GetAllProcessInfo() } return processInfoVec; } + +std::set IpcServerListener::GetSyatemSA() +{ + return {}; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/ipc/standard/ipc_cmd_parser.cpp b/services/service/src/ipc/standard/ipc_cmd_parser.cpp index e3dc7b57c..363dd3268 100644 --- a/services/service/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/standard/ipc_cmd_parser.cpp @@ -44,9 +44,11 @@ #include "ipc_server_client_proxy.h" #include "ipc_server_stub.h" #include "multiple_user_connector.h" - #include "nlohmann/json.hpp" - +#include "parameter.h" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "multiple_user_connector.h" +#endif namespace OHOS { namespace DistributedHardware { const unsigned int XCOLLIE_TIMEOUT_S = 5; @@ -421,10 +423,8 @@ ON_IPC_CMD(REGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParcel return ERR_DM_POINT_NULL; } ProcessInfo processInfo; - uint32_t tokenId; - MultipleUserConnector::GetTokenIdAndUserId(tokenId, processInfo.userId); - processInfo.tokenId = tokenId; processInfo.pkgName = pkgName; + MultipleUserConnector::GetCallerUserId(processInfo.userId); DeviceManagerService::GetInstance().RegisterCallerAppId(pkgName); int32_t result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, callback); if (!reply.WriteInt32(result)) { @@ -440,10 +440,8 @@ ON_IPC_CMD(UNREGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParce { std::string pkgName = data.ReadString(); ProcessInfo processInfo; - uint32_t tokenId; - MultipleUserConnector::GetTokenIdAndUserId(tokenId, processInfo.userId); processInfo.pkgName = pkgName; - processInfo.tokenId = tokenId; + MultipleUserConnector::GetCallerUserId(processInfo.userId); DeviceManagerService::GetInstance().UnRegisterCallerAppId(pkgName); int32_t result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); if (!reply.WriteInt32(result)) { @@ -453,48 +451,6 @@ ON_IPC_CMD(UNREGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParce return DM_OK; } -ON_IPC_CMD(START_DEVICE_DISCOVER, MessageParcel &data, MessageParcel &reply) -{ - std::string pkgName = data.ReadString(); - std::string extra = data.ReadString(); - DmSubscribeInfo *subscribeInfo = - static_cast(const_cast(data.ReadRawData(sizeof(DmSubscribeInfo)))); - int32_t result = ERR_DM_POINT_NULL; - - if (subscribeInfo != nullptr) { - result = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, *subscribeInfo, extra); - } - if (!reply.WriteInt32(result)) { - LOGE("write result failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - return DM_OK; -} - -ON_IPC_CMD(START_DEVICE_DISCOVERY, MessageParcel &data, MessageParcel &reply) -{ - std::string pkgName = data.ReadString(); - std::string filterOption = data.ReadString(); - uint16_t subscribeId = data.ReadUint16(); - int32_t result = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeId, filterOption); - if (!reply.WriteInt32(result)) { - LOGE("write result failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - return DM_OK; -} - -ON_IPC_CMD(STOP_DEVICE_DISCOVER, MessageParcel &data, MessageParcel &reply) -{ - std::string pkgName = data.ReadString(); - uint16_t subscribeId = data.ReadUint16(); - int32_t result = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); - if (!reply.WriteInt32(result)) { - LOGE("write result failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - return DM_OK; -} ON_IPC_CMD(PUBLISH_DEVICE_DISCOVER, MessageParcel &data, MessageParcel &reply) { diff --git a/services/service/src/ipc/standard/ipc_server_listener.cpp b/services/service/src/ipc/standard/ipc_server_listener.cpp index 7a692d6cb..9c9cec34a 100644 --- a/services/service/src/ipc/standard/ipc_server_listener.cpp +++ b/services/service/src/ipc/standard/ipc_server_listener.cpp @@ -48,5 +48,10 @@ std::vector IpcServerListener::GetAllProcessInfo() { return IpcServerStub::GetInstance().GetAllProcessInfo(); } + +std::set IpcServerListener::GetSystemSA() +{ + return IpcServerStub::GetInstance().GetSystemSA(); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/ipc/standard/ipc_server_stub.cpp b/services/service/src/ipc/standard/ipc_server_stub.cpp index ce10a362a..c09e16d3e 100644 --- a/services/service/src/ipc/standard/ipc_server_stub.cpp +++ b/services/service/src/ipc/standard/ipc_server_stub.cpp @@ -36,6 +36,7 @@ #include "dm_device_info.h" #include "dm_log.h" #include "multiple_user_connector.h" +#include "permission_manager.h" namespace OHOS { namespace DistributedHardware { @@ -226,13 +227,13 @@ int32_t IpcServerStub::RegisterDeviceManagerListener(const ProcessInfo &processI dmListener_.erase(processInfo); } } - sptr appRecipient = sptr(new AppDeathRecipient()); if (!listener->AsObject()->AddDeathRecipient(appRecipient)) { LOGE("AddDeathRecipient Failed"); } dmListener_[processInfo] = listener; appRecipient_[processInfo] = appRecipient; + AddSystemSA(processInfo.pkgName); LOGI("Register listener complete."); return DM_OK; } @@ -261,6 +262,7 @@ int32_t IpcServerStub::UnRegisterDeviceManagerListener(const ProcessInfo &proces listener->AsObject()->RemoveDeathRecipient(appRecipient); appRecipient_.erase(processInfo); dmListener_.erase(processInfo); + RemoveSystemSA(processInfo.pkgName); return DM_OK; } @@ -330,5 +332,29 @@ void AppDeathRecipient::OnRemoteDied(const wptr &remote) IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); DeviceManagerService::GetInstance().ClearDiscoveryCache(processInfo); } + +void IpcServerStub::AddSystemSA(const std::string &pkgName) +{ + if (PermissionManager::GetInstance().CheckSystemSA(pkgName)) { + systemSA_.insert(pkgName); + } +} + +void IpcServerStub::RemoveSystemSA(const std::string &pkgName) +{ + if (PermissionManager::GetInstance().CheckSystemSA(pkgName) || systemSA_.find(pkgName) != systemSA_.end()) { + systemSA_.erase(pkgName); + } +} + +std::set IpcServerStub::GetSystemSA() +{ + std::lock_guard autoLock(listenerLock_); + std::set systemSA; + for (const auto &item : systemSA_) { + systemSA.insert(item); + } + return systemSA; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/permission/lite/permission_manager.cpp b/services/service/src/permission/lite/permission_manager.cpp index f6d416435..f47abe78e 100644 --- a/services/service/src/permission/lite/permission_manager.cpp +++ b/services/service/src/permission/lite/permission_manager.cpp @@ -54,15 +54,21 @@ bool PermissionManager::CheckProcessNameValidOnPinHolder(const std::string &proc return true; } -bool PermissionManager::CheckSystemSA(const std::string &pkgName) +bool PermissionManager::CheckWhiteListSystemSA(const std::string &pkgName) { (void)pkgName; return true; } -std::unordered_set PermissionManager::GetSystemSA() +std::unordered_set PermissionManager::GetWhiteListSystemSA() { return std::unordered_set{}; } + +bool PermissionManager::CheckSystemSA(const std::string &pkgName) +{ + (void)pkgName; + return true; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/permission/standard/permission_manager.cpp b/services/service/src/permission/standard/permission_manager.cpp index 23fc34d23..c43d639c4 100644 --- a/services/service/src/permission/standard/permission_manager.cpp +++ b/services/service/src/permission/standard/permission_manager.cpp @@ -192,7 +192,7 @@ bool PermissionManager::CheckProcessNameValidOnPinHolder(const std::string &proc return false; } -bool PermissionManager::CheckSystemSA(const std::string &pkgName) +bool PermissionManager::CheckWhiteListSystemSA(const std::string &pkgName) { for (uint16_t index = 0; index < SYSTEM_SA_WHITE_LIST_NUM; ++index) { std::string tmp(systemSaWhiteList[index]); @@ -203,7 +203,7 @@ bool PermissionManager::CheckSystemSA(const std::string &pkgName) return false; } -std::unordered_set PermissionManager::GetSystemSA() +std::unordered_set PermissionManager::GetWhiteListSystemSA() { std::unordered_set systemSA; for (uint16_t index = 0; index < SYSTEM_SA_WHITE_LIST_NUM; ++index) { @@ -212,5 +212,19 @@ std::unordered_set PermissionManager::GetSystemSA() } return systemSA; } + +bool PermissionManager::CheckSystemSA(const std::string &pkgName) +{ + AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); + if (tokenCaller == 0) { + LOGE("CheckMonitorPermission GetCallingTokenID error."); + return false; + } + ATokenTypeEnum tokenTypeFlag = AccessTokenKit::GetTokenTypeFlag(tokenCaller); + if (tokenTypeFlag == ATokenTypeEnum::TOKEN_NATIVE) { + return true; + } + return false; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/pinholder/pin_holder.cpp b/services/service/src/pinholder/pin_holder.cpp index 8b86a63d2..400d9ddf2 100644 --- a/services/service/src/pinholder/pin_holder.cpp +++ b/services/service/src/pinholder/pin_holder.cpp @@ -20,6 +20,9 @@ #include "dm_log.h" #include "dm_radar_helper.h" #include "nlohmann/json.hpp" +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) +#include "multiple_user_connector.h" +#endif namespace OHOS { namespace DistributedHardware { @@ -82,7 +85,10 @@ int32_t PinHolder::RegisterPinHolderCallback(const std::string &pkgName) LOGE("RegisterPinHolderCallback session is nullptr."); return ERR_DM_FAILED; } - registerPkgName_ = pkgName; + int32_t userId = -1; + MultipleUserConnector::GetCallerUserId(userId); + processInfo_.userId = userId; + processInfo_.pkgName = pkgName; session_->RegisterSessionCallback(shared_from_this()); return DM_OK; } @@ -91,7 +97,7 @@ int32_t PinHolder::CreatePinHolder(const std::string &pkgName, const PeerTargetId &targetId, DmPinType pinType, const std::string &payload) { LOGI("CreatePinHolder."); - if (registerPkgName_.empty() || registerPkgName_ != pkgName) { + if (processInfo_.pkgName.empty() || processInfo_.pkgName != pkgName) { LOGE("CreatePinHolder pkgName: %{public}s is not register callback.", pkgName.c_str()); return ERR_DM_FAILED; } @@ -118,11 +124,11 @@ int32_t PinHolder::CreatePinHolder(const std::string &pkgName, int32_t stageRes = sessionId_ > 0 ? static_cast(StageRes::STAGE_SUCC) : static_cast(StageRes::STAGE_FAIL); DmRadarHelper::GetInstance().ReportCreatePinHolder( - registerPkgName_, sessionId_, targetId.deviceId, sessionId_, stageRes); + processInfo_.pkgName, sessionId_, targetId.deviceId, sessionId_, stageRes); if (sessionId_ < 0) { LOGE("[SOFTBUS]open session error, sessionId: %{public}d.", sessionId_); - listener_->OnCreateResult(registerPkgName_, sessionId_); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::CREATE_RESULT, + listener_->OnCreateResult(processInfo_, sessionId_); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::CREATE_RESULT, sessionId_, ""); sessionId_ = SESSION_ID_INVALID; return sessionId_; @@ -140,7 +146,7 @@ int32_t PinHolder::DestroyPinHolder(const std::string &pkgName, const PeerTarget LOGE("DestroyPinHolder listener or session is nullptr."); return ERR_DM_FAILED; } - if (registerPkgName_.empty() || pkgName != registerPkgName_) { + if (processInfo_.pkgName.empty() || pkgName != processInfo_.pkgName) { LOGE("DestroyPinHolder pkgName: %{public}s is not register callback.", pkgName.c_str()); return ERR_DM_FAILED; } @@ -151,8 +157,8 @@ int32_t PinHolder::DestroyPinHolder(const std::string &pkgName, const PeerTarget } if (sessionId_ == SESSION_ID_INVALID) { LOGI("DestroyPinHolder session already destroy."); - listener_->OnDestroyResult(registerPkgName_, ret); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY_RESULT, ret, ""); + listener_->OnDestroyResult(processInfo_, ret); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY_RESULT, ret, ""); return ret; } if (sourceState_ != SOURCE_CREATE) { @@ -173,11 +179,11 @@ int32_t PinHolder::DestroyPinHolder(const std::string &pkgName, const PeerTarget ret = session_->SendData(sessionId_, message); int32_t stageRes = ret == DM_OK ? static_cast(StageRes::STAGE_SUCC) : static_cast(StageRes::STAGE_FAIL); - DmRadarHelper::GetInstance().ReportDestroyPinHolder(registerPkgName_, targetId.deviceId, ret, stageRes); + DmRadarHelper::GetInstance().ReportDestroyPinHolder(processInfo_.pkgName, targetId.deviceId, ret, stageRes); if (ret != DM_OK) { LOGE("[SOFTBUS]SendBytes failed, ret: %{public}d.", ret); - listener_->OnDestroyResult(registerPkgName_, ERR_DM_FAILED); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY_RESULT, ERR_DM_FAILED, ""); + listener_->OnDestroyResult(processInfo_, ERR_DM_FAILED); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY_RESULT, ERR_DM_FAILED, ""); return ret; } return ret; @@ -209,8 +215,8 @@ int32_t PinHolder::CreateGeneratePinHolderMsg() std::string("CreateGeneratePinHolderMsg"), ""); if (ret != DM_OK) { LOGE("[SOFTBUS]SendBytes failed, ret: %{public}d.", ret); - listener_->OnCreateResult(registerPkgName_, ret); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::CREATE_RESULT, ret, ""); + listener_->OnCreateResult(processInfo_, ret); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::CREATE_RESULT, ret, ""); return ret; } return ret; @@ -259,13 +265,13 @@ void PinHolder::ProcessCreateMsg(const std::string &message) jsonObj[TAG_REPLY] = REPLY_SUCCESS; sinkState_ = SINK_CREATE; sourceState_ = SOURCE_CREATE; - listener_->OnPinHolderCreate(registerPkgName_, remoteDeviceId_, pinType, payload); + listener_->OnPinHolderCreate(processInfo_, remoteDeviceId_, pinType, payload); nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType; jsonContent[TAG_PAYLOAD] = payload; jsonContent[TAG_REMOTE_DEVICE_ID] = remoteDeviceId_; std::string content = jsonContent.dump(); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::CREATE, DM_OK, content); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::CREATE, DM_OK, content); } jsonObj[TAG_DM_VERSION] = ""; @@ -296,14 +302,14 @@ void PinHolder::ProcessCreateRespMsg(const std::string &message) return; } if (reply == REPLY_SUCCESS) { - listener_->OnCreateResult(registerPkgName_, DM_OK); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::CREATE_RESULT, DM_OK, ""); + listener_->OnCreateResult(processInfo_, DM_OK); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::CREATE_RESULT, DM_OK, ""); sourceState_ = SOURCE_CREATE; sinkState_ = SINK_CREATE; } else { LOGE("ProcessCreateRespMsg remote state is wrong."); - listener_->OnCreateResult(registerPkgName_, ERR_DM_FAILED); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::CREATE_RESULT, ERR_DM_FAILED, ""); + listener_->OnCreateResult(processInfo_, ERR_DM_FAILED); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::CREATE_RESULT, ERR_DM_FAILED, ""); session_->CloseSessionServer(sessionId_); sessionId_ = SESSION_ID_INVALID; destroyState_ = STATE_REMOTE_WRONG; @@ -338,12 +344,12 @@ void PinHolder::ProcessDestroyMsg(const std::string &message) sinkState_ = SINK_INIT; sourceState_ = SOURCE_INIT; if (!isDestroy_.load()) { - listener_->OnPinHolderDestroy(registerPkgName_, pinType, payload); + listener_->OnPinHolderDestroy(processInfo_, pinType, payload); nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType; jsonContent[TAG_PAYLOAD] = payload; std::string content = jsonContent.dump(); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY, DM_OK, content); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY, DM_OK, content); isDestroy_.store(true); } } @@ -368,12 +374,12 @@ void PinHolder::CloseSession(const std::string &name) jsonObj[DM_CONNECTION_DISCONNECTED] = true; std::string payload = jsonObj.dump(); if (listener_ != nullptr && !isDestroy_.load()) { - listener_->OnPinHolderDestroy(registerPkgName_, pinType_, payload); + listener_->OnPinHolderDestroy(processInfo_, pinType_, payload); nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType_; jsonContent[TAG_PAYLOAD] = payload; std::string content = jsonContent.dump(); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY, ERR_DM_TIME_OUT, content); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY, ERR_DM_TIME_OUT, content); isDestroy_.store(true); } session_->CloseSessionServer(sessionId_); @@ -403,15 +409,15 @@ void PinHolder::ProcessDestroyResMsg(const std::string &message) return; } if (reply == REPLY_SUCCESS) { - listener_->OnDestroyResult(registerPkgName_, DM_OK); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY_RESULT, DM_OK, ""); + listener_->OnDestroyResult(processInfo_, DM_OK); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY_RESULT, DM_OK, ""); sourceState_ = SOURCE_INIT; sinkState_ = SINK_INIT; timer_->DeleteAll(); } else { LOGE("ProcessDestroyResMsg remote state is wrong."); - listener_->OnDestroyResult(registerPkgName_, ERR_DM_FAILED); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY_RESULT, ERR_DM_FAILED, ""); + listener_->OnDestroyResult(processInfo_, ERR_DM_FAILED); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY_RESULT, ERR_DM_FAILED, ""); } session_->CloseSessionServer(sessionId_); sessionId_ = SESSION_ID_INVALID; @@ -492,8 +498,8 @@ void PinHolder::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t LOGE("[SOFTBUS]onSesssionOpened failed. sessionId: %{public}d.", sessionId); sessionId_ = SESSION_ID_INVALID; if (listener_ != nullptr) { - listener_->OnCreateResult(registerPkgName_, result); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::CREATE_RESULT, result, ""); + listener_->OnCreateResult(processInfo_, result); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::CREATE_RESULT, result, ""); } return; } @@ -510,17 +516,17 @@ void PinHolder::OnSessionClosed(int32_t sessionId) jsonObj[DM_CONNECTION_DISCONNECTED] = true; std::string payload = jsonObj.dump(); if (listener_ != nullptr && !isDestroy_.load()) { - listener_->OnPinHolderDestroy(registerPkgName_, pinType_, payload); + listener_->OnPinHolderDestroy(processInfo_, pinType_, payload); nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType_; jsonContent[TAG_PAYLOAD] = payload; std::string content = jsonContent.dump(); if (destroyState_ == STATE_UNKNOW) { - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY, sessionId, content); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY, sessionId, content); } else if (destroyState_ == STATE_REMOTE_WRONG) { - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY, ERR_DM_FAILED, content); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY, ERR_DM_FAILED, content); } else if (destroyState_ == STATE_TIME_OUT) { - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::DESTROY, ERR_DM_TIME_OUT, content); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::DESTROY, ERR_DM_TIME_OUT, content); } isDestroy_.store(true); } @@ -546,7 +552,7 @@ int32_t PinHolder::NotifyPinHolderEvent(const std::string &pkgName, const std::s LOGE("NotifyPinHolderEvent listener or session is nullptr."); return ERR_DM_FAILED; } - if (registerPkgName_.empty() || pkgName != registerPkgName_ || event.empty()) { + if (processInfo_.pkgName.empty() || pkgName != processInfo_.pkgName || event.empty()) { LOGE("NotifyPinHolderEvent pkgName: %{public}s is not register callback.", pkgName.c_str()); return ERR_DM_FAILED; } @@ -578,7 +584,7 @@ int32_t PinHolder::NotifyPinHolderEvent(const std::string &pkgName, const std::s int32_t ret = session_->SendData(sessionId_, message); if (ret != DM_OK) { LOGE("[SOFTBUS]SendBytes failed, ret: %{public}d.", ret); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::PIN_TYPE_CHANGE_RESULT, ERR_DM_FAILED, ""); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::PIN_TYPE_CHANGE_RESULT, ERR_DM_FAILED, ""); return ERR_DM_FAILED; } return ret; @@ -610,7 +616,7 @@ void PinHolder::ProcessChangeMsg(const std::string &message) nlohmann::json jsonContent; jsonContent[TAG_PIN_TYPE] = pinType; std::string content = jsonContent.dump(); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::PIN_TYPE_CHANGE, DM_OK, content); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::PIN_TYPE_CHANGE, DM_OK, content); timer_->DeleteAll(); timer_->StartTimer(std::string(PINHOLDER_CREATE_TIMEOUT_TASK), PIN_HOLDER_SESSION_CREATE_TIMEOUT, [this] (std::string name) { @@ -644,10 +650,10 @@ void PinHolder::ProcessChangeRespMsg(const std::string &message) return; } if (reply == REPLY_SUCCESS) { - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::PIN_TYPE_CHANGE_RESULT, DM_OK, ""); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::PIN_TYPE_CHANGE_RESULT, DM_OK, ""); } else { LOGE("ProcessChangeRespMsg remote state is wrong."); - listener_->OnPinHolderEvent(registerPkgName_, DmPinHolderEvent::PIN_TYPE_CHANGE_RESULT, ERR_DM_FAILED, ""); + listener_->OnPinHolderEvent(processInfo_, DmPinHolderEvent::PIN_TYPE_CHANGE_RESULT, ERR_DM_FAILED, ""); } } } // namespace DistributedHardware diff --git a/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp b/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp index 54241e5b2..3f1ee3fc8 100644 --- a/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp +++ b/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp @@ -320,7 +320,7 @@ void AuthenticateDeviceFourthFuzzTest(const uint8_t* data, size_t size) DeviceManagerImpl::GetInstance().UnbindTarget(str, targetId, discoverParam, nullptr); DeviceManagerImpl::GetInstance().GetTrustedDeviceList(str, discoverParam, false, g_deviceList); DeviceManagerImpl::GetInstance().RegisterDevStateCallback(str, discoverParam, nullptr); - DeviceManagerImpl::GetInstance().AddDiscoveryCallback("test", nullptr); + DeviceManagerImpl::GetInstance().AddDiscoveryCallback("test", discoverParam, nullptr); DeviceManagerImpl::GetInstance().RemoveDiscoveryCallback("test"); DeviceManagerImpl::GetInstance().AddPublishCallback("test"); DeviceManagerImpl::GetInstance().RemovePublishCallback("test"); diff --git a/test/commonunittest/UTTest_discovery_manager.cpp b/test/commonunittest/UTTest_discovery_manager.cpp index 65d8cbd12..9a2d26d00 100644 --- a/test/commonunittest/UTTest_discovery_manager.cpp +++ b/test/commonunittest/UTTest_discovery_manager.cpp @@ -361,7 +361,7 @@ HWTEST_F(DiscoveryManagerTest, GetDeviceAclParam_001, testing::ext::TestSize.Lev std::string deviceId; bool isonline = true; int32_t authForm = 0; - int32_t ret = manager->GetDeviceAclParam(pkgName, deviceId, isonline, authForm); + int32_t ret = manager->GetDeviceAclParam(pkgName, 100, deviceId, isonline, authForm); EXPECT_EQ(ret, DM_OK); } diff --git a/test/commonunittest/UTTest_dm_auth_manager_first.cpp b/test/commonunittest/UTTest_dm_auth_manager_first.cpp index c0e6a625c..2943deaf9 100644 --- a/test/commonunittest/UTTest_dm_auth_manager_first.cpp +++ b/test/commonunittest/UTTest_dm_auth_manager_first.cpp @@ -267,7 +267,6 @@ HWTEST_F(DmAuthManagerTest, JoinNetwork_002, testing::ext::TestSize.Level0) { authManager_->authResponseContext_ = nullptr; authManager_->AuthenticateFinish(); - authManager_->CancelDisplay(); int32_t ret = authManager_->JoinNetwork(); ASSERT_EQ(ret, ERR_DM_FAILED); } diff --git a/test/commonunittest/UTTest_dm_credential_manager.h b/test/commonunittest/UTTest_dm_credential_manager.h index 1347ebfdb..50ac9b450 100644 --- a/test/commonunittest/UTTest_dm_credential_manager.h +++ b/test/commonunittest/UTTest_dm_credential_manager.h @@ -42,7 +42,7 @@ class MockDeviceManagerServiceListener : public DeviceManagerServiceListener { public: MockDeviceManagerServiceListener() = default; ~MockDeviceManagerServiceListener() = default; - void OnCredentialResult(const std::string &pkgName, int32_t action, const std::string &resultInfo) override {} + void OnCredentialResult(const ProcessInfo &processInfo, int32_t action, const std::string &resultInfo) override {} }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/commonunittest/UTTest_dm_device_state_manager.cpp b/test/commonunittest/UTTest_dm_device_state_manager.cpp index 9d7bec6bf..80aaf0bbf 100644 --- a/test/commonunittest/UTTest_dm_device_state_manager.cpp +++ b/test/commonunittest/UTTest_dm_device_state_manager.cpp @@ -252,14 +252,6 @@ HWTEST_F(DmDeviceStateManagerTest, ProcNotifyEvent_001, testing::ext::TestSize.L dmDeviceStateManager->ChangeDeviceInfo(info); EXPECT_EQ(ret, DM_OK); } - -HWTEST_F(DmDeviceStateManagerTest, HandleCandidateRestrictStatus_001, testing::ext::TestSize.Level0) -{ - uint16_t deviceTypeId = 0x00; - int32_t errcode = -1; - dmDeviceStateManager->HandleCredentialAuthStatus(deviceTypeId, errcode); - EXPECT_NE(dmDeviceStateManager->softbusConnector_, nullptr); -} } // namespace } // namespace DistributedHardware } // namespace OHOS diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index 6fb2e5905..219c7dac1 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -47,8 +47,7 @@ HWTEST_F(DeviceProfileConnectorTest, GetAppTrustDeviceList_001, testing::ext::Te { std::string pkgName; std::string deviceId = "deviceId"; - int32_t userId = 100; - auto ret = DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgName, deviceId, userId); + auto ret = DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgName, deviceId, 100); EXPECT_EQ(ret.empty(), true); } @@ -56,8 +55,7 @@ HWTEST_F(DeviceProfileConnectorTest, GetAppTrustDeviceList_002, testing::ext::Te { std::string pkgName = "bundleName"; std::string deviceId = "deviceId"; - int32_t userId = 100; - auto ret = DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgName, deviceId, userId); + auto ret = DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgName, deviceId, 100); EXPECT_EQ(ret.empty(), true); } @@ -794,8 +792,9 @@ HWTEST_F(DeviceProfileConnectorTest, HandleAppUnBindEvent_001, testing::ext::Tes std::string remoteUdid = "remoteDeviceId"; std::string localUdid = "localDeviceId"; std::string pkgName = ""; - ProcessInfo res - = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid); + ProcessInfo res; + + res = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid); EXPECT_EQ(pkgName, res.pkgName); } diff --git a/test/commonunittest/UTTest_permission_manager.cpp b/test/commonunittest/UTTest_permission_manager.cpp index 8c8ef0f39..12ad9a7f9 100644 --- a/test/commonunittest/UTTest_permission_manager.cpp +++ b/test/commonunittest/UTTest_permission_manager.cpp @@ -199,54 +199,54 @@ HWTEST_F(PermissionManagerTest, CheckProcessNameValidOnPinHolder_004, testing::e ASSERT_TRUE(ret); } /** - * @tc.name: PinAuthUi::CheckSystemSA_001 + * @tc.name: PinAuthUi::CheckWhiteListSystemSA_001 * @tc.desc: the return value is false * @tc.type:FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(PermissionManagerTest, CheckSystemSA_001, testing::ext::TestSize.Level0) +HWTEST_F(PermissionManagerTest, CheckWhiteListSystemSA_001, testing::ext::TestSize.Level0) { std::string pkgName; - bool ret = PermissionManager::GetInstance().CheckSystemSA(pkgName); + bool ret = PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName); ASSERT_EQ(ret, false); pkgName = "pkgName"; - ret = PermissionManager::GetInstance().CheckSystemSA(pkgName); + ret = PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName); ASSERT_EQ(ret, false); } /** - * @tc.name: PinAuthUi::CheckSystemSA_002 + * @tc.name: PinAuthUi::CheckWhiteListSystemSA_002 * @tc.desc: the return value is true * @tc.type:FUNC * @tc.require: AR000GHSJK */ -HWTEST_F(PermissionManagerTest, CheckSystemSA_002, testing::ext::TestSize.Level0) +HWTEST_F(PermissionManagerTest, CheckWhiteListSystemSA_002, testing::ext::TestSize.Level0) { std::string pkgName1(systemSaWhiteList[0]); - bool ret = PermissionManager::GetInstance().CheckSystemSA(pkgName1); + bool ret = PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName1); ASSERT_EQ(ret, true); std::string pkgName2(systemSaWhiteList[1]); - ret = PermissionManager::GetInstance().CheckSystemSA(pkgName2); + ret = PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName2); ASSERT_EQ(ret, true); std::string pkgName3(systemSaWhiteList[2]); - ret = PermissionManager::GetInstance().CheckSystemSA(pkgName3); + ret = PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName3); ASSERT_EQ(ret, true); std::string pkgName4(systemSaWhiteList[3]); - ret = PermissionManager::GetInstance().CheckSystemSA(pkgName4); + ret = PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName4); ASSERT_EQ(ret, true); } -HWTEST_F(PermissionManagerTest, CheckSystemSA_101, testing::ext::TestSize.Level0) +HWTEST_F(PermissionManagerTest, CheckWhiteListSystemSA_101, testing::ext::TestSize.Level0) { std::string pkgName = "pkgName"; - bool ret = PermissionManager::GetInstance().CheckSystemSA(pkgName); + bool ret = PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName); ASSERT_FALSE(ret); } -HWTEST_F(PermissionManagerTest, CheckSystemSA_102, testing::ext::TestSize.Level0) +HWTEST_F(PermissionManagerTest, CheckWhiteListSystemSA_102, testing::ext::TestSize.Level0) { std::string pkgName = "ohos.dhardware"; - bool ret = PermissionManager::GetInstance().CheckSystemSA(pkgName); + bool ret = PermissionManager::GetInstance().CheckWhiteListSystemSA(pkgName); ASSERT_TRUE(ret); } } diff --git a/test/servicesfuzztest/devicemanagerservice_fuzzer/device_manager_service_fuzzer.cpp b/test/servicesfuzztest/devicemanagerservice_fuzzer/device_manager_service_fuzzer.cpp index dfa125cbc..51e187c50 100644 --- a/test/servicesfuzztest/devicemanagerservice_fuzzer/device_manager_service_fuzzer.cpp +++ b/test/servicesfuzztest/devicemanagerservice_fuzzer/device_manager_service_fuzzer.cpp @@ -38,12 +38,9 @@ void DeviceManagerServiceFuzzTest(const uint8_t* data, size_t size) DmPublishInfo publishInfo; std::map parametricMap; - DeviceManagerService::GetInstance().StartDeviceDiscovery(inputStr, subscribeInfo, inputStr); DeviceManagerService::GetInstance().PublishDeviceDiscovery(inputStr, publishInfo); DeviceManagerService::GetInstance().RequestCredential(inputStr, inputStr); - DeviceManagerService::GetInstance().StopDeviceDiscovery(inputStr, subscribeId); DeviceManagerService::GetInstance().UnPublishDeviceDiscovery(inputStr, publishId); - DeviceManagerService::GetInstance().StartDeviceDiscovery(inputStr, subscribeId, inputStr); DeviceManagerService::GetInstance().GetDeviceInfo(inputStr, info); DeviceManagerService::GetInstance().GetLocalDeviceInfo(info); DeviceManagerService::GetInstance().GetDeviceSecurityLevel(inputStr, inputStr, publishId); diff --git a/test/servicesfuzztest/ipccmdregister_fuzzer/ipc_cmd_register_fuzzer.cpp b/test/servicesfuzztest/ipccmdregister_fuzzer/ipc_cmd_register_fuzzer.cpp index f8e05ec0a..99d41ffae 100644 --- a/test/servicesfuzztest/ipccmdregister_fuzzer/ipc_cmd_register_fuzzer.cpp +++ b/test/servicesfuzztest/ipccmdregister_fuzzer/ipc_cmd_register_fuzzer.cpp @@ -28,8 +28,6 @@ #include "ipc_get_info_by_network_rsp.h" #include "ipc_get_info_by_network_req.h" #include "ipc_get_trustdevice_req.h" -#include "ipc_start_discovery_req.h" -#include "ipc_stop_discovery_req.h" #include "ipc_publish_req.h" #include "ipc_unpublish_req.h" #include "ipc_set_useroperation_req.h" diff --git a/test/servicesfuzztest/ipcserverstub_fuzzer/ipc_server_stub_fuzzer.cpp b/test/servicesfuzztest/ipcserverstub_fuzzer/ipc_server_stub_fuzzer.cpp index b4d6047b6..1a75d5056 100644 --- a/test/servicesfuzztest/ipcserverstub_fuzzer/ipc_server_stub_fuzzer.cpp +++ b/test/servicesfuzztest/ipcserverstub_fuzzer/ipc_server_stub_fuzzer.cpp @@ -44,12 +44,13 @@ void IpcServerStubFuzzTest(const uint8_t* data, size_t size) MessageParcel data1; MessageParcel reply; MessageOption option; + ProcessInfo processInfo; std::string pkgName(reinterpret_cast(data), size); + processInfo.pkgName = pkgName; sptr listener = sptr(new IpcServerStub()); std::shared_ptr req = nullptr; std::shared_ptr rsp = std::make_shared(); - ProcessInfo processInfo; - processInfo.pkgName = pkgName; + IpcServerStub::GetInstance().Init(); IpcServerStub::GetInstance().OnRemoteRequest(code, data1, reply, option); IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); diff --git a/test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.cpp b/test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.cpp index caa6d47cf..58ec42820 100644 --- a/test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.cpp +++ b/test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.cpp @@ -38,9 +38,6 @@ void SoftBusConnectorCommonFuzzTest(const uint8_t* data, size_t size) softbusConnector->GetDeviceUdidHashByUdid(str); softbusConnector->EraseUdidFromMap(str); softbusConnector->GetNetworkIdByDeviceId(str); - ProcessInfo processInfo; - processInfo.pkgName = str; - softbusConnector->SetProcessInfo(processInfo); softbusConnector->CheckIsOnline(str); softbusConnector->GetDeviceInfoByDeviceId(str); } diff --git a/test/softbusunittest/UTTest_softbus_connector.cpp b/test/softbusunittest/UTTest_softbus_connector.cpp index 92c14664b..9b18910f0 100644 --- a/test/softbusunittest/UTTest_softbus_connector.cpp +++ b/test/softbusunittest/UTTest_softbus_connector.cpp @@ -814,10 +814,10 @@ HWTEST_F(SoftbusConnectorTest, AddMemberToDiscoverMap_002, testing::ext::TestSiz */ HWTEST_F(SoftbusConnectorTest, SetProcessInfo_001, testing::ext::TestSize.Level0) { - std::string pkgName = "pkgName"; ProcessInfo processInfo; - processInfo.pkgName = pkgName; std::vector processInfoVec; + std::string pkgName = "pkgName"; + std::vector pkgNameVec; std::shared_ptr softbusConnector = std::make_shared(); softbusConnector->SetProcessInfoVec(processInfoVec); softbusConnector->SetProcessInfo(processInfo); diff --git a/test/unittest/UTTest_device_manager_impl.cpp b/test/unittest/UTTest_device_manager_impl.cpp index 8e236a814..d7bd61aa0 100644 --- a/test/unittest/UTTest_device_manager_impl.cpp +++ b/test/unittest/UTTest_device_manager_impl.cpp @@ -31,8 +31,6 @@ #include "ipc_rsp.h" #include "ipc_set_useroperation_req.h" #include "ipc_skeleton.h" -#include "ipc_start_discovery_req.h" -#include "ipc_stop_discovery_req.h" #include "ipc_publish_req.h" #include "ipc_unpublish_req.h" #include "ipc_unauthenticate_device_req.h" diff --git a/test/unittest/UTTest_device_manager_impl_three.cpp b/test/unittest/UTTest_device_manager_impl_three.cpp index 3d5eb2410..a9ef55026 100644 --- a/test/unittest/UTTest_device_manager_impl_three.cpp +++ b/test/unittest/UTTest_device_manager_impl_three.cpp @@ -31,8 +31,6 @@ #include "ipc_rsp.h" #include "ipc_set_useroperation_req.h" #include "ipc_skeleton.h" -#include "ipc_start_discovery_req.h" -#include "ipc_stop_discovery_req.h" #include "ipc_publish_req.h" #include "ipc_unpublish_req.h" #include "ipc_unauthenticate_device_req.h" @@ -839,7 +837,6 @@ HWTEST_F(DeviceManagerImplTest, StartDeviceDiscovery_106, testing::ext::TestSize std::string packName = "com.ohos.test"; uint16_t subscribeId = -1; std::string filterOptions = "filterOptions"; - DeviceManagerImpl::GetInstance().subscribIdMap_.clear(); std::shared_ptr callback = std::make_shared(); std::shared_ptr initcallback = std::make_shared(); int32_t ret = DeviceManager::GetInstance().InitDeviceManager(packName, initcallback); @@ -1193,9 +1190,7 @@ HWTEST_F(DeviceManagerImplTest, StopDeviceDiscovery_302, testing::ext::TestSize. uint64_t tokenId = 123; std::shared_ptr callback = std::make_shared(); DeviceManagerImpl::GetInstance().InitDeviceManager(packName, callback); - DeviceManagerImpl::GetInstance().subscribIdMap_[tokenId] = 12345; DeviceManagerImpl::GetInstance().StopDeviceDiscovery(tokenId, packName); - DeviceManagerImpl::GetInstance().subscribIdMap_.erase(tokenId); int32_t ret = DeviceManagerImpl::GetInstance().StopDeviceDiscovery(tokenId, packName); ASSERT_EQ(ret, ERR_DM_STOP_DISCOVERY); DeviceManagerImpl::GetInstance().UnInitDeviceManager(packName); diff --git a/test/unittest/UTTest_device_manager_impl_two.cpp b/test/unittest/UTTest_device_manager_impl_two.cpp index 7cd7c5d14..b979e8e45 100644 --- a/test/unittest/UTTest_device_manager_impl_two.cpp +++ b/test/unittest/UTTest_device_manager_impl_two.cpp @@ -31,9 +31,7 @@ #include "ipc_rsp.h" #include "ipc_set_useroperation_req.h" #include "ipc_skeleton.h" -#include "ipc_start_discovery_req.h" -#include "ipc_stop_discovery_req.h" -#include "ipc_publish_req.h" + #include "ipc_publish_req.h" #include "ipc_unpublish_req.h" #include "ipc_unauthenticate_device_req.h" #include "nativetoken_kit.h" diff --git a/test/unittest/UTTest_device_manager_service.cpp b/test/unittest/UTTest_device_manager_service.cpp index a2a03fe49..a2fd6830d 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -105,100 +105,6 @@ HWTEST_F(DeviceManagerServiceTest, InitDMServiceListener_001, testing::ext::Test DeviceManagerService::GetInstance().UninitDMServiceListener(); } -/** - * @tc.name: StartDeviceDiscovery_001 - * @tc.desc: Start device discovery and return ERR_DM_NO_PERMISSION - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_001, testing::ext::TestSize.Level0) -{ - DeletePermission(); - std::string pkgName = "com.ohos.test"; - DmSubscribeInfo subscribeInfo; - std::string extra; - int ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeInfo, extra); - EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); -} - -/** - * @tc.name: StartDeviceDiscovery_002 - * @tc.desc: Empty pkgName of StartDeviceDiscovery and return ERR_DM_INPUT_PARA_INVALID - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_002, testing::ext::TestSize.Level0) -{ - std::string pkgName; - DmSubscribeInfo subscribeInfo; - std::string extra = "test"; - int ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeInfo, extra); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -/** - * @tc.name: StartDeviceDiscovery_003 - * @tc.desc: Call StartDeviceDiscovery twice with pkgName not null and flag bit not false and return - * ERR_DM_DISCOVERY_REPEATED - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_003, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.ohos.test"; - DmSubscribeInfo subscribeInfo; - std::string extra = "test"; - DeviceManagerService::GetInstance().InitDMServiceListener(); - int ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeInfo, extra); - EXPECT_EQ(ret, ERR_DM_DISCOVERY_REPEATED); - DeviceManagerService::GetInstance().UninitDMServiceListener(); -} - -/** - * @tc.name: StopDeviceDiscovery_001 - * @tc.desc: Stop device discovery and return SOFTBUS_ERR - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_001, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.ohos.test"; - uint16_t subscribeId = 1; - DeviceManagerService::GetInstance().InitDMServiceListener(); - int ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); - EXPECT_TRUE(ret == SOFTBUS_IPC_ERR || ret == SOFTBUS_ERR); - DeviceManagerService::GetInstance().UninitDMServiceListener(); -} - -/** - * @tc.name:StopDeviceDiscovery_002 - * @tc.desc: StopDeviceDiscovery is initialized, pkgName is null, and its return value is ERR_DM_INPUT_PARA_INVALID - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_002, testing::ext::TestSize.Level0) -{ - std::string pkgName; - uint16_t subscribeId = 1; - int ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -/** - * @tc.name:StopDeviceDiscovery_003 - * @tc.desc: StopDeviceDiscovery is initialized, pkgName is null, and its return value is ERR_DM_INPUT_PARA_INVALID - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_003, testing::ext::TestSize.Level0) -{ - DeletePermission(); - std::string pkgName = "StopDeviceDiscovery_003"; - uint16_t subscribeId = 1; - int ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); - EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); -} - /** * @tc.name: PublishDeviceDiscovery_001 * @tc.desc: Publish device discovery and return ERR_DM_NO_PERMISSION @@ -326,21 +232,20 @@ HWTEST_F(DeviceManagerServiceTest, UnPublishDeviceDiscovery_004, testing::ext::T std::string pkgName = "com.ohos.test003"; int32_t publishId = 1; int32_t userId = 23; - int32_t userId1 = 101; std::string accountId = "hello123"; int32_t preUserId = 3; std::vector peerUdids; std::string accountName = "openharmony123"; std::string commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED; - DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, userId1); + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, preUserId); commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGIN; - DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, userId1); + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, preUserId); commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT; - DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, userId1); + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, preUserId); commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED; - DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, userId1); + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, preUserId); commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_BOOT_COMPLETED; - DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, userId1); + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, preUserId); DeviceManagerService::GetInstance().HandleAccountLogout(userId, accountId); DeviceManagerService::GetInstance().HandleUserRemoved(preUserId); DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); @@ -1229,34 +1134,6 @@ HWTEST_F(DeviceManagerServiceTest, UnRegisterCallerAppId_002, testing::ext::Test EXPECT_EQ(DeviceManagerService::GetInstance().listener_, nullptr); } -HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_004, testing::ext::TestSize.Level0) -{ - std::string pkgName; - uint16_t subscribeId = 1; - std::string filterOptions; - int32_t ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeId, filterOptions); - EXPECT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); -} - -HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_005, testing::ext::TestSize.Level0) -{ - DeletePermission(); - std::string pkgName = "com.ohos.test"; - uint16_t subscribeId = 1; - std::string filterOptions; - int32_t ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeId, filterOptions); - EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); -} - -HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_006, testing::ext::TestSize.Level0) -{ - std::string pkgName; - uint16_t subscribeId = 1; - std::string filterOptions = "filterOptions"; - int32_t ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeId, filterOptions); - EXPECT_NE(ret, ERR_DM_FAILED); -} - HWTEST_F(DeviceManagerServiceTest, BindDevice_001, testing::ext::TestSize.Level0) { std::string pkgName; @@ -2231,24 +2108,6 @@ HWTEST_F(DeviceManagerServiceTest, SetDnPolicy_003, testing::ext::TestSize.Level EXPECT_NE(ret, DM_OK); } -/** - * @tc.name: StartDeviceDiscovery_007 - * @tc.desc: Call StartDeviceDiscovery twice with pkgName not null and flag bit not false and return - * ERR_DM_DISCOVERY_REPEATED - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(DeviceManagerServiceTest, StartDeviceDiscovery_007, testing::ext::TestSize.Level0) -{ - std::string pkgName = "com.ohos.test7"; - uint16_t subscribeId = 1; - std::string extra = "test"; - DeviceManagerService::GetInstance().InitDMServiceListener(); - int ret = DeviceManagerService::GetInstance().StartDeviceDiscovery(pkgName, subscribeId, extra); - EXPECT_NE(ret, DM_OK); - DeviceManagerService::GetInstance().UninitDMServiceListener(); -} - HWTEST_F(DeviceManagerServiceTest, DestroyPinHolder_003, testing::ext::TestSize.Level0) { std::string pkgName = ""; diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 610bea99d..7f707abf2 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -1333,7 +1333,7 @@ HWTEST_F(DeviceManagerServiceImplTest, GetAppTrustDeviceIdList_003, testing::ext if (deviceManagerServiceImpl_ == nullptr) { deviceManagerServiceImpl_ = std::make_shared(); } - auto ret = deviceManagerServiceImpl_->GetAppTrustDeviceIdList(pkgname, 0); + auto ret = deviceManagerServiceImpl_->GetAppTrustDeviceIdList(pkgname, 100); EXPECT_EQ(ret.empty(), true); } diff --git a/test/unittest/UTTest_device_manager_service_listener.cpp b/test/unittest/UTTest_device_manager_service_listener.cpp index c8d1de00c..392e34b7b 100644 --- a/test/unittest/UTTest_device_manager_service_listener.cpp +++ b/test/unittest/UTTest_device_manager_service_listener.cpp @@ -59,7 +59,6 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceStateChange_001, testing::ext ProcessInfo processInfo; processInfo.pkgName = "com.ohos.helloworld"; processInfo.userId = 100; - processInfo.tokenId = 123456; DmDeviceState state = DEVICE_STATE_ONLINE; DmDeviceInfo info = { .deviceId = "asdad", @@ -83,7 +82,6 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceStateChange_002, testing::ext ProcessInfo processInfo; processInfo.pkgName = "ohos.distributedhardware.devicemanager"; processInfo.userId = 100; - processInfo.tokenId = 123456; DmDeviceState state = DEVICE_STATE_OFFLINE; DmDeviceInfo info = { .deviceId = "asdad", @@ -103,12 +101,14 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceStateChange_002, testing::ext HWTEST_F(DeviceManagerServiceListenerTest, OnAuthResult_001, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; std::string deviceId = "dkdkd"; std::string token = "kdkddk"; int32_t status = 3; int32_t reason = 2006; - listener_->OnAuthResult(pkgName, deviceId, token, status, reason); + ProcessInfo processInfo; + processInfo.pkgName = "com.ohos.helloworld"; + processInfo.userId = 100; + listener_->OnAuthResult(processInfo, deviceId, token, status, reason); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -121,12 +121,14 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnAuthResult_001, testing::ext::TestS HWTEST_F(DeviceManagerServiceListenerTest, OnAuthResult_002, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; std::string deviceId = "dkdkd"; std::string token = "kdkddk"; int32_t status = 8; int32_t reason = 2006; - listener_->OnAuthResult(pkgName, deviceId, token, status, reason); + ProcessInfo processInfo; + processInfo.pkgName = "com.ohos.helloworld"; + processInfo.userId = 100; + listener_->OnAuthResult(processInfo, deviceId, token, status, reason); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -139,12 +141,14 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnAuthResult_002, testing::ext::TestS HWTEST_F(DeviceManagerServiceListenerTest, OnAuthResult_003, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; std::string deviceId = "dkdkd"; std::string token = "kdkddk"; int32_t status = -1; int32_t reason = 2006; - listener_->OnAuthResult(pkgName, deviceId, token, status, reason); + ProcessInfo processInfo; + processInfo.pkgName = "com.ohos.helloworld"; + processInfo.userId = 100; + listener_->OnAuthResult(processInfo, deviceId, token, status, reason); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -159,13 +163,15 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceFound_001, testing::ext::Test { std::shared_ptr listener_ = std::make_shared(); std::string pkgName = "com.ohos.helloworld"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; DmDeviceInfo info = { .deviceId = "dkdkd", .deviceName = "asda", .deviceTypeId = 1, }; uint16_t subscribeId = 1; - listener_->OnDeviceFound(pkgName, subscribeId, info); + listener_->OnDeviceFound(processInfo, subscribeId, info); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -180,9 +186,11 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDiscoveryFailed_001, testing::ext:: std::shared_ptr listener_ = std::make_shared(); std::string pkgName = "com.ohos.helloworld"; std::string deviceId = "dkdkd"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; uint16_t subscribeId = 1; int32_t failedReason = 1; - listener_->OnDiscoveryFailed(pkgName, subscribeId, failedReason); + listener_->OnDiscoveryFailed(processInfo, subscribeId, failedReason); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -197,7 +205,9 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDiscoverySuccess_001, testing::ext: std::shared_ptr listener_ = std::make_shared(); std::string pkgName = "com.ohos.helloworld"; uint16_t subscribeId = 1; - listener_->OnDiscoverySuccess(pkgName, subscribeId); + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + listener_->OnDiscoverySuccess(processInfo, subscribeId); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -243,9 +253,11 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnPublishResult_002, testing::ext::Te HWTEST_F(DeviceManagerServiceListenerTest, OnUiCall_001, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; std::string paramJson = "ahaha"; - listener_->OnUiCall(pkgName, paramJson); + ProcessInfo processInfo; + processInfo.pkgName = "com.ohos.helloworld"; + processInfo.userId = 100; + listener_->OnUiCall(processInfo, paramJson); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -258,9 +270,11 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnCredentialResult_001, testing::ext: { std::shared_ptr listener_ = std::make_shared(); std::string pkgName = "com.ohos.helloworld"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; int32_t action = 1; std::string resultInfo = "resultInfo"; - listener_->OnCredentialResult(pkgName, action, resultInfo); + listener_->OnCredentialResult(processInfo, action, resultInfo); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -272,12 +286,14 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnCredentialResult_001, testing::ext: HWTEST_F(DeviceManagerServiceListenerTest, OnBindResult_001, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; PeerTargetId targetId; int32_t result = 0; int32_t status = 1; std::string content = "content"; - listener_->OnBindResult(pkgName, targetId, result, status, content); + ProcessInfo processInfo; + processInfo.pkgName = "com.ohos.helloworld"; + processInfo.userId = 100; + listener_->OnBindResult(processInfo, targetId, result, status, content); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -289,12 +305,14 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnBindResult_001, testing::ext::TestS HWTEST_F(DeviceManagerServiceListenerTest, OnBindResult_002, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; PeerTargetId targetId; int32_t result = 0; int32_t status = 8; std::string content = "content"; - listener_->OnBindResult(pkgName, targetId, result, status, content); + ProcessInfo processInfo; + processInfo.pkgName = "com.ohos.helloworld"; + processInfo.userId = 100; + listener_->OnBindResult(processInfo, targetId, result, status, content); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -306,12 +324,14 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnBindResult_002, testing::ext::TestS HWTEST_F(DeviceManagerServiceListenerTest, OnBindResult_003, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; PeerTargetId targetId; int32_t result = 0; int32_t status = -1; std::string content = "content"; - listener_->OnBindResult(pkgName, targetId, result, status, content); + ProcessInfo processInfo; + processInfo.pkgName = "com.ohos.helloworld"; + processInfo.userId = 100; + listener_->OnBindResult(processInfo, targetId, result, status, content); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -323,11 +343,13 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnBindResult_003, testing::ext::TestS HWTEST_F(DeviceManagerServiceListenerTest, OnUnbindResult_001, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; PeerTargetId targetId; int32_t result = 0; std::string content = "content"; - listener_->OnUnbindResult(pkgName, targetId, result, content); + ProcessInfo processInfo; + processInfo.pkgName = "com.ohos.helloworld"; + processInfo.userId = 100; + listener_->OnUnbindResult(processInfo, targetId, result, content); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -350,21 +372,6 @@ HWTEST_F(DeviceManagerServiceListenerTest, ConvertDeviceInfoToDeviceBasicInfo_00 EXPECT_EQ(deviceBasicInfo.deviceTypeId, 1); } -/** - * @tc.name: OnDeviceFound_002 - * @tc.desc: OnDeviceFound, construct a dummy listener, pass in pkgName, subscribeId, DmDeviceInfo - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceFound_002, testing::ext::TestSize.Level0) -{ - std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; - uint16_t subscribeId = 1; - DmDeviceBasicInfo info; - listener_->OnDeviceFound(pkgName, subscribeId, info); - EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); -} - /** * @tc.name: OnPinHolderCreate_001 * @tc.type: FUNC @@ -373,11 +380,13 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDeviceFound_002, testing::ext::Test HWTEST_F(DeviceManagerServiceListenerTest, OnPinHolderCreate_001, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; std::string deviceId = "153123"; DmPinType pinType = static_cast(1); std::string payload = "payload"; - listener_->OnPinHolderCreate(pkgName, deviceId, pinType, payload); + ProcessInfo processInfo; + processInfo.userId = 100; + processInfo.pkgName = "com.ohos.helloworld"; + listener_->OnPinHolderCreate(processInfo, deviceId, pinType, payload); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -389,10 +398,12 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnPinHolderCreate_001, testing::ext:: HWTEST_F(DeviceManagerServiceListenerTest, OnPinHolderDestroy_001, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; + ProcessInfo processInfo; + processInfo.userId = 100; + processInfo.pkgName = "com.ohos.helloworld"; DmPinType pinType = static_cast(1); std::string payload = "payload"; - listener_->OnPinHolderDestroy(pkgName, pinType, payload); + listener_->OnPinHolderDestroy(processInfo, pinType, payload); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -404,9 +415,11 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnPinHolderDestroy_001, testing::ext: HWTEST_F(DeviceManagerServiceListenerTest, OnCreateResult_001, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; + ProcessInfo processInfo; + processInfo.userId = 100; + processInfo.pkgName = "com.ohos.helloworld"; int32_t result = 0; - listener_->OnCreateResult(pkgName, result); + listener_->OnCreateResult(processInfo, result); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -418,9 +431,11 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnCreateResult_001, testing::ext::Tes HWTEST_F(DeviceManagerServiceListenerTest, OnDestroyResult_001, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; + ProcessInfo processInfo; + processInfo.userId = 100; + processInfo.pkgName = "com.ohos.helloworld"; int32_t result = 0; - listener_->OnDestroyResult(pkgName, result); + listener_->OnDestroyResult(processInfo, result); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } @@ -432,11 +447,13 @@ HWTEST_F(DeviceManagerServiceListenerTest, OnDestroyResult_001, testing::ext::Te HWTEST_F(DeviceManagerServiceListenerTest, OnPinHolderEvent_001, testing::ext::TestSize.Level0) { std::shared_ptr listener_ = std::make_shared(); - std::string pkgName = "com.ohos.helloworld"; + ProcessInfo processInfo; + processInfo.userId = 100; + processInfo.pkgName = "com.ohos.helloworld"; DmPinHolderEvent event = DmPinHolderEvent::CREATE_RESULT; int32_t result = 0; std::string content = "content"; - listener_->OnPinHolderEvent(pkgName, event, result, content); + listener_->OnPinHolderEvent(processInfo, event, result, content); EXPECT_EQ(listener_->alreadyOnlinePkgName_.empty(), true); } } // namespace diff --git a/test/unittest/UTTest_device_manager_service_two.cpp b/test/unittest/UTTest_device_manager_service_two.cpp index 9f1ac7520..907d1cc3a 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -81,19 +81,6 @@ HWTEST_F(DeviceManagerServiceTest, GetDeviceInfo_201, testing::ext::TestSize.Lev EXPECT_EQ(ret, ERR_DM_POINT_NULL); } -/** - * @tc.name: GetLocalDeviceInfo_201 - * @tc.type: FUNC - */ -HWTEST_F(DeviceManagerServiceTest, StopDeviceDiscovery_201, testing::ext::TestSize.Level0) -{ - DeletePermission(); - std::string pkgName = "pkgName"; - uint16_t subscribeId = 111; - int32_t ret = DeviceManagerService::GetInstance().StopDeviceDiscovery(pkgName, subscribeId); - EXPECT_EQ(ret, ERR_DM_NO_PERMISSION); -} - /** * @tc.name: RegisterUiStateCallback_001 * @tc.type: FUNC @@ -244,11 +231,10 @@ HWTEST_F(DeviceManagerServiceTest, CheckIsSameAccount_202, testing::ext::TestSiz HWTEST_F(DeviceManagerServiceTest, InitAccountInfo_201, testing::ext::TestSize.Level0) { int32_t userId = 100; - int32_t userId1 = 101; std::string commonEventType = "usual.event.USER_SWITCHED"; - DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, userId1); + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, 101); commonEventType = "common.event.HWID_LOGIN"; - DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, userId1); + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, 101); int32_t ret = DeviceManagerService::GetInstance().InitAccountInfo(); EXPECT_EQ(ret, DM_OK); } diff --git a/test/unittest/UTTest_dm_pin_holder.cpp b/test/unittest/UTTest_dm_pin_holder.cpp index f66bfbe80..fa302b097 100644 --- a/test/unittest/UTTest_dm_pin_holder.cpp +++ b/test/unittest/UTTest_dm_pin_holder.cpp @@ -31,8 +31,6 @@ #include "ipc_rsp.h" #include "ipc_set_useroperation_req.h" #include "ipc_skeleton.h" -#include "ipc_start_discovery_req.h" -#include "ipc_stop_discovery_req.h" #include "ipc_publish_req.h" #include "ipc_unpublish_req.h" #include "ipc_unauthenticate_device_req.h" @@ -191,7 +189,8 @@ HWTEST_F(DmPinHolderTest, CreatePinholder_102, testing::ext::TestSize.Level0) std::string payload; std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); - pinHolder->registerPkgName_ = ""; + pinHolder->processInfo_.pkgName = ""; + pinHolder->processInfo_.userId = 100; int32_t ret = pinHolder->CreatePinHolder(packName, targetId, pinType, payload); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -204,7 +203,8 @@ HWTEST_F(DmPinHolderTest, CreatePinholder_103, testing::ext::TestSize.Level0) std::string payload; std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); - pinHolder->registerPkgName_ = "dmtest"; + pinHolder->processInfo_.pkgName = "dmtest"; + pinHolder->processInfo_.userId = 100; int32_t ret = pinHolder->CreatePinHolder(packName, targetId, pinType, payload); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -223,7 +223,8 @@ HWTEST_F(DmPinHolderTest, CreatePinholder_105, testing::ext::TestSize.Level0) std::string payload; std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); - pinHolder->registerPkgName_ = packName; + pinHolder->processInfo_.pkgName = packName; + pinHolder->processInfo_.userId = 100; int32_t ret = pinHolder->CreatePinHolder(packName, targetId, pinType, payload); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -242,7 +243,8 @@ HWTEST_F(DmPinHolderTest, CreatePinholder_106, testing::ext::TestSize.Level0) std::string payload; std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); - pinHolder->registerPkgName_ = packName; + pinHolder->processInfo_.pkgName = packName; + pinHolder->processInfo_.userId = 100; pinHolder->listener_ = nullptr; int32_t ret = pinHolder->CreatePinHolder(packName, targetId, pinType, payload); ASSERT_EQ(ret, ERR_DM_FAILED); @@ -262,7 +264,8 @@ HWTEST_F(DmPinHolderTest, CreatePinholder_107, testing::ext::TestSize.Level0) std::string payload; std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); - pinHolder->registerPkgName_ = packName; + pinHolder->processInfo_.pkgName = packName; + pinHolder->processInfo_.userId = 100; pinHolder->session_ = nullptr; int32_t ret = pinHolder->CreatePinHolder(packName, targetId, pinType, payload); ASSERT_EQ(ret, ERR_DM_FAILED); @@ -282,7 +285,8 @@ HWTEST_F(DmPinHolderTest, CreatePinholder_108, testing::ext::TestSize.Level0) std::string payload; std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); - pinHolder->registerPkgName_ = packName; + pinHolder->processInfo_.pkgName = packName; + pinHolder->processInfo_.userId = 100; pinHolder->sourceState_ = SOURCE_CREATE; int32_t ret = pinHolder->CreatePinHolder(packName, targetId, pinType, payload); ASSERT_EQ(ret, ERR_DM_FAILED); @@ -337,7 +341,8 @@ HWTEST_F(DmPinHolderTest, DestroyPinHolder_103, testing::ext::TestSize.Level0) std::string payload; std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); - pinHolder->registerPkgName_ = ""; + pinHolder->processInfo_.pkgName = ""; + pinHolder->processInfo_.userId = 100; int32_t ret = pinHolder->DestroyPinHolder(packName, targetId, pinType, payload); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -355,7 +360,8 @@ HWTEST_F(DmPinHolderTest, DestroyPinHolder_104, testing::ext::TestSize.Level0) std::string payload; std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); - pinHolder->registerPkgName_ = "dmtest"; + pinHolder->processInfo_.pkgName = "dmtest"; + pinHolder->processInfo_.userId = 100; int32_t ret = pinHolder->DestroyPinHolder(packName, targetId, pinType, payload); ASSERT_EQ(ret, ERR_DM_FAILED); } @@ -373,7 +379,8 @@ HWTEST_F(DmPinHolderTest, DestroyPinHolder_105, testing::ext::TestSize.Level0) std::string payload; std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); - pinHolder->registerPkgName_ = packName; + pinHolder->processInfo_.pkgName = packName; + pinHolder->processInfo_.userId = 100; int32_t ret = pinHolder->DestroyPinHolder(packName, targetId, pinType, payload); ASSERT_EQ(ret, ERR_DM_INPUT_PARA_INVALID); } @@ -391,7 +398,8 @@ HWTEST_F(DmPinHolderTest, DestroyPinHolder_106, testing::ext::TestSize.Level0) std::string payload; std::shared_ptr listener = std::make_shared(); std::shared_ptr pinHolder = std::make_shared(listener); - pinHolder->registerPkgName_ = packName; + pinHolder->processInfo_.pkgName = packName; + pinHolder->processInfo_.userId = 100; pinHolder->sessionId_ = 0; pinHolder->sourceState_ = SOURCE_DESTROY; pinHolder->listener_ = std::make_shared(); diff --git a/test/unittest/UTTest_dm_pin_holder.h b/test/unittest/UTTest_dm_pin_holder.h index 8cd1e8eca..874e2e363 100644 --- a/test/unittest/UTTest_dm_pin_holder.h +++ b/test/unittest/UTTest_dm_pin_holder.h @@ -69,30 +69,23 @@ public: (void)info; } - void OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, const DmDeviceInfo &info) override + void OnDeviceFound(const ProcessInfo &processInfo, uint16_t subscribeId, const DmDeviceInfo &info) override { - (void)pkgName; - (void)subscribeId; - (void)info; - } - - void OnDeviceFound(const std::string &pkgName, uint16_t subscribeId, DmDeviceBasicInfo &info) override - { - (void)pkgName; + (void)processInfo; (void)subscribeId; (void)info; } - void OnDiscoveryFailed(const std::string &pkgName, uint16_t subscribeId, int32_t failedReason) override + void OnDiscoveryFailed(const ProcessInfo &processInfo, uint16_t subscribeId, int32_t failedReason) override { - (void)pkgName; + (void)processInfo; (void)subscribeId; (void)failedReason; } - void OnDiscoverySuccess(const std::string &pkgName, int32_t subscribeId) override + void OnDiscoverySuccess(const ProcessInfo &processInfo, int32_t subscribeId) override { - (void)pkgName; + (void)processInfo; (void)subscribeId; } @@ -103,80 +96,80 @@ public: (void)publishResult; } - void OnAuthResult(const std::string &pkgName, const std::string &deviceId, const std::string &token, int32_t status, + void OnAuthResult(const ProcessInfo &processInfo, const std::string &deviceId, const std::string &token, int32_t status, int32_t reason) override { - (void)pkgName; + (void)processInfo; (void)deviceId; (void)token; (void)status; (void)reason; } - void OnUiCall(std::string &pkgName, std::string ¶mJson) override + void OnUiCall(const ProcessInfo &processInfo, std::string ¶mJson) override { - (void)pkgName; + (void)processInfo; (void)paramJson; } - void OnCredentialResult(const std::string &pkgName, int32_t action, const std::string &resultInfo) override + void OnCredentialResult(const ProcessInfo &processInfo, int32_t action, const std::string &resultInfo) override { - (void)pkgName; + (void)processInfo; (void)action; (void)resultInfo; } - void OnBindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, int32_t status, + void OnBindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, int32_t status, std::string content) override { - (void)pkgName; + (void)processInfo; (void)targetId; (void)result; (void)status; (void)content; } - void OnUnbindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, + void OnUnbindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, std::string content) override { - (void)pkgName; + (void)processInfo; (void)targetId; (void)result; (void)content; } - void OnPinHolderCreate(const std::string &pkgName, const std::string &deviceId, DmPinType pinType, + void OnPinHolderCreate(const ProcessInfo &processInfo, const std::string &deviceId, DmPinType pinType, const std::string &payload) override { - (void)pkgName; + (void)processInfo; (void)deviceId; (void)pinType; (void)payload; } - void OnPinHolderDestroy(const std::string &pkgName, DmPinType pinType, const std::string &payload) override + void OnPinHolderDestroy(const ProcessInfo &processInfo, DmPinType pinType, const std::string &payload) override { - (void)pkgName; + (void)processInfo; (void)pinType; (void)payload; } - void OnCreateResult(const std::string &pkgName, int32_t result) override + void OnCreateResult(const ProcessInfo &processInfo, int32_t result) override { - (void)pkgName; + (void)processInfo; (void)result; } - void OnDestroyResult(const std::string &pkgName, int32_t result) override + void OnDestroyResult(const ProcessInfo &processInfo, int32_t result) override { - (void)pkgName; + (void)processInfo; (void)result; } - void OnPinHolderEvent(const std::string &pkgName, DmPinHolderEvent event, int32_t result, + void OnPinHolderEvent(const ProcessInfo &processInfo, DmPinHolderEvent event, int32_t result, const std::string &content) override { - (void)pkgName; + (void)processInfo; (void)event; (void)result; (void)content; @@ -195,9 +188,9 @@ public: (void)devInfo; } - void OnCredentialAuthStatus(const std::string &pkgName, uint16_t deviceTypeId, int32_t errcode) override + void OnCredentialAuthStatus(const ProcessInfo &processInfo, uint16_t deviceTypeId, int32_t errcode) override { - (void)pkgName; + (void)processInfo; (void)deviceTypeId; (void)errcode; } diff --git a/test/unittest/UTTest_ipc_client_server_proxy.cpp b/test/unittest/UTTest_ipc_client_server_proxy.cpp index ac258affd..5aed918cd 100644 --- a/test/unittest/UTTest_ipc_client_server_proxy.cpp +++ b/test/unittest/UTTest_ipc_client_server_proxy.cpp @@ -28,8 +28,6 @@ #include "ipc_def.h" #include "ipc_types.h" #include "ipc_set_useroperation_req.h" -#include "ipc_stop_discovery_req.h" -#include "ipc_start_discovery_req.h" namespace OHOS { namespace DistributedHardware { diff --git a/test/unittest/UTTest_ipc_cmd_parser_client.cpp b/test/unittest/UTTest_ipc_cmd_parser_client.cpp index e4bb68919..f8ed9f053 100644 --- a/test/unittest/UTTest_ipc_cmd_parser_client.cpp +++ b/test/unittest/UTTest_ipc_cmd_parser_client.cpp @@ -26,8 +26,6 @@ #include "ipc_register_listener_req.h" #include "ipc_get_info_by_network_req.h" #include "ipc_get_trustdevice_req.h" -#include "ipc_start_discovery_req.h" -#include "ipc_stop_discovery_req.h" #include "ipc_publish_req.h" #include "ipc_unpublish_req.h" #include "ipc_unauthenticate_device_req.h" @@ -130,12 +128,6 @@ HWTEST_F(IpcCmdParserClientTest, ReadResponseFunc_001, testing::ext::TestSize.Le ASSERT_EQ(ERR_DM_FAILED, TestReadResponseRspNull(cmdCode)); } -HWTEST_F(IpcCmdParserClientTest, ReadResponseFunc_003, testing::ext::TestSize.Level0) -{ - int32_t cmdCode = STOP_DEVICE_DISCOVER; - ASSERT_EQ(TestReadResponseRspNull(cmdCode), ERR_DM_FAILED); -} - HWTEST_F(IpcCmdParserClientTest, ReadResponseFunc_004, testing::ext::TestSize.Level0) { int32_t cmdCode = UNPUBLISH_DEVICE_DISCOVER; diff --git a/test/unittest/UTTest_ipc_cmd_parser_service.cpp b/test/unittest/UTTest_ipc_cmd_parser_service.cpp index 8bcddad18..d7970621f 100644 --- a/test/unittest/UTTest_ipc_cmd_parser_service.cpp +++ b/test/unittest/UTTest_ipc_cmd_parser_service.cpp @@ -45,8 +45,6 @@ #include "ipc_set_credential_req.h" #include "ipc_set_credential_rsp.h" #include "ipc_set_useroperation_req.h" -#include "ipc_start_discovery_req.h" -#include "ipc_stop_discovery_req.h" #include "ipc_unauthenticate_device_req.h" #include "ipc_unpublish_req.h" #include "nlohmann/json.hpp" @@ -912,62 +910,6 @@ HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_026, testing::ext::TestSize.Level ASSERT_EQ(ret, DM_OK); } -HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_027, testing::ext::TestSize.Level0) -{ - int32_t cmdCode = START_DEVICE_DISCOVER; - int32_t ret = ERR_DM_UNSUPPORTED_IPC_COMMAND; - MessageParcel data; - MessageParcel reply; - std::string pkgName = "ohos.dm.test"; - std::string extra = ""; - DmSubscribeInfo dmSubscribeInfo; - dmSubscribeInfo.subscribeId = 100; - data.WriteString(pkgName); - data.WriteString(extra); - data.WriteRawData(&dmSubscribeInfo, sizeof(DmSubscribeInfo)); - OnIpcCmdFunc ptr = GetIpcCmdFunc(cmdCode); - if (ptr) { - ret = ptr(data, reply); - } - ASSERT_EQ(ret, DM_OK); -} - -HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_028, testing::ext::TestSize.Level0) -{ - int32_t cmdCode = START_DEVICE_DISCOVERY; - int32_t ret = ERR_DM_UNSUPPORTED_IPC_COMMAND; - MessageParcel data; - MessageParcel reply; - std::string pkgName = "ohos.dm.test"; - std::string extra = ""; - uint16_t subscribeId = 100; - data.WriteString(pkgName); - data.WriteString(extra); - data.WriteUint16(subscribeId); - OnIpcCmdFunc ptr = GetIpcCmdFunc(cmdCode); - if (ptr) { - ret = ptr(data, reply); - } - ASSERT_EQ(ret, DM_OK); -} - -HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_029, testing::ext::TestSize.Level0) -{ - int32_t cmdCode = STOP_DEVICE_DISCOVER; - int32_t ret = ERR_DM_UNSUPPORTED_IPC_COMMAND; - MessageParcel data; - MessageParcel reply; - std::string pkgName = "ohos.dm.test"; - uint16_t subscribeId = 100; - data.WriteString(pkgName); - data.WriteUint16(subscribeId); - OnIpcCmdFunc ptr = GetIpcCmdFunc(cmdCode); - if (ptr) { - ret = ptr(data, reply); - } - ASSERT_EQ(ret, DM_OK); -} - HWTEST_F(IpcCmdParserServiceTest, OnIpcCmdFunc_030, testing::ext::TestSize.Level0) { int32_t cmdCode = PUBLISH_DEVICE_DISCOVER; diff --git a/test/unittest/UTTest_ipc_cmd_register.cpp b/test/unittest/UTTest_ipc_cmd_register.cpp index 6e20ac4c5..912b90eeb 100644 --- a/test/unittest/UTTest_ipc_cmd_register.cpp +++ b/test/unittest/UTTest_ipc_cmd_register.cpp @@ -24,8 +24,6 @@ #include "ipc_get_info_by_network_rsp.h" #include "ipc_get_info_by_network_req.h" #include "ipc_get_trustdevice_req.h" -#include "ipc_start_discovery_req.h" -#include "ipc_stop_discovery_req.h" #include "ipc_publish_req.h" #include "ipc_unpublish_req.h" #include "ipc_set_useroperation_req.h" @@ -280,44 +278,6 @@ HWTEST_F(IpcCmdRegisterTest, SetRequest_010, testing::ext::TestSize.Level0) ASSERT_EQ(ret, DM_OK); } -/** - * @tc.name: SetRequest_011 - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(IpcCmdRegisterTest, SetRequest_011, testing::ext::TestSize.Level0) -{ - int32_t cmdCode = START_DEVICE_DISCOVER; - MessageParcel data; - std::shared_ptr req = std::make_shared(); - std::string pkgName = "ohos.test"; - std::string extra = "1234"; - DmSubscribeInfo dmSubscribeInfo; - req->SetPkgName(pkgName); - req->SetExtra(extra); - req->SetSubscribeInfo(dmSubscribeInfo); - int ret = IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, data); - ASSERT_EQ(ret, DM_OK); -} - -/** - * @tc.name: SetRequest_012 - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(IpcCmdRegisterTest, SetRequest_012, testing::ext::TestSize.Level0) -{ - int32_t cmdCode = STOP_DEVICE_DISCOVER; - MessageParcel data; - std::shared_ptr req = std::make_shared(); - std::string pkgName = "ohos.test"; - uint16_t subscribeId = 12; - req->SetPkgName(pkgName); - req->SetSubscribeId(subscribeId); - int ret = IpcCmdRegister::GetInstance().SetRequest(cmdCode, req, data); - ASSERT_EQ(ret, DM_OK); -} - /** * @tc.name: SetRequest_013 * @tc.type: FUNC @@ -643,34 +603,6 @@ HWTEST_F(IpcCmdRegisterTest, ReadResponse_008, testing::ext::TestSize.Level0) ASSERT_EQ(ret, DM_OK); } -/** - * @tc.name: ReadResponse_009 - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(IpcCmdRegisterTest, ReadResponse_009, testing::ext::TestSize.Level0) -{ - int32_t cmdCode = START_DEVICE_DISCOVER; - MessageParcel reply; - std::shared_ptr rsp = std::make_shared(); - int ret = IpcCmdRegister::GetInstance().ReadResponse(cmdCode, reply, rsp); - ASSERT_EQ(ret, DM_OK); -} - -/** - * @tc.name: ReadResponse_010 - * @tc.type: FUNC - * @tc.require: AR000GHSJK - */ -HWTEST_F(IpcCmdRegisterTest, ReadResponse_010, testing::ext::TestSize.Level0) -{ - int32_t cmdCode = STOP_DEVICE_DISCOVER; - MessageParcel reply; - std::shared_ptr rsp = std::make_shared(); - int ret = IpcCmdRegister::GetInstance().ReadResponse(cmdCode, reply, rsp); - ASSERT_EQ(ret, DM_OK); -} - /** * @tc.name: ReadResponse_011 * @tc.type: FUNC diff --git a/test/unittest/UTTest_ipc_server_client_proxy.cpp b/test/unittest/UTTest_ipc_server_client_proxy.cpp index 46b1c3f5e..f37d754c0 100644 --- a/test/unittest/UTTest_ipc_server_client_proxy.cpp +++ b/test/unittest/UTTest_ipc_server_client_proxy.cpp @@ -95,13 +95,14 @@ HWTEST_F(IpcServerClientProxyTest, SendCmd_002, testing::ext::TestSize.Level0) int32_t cmdCode = SERVER_DEVICE_STATE_NOTIFY; // set pkgName not null std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; // set action not null int deviceState = 1; DmDeviceInfo deviceInfo; // 2. set remoteObject not nullptr sptr remoteObject = sptr(new IpcClientStub()); - ProcessInfo processInfo; - processInfo.pkgName = pkgName; IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -137,13 +138,14 @@ HWTEST_F(IpcServerClientProxyTest, SendCmd_003, testing::ext::TestSize.Level0) int32_t cmdCode = SERVER_DEVICE_FOUND; // set pkgName not null std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; // set action not null uint16_t subscribeId = 1; DmDeviceInfo dmDeviceInfo; // 2. set remoteObject not nullptr sptr remoteObject = sptr(new IpcClientStub()); - ProcessInfo processInfo; - processInfo.pkgName = pkgName; IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -179,13 +181,14 @@ HWTEST_F(IpcServerClientProxyTest, SendCmd_004, testing::ext::TestSize.Level0) int32_t cmdCode = SERVER_DISCOVER_FINISH; // set pkgName not null std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; // set action not null uint16_t subscribeId = 1; int32_t result = 1; // 2. set remoteObject not nullptr sptr remoteObject = sptr(new IpcClientStub()); - ProcessInfo processInfo; - processInfo.pkgName = pkgName; IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); @@ -221,13 +224,14 @@ HWTEST_F(IpcServerClientProxyTest, SendCmd_005, testing::ext::TestSize.Level0) int32_t cmdCode = SERVER_PUBLISH_FINISH; // set pkgName not null std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; // set action not null int32_t publishId = 1; int32_t result = 1; // 2. set remoteObject not nullptr sptr remoteObject = sptr(new IpcClientStub()); - ProcessInfo processInfo; - processInfo.pkgName = pkgName; IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); diff --git a/test/unittest/UTTest_ipc_server_listener.cpp b/test/unittest/UTTest_ipc_server_listener.cpp index eaafad6c5..e73bf2e5d 100644 --- a/test/unittest/UTTest_ipc_server_listener.cpp +++ b/test/unittest/UTTest_ipc_server_listener.cpp @@ -129,10 +129,11 @@ HWTEST_F(IpcServerListenerTest, SendRequest_003, testing::ext::TestSize.Level0) int32_t cmdCode = 9999; // set pkgName not null std::string pkgName = "com.ohos.test"; - // 2. set remoteObject not nullptr - sptr remoteObject = sptr(new IpcClientStub()); ProcessInfo processInfo; processInfo.pkgName = pkgName; + processInfo.userId = 100; + // 2. set remoteObject not nullptr + sptr remoteObject = sptr(new IpcClientStub()); IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); // set req not null std::shared_ptr req = std::make_shared(); @@ -164,11 +165,12 @@ HWTEST_F(IpcServerListenerTest, SendRequest_004, testing::ext::TestSize.Level0) int32_t cmdCode = 999; // set pkgName not null std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; // 2. set remoteObject nullptr sptr remoteObject = sptr(new IpcClientStub()); remoteObject = nullptr; - ProcessInfo processInfo; - processInfo.pkgName = pkgName; IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); // set req not null std::shared_ptr req = std::make_shared(); @@ -201,10 +203,11 @@ HWTEST_F(IpcServerListenerTest, SendRequest_005, testing::ext::TestSize.Level0) int32_t cmdCode = 9999; // set pkgName not null std::string pkgName = "com.ohos.test"; - // 2. set remoteObject nullptr - sptr remoteObject = sptr(new IpcClientStub()); ProcessInfo processInfo; processInfo.pkgName = pkgName; + processInfo.userId = 100; + // 2. set remoteObject nullptr + sptr remoteObject = sptr(new IpcClientStub()); IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); // set req not null std::shared_ptr req = std::make_shared(); @@ -236,10 +239,11 @@ HWTEST_F(IpcServerListenerTest, SendRequest_006, testing::ext::TestSize.Level0) int32_t cmdCode = 0; // set pkgName not null std::string pkgName = "com.ohos.test"; - // 2. set remoteObject nullptr - sptr remoteObject = sptr(new IpcClientStub()); ProcessInfo processInfo; processInfo.pkgName = pkgName; + processInfo.userId = 100; + // 2. set remoteObject nullptr + sptr remoteObject = sptr(new IpcClientStub()); IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); // set req not null std::shared_ptr req = std::make_shared(); @@ -271,10 +275,11 @@ HWTEST_F(IpcServerListenerTest, SendRequest_007, testing::ext::TestSize.Level0) int32_t cmdCode = -1; // set pkgName not null std::string pkgName = "com.ohos.test"; - // 2. set remoteObject nullptr - sptr remoteObject = sptr(new IpcClientStub()); ProcessInfo processInfo; processInfo.pkgName = pkgName; + processInfo.userId = 100; + // 2. set remoteObject nullptr + sptr remoteObject = sptr(new IpcClientStub()); IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); // set req not null std::shared_ptr req = std::make_shared(); diff --git a/test/unittest/UTTest_ipc_server_stub.cpp b/test/unittest/UTTest_ipc_server_stub.cpp index f0fec3f64..83bbb6c76 100644 --- a/test/unittest/UTTest_ipc_server_stub.cpp +++ b/test/unittest/UTTest_ipc_server_stub.cpp @@ -227,10 +227,11 @@ HWTEST_F(IpcServerStubTest, QueryServiceState_001, testing::ext::TestSize.Level0 HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_001, testing::ext::TestSize.Level0) { std::string pkgName = ""; - int ret = 0; - sptr listener = nullptr; ProcessInfo processInfo; processInfo.pkgName = pkgName; + processInfo.userId = 100; + int ret = 0; + sptr listener = nullptr; ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); ASSERT_EQ(ret, ERR_DM_POINT_NULL); } @@ -245,10 +246,11 @@ HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_001, testing::ext::Tes HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_002, testing::ext::TestSize.Level0) { std::string pkgName = "com.ohos.test"; - int ret = 0; - sptr listener = sptr(new IpcClientStub()); ProcessInfo processInfo; processInfo.pkgName = pkgName; + processInfo.userId = 100; + int ret = 0; + sptr listener = sptr(new IpcClientStub()); ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); ASSERT_EQ(ret, DM_OK); } @@ -263,10 +265,11 @@ HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_002, testing::ext::Tes HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_003, testing::ext::TestSize.Level0) { std::string pkgName = ""; - int ret = 0; - sptr listener = sptr(new IpcClientStub()); ProcessInfo processInfo; processInfo.pkgName = pkgName; + processInfo.userId = 100; + int ret = 0; + sptr listener = sptr(new IpcClientStub()); ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); ASSERT_EQ(ret, ERR_DM_POINT_NULL); } @@ -283,11 +286,12 @@ HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_004, testing::ext::Tes { // 1. Set PkgName is com.ohos.test std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; int ret = 0; sptr listener = sptr(new IpcClientStub()); // 2. Call IpcServerStub RegisterDeviceManagerListener with param - ProcessInfo processInfo; - processInfo.pkgName = pkgName; ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is DM_OK ASSERT_EQ(ret, DM_OK); @@ -309,12 +313,13 @@ HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_005, testing::ext::Tes { // 1. Set PkgName is com.ohos.test std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; int ret = 0; int result = 0; sptr listener = sptr(new IpcClientStub()); // 2. Call IpcServerStub RegisterDeviceManagerListener with param - ProcessInfo processInfo; - processInfo.pkgName = pkgName; ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is DM_OK ASSERT_EQ(ret, DM_OK); @@ -360,10 +365,11 @@ HWTEST_F(IpcServerStubTest, UnRegisterDeviceManagerListener_002, testing::ext::T { // 1. Set PkgName is com.ohos.test std::string pkgName = "com.ohos.test"; - int ret = 0; - sptr listener = sptr(new IpcClientStub()); ProcessInfo processInfo; processInfo.pkgName = pkgName; + processInfo.userId = 100; + int ret = 0; + sptr listener = sptr(new IpcClientStub()); // 2. Call IpcServerStub RegisterDeviceManagerListener with param ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is DM_OK @@ -387,10 +393,11 @@ HWTEST_F(IpcServerStubTest, UnRegisterDeviceManagerListener_003, testing::ext::T { // 1. Set pkgName is com.ohos.test std::string pkgName = "com.ohos.test"; - int ret = 0; - // 2. Call IpcServerStub UnRegisterDeviceManagerListener ProcessInfo processInfo; processInfo.pkgName = pkgName; + processInfo.userId = 100; + int ret = 0; + // 2. Call IpcServerStub UnRegisterDeviceManagerListener ret = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); // 3. check ret is DM_OK ASSERT_EQ(ret, DM_OK); @@ -412,6 +419,7 @@ HWTEST_F(IpcServerStubTest, UnRegisterDeviceManagerListener_004, testing::ext::T std::string pkgName = "com.ohos.test1"; ProcessInfo processInfo; processInfo.pkgName = pkgName; + processInfo.userId = 100; int ret = 0; sptr listener = sptr(new IpcClientStub()); // 2. Call IpcServerStub RegisterDeviceManagerListener with param @@ -443,20 +451,19 @@ HWTEST_F(IpcServerStubTest, UnRegisterDeviceManagerListener_005, testing::ext::T { // 1. Set PkgName is com.ohos.test std::string pkgName = "com.ohos.test2"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; int ret = 0; sptr listener = sptr(new IpcClientStub()); // 2. Call IpcServerStub RegisterDeviceManagerListener with param - ProcessInfo processInfo; - processInfo.pkgName = pkgName; ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is DM_OK ASSERT_EQ(ret, DM_OK); int result = 0; // 4. Call IpcServerStub UnRegisterDeviceManagerListener std::string testPkgName = "com.test"; - ProcessInfo processInfo1; - processInfo1.pkgName = testPkgName; - result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo1); + result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); // 5. check ret is DM_OK ASSERT_EQ(result, DM_OK); IpcServerStub::GetInstance().appRecipient_.erase(processInfo); @@ -547,19 +554,17 @@ HWTEST_F(IpcServerStubTest, GetDmListener_003, testing::ext::TestSize.Level0) { // 1. Set pkgName is com.ohos.test std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; int result = 0; sptr listener = sptr(new IpcClientStub()); // 2. Call IpcServerStub RegisterDeviceManagerListener with param - ProcessInfo processInfo; - processInfo.pkgName = "test"; result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is DM_OK ASSERT_EQ(result, DM_OK); sptr ret = nullptr; // 2. Call IpcServerStub UnRegisterDeviceManagerListener - ProcessInfo processInfo1; - processInfo1.pkgName = "test"; - ret = IpcServerStub::GetInstance().GetDmListener(processInfo1); + ret = IpcServerStub::GetInstance().GetDmListener(processInfo); // 3. check ret is DM_OK ASSERT_EQ(ret, nullptr); } @@ -576,11 +581,11 @@ HWTEST_F(IpcServerStubTest, GetDmListener_004, testing::ext::TestSize.Level0) { // 1. Set pkgName is null std::string pkgName = ""; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; int result = 0; sptr listener = sptr(new IpcClientStub()); // 2. Call IpcServerStub RegisterDeviceManagerListener with param - ProcessInfo processInfo; - processInfo.pkgName = ""; result = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is ERR_DM_POINT_NULL ASSERT_EQ(result, ERR_DM_POINT_NULL); diff --git a/test/unittest/mock/ipc_server_listener.h b/test/unittest/mock/ipc_server_listener.h index d13d77a6c..74d538f59 100644 --- a/test/unittest/mock/ipc_server_listener.h +++ b/test/unittest/mock/ipc_server_listener.h @@ -18,6 +18,7 @@ #include #include +#include #include "dm_device_info.h" #include "ipc_req.h" #include "ipc_rsp.h" @@ -43,6 +44,7 @@ public: * @tc.type: FUNC */ std::vector GetAllProcessInfo(); + std::set GetSystemSA(); std::shared_ptr req_; }; } // namespace DistributedHardware -- Gitee From 202f4e3c0fb361796a6749912d5608e7dcb10ba6 Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Thu, 7 Nov 2024 09:13:16 +0800 Subject: [PATCH 20/27] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E7=BB=91=E5=AE=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- utils/include/appInfo/lite/app_manager.h | 4 ++-- utils/include/appInfo/standard/app_manager.h | 4 ++-- utils/src/appInfo/lite/app_manager.cpp | 4 ++-- utils/src/appInfo/standard/app_manager.cpp | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/utils/include/appInfo/lite/app_manager.h b/utils/include/appInfo/lite/app_manager.h index dc6b24018..52dc07f81 100644 --- a/utils/include/appInfo/lite/app_manager.h +++ b/utils/include/appInfo/lite/app_manager.h @@ -31,8 +31,8 @@ public: int32_t GetAppIdByPkgName(const std::string &pkgName, std::string &appId); bool IsSystemSA(); int32_t GetCallerName(bool isSystemSA, std::string &callerName); - int32_t GetNativeTokenIdByName(std::string &processName, int64_t tokenId); - int32_t GetHapTokenIdByName(int32_t userId, std::string &bundleName, int32_t instIndex, int64_t tokenId); + int32_t GetNativeTokenIdByName(std::string &processName, int64_t &tokenId); + int32_t GetHapTokenIdByName(int32_t userId, std::string &bundleName, int32_t instIndex, int64_t &tokenId); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/utils/include/appInfo/standard/app_manager.h b/utils/include/appInfo/standard/app_manager.h index 828e5b123..8f19166a6 100644 --- a/utils/include/appInfo/standard/app_manager.h +++ b/utils/include/appInfo/standard/app_manager.h @@ -37,8 +37,8 @@ public: int32_t GetAppIdByPkgName(const std::string &pkgName, std::string &appId); bool IsSystemSA(); int32_t GetCallerName(bool isSystemSA, std::string &callerName); - int32_t GetNativeTokenIdByName(std::string &processName, int64_t tokenId); - int32_t GetHapTokenIdByName(int32_t userId, std::string &bundleName, int32_t instIndex, int64_t tokenId); + int32_t GetNativeTokenIdByName(std::string &processName, int64_t &tokenId); + int32_t GetHapTokenIdByName(int32_t userId, std::string &bundleName, int32_t instIndex, int64_t &tokenId); private: bool GetBundleManagerProxy(sptr &bundleManager); std::mutex appIdMapLock_; diff --git a/utils/src/appInfo/lite/app_manager.cpp b/utils/src/appInfo/lite/app_manager.cpp index 40e89b598..fd2aeb768 100644 --- a/utils/src/appInfo/lite/app_manager.cpp +++ b/utils/src/appInfo/lite/app_manager.cpp @@ -53,14 +53,14 @@ int32_t AppManager::GetCallerName(bool isSystemSA, std::string &callerName) (void)callerName; return DM_OK; } -int32_t AppManager::GetNativeTokenIdByName(std::string &processName, int64_t tokenId) +int32_t AppManager::GetNativeTokenIdByName(std::string &processName, int64_t &tokenId) { (void)processName; (void)tokenId; return DM_OK; } -int32_t AppManager::GetHapTokenIdByName(int32_t userId, std::string &bundleName, int32_t instIndex, int64_t tokenId) +int32_t AppManager::GetHapTokenIdByName(int32_t userId, std::string &bundleName, int32_t instIndex, int64_t &tokenId) { (void)userId; (void)bundleName; diff --git a/utils/src/appInfo/standard/app_manager.cpp b/utils/src/appInfo/standard/app_manager.cpp index 3bb47c8fb..aed6cd78d 100644 --- a/utils/src/appInfo/standard/app_manager.cpp +++ b/utils/src/appInfo/standard/app_manager.cpp @@ -184,7 +184,7 @@ int32_t AppManager::GetCallerName(bool isSystemSA, std::string &callerName) return DM_OK; } -int32_t AppManager::GetNativeTokenIdByName(std::string &processName, int64_t tokenId) +int32_t AppManager::GetNativeTokenIdByName(std::string &processName, int64_t &tokenId) { AccessTokenID nativeTokenId = AccessTokenKit::GetNativeTokenId(processName); if (nativeTokenId == INVALID_TOKENID) { @@ -195,7 +195,7 @@ int32_t AppManager::GetNativeTokenIdByName(std::string &processName, int64_t tok return DM_OK; } -int32_t AppManager::GetHapTokenIdByName(int32_t userId, std::string &bundleName, int32_t instIndex, int64_t tokenId) +int32_t AppManager::GetHapTokenIdByName(int32_t userId, std::string &bundleName, int32_t instIndex, int64_t &tokenId) { auto hapTokenId = AccessTokenKit::GetHapTokenID(userId, bundleName, instIndex); if (hapTokenId == 0) { -- Gitee From f07e8c09ad5917c04486138721f32351d25e105d Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Thu, 7 Nov 2024 14:41:50 +0800 Subject: [PATCH 21/27] =?UTF-8?q?=E8=B0=83=E8=AF=95=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common/include/dm_anonymous.h | 1 + common/src/dm_anonymous.cpp | 17 ++++ .../src/deviceprofile_connector.cpp | 1 + .../native_cpp/include/device_manager_impl.h | 1 + .../include/notify/device_manager_notify.h | 1 + .../native_cpp/src/device_manager_impl.cpp | 41 ++++---- .../src/notify/device_manager_notify.cpp | 96 ++++++------------- .../src/authentication/dm_auth_manager.cpp | 7 +- .../src/device_manager_service_impl_lite.cpp | 2 +- 9 files changed, 79 insertions(+), 88 deletions(-) diff --git a/common/include/dm_anonymous.h b/common/include/dm_anonymous.h index 3a6d21396..69efd3c68 100644 --- a/common/include/dm_anonymous.h +++ b/common/include/dm_anonymous.h @@ -47,6 +47,7 @@ bool CompareVecNum(const std::vector &srcVecNum, const std::vector std::string GetAnonyInteger(const T value) { diff --git a/common/src/dm_anonymous.cpp b/common/src/dm_anonymous.cpp index e370b32b0..79e2b422f 100644 --- a/common/src/dm_anonymous.cpp +++ b/common/src/dm_anonymous.cpp @@ -297,5 +297,22 @@ std::string GetCallerPkgName(const std::string &pkgName) getline(stream, item, '#'); return item; } + +uint16_t GetSubscribeId(const std::string &pkgName) { + std::vector strVec; + size_t start = 0; + size_t end = pkgName.find("#"); + + while (end != std::string::npos) { + strVec.push_back(pkgName.substr(start, end - start)); + start = end + 1; + end = pkgName.find("#", start); + } + strVec.push_back(pkgName.substr(start)); + if (strVec.size() >= 2) { + return std::atoi(strVec.at(1).c_str()); + } + return 0; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index f422ec48a..4abb6bd8a 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -375,6 +375,7 @@ std::vector DeviceProfileConnector::GetP OHOS::DistributedHardware::ProcessInfo processInfo; processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); processInfo.userId = MultipleUserConnector::GetForegroundUser(); + processInfoVec.push_back(processInfo); } return processInfoVec; } diff --git a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h index 7228d508e..973a47fcc 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -416,6 +416,7 @@ private: int32_t RemovePublishCallback(const std::string &pkgName); int32_t CheckApiPermission(int32_t permissionLevel); void ConvertDeviceInfoToDeviceBasicInfo(const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo); + uint16_t GetSubscribeIdFromMap(const std::string &pkgName); private: #if !defined(__LITEOS_M__) diff --git a/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h b/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h index 70f50b5e2..046cb1c58 100644 --- a/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h +++ b/interfaces/inner_kits/native_cpp/include/notify/device_manager_notify.h @@ -120,6 +120,7 @@ public: int32_t authForm); void OnDeviceScreenStatus(const std::string &pkgName, const DmDeviceInfo &deviceInfo); void OnCredentialAuthStatus(const std::string &pkgName, uint16_t deviceTypeId, int32_t errcode); + std::shared_ptr GetDiscoveryCallback(const std::string &pkgName, uint16_t subscribeId); private: #if !defined(__LITEOS_M__) diff --git a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp index 3b777cd31..f00566fed 100644 --- a/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp +++ b/interfaces/inner_kits/native_cpp/src/device_manager_impl.cpp @@ -549,17 +549,14 @@ int32_t DeviceManagerImpl::StopDiscovering(const std::string &pkgName, if (discoverParam.find(PARAM_KEY_SUBSCRIBE_ID) != discoverParam.end()) { subscribeId = std::atoi((discoverParam.find(PARAM_KEY_SUBSCRIBE_ID)->second).c_str()); } - std::string discoveryFlag = ComposeStr(pkgName, subscribeId); - { - std::lock_guard autoLock(subMapLock); - if (pkgName2SubIdMap_.find(discoveryFlag) != pkgName2SubIdMap_.end()) { - subscribeId = pkgName2SubIdMap_[discoveryFlag]; - } + if (subscribeId == DM_INVALID_FLAG_ID) { + subscribeId = GetSubscribeIdFromMap(pkgName); } if (subscribeId == DM_INVALID_FLAG_ID) { LOGE("DeviceManagerImpl::StopDiscovering failed: cannot find pkgName in cache map."); return ERR_DM_INPUT_PARA_INVALID; } + std::string discoveryFlag = ComposeStr(pkgName, subscribeId); discoverParam.emplace(PARAM_KEY_SUBSCRIBE_ID, std::to_string(subscribeId)); std::string discParaStr = ConvertMapToJsonString(discoverParam); @@ -1896,19 +1893,18 @@ uint16_t DeviceManagerImpl::AddDiscoveryCallback(const std::string &pkgName, if (discoverParam.find(PARAM_KEY_SUBSCRIBE_ID) != discoverParam.end()) { subscribeId = std::atoi((discoverParam.find(PARAM_KEY_SUBSCRIBE_ID)->second).c_str()); } + if (subscribeId == DM_INVALID_FLAG_ID) { + subscribeId = GetSubscribeIdFromMap(pkgName); + } + if (subscribeId == DM_INVALID_FLAG_ID) { + subscribeId = GenRandUint(DM_MIN_RANDOM, DM_MAX_RANDOM); + } std::string discoveryFlag = ComposeStr(pkgName, subscribeId); { std::lock_guard autoLock(subMapLock); - { - auto iter = pkgName2SubIdMap_.find(pkgName); - if (iter == pkgName2SubIdMap_.end() && subscribeId != DM_INVALID_FLAG_ID) { - pkgName2SubIdMap_[discoveryFlag] = subscribeId; - } else if (iter == pkgName2SubIdMap_.end() && subscribeId == DM_INVALID_FLAG_ID) { - subscribeId = GenRandUint(DM_MIN_RANDOM, DM_MAX_RANDOM); - pkgName2SubIdMap_[discoveryFlag] = subscribeId; - } else if (iter != pkgName2SubIdMap_.end()) { - subscribeId = pkgName2SubIdMap_[discoveryFlag]; - } + auto iter = pkgName2SubIdMap_.find(discoveryFlag); + if (iter == pkgName2SubIdMap_.end()) { + pkgName2SubIdMap_[discoveryFlag] = subscribeId; } } DeviceManagerNotify::GetInstance().RegisterDiscoveryCallback(discoveryFlag, subscribeId, callback); @@ -2382,5 +2378,18 @@ int32_t DeviceManagerImpl::UnRegisterCredentialAuthStatusCallback(const std::str LOGI("Completed, pkgName: %{public}s", pkgName.c_str()); return DM_OK; } + +uint16_t DeviceManagerImpl::GetSubscribeIdFromMap(const std::string &pkgName) +{ + { + std::lock_guard autoLock(subMapLock); + for (auto &item : pkgName2SubIdMap_) { + if (item.first.find(pkgName) == 0) { + return GetSubscribeId(item.first); + } + } + } + return DM_INVALID_FLAG_ID; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp index fba6df1e4..827051359 100644 --- a/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp +++ b/interfaces/inner_kits/native_cpp/src/notify/device_manager_notify.cpp @@ -526,23 +526,7 @@ void DeviceManagerNotify::OnDeviceFound(const std::string &pkgName, uint16_t sub LOGE("Invalid parameter, pkgName is empty."); return; } - std::string discNoSubscribeId = ComposeStr(pkgName, DM_INVALID_FLAG_ID); - std::string discWithSubscribeId = ComposeStr(pkgName, subscribeId); - std::shared_ptr tempCbk; - { - std::lock_guard autoLock(lock_); - for (const auto &item : deviceDiscoveryCallbacks_) { - if (item.first != discNoSubscribeId && item.first != discWithSubscribeId) { - continue; - } - std::map> &discoverCallMap = - deviceDiscoveryCallbacks_[pkgName]; - auto iter = discoverCallMap.find(subscribeId); - if (iter != discoverCallMap.end()) { - tempCbk = iter->second; - } - } - } + std::shared_ptr tempCbk = GetDiscoveryCallback(pkgName, subscribeId); if (tempCbk == nullptr) { LOGE("OnDeviceFound error, registered device discovery callback is nullptr."); return; @@ -559,23 +543,7 @@ void DeviceManagerNotify::OnDeviceFound(const std::string &pkgName, uint16_t sub LOGE("Invalid parameter, pkgName is empty."); return; } - std::string discNoSubscribeId = ComposeStr(pkgName, DM_INVALID_FLAG_ID); - std::string discWithSubscribeId = ComposeStr(pkgName, subscribeId); - std::shared_ptr tempCbk; - { - std::lock_guard autoLock(lock_); - for (const auto &item : deviceDiscoveryCallbacks_) { - if (item.first != discNoSubscribeId && item.first != discWithSubscribeId) { - continue; - } - std::map> &discoverCallMap = - deviceDiscoveryCallbacks_[pkgName]; - auto iter = discoverCallMap.find(subscribeId); - if (iter != discoverCallMap.end()) { - tempCbk = iter->second; - } - } - } + std::shared_ptr tempCbk = GetDiscoveryCallback(pkgName, subscribeId); if (tempCbk == nullptr) { LOGE("OnDeviceFound error, registered device discovery callback is nullptr."); return; @@ -591,23 +559,7 @@ void DeviceManagerNotify::OnDiscoveryFailed(const std::string &pkgName, uint16_t } LOGI("DeviceManagerNotify::OnDiscoveryFailed in, pkgName:%{public}s, subscribeId %{public}d, failed" "reason %{public}d", pkgName.c_str(), (int32_t)subscribeId, failedReason); - std::string discNoSubscribeId = ComposeStr(pkgName, DM_INVALID_FLAG_ID); - std::string discWithSubscribeId = ComposeStr(pkgName, subscribeId); - std::shared_ptr tempCbk; - { - std::lock_guard autoLock(lock_); - for (const auto &item : deviceDiscoveryCallbacks_) { - if (item.first != discNoSubscribeId && item.first != discWithSubscribeId) { - continue; - } - std::map> &discoverCallMap = - deviceDiscoveryCallbacks_[pkgName]; - auto iter = discoverCallMap.find(subscribeId); - if (iter != discoverCallMap.end()) { - tempCbk = iter->second; - } - } - } + std::shared_ptr tempCbk = GetDiscoveryCallback(pkgName, subscribeId); if (tempCbk == nullptr) { LOGE("OnDiscoveryFailed error, registered device discovery callback is nullptr."); return; @@ -622,23 +574,7 @@ void DeviceManagerNotify::OnDiscoverySuccess(const std::string &pkgName, uint16_ return; } LOGI("PkgName:%{public}s, subscribeId:%{public}d.", GetAnonyString(pkgName).c_str(), subscribeId); - std::string discNoSubscribeId = ComposeStr(pkgName, DM_INVALID_FLAG_ID); - std::string discWithSubscribeId = ComposeStr(pkgName, subscribeId); - std::shared_ptr tempCbk; - { - std::lock_guard autoLock(lock_); - for (const auto &item : deviceDiscoveryCallbacks_) { - if (item.first != discNoSubscribeId && item.first != discWithSubscribeId) { - continue; - } - std::map> &discoverCallMap = - deviceDiscoveryCallbacks_[pkgName]; - auto iter = discoverCallMap.find(subscribeId); - if (iter != discoverCallMap.end()) { - tempCbk = iter->second; - } - } - } + std::shared_ptr tempCbk = GetDiscoveryCallback(pkgName, subscribeId); if (tempCbk == nullptr) { LOGE("OnDiscoverySuccess error, registered device discovery callback is nullptr."); return; @@ -1190,5 +1126,29 @@ void DeviceManagerNotify::OnCredentialAuthStatus(const std::string &pkgName, uin } tempCbk->OnCredentialAuthStatus(deviceTypeId, errcode); } + +std::shared_ptr DeviceManagerNotify::GetDiscoveryCallback(const std::string &pkgName, + uint16_t subscribeId) +{ + std::string discWithSubscribeId = ComposeStr(pkgName, subscribeId); + std::lock_guard autoLock(lock_); + auto iter = deviceDiscoveryCallbacks_.find(discWithSubscribeId); + if (iter != deviceDiscoveryCallbacks_.end()) { + auto subIter = iter->second.find(subscribeId); + if (subIter != iter->second.end()) { + return subIter->second; + } + return nullptr; + } + std::string discNoSubscribeId = ComposeStr(pkgName, DM_INVALID_FLAG_ID); + iter = deviceDiscoveryCallbacks_.find(discNoSubscribeId); + if (iter != deviceDiscoveryCallbacks_.end()) { + auto subIter = iter->second.find(DM_INVALID_FLAG_ID); + if (subIter != iter->second.end()) { + return subIter->second; + } + } + return nullptr; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index d1bcb4c5c..cc4a026ea 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -2123,9 +2123,7 @@ void DmAuthManager::ProcRespNegotiateExt(const int32_t &sessionId) remoteDeviceId_ = authResponseContext_->localDeviceId; authResponseContext_->remoteAccountId = authResponseContext_->localAccountId; authResponseContext_->remoteUserId = authResponseContext_->localUserId; - if (GetBinderInfo() != DM_OK) { - authResponseContext_->reply = ERR_DM_GET_CALLER_DATA_FAILED; - } + GetBinderInfo(); MultipleUserConnector::SetSwitchOldAccountId(authResponseContext_->localAccountId); MultipleUserConnector::SetSwitchOldUserId(authResponseContext_->localUserId); authResponseContext_->isIdenticalAccount = false; @@ -2531,6 +2529,7 @@ int32_t DmAuthManager::GetBinderInfo() { CHECK_NULL_RETURN(authResponseContext_, ERR_DM_POINT_NULL); if (authResponseContext_->bundleName.empty()) { + LOGI("bundleName is empty"); authResponseContext_->localUserId = MultipleUserConnector::GetCurrentAccountUserID(); authResponseContext_->localAccountId = MultipleUserConnector::GetOhosAccountId(); authResponseContext_->tokenId = authResponseContext_->remoteTokenId; @@ -2542,11 +2541,13 @@ int32_t DmAuthManager::GetBinderInfo() int32_t ret = AppManager::GetInstance(). GetNativeTokenIdByName(authResponseContext_->bundleName, authResponseContext_->tokenId); if (ret == DM_OK) { + LOGI("bundleName is sa"); return DM_OK; } ret = AppManager::GetInstance().GetHapTokenIdByName(authResponseContext_->localUserId, authResponseContext_->bundleName, 0, authResponseContext_->tokenId); if (ret != DM_OK) { + LOGI("get tokenId by bundleName failed %{public}s", GetAnonyString(authResponseContext_->bundleName).c_str()); authResponseContext_->tokenId = authResponseContext_->remoteTokenId; } return ret; diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index 24996f46d..740131561 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -515,7 +515,7 @@ void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devI void DeviceManagerServiceImpl::HandleUserSwitched(int32_t currentUserId, int32_t beforeUserId) { - (void)switchUserId; + (void)currentUserId; (void)beforeUserId; return; } -- Gitee From 3e3571263ff473c946dbfcbfa406957d04bb5fbf Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Fri, 8 Nov 2024 01:28:46 +0800 Subject: [PATCH 22/27] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=8F=91=E7=8E=B0?= =?UTF-8?q?=E5=9B=9E=E8=B0=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- .../include/deviceprofile_connector.h | 19 +- .../include/multiple_user_connector.h | 1 + .../src/deviceprofile_connector.cpp | 243 ++++++++++++------ .../src/multiple_user_connector.cpp | 16 ++ .../include/device_manager_service_impl.h | 6 +- .../device_manager_service_impl_lite.h | 5 +- .../src/device_manager_service_impl.cpp | 109 ++++++-- .../src/device_manager_service_impl_lite.cpp | 11 +- .../devicestate/dm_device_state_manager.cpp | 1 + .../service/include/device_manager_service.h | 2 +- .../include/device_manager_service_listener.h | 6 +- .../include/idevice_manager_service_impl.h | 5 +- .../service/src/device_manager_service.cpp | 39 +-- .../src/device_manager_service_listener.cpp | 33 ++- .../UTTest_dm_deviceprofile_connector.cpp | 36 +-- .../device_profile_connector_fuzzer.cpp | 3 +- 16 files changed, 347 insertions(+), 188 deletions(-) diff --git a/commondependency/include/deviceprofile_connector.h b/commondependency/include/deviceprofile_connector.h index 570adb65f..d336aa2d8 100644 --- a/commondependency/include/deviceprofile_connector.h +++ b/commondependency/include/deviceprofile_connector.h @@ -101,7 +101,6 @@ public: int32_t UpdateAccessControlList(int32_t userId, std::string &oldAccountId, std::string &newAccountId); std::unordered_map GetAppTrustDeviceList(const std::string &pkgName, const std::string &deviceId, int32_t userId); - DmOfflineParam GetOfflineParamFromAcl(std::string trustDeviceId, std::string requestDeviceId); std::vector GetBindTypeByPkgName(std::string pkgName, std::string requestDeviceId, std::string trustUdid); std::vector SyncAclByBindType(std::string pkgName, std::vector bindTypeVec, @@ -111,8 +110,8 @@ public: void DeleteAclForUserRemoved(int32_t userId); DmOfflineParam DeleteAccessControlList(const std::string &pkgName, const std::string &localDeviceId, const std::string &remoteDeviceId, int32_t bindLevel); - std::vector GetProcessInfoFromAcl(std::string &localDeviceId, - std::string &targetDeviceId); + std::vector GetProcessInfoFromAclByUserId(const std::string &localDeviceId, + const std::string &targetDeviceId, int32_t userId); bool CheckIdenticalAccount(int32_t userId, const std::string &accountId); bool CheckSrcDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId); bool CheckSinkDevIdInAclForDevBind(const std::string &pkgName, const std::string &deviceId); @@ -129,7 +128,7 @@ public: void DeleteAccessControlList(const std::string &udid); int32_t GetBindLevel(const std::string &pkgName, const std::string &localUdid, const std::string &udid, uint64_t &tokenId); - std::map GetDeviceIdAndBindType(int32_t userId, const std::string &localUdid); + std::map GetDeviceIdAndBindLevel(std::vector userIds, const std::string &localUdid); std::map GetDeviceIdAndBindType(int32_t userId, const std::string &accountId, const std::string &localUdid); int32_t HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, @@ -140,6 +139,12 @@ public: std::vector GetAllAccessControlProfile(); void DeleteAccessControlById(int64_t accessControlId); int32_t HandleUserSwitched(const std::string &localUdid, int32_t currentUserId, int32_t beforeUserId); + void HandleSyncForegroundUserIdEvent(const std::vector &remoteUserIds, const std::string &remoteUdid, + const std::vector &localUserIds, std::string &localUdid); + std::vector GetOfflineProcessInfo(const std::vector &localUserIds, std::string &localUdid, + const std::vector &remoteUserIds, const std::string &remoteUdid); + std::vector GetOnlineProcessInfo(const std::vector &localUserIds, std::string &localUdid, + const std::vector &remoteUserIds, const std::string &remoteUdid, int32_t &bindLevel); private: int32_t HandleDmAuthForm(DistributedDeviceProfile::AccessControlProfile profiles, DmDiscoveryInfo discoveryInfo); @@ -162,9 +167,9 @@ private: void DeleteServiceBindLevel(DmOfflineParam &offlineParam, const std::string &pkgName, const std::vector &profiles, const std::string &localUdid, const std::string &remoteUdid); - void UpdateBindType(const std::string &udid, int32_t bindType, std::map &deviceMap); - std::vector FilterAclProfileByUserId(const std::string &localUdid, - const std::string &remoteUdid, const std::vector &profiles); + void UpdateBindType(const std::string &udid, int32_t compareParam, std::map &deviceMap); + std::vector GetCurrentUserAclProfile(const std::string &localUdid, + int32_t localUserId, const std::string &remoteUdid); }; extern "C" IDeviceProfileConnector *CreateDpConnectorInstance(); diff --git a/commondependency/include/multiple_user_connector.h b/commondependency/include/multiple_user_connector.h index f26f65898..5733f02da 100644 --- a/commondependency/include/multiple_user_connector.h +++ b/commondependency/include/multiple_user_connector.h @@ -98,6 +98,7 @@ public: static void GetCallerUserId(int32_t &userId); static int32_t GetForegroundUsers(std::vector &userVec); static int32_t GetForegroundUser(void); + static int32_t GetBackGroundUserIds(std::vector &userIdVec); private: static int32_t oldUserId_; diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index 4abb6bd8a..e58ed0540 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -165,8 +165,8 @@ int32_t DeviceProfileConnector::HandleDmAuthForm(AccessControlProfile profiles, uint32_t DeviceProfileConnector::CheckBindType(std::string peerUdid, std::string localUdid) { - std::vector allProfiles = GetAllAccessControlProfile(); - std::vector filterProfiles = FilterAclProfileByUserId(localUdid, peerUdid, allProfiles); + std::vector filterProfiles = GetCurrentUserAclProfile(localUdid, + MultipleUserConnector::GetForegroundUser(), peerUdid); LOGI("filterProfiles size is %{public}zu", filterProfiles.size()); uint32_t highestPriority = INVALIED_TYPE; for (auto &item : filterProfiles) { @@ -360,12 +360,11 @@ std::vector DeviceProfileConnector::SyncAclByBindType(std::string pkgNa return bindType; } -std::vector DeviceProfileConnector::GetProcessInfoFromAcl( - std::string &localDeviceId, std::string &targetDeviceId) +std::vector DeviceProfileConnector::GetProcessInfoFromAclByUserId( + const std::string &localDeviceId, const std::string &targetDeviceId, int32_t userId) { - std::vector allProfiles = GetAllAccessControlProfile(); - std::vector filterProfiles = FilterAclProfileByUserId(localDeviceId, - targetDeviceId, allProfiles); + std::vector filterProfiles = GetCurrentUserAclProfile(localDeviceId, + MultipleUserConnector::GetForegroundUser(), targetDeviceId); LOGI("filterProfiles size is %{public}zu", filterProfiles.size()); std::vector processInfoVec; for (auto &item : filterProfiles) { @@ -374,55 +373,11 @@ std::vector DeviceProfileConnector::GetP } OHOS::DistributedHardware::ProcessInfo processInfo; processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); - processInfo.userId = MultipleUserConnector::GetForegroundUser(); - processInfoVec.push_back(processInfo); + processInfo.userId = item.GetAccesser().GetAccesserUserId(); } return processInfoVec; } -DmOfflineParam DeviceProfileConnector::GetOfflineParamFromAcl(std::string trustDeviceId, std::string requestDeviceId) -{ - LOGI("TrustDeviceId = %{public}s and requestDeviceId = %{public}s", - GetAnonyString(trustDeviceId).c_str(), GetAnonyString(requestDeviceId).c_str()); - std::vector profiles = - GetAccessControlProfileByUserId(MultipleUserConnector::GetForegroundUser()); - LOGI("AccessControlProfile size is %{public}zu", profiles.size()); - DmOfflineParam offlineParam; - offlineParam.leftAclNumber = 0; - offlineParam.bindType = INVALIED_TYPE; - for (auto &item : profiles) { - if (item.GetTrustDeviceId() != trustDeviceId || item.GetStatus() != ACTIVE) { - continue; - } - offlineParam.leftAclNumber++; - uint32_t priority = INVALIED_TYPE; - if (item.GetBindType() == DM_IDENTICAL_ACCOUNT) { - priority = IDENTICAL_ACCOUNT_TYPE; - } else if (item.GetBindLevel() == DEVICE && item.GetAuthenticationType() == ALLOW_AUTH_ALWAYS) { - priority = DEVICE_PEER_TO_PEER_TYPE; - } else if (item.GetBindLevel() == DEVICE && item.GetAuthenticationType() == ALLOW_AUTH_ONCE) { - priority = DEVICE_PEER_TO_PEER_TYPE; - OHOS::DistributedHardware::ProcessInfo processInfo; - processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); - processInfo.userId = item.GetAccesser().GetAccesserUserId(); - offlineParam.processVec.push_back(processInfo); - } else if ((item.GetAccesser().GetAccesserDeviceId() == requestDeviceId && - item.GetAccessee().GetAccesseeDeviceId() == trustDeviceId) || - (item.GetAccesser().GetAccesserDeviceId() == trustDeviceId && - item.GetAccessee().GetAccesseeDeviceId() == requestDeviceId)) { - priority = APP_PEER_TO_PEER_TYPE; - OHOS::DistributedHardware::ProcessInfo processInfo; - processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); - processInfo.userId = item.GetAccesser().GetAccesserUserId(); - offlineParam.processVec.push_back(processInfo); - } - if (priority > offlineParam.bindType) { - offlineParam.bindType = priority; - } - } - return offlineParam; -} - int32_t DeviceProfileConnector::PutAccessControlList(DmAclInfo aclInfo, DmAccesser dmAccesser, DmAccessee dmAccessee) { LOGI("Start."); @@ -871,23 +826,25 @@ int32_t DeviceProfileConnector::GetBindLevel(const std::string &pkgName, const s return bindLevel; } -std::map DeviceProfileConnector::GetDeviceIdAndBindType(int32_t userId, +std::map DeviceProfileConnector::GetDeviceIdAndBindLevel(std::vector userIds, const std::string &localUdid) { - LOGI("userId %{public}d", userId); - std::vector profiles = GetAccessControlProfileByUserId(userId); + std::vector profiles = GetAllAccessControlProfile(); std::map deviceIdMap; for (const auto &item : profiles) { - if (item.GetAccesser().GetAccesserUserId() == userId && + if (item.GetStatus() != ACTIVE) { + continue; + } + if (find(userIds.begin(), userIds.end(), item.GetAccesser().GetAccesserUserId()) != userIds.end() && item.GetAccesser().GetAccesserDeviceId() == localUdid) { LOGI("Get Device Bind type localUdid %{public}s is src.", GetAnonyString(localUdid).c_str()); - UpdateBindType(item.GetTrustDeviceId(), item.GetBindType(), deviceIdMap); + UpdateBindType(item.GetTrustDeviceId(), item.GetBindLevel(), deviceIdMap); continue; } - if (item.GetAccessee().GetAccesseeUserId() == userId && + if (find(userIds.begin(), userIds.end(), item.GetAccessee().GetAccesseeUserId()) != userIds.end() && item.GetAccessee().GetAccesseeDeviceId() == localUdid) { LOGI("Get Device Bind type localUdid %{public}s is sink.", GetAnonyString(localUdid).c_str()); - UpdateBindType(item.GetTrustDeviceId(), item.GetBindType(), deviceIdMap); + UpdateBindType(item.GetTrustDeviceId(), item.GetBindLevel(), deviceIdMap); continue; } } @@ -919,14 +876,14 @@ std::map DeviceProfileConnector::GetDeviceIdAndBindType(in return deviceIdMap; } -void DeviceProfileConnector::UpdateBindType(const std::string &udid, int32_t bindType, +void DeviceProfileConnector::UpdateBindType(const std::string &udid, int32_t compareParam, std::map &deviceMap) { - LOGI("BindType %{public}d.", bindType); + LOGI("BindType %{public}d.", compareParam); if (deviceMap.find(udid) == deviceMap.end()) { - deviceMap[udid] = bindType; + deviceMap[udid] = compareParam; } else { - deviceMap[udid] = std::min(deviceMap[udid], bindType); + deviceMap[udid] = std::min(deviceMap[udid], compareParam); } } @@ -1054,34 +1011,23 @@ int32_t DeviceProfileConnector::HandleUserSwitched(const std::string &localUdid, DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); } } - profiles = GetAccessControlProfileByUserId(currentUserId); - LOGI("to active ACL size is %{public}zu", profiles.size()); - for (auto &item : profiles) { - if ((item.GetAccesser().GetAccesserUserId() == beforeUserId && - item.GetAccesser().GetAccesserDeviceId() == localUdid) || - (item.GetAccessee().GetAccesseeUserId() == beforeUserId && - item.GetAccessee().GetAccesseeDeviceId() == localUdid)) { - item.SetStatus(ACTIVE); - DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); - } - } return DM_OK; } -std::vector DeviceProfileConnector::FilterAclProfileByUserId(const std::string &localUdid, - const std::string &remoteUdid, const std::vector &profiles) +std::vector DeviceProfileConnector::GetCurrentUserAclProfile(const std::string &localUdid, + int32_t localUserId, const std::string &remoteUdid) { - LOGI("localUdid %{public}s, remoteUdid %{public}s.", GetAnonyString(localUdid).c_str(), - GetAnonyString(remoteUdid).c_str()); + LOGI("localUdid %{public}s, localUserId %{public}d, remoteUdid %{public}s.", GetAnonyString(localUdid).c_str(), + localUserId, GetAnonyString(remoteUdid).c_str()); + std::vector profiles = GetAllAccessControlProfile(); std::vector profilesTemp; - int32_t userId = MultipleUserConnector::GetForegroundUser(); for (const auto &item : profiles) { if (item.GetAccesser().GetAccesserDeviceId() == localUdid && - item.GetAccesser().GetAccesserUserId() == userId && + item.GetAccesser().GetAccesserUserId() == localUserId && item.GetAccessee().GetAccesseeDeviceId() == remoteUdid) { profilesTemp.push_back(item); } else if (item.GetAccessee().GetAccesseeDeviceId() == localUdid && - item.GetAccessee().GetAccesseeUserId() == userId && + item.GetAccessee().GetAccesseeUserId() == localUserId && item.GetAccesser().GetAccesserDeviceId() == remoteUdid) { profilesTemp.push_back(item); } @@ -1089,6 +1035,141 @@ std::vector DeviceProfileConnector::FilterAclProfileByUser return profilesTemp; } +void DeviceProfileConnector::HandleSyncForegroundUserIdEvent(const std::vector &remoteUserIds, + const std::string &remoteUdid, const std::vector &localUserIds, std::string &localUdid) +{ + LOGI("localUdid %{public}s, remoteUdid %{public}s.", GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + std::vector profiles = GetAllAccessControlProfile(); + for (auto &item : profiles) { + if (item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccessee().GetAccesseeDeviceId() == remoteUdid && + find(localUserIds.begin(), localUserIds.end(), + item.GetAccesser().GetAccesserUserId()) != localUserIds.end() && + find(remoteUserIds.begin(), remoteUserIds.end(), + item.GetAccessee().GetAccesseeUserId()) != remoteUserIds.end()) { + item.SetStatus(ACTIVE); + DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); + } else if ((item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccessee().GetAccesseeDeviceId() == remoteUdid) && + (find(localUserIds.begin(), localUserIds.end(), + item.GetAccesser().GetAccesserUserId()) == localUserIds.end() || + find(remoteUserIds.begin(), remoteUserIds.end(), + item.GetAccessee().GetAccesseeUserId()) == remoteUserIds.end())) { + item.SetStatus(INACTIVE); + DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); + } else if (item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccesser().GetAccesserDeviceId() == remoteUdid && + find(localUserIds.begin(), localUserIds.end(), + item.GetAccessee().GetAccesseeUserId()) != localUserIds.end() && + find(remoteUserIds.begin(), remoteUserIds.end(), + item.GetAccesser().GetAccesserUserId()) != remoteUserIds.end()) { + item.SetStatus(ACTIVE); + DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); + } else if ((item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccesser().GetAccesserDeviceId() == remoteUdid) && + (find(localUserIds.begin(), localUserIds.end(), + item.GetAccessee().GetAccesseeUserId()) == localUserIds.end() || + find(remoteUserIds.begin(), remoteUserIds.end(), + item.GetAccesser().GetAccesserUserId()) == remoteUserIds.end())) { + item.SetStatus(INACTIVE); + DistributedDeviceProfileClient::GetInstance().UpdateAccessControlProfile(item); + } + } +} + +std::vector DeviceProfileConnector::GetOfflineProcessInfo(const std::vector &localUserIds, + std::string &localUdid, const std::vector &remoteUserIds, const std::string &remoteUdid) +{ + LOGI("localUdid %{public}s, remoteUdid %{public}s.", GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + std::vector profiles = GetAllAccessControlProfile(); + std::vector processInfos; + int32_t bindLevel = 100; + for (const auto &item : profiles) { + ProcessInfo processInfo; + if (item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccessee().GetAccesseeDeviceId() == remoteUdid && + find(localUserIds.begin(), localUserIds.end(), + item.GetAccesser().GetAccesserUserId()) != localUserIds.end() && + find(remoteUserIds.begin(), remoteUserIds.end(), + item.GetAccessee().GetAccesseeUserId()) == remoteUserIds.end() && + item.GetStatus() == ACTIVE) { + processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.userId = item.GetAccesser().GetAccesserUserId(); + bindLevel = std::min(bindLevel, static_cast(item.GetBindLevel())); + } else if (item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccesser().GetAccesserDeviceId() == remoteUdid && + find(localUserIds.begin(), localUserIds.end(), + item.GetAccessee().GetAccesseeUserId()) != localUserIds.end() && + find(remoteUserIds.begin(), remoteUserIds.end(), + item.GetAccesser().GetAccesserUserId()) == remoteUserIds.end() && + item.GetStatus() == ACTIVE) { + processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); + processInfo.userId = item.GetAccessee().GetAccesseeUserId(); + bindLevel = std::min(bindLevel, static_cast(item.GetBindLevel())); + } + processInfos.push_back(processInfo); + } + if (bindLevel == INVALIED_TYPE || bindLevel == DEVICE) { + processInfos.clear(); + for (const auto &item : localUserIds) { + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = item; + processInfos.push_back(processInfo); + } + } + return processInfos; +} + +std::vector DeviceProfileConnector::GetOnlineProcessInfo(const std::vector &localUserIds, + std::string &localUdid, const std::vector &remoteUserIds, + const std::string &remoteUdid, int32_t &bindLevel) +{ + LOGI("localUdid %{public}s, remoteUdid %{public}s.", GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + std::vector profiles = GetAllAccessControlProfile(); + std::vector processInfos; + int32_t bindLevelTemp = 100; + for (const auto &item : profiles) { + ProcessInfo processInfo; + if (item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccessee().GetAccesseeDeviceId() == remoteUdid && + find(localUserIds.begin(), localUserIds.end(), + item.GetAccesser().GetAccesserUserId()) == localUserIds.end() && + find(remoteUserIds.begin(), remoteUserIds.end(), + item.GetAccessee().GetAccesseeUserId()) == remoteUserIds.end() && + item.GetStatus() == INACTIVE) { + processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.userId = item.GetAccesser().GetAccesserUserId(); + bindLevel = std::min(bindLevelTemp, static_cast(item.GetBindLevel())); + } else if (item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccesser().GetAccesserDeviceId() == remoteUdid && + find(localUserIds.begin(), localUserIds.end(), + item.GetAccessee().GetAccesseeUserId()) == localUserIds.end() && + find(remoteUserIds.begin(), remoteUserIds.end(), + item.GetAccesser().GetAccesserUserId()) == remoteUserIds.end() && + item.GetStatus() == INACTIVE) { + processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); + processInfo.userId = item.GetAccessee().GetAccesseeUserId(); + bindLevelTemp = std::min(bindLevelTemp, static_cast(item.GetBindLevel())); + } + processInfos.push_back(processInfo); + } + if (bindLevelTemp == INVALIED_TYPE || bindLevelTemp == DEVICE) { + processInfos.clear(); + for (const auto &item : localUserIds) { + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = item; + processInfos.push_back(processInfo); + } + bindLevel = bindLevelTemp; + } + return processInfos; +} + IDeviceProfileConnector *CreateDpConnectorInstance() { return &DeviceProfileConnector::GetInstance(); diff --git a/commondependency/src/multiple_user_connector.cpp b/commondependency/src/multiple_user_connector.cpp index 0fccd4c17..37eca6ddb 100644 --- a/commondependency/src/multiple_user_connector.cpp +++ b/commondependency/src/multiple_user_connector.cpp @@ -198,5 +198,21 @@ int32_t MultipleUserConnector::GetForegroundUser(void) } return userVec[0]; } + +int32_t MultipleUserConnector::GetBackGroundUserIds(std::vector &userIdVec) +{ +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) + return DM_OK; +#elif OS_ACCOUNT_PART_EXISTS + ErrCode ret = OsAccountManager::GetBackgroundOsAccountLocalIds(userIdVec); + if (ret != 0) { + LOGE("error ret: %{public}d", ret); + return ret; + } + return DM_OK; +#else + return DM_OK; +#endif +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index e8b435d6e..d370f7aa5 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -135,13 +135,15 @@ public: int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId); void HandleSyncForegroundUserIdEvent(const std::vector &remoteUserIds, const std::string &remoteUdid); + void HandleUserSwitched(const std::map &deviceMap, int32_t currentUserId, + int32_t beforeUserId); private: int32_t PraseNotifyEventJson(const std::string &event, nlohmann::json &jsonObject); std::string GetUdidHashByNetworkId(const std::string &networkId); void HandleOffline(DmDeviceState devState, DmDeviceInfo &devInfo); void HandleOnline(DmDeviceState devState, DmDeviceInfo &devInfo); void PutIdenticalAccountToAcl(std::string requestDeviceId, std::string trustDeviceId); - std::map GetDeviceIdAndBindType(int32_t userId); + std::map GetDeviceIdAndBindLevel(int32_t userId); std::map GetDeviceIdAndBindType(int32_t userId, const std::string &accountId); void HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, const std::string &remoteUdid); @@ -150,7 +152,7 @@ private: void HandleUserRemoved(int32_t preUserId); void HandleRemoteUserRemoved(int32_t preUserId, const std::string &remoteUdid); DmAuthForm ConvertBindTypeToAuthForm(int32_t bindType); - void HandleUserSwitched(int32_t currentUserId, int32_t beforeUserId); + private: std::shared_ptr authMgr_; diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index 9d89973c5..8bab21877 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -135,12 +135,15 @@ public: void HandleIdentAccountLogout(const std::string &udid, int32_t userId, const std::string &accountId); void HandleUserRemoved(int32_t preUserId); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); - void HandleUserSwitched(int32_t currentUserId, int32_t beforeUserId); + void HandleUserSwitched(const std::map &deviceMap, int32_t currentUserId, + int32_t beforeUserId); int32_t StopAuthenticateDevice(const std::string &pkgName); void HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode); int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId); void HandleSyncForegroundUserIdEvent(const std::vector &remoteUserIds, const std::string &remoteUdid); + std::map GetDeviceIdAndBindLevel(int32_t userId); + private: std::string GetUdidHashByNetworkId(const std::string &networkId); diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index d3f6630ee..e0523d1b8 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -212,26 +212,39 @@ void DeviceManagerServiceImpl::HandleOffline(DmDeviceState devState, DmDeviceInf char localUdid[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localUdid, DEVICE_UUID_LENGTH); std::string requestDeviceId = std::string(localUdid); - DmOfflineParam offlineParam = - DeviceProfileConnector::GetInstance().GetOfflineParamFromAcl(trustDeviceId, requestDeviceId); - LOGI("The offline device bind type is %{public}d.", offlineParam.bindType); - if (offlineParam.leftAclNumber == 0 && offlineParam.bindType == INVALIED_TYPE) { - deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); - } else if (offlineParam.bindType == IDENTICAL_ACCOUNT_TYPE) { - LOGI("The offline device is identical account bind type."); - deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); - } else if (offlineParam.bindType == DEVICE_PEER_TO_PEER_TYPE) { - LOGI("The offline device is device-level bind type."); - deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); - } else if (offlineParam.bindType == APP_PEER_TO_PEER_TYPE) { - LOGI("The offline device is app-level bind type."); - softbusConnector_->SetProcessInfoVec(offlineParam.processVec); - deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); - } - if (offlineParam.leftAclNumber == 0) { - LOGI("Delete credential in HandleDeviceOffline."); + uint32_t bindType = DeviceProfileConnector::GetInstance().CheckBindType(trustDeviceId, requestDeviceId); + LOGI("The offline device bind type is %{public}d.", bindType); + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = MultipleUserConnector::GetForegroundUser(); + if (bindType == INVALIED_TYPE) { hiChainAuthConnector_->DeleteCredential(trustDeviceId, MultipleUserConnector::GetForegroundUser()); + } else if (bindType == IDENTICAL_ACCOUNT_TYPE) { + LOGI("The offline device is identical account bind type."); + devInfo.authForm = DmAuthForm::IDENTICAL_ACCOUNT; + softbusConnector_->SetProcessInfo(processInfo); + } else if (bindType == DEVICE_PEER_TO_PEER_TYPE) { + LOGI("The offline device is PEER_TO_PEER bind type."); + devInfo.authForm = DmAuthForm::PEER_TO_PEER; + softbusConnector_->SetProcessInfo(processInfo); + } else if (bindType == DEVICE_ACROSS_ACCOUNT_TYPE) { + LOGI("The offline device is ACROSS_ACCOUNT bind type."); + devInfo.authForm = DmAuthForm::ACROSS_ACCOUNT; + softbusConnector_->SetProcessInfo(processInfo); + } else if (bindType == APP_PEER_TO_PEER_TYPE) { + LOGI("The offline device is APP_PEER_TO_PEER_TYPE bind type."); + std::vector processInfoVec = + DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(requestDeviceId, trustDeviceId, + MultipleUserConnector::GetForegroundUser()); + softbusConnector_->SetProcessInfoVec(processInfoVec); + } else if (bindType == APP_ACROSS_ACCOUNT_TYPE) { + LOGI("The offline device is APP_ACROSS_ACCOUNT_TYPE bind type."); + std::vector processInfoVec = + DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(requestDeviceId, trustDeviceId, + MultipleUserConnector::GetForegroundUser()); + softbusConnector_->SetProcessInfoVec(processInfoVec); } + deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); } void DeviceManagerServiceImpl::HandleOnline(DmDeviceState devState, DmDeviceInfo &devInfo) @@ -239,7 +252,7 @@ void DeviceManagerServiceImpl::HandleOnline(DmDeviceState devState, DmDeviceInfo LOGI("DeviceManagerServiceImpl::HandleOnline"); std::string trustDeviceId = ""; if (softbusConnector_->GetUdidByNetworkId(devInfo.networkId, trustDeviceId) != DM_OK) { - LOGE("HandleDeviceOffline get udid failed."); + LOGE("HandleOnline get udid failed."); return; } std::string udisHash = softbusConnector_->GetDeviceUdidHashByUdid(trustDeviceId); @@ -271,12 +284,14 @@ void DeviceManagerServiceImpl::HandleOnline(DmDeviceState devState, DmDeviceInfo softbusConnector_->SetProcessInfo(processInfo); } else if (bindType == APP_PEER_TO_PEER_TYPE) { std::vector processInfoVec = - DeviceProfileConnector::GetInstance().GetProcessInfoFromAcl(requestDeviceId, trustDeviceId); + DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(requestDeviceId, trustDeviceId, + MultipleUserConnector::GetForegroundUser()); softbusConnector_->SetProcessInfoVec(processInfoVec); devInfo.authForm = DmAuthForm::PEER_TO_PEER; } else if (bindType == APP_ACROSS_ACCOUNT_TYPE) { std::vector processInfoVec = - DeviceProfileConnector::GetInstance().GetProcessInfoFromAcl(requestDeviceId, trustDeviceId); + DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(requestDeviceId, trustDeviceId, + MultipleUserConnector::GetForegroundUser()); softbusConnector_->SetProcessInfoVec(processInfoVec); devInfo.authForm = DmAuthForm::ACROSS_ACCOUNT; } @@ -702,13 +717,28 @@ void DeviceManagerServiceImpl::HandleRemoteUserRemoved(int32_t userId, const std //TOOD: process remote device delete user } -void DeviceManagerServiceImpl::HandleUserSwitched(int32_t currentUserId, int32_t beforeUserId) +void DeviceManagerServiceImpl::HandleUserSwitched(const std::map &deviceMap, + int32_t currentUserId, int32_t beforeUserId) { LOGI("currentUserId: %{public}s, beforeUserId: %{public}s", GetAnonyInt32(currentUserId).c_str(), GetAnonyInt32(beforeUserId).c_str()); char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); std::string localUdid = static_cast(localDeviceId); + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = beforeUserId; + for (const auto &item : deviceMap) { + if (item.second == INVALIED_TYPE || item.second == DEVICE) { + softbusConnector_->SetProcessInfo(processInfo); + } else { + std::vector processInfoVec = + DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(localUdid, + item.first, beforeUserId); + softbusConnector_->SetProcessInfoVec(processInfoVec); + } + softbusConnector_->HandleDeviceOffline(item.first); + } DeviceProfileConnector::GetInstance().HandleUserSwitched(localUdid, currentUserId, beforeUserId); } @@ -751,12 +781,14 @@ int32_t DeviceManagerServiceImpl::GetBindLevel(const std::string &pkgName, const return DeviceProfileConnector::GetInstance().GetBindLevel(pkgName, localUdid, udid, tokenId); } -std::map DeviceManagerServiceImpl::GetDeviceIdAndBindType(int32_t userId) +std::map DeviceManagerServiceImpl::GetDeviceIdAndBindLevel(int32_t userId) { char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); std::string localUdid = std::string(localUdidTemp); - return DeviceProfileConnector::GetInstance().GetDeviceIdAndBindType(userId, localUdid); + std::vector userIds; + userIds.push_back(userId); + return DeviceProfileConnector::GetInstance().GetDeviceIdAndBindLevel(userIds, localUdid); } std::map DeviceManagerServiceImpl::GetDeviceIdAndBindType(int32_t userId, @@ -842,6 +874,32 @@ void DeviceManagerServiceImpl::HandleSyncForegroundUserIdEvent(const std::vector { LOGI("receive remote foreground userids: %{public}s, remote udid: %{public}s", GetAnonyIntegerList(remoteUserIds).c_str(), GetAnonyString(remoteUdid).c_str()); + char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localUdidTemp); + std::vector remoteUserIdsTemp(remoteUserIds.begin(), remoteUserIds.end()); + std::vector localUserIds; + int32_t ret = MultipleUserConnector::GetForegroundUsers(localUserIds); + if (ret != DM_OK || localUserIds.empty()) { + LOGE("Get foreground userids failed, ret: %{public}d", ret); + } + std::vector offlineProcInfo = + DeviceProfileConnector::GetInstance().GetOfflineProcessInfo(localUserIds, localUdid, + remoteUserIdsTemp, remoteUdid); + int32_t bindLevel = 100; + std::vector onlineProcInfo = + DeviceProfileConnector::GetInstance().GetOnlineProcessInfo(localUserIds, localUdid, remoteUserIdsTemp, + remoteUdid, bindLevel); + softbusConnector_->SetProcessInfoVec(offlineProcInfo); + softbusConnector_->HandleDeviceOffline(remoteUdid); + softbusConnector_->SetProcessInfoVec(onlineProcInfo); + if (bindLevel == INVALIED_TYPE) { + softbusConnector_->HandleDeviceOnline(remoteUdid, DmAuthForm::IDENTICAL_ACCOUNT); + } else { + softbusConnector_->HandleDeviceOnline(remoteUdid, DmAuthForm::PEER_TO_PEER); + } + DeviceProfileConnector::GetInstance().HandleSyncForegroundUserIdEvent(remoteUserIdsTemp, remoteUdid, + localUserIds, localUdid); } void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) @@ -874,7 +932,8 @@ void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devI softbusConnector_->SetProcessInfo(processInfo); } else if (bindType == APP_PEER_TO_PEER_TYPE || bindType == APP_ACROSS_ACCOUNT_TYPE) { std::vector processInfoVec = - DeviceProfileConnector::GetInstance().GetProcessInfoFromAcl(requestDeviceId, trustDeviceId); + DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(requestDeviceId, trustDeviceId, + MultipleUserConnector::GetForegroundUser()); softbusConnector_->SetProcessInfoVec(processInfoVec); } deviceStateMgr_->HandleDeviceScreenStatusChange(devInfo); diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index 740131561..59f9a489c 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -513,9 +513,11 @@ void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devI return; } -void DeviceManagerServiceImpl::HandleUserSwitched(int32_t currentUserId, int32_t beforeUserId) +void DeviceManagerServiceImpl::HandleUserSwitched(const std::map &deviceMap, + int32_t currentUserId, int32_t beforeUserId) { - (void)currentUserId; + (void)deviceMap; + (void)switchUserId; (void)beforeUserId; return; } @@ -547,6 +549,11 @@ void DeviceManagerServiceImpl::HandleSyncForegroundUserIdEvent(const std::vector (void)remoteUdid; } +std::map DeviceManagerServiceImpl::GetDeviceIdAndBindLevel(int32_t userId) +{ + (void)userId; +} + extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) { return new DeviceManagerServiceImpl; diff --git a/services/implementation/src/devicestate/dm_device_state_manager.cpp b/services/implementation/src/devicestate/dm_device_state_manager.cpp index eaed6d51e..a53fa6eed 100644 --- a/services/implementation/src/devicestate/dm_device_state_manager.cpp +++ b/services/implementation/src/devicestate/dm_device_state_manager.cpp @@ -198,6 +198,7 @@ void DmDeviceStateManager::OnDbReady(const std::string &pkgName, const std::stri DmDeviceState state = DEVICE_INFO_READY; ProcessInfo processInfo; processInfo.pkgName = pkgName; + processInfo.userId = MultipleUserConnector::GetForegroundUser(); listener_->OnDeviceStateChange(processInfo, state, saveInfo); } } diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index 25141ceb1..c93312c70 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -229,7 +229,7 @@ private: * @param currentUserId the user id which switched to foreground. * @param beforeUserId the user id which switched to backend. */ - void HandleUserSwitched(int32_t currentUserId, int32_t beforeUserId); + void HandleUserSwitched(int32_t curUserId, int32_t preUserId); #if defined(SUPPORT_BLUETOOTH) || defined(SUPPORT_WIFI) void SubscribePublishCommonEvent(); void QueryDependsSwitchState(); diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index 97144f236..e7d6cfeb8 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -80,7 +80,7 @@ private: const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo); void SetDeviceInfo(std::shared_ptr pReq, const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &deviceInfo, const DmDeviceBasicInfo &deviceBasicInfo); - void ProcessDeviceStateChange(const DmDeviceState &state, const DmDeviceInfo &info, + void ProcessDeviceStateChange(const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); void ProcessAppStateChange(const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); @@ -92,8 +92,8 @@ private: int32_t ConvertUdidHashToAnoyDeviceId(const std::string &pkgName, const std::string &udidHash, std::string &anoyDeviceId); #endif - void GetNotifyProcessInfos(const ProcessInfo &processInfo, std::set &processInfoSet); - std::vector GetNotifyProcessInfo(); + std::vector GetWhiteListSAProcessInfo(); + std::vector GetNotifyProcessInfoByUserId(int32_t userId); private: #if !defined(__LITEOS_M__) IpcServerListener ipcServerListener_; diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index 74d154bf8..00d8fd798 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -261,7 +261,6 @@ public: virtual int32_t CheckAccessControl(const DmAccessCaller &caller, const std::string &srcUdid, const DmAccessCallee &callee, const std::string &sinkUdid) = 0; virtual void HandleDeviceNotTrust(const std::string &udid) = 0; - virtual std::map GetDeviceIdAndBindType(int32_t userId) = 0; virtual std::map GetDeviceIdAndBindType(int32_t userId, const std::string &accountId) = 0; virtual void HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, const std::string &remoteUdid) = 0; @@ -272,13 +271,15 @@ public: virtual void HandleIdentAccountLogout(const std::string &udid, int32_t userId, const std::string &accountId) = 0; virtual void HandleUserRemoved(int32_t preUserId) = 0; virtual void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) = 0; - virtual void HandleUserSwitched(int32_t currentUserId, int32_t beforeUserId) = 0; + virtual void HandleUserSwitched(const std::map &deviceMap, int32_t currentUserId, + int32_t beforeUserId) = 0; virtual int32_t StopAuthenticateDevice(const std::string &pkgName) = 0; virtual void HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode) = 0; virtual int32_t ProcessAppUnintall(const std::string &appId, int32_t accessTokenId) = 0; virtual void HandleSyncForegroundUserIdEvent(const std::vector &remoteUserIds, const std::string &remoteUdid) = 0; virtual void HandleRemoteUserRemoved(int32_t userId, const std::string &remoteUdid) = 0; + virtual std::map GetDeviceIdAndBindLevel(int32_t userId) = 0; }; using CreateDMServiceFuncPtr = IDeviceManagerServiceImpl *(*)(void); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index b1454f904..fba0a4d9d 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -1569,19 +1569,17 @@ void DeviceManagerService::AccountCommonEventCallback(const std::string commonEv LOGI("CommonEventType: %{public}s, currentUserId: %{public}d, beforeUserId: %{public}d", commonEventType.c_str(), currentUserId, beforeUserId); if (commonEventType == CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { - if (MultipleUserConnector::GetSwitchOldUserId() > 0 && - (currentUserId != MultipleUserConnector::GetSwitchOldUserId())) { - HandleUserSwitched(currentUserId, beforeUserId); - } MultipleUserConnector::SetSwitchOldUserId(currentUserId); MultipleUserConnector::SetSwitchOldAccountId(MultipleUserConnector::GetOhosAccountId()); MultipleUserConnector::SetSwitchOldAccountName(MultipleUserConnector::GetOhosAccountName()); + if (beforeUserId == -1 || currentUserId == -1) { + return; + } else if (beforeUserId != -1 && currentUserId != -1) { + HandleUserSwitched(currentUserId, beforeUserId); + } if (IsDMServiceAdapterLoad()) { dmServiceImplExt_->AccountUserSwitched(currentUserId, MultipleUserConnector::GetOhosAccountId()); } - - //TODO: 根据切换的beforeUserId,报逻辑下线 - //TODO: 根据切换的currentUserId,报逻辑上线(NO,需要总线在新用户下重新上线,才能报逻辑上线) } else if (commonEventType == CommonEventSupport::COMMON_EVENT_HWID_LOGIN) { MultipleUserConnector::SetSwitchOldAccountId(MultipleUserConnector::GetOhosAccountId()); MultipleUserConnector::SetSwitchOldAccountName(MultipleUserConnector::GetOhosAccountName()); @@ -1626,14 +1624,25 @@ void DeviceManagerService::HandleAccountLogout(int32_t userId, const std::string } } -void DeviceManagerService::HandleUserSwitched(int32_t currentUserId, int32_t beforeUserId) +void DeviceManagerService::HandleUserSwitched(int32_t curUserId, int32_t preUserId) { - LOGI("currentUserId: %{public}d. beforeUserId: %{public}d", currentUserId, beforeUserId); - std::map deviceMap; + LOGI("currentUserId: %{public}d. previousUserId: %{public}d", curUserId, preUserId); + if (!IsDMServiceImplReady()) { + LOGE("Init impl failed."); + return; + } + std::map curUserDeviceMap; + std::map preUserDeviceMap; std::vector peerUdids; - deviceMap = dmServiceImpl_->GetDeviceIdAndBindType(beforeUserId); - for (const auto &item : deviceMap) { - peerUdids.emplace_back(item.first); + curUserDeviceMap = dmServiceImpl_->GetDeviceIdAndBindLevel(curUserId); + preUserDeviceMap = dmServiceImpl_->GetDeviceIdAndBindLevel(preUserId); + for (const auto &item : curUserDeviceMap) { + peerUdids.push_back(item.first); + } + for (const auto &item : preUserDeviceMap) { + if (find(peerUdids.begin(), peerUdids.end(), item.first) == peerUdids.end()) { + peerUdids.push_back(item.first); + } } if (!peerUdids.empty()) { std::vector userVec; @@ -1646,7 +1655,7 @@ void DeviceManagerService::HandleUserSwitched(int32_t currentUserId, int32_t bef } } if (IsDMServiceImplReady()) { - dmServiceImpl_->HandleUserSwitched(currentUserId, beforeUserId); + dmServiceImpl_->HandleUserSwitched(preUserDeviceMap, curUserId, preUserId); } } @@ -1655,7 +1664,7 @@ void DeviceManagerService::HandleUserRemoved(int32_t removedUserId) LOGI("PreUserId %{public}d.", removedUserId); std::map deviceMap; std::vector peerUdids; - deviceMap = dmServiceImpl_->GetDeviceIdAndBindType(removedUserId); + deviceMap = dmServiceImpl_->GetDeviceIdAndBindType(removedUserId, MultipleUserConnector::GetSwitchOldAccountId()); for (const auto &item : deviceMap) { peerUdids.emplace_back(item.first); } diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index 5526b6d4d..5f6e71a71 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -112,13 +112,13 @@ void DeviceManagerServiceListener::SetDeviceInfo(std::shared_ptrSetDeviceBasicInfo(deviceBasicInfo); } -void DeviceManagerServiceListener::ProcessDeviceStateChange(const DmDeviceState &state, const DmDeviceInfo &info, - const DmDeviceBasicInfo &deviceBasicInfo) +void DeviceManagerServiceListener::ProcessDeviceStateChange(const ProcessInfo &processInfo, const DmDeviceState &state, + const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo) { LOGI("In"); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - std::vector processInfoVec = GetNotifyProcessInfo(); + std::vector processInfoVec = GetNotifyProcessInfoByUserId(processInfo.userId); if (state == DEVICE_STATE_OFFLINE) { RemoveOnlinePkgName(info); for (const auto &it : processInfoVec) { @@ -155,10 +155,9 @@ void DeviceManagerServiceListener::ProcessAppStateChange(const ProcessInfo &proc LOGI("In"); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - std::set processInfoSet; - GetNotifyProcessInfos(processInfo, processInfoSet); + std::vector processInfos = GetWhiteListSAProcessInfo(); if (state == DEVICE_STATE_ONLINE) { - for (const auto &it : processInfoSet) { + for (const auto &it : processInfos) { { std::lock_guard autoLock(alreadyOnlinePkgNameLock_); if (alreadyOnlinePkgName_.find(it) != alreadyOnlinePkgName_.end()) { @@ -173,7 +172,7 @@ void DeviceManagerServiceListener::ProcessAppStateChange(const ProcessInfo &proc if (state == DEVICE_STATE_OFFLINE) { if (!SoftbusCache::GetInstance().CheckIsOnline(std::string(info.deviceId))) { RemoveOnlinePkgName(info); - for (const auto &it : processInfoSet) { + for (const auto &it : processInfos) { SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); } @@ -201,7 +200,7 @@ void DeviceManagerServiceListener::OnDeviceStateChange(const ProcessInfo &proces DmDeviceBasicInfo deviceBasicInfo; ConvertDeviceInfoToDeviceBasicInfo(processInfo.pkgName, info, deviceBasicInfo); if (processInfo.pkgName == std::string(DM_PKG_NAME)) { - ProcessDeviceStateChange(state, info, deviceBasicInfo); + ProcessDeviceStateChange(processInfo, state, info, deviceBasicInfo); } else { ProcessAppStateChange(processInfo, state, info, deviceBasicInfo); } @@ -484,7 +483,7 @@ void DeviceManagerServiceListener::OnDeviceTrustChange(const std::string &udid, GetAnonyString(uuid).c_str(), authForm); std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - std::vector processInfoVec = GetNotifyProcessInfo(); + std::vector processInfoVec = GetNotifyProcessInfoByUserId(MultipleUserConnector::GetForegroundUser()); for (const auto &item : processInfoVec) { pReq->SetPkgName(item.pkgName); pReq->SetUdid(udid); @@ -521,7 +520,8 @@ void DeviceManagerServiceListener::OnDeviceScreenStateChange(const ProcessInfo & if (processInfo.pkgName == std::string(DM_PKG_NAME)) { std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); - std::vector processInfoVec = GetNotifyProcessInfo(); + std::vector processInfoVec = + GetNotifyProcessInfoByUserId(MultipleUserConnector::GetForegroundUser()); for (const auto &item : processInfoVec) { SetDeviceScreenInfo(pReq, item, devInfo); ipcServerListener_.SendRequest(SERVER_DEVICE_SCREEN_STATE_NOTIFY, pReq, pRsp); @@ -583,20 +583,20 @@ void DeviceManagerServiceListener::OnAppUnintall(const std::string &pkgName) } } -void DeviceManagerServiceListener::GetNotifyProcessInfos(const ProcessInfo &processInfo, - std::set &processInfoSet) +std::vector DeviceManagerServiceListener::GetWhiteListSAProcessInfo() { std::unordered_set notifyPkgnames = PermissionManager::GetInstance().GetWhiteListSystemSA(); + std::vector processInfos; for (const auto &it : notifyPkgnames) { ProcessInfo processInfo; processInfo.pkgName = it; processInfo.userId = 0; - processInfoSet.emplace(processInfo); + processInfos.push_back(processInfo); } - processInfoSet.emplace(processInfo); + return processInfos; } -std::vector DeviceManagerServiceListener::GetNotifyProcessInfo() +std::vector DeviceManagerServiceListener::GetNotifyProcessInfoByUserId(int32_t userId) { std::vector processInfos = ipcServerListener_.GetAllProcessInfo(); std::set systemSA = ipcServerListener_.GetSystemSA(); @@ -605,8 +605,7 @@ std::vector DeviceManagerServiceListener::GetNotifyProcessInfo() if (systemSA.find(item.pkgName) != systemSA.end()) { item.userId = 0; processInfosTemp.push_back(item); - } - if (item.userId == MultipleUserConnector::GetForegroundUser()) { + } else if (item.userId == userId) { processInfosTemp.push_back(item); } } diff --git a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index 219c7dac1..6665ccc34 100644 --- a/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp +++ b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp @@ -452,54 +452,30 @@ HWTEST_F(DeviceProfileConnectorTest, SyncAclByBindType_001, testing::ext::TestSi EXPECT_EQ(ret.empty(), true); } -HWTEST_F(DeviceProfileConnectorTest, GetProcessInfoFromAcl_001, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, GetProcessInfoFromAclByUserId_001, testing::ext::TestSize.Level0) { std::string localDeviceId = "localDeviceId"; std::string targetDeviceId = "targetDeviceId"; - auto ret = DeviceProfileConnector::GetInstance().GetProcessInfoFromAcl(localDeviceId, targetDeviceId); + auto ret = DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(localDeviceId, targetDeviceId, 100); EXPECT_EQ(ret.empty(), true); } -HWTEST_F(DeviceProfileConnectorTest, GetProcessInfoFromAcl_002, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, GetProcessInfoFromAclByUserId_002, testing::ext::TestSize.Level0) { std::string localDeviceId = "123456"; std::string targetDeviceId = "deviceId"; - auto ret = DeviceProfileConnector::GetInstance().GetProcessInfoFromAcl(localDeviceId, targetDeviceId); + auto ret = DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(localDeviceId, targetDeviceId, 100); EXPECT_EQ(ret.empty(), true); } -HWTEST_F(DeviceProfileConnectorTest, GetProcessInfoFromAcl_003, testing::ext::TestSize.Level0) +HWTEST_F(DeviceProfileConnectorTest, GetProcessInfoFromAclByUserId_003, testing::ext::TestSize.Level0) { std::string localDeviceId = "deviceId"; std::string targetDeviceId = "deviceId"; - auto ret = DeviceProfileConnector::GetInstance().GetProcessInfoFromAcl(localDeviceId, targetDeviceId); + auto ret = DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(localDeviceId, targetDeviceId, 100); EXPECT_EQ(ret.empty(), false); } -HWTEST_F(DeviceProfileConnectorTest, GetOfflineParamFromAcl_001, testing::ext::TestSize.Level0) -{ - std::string trustDeviceId = "trustDeviceId"; - std::string requestDeviceId = "deviceId"; - auto ret = DeviceProfileConnector::GetInstance().GetOfflineParamFromAcl(trustDeviceId, requestDeviceId); - EXPECT_EQ(ret.bindType, INVALIED_TYPE); -} - -HWTEST_F(DeviceProfileConnectorTest, GetOfflineParamFromAcl_002, testing::ext::TestSize.Level0) -{ - std::string trustDeviceId = "123456"; - std::string requestDeviceId = "deviceId"; - auto ret = DeviceProfileConnector::GetInstance().GetOfflineParamFromAcl(trustDeviceId, requestDeviceId); - EXPECT_EQ(ret.bindType, INVALIED_TYPE); -} - -HWTEST_F(DeviceProfileConnectorTest, GetOfflineParamFromAcl_003, testing::ext::TestSize.Level0) -{ - std::string trustDeviceId = "deviceId"; - std::string requestDeviceId = "deviceId"; - auto ret = DeviceProfileConnector::GetInstance().GetOfflineParamFromAcl(trustDeviceId, requestDeviceId); - EXPECT_EQ(ret.bindType, IDENTICAL_ACCOUNT_TYPE); -} - HWTEST_F(DeviceProfileConnectorTest, PutAccessControlList_001, testing::ext::TestSize.Level0) { DmAclInfo aclInfo; diff --git a/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp b/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp index e4d7e8c31..a8b1fab7a 100644 --- a/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp +++ b/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp @@ -57,8 +57,7 @@ void DeviceProfileConnectorFuzzTest(const uint8_t* data, size_t size) DeviceProfileConnector::GetInstance().CheckBindType(trustDeviceId, requestDeviceId); DeviceProfileConnector::GetInstance().GetBindTypeByPkgName(pkgName, requestDeviceId, trustUdid); - DeviceProfileConnector::GetInstance().GetProcessInfoFromAcl(localDeviceId, targetDeviceId); - DeviceProfileConnector::GetInstance().GetOfflineParamFromAcl(trustDeviceId, requestDeviceId); + DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(localDeviceId, targetDeviceId, 100); DeviceProfileConnector::GetInstance().PutAccessControlList(aclInfo, dmAccesser, dmAccessee); DeviceProfileConnector::GetInstance().DeleteAccessControlList(pkgName, localDeviceId, requestDeviceId, bindLevel); DeviceProfileConnector::GetInstance().UpdateAccessControlList(userId, accountId, accountId); -- Gitee From 57f2281be504ddd4f23d9a6a7df5ec8ad861d54c Mon Sep 17 00:00:00 2001 From: liuzhongming Date: Fri, 8 Nov 2024 11:46:34 +0800 Subject: [PATCH 23/27] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E8=B0=83=E8=AF=95?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common/src/dm_anonymous.cpp | 5 +- .../src/deviceprofile_connector.cpp | 7 +-- .../src/multiple_user_connector.cpp | 2 +- .../include/authentication/dm_auth_manager.h | 1 + .../include/device_manager_service_impl.h | 1 - .../device_manager_service_impl_lite.h | 1 - .../authentication/auth_message_processor.cpp | 2 +- .../src/authentication/dm_auth_manager.cpp | 50 +++++++++---------- .../src/device_manager_service_impl.cpp | 4 ++ .../include/device_manager_service_listener.h | 1 + .../include/idevice_manager_service_impl.h | 3 +- .../service/src/device_manager_service.cpp | 4 +- .../src/device_manager_service_listener.cpp | 13 +++++ .../src/discovery/discovery_manager.cpp | 2 +- .../relationship_sync_mgr.cpp | 2 +- 15 files changed, 59 insertions(+), 39 deletions(-) diff --git a/common/src/dm_anonymous.cpp b/common/src/dm_anonymous.cpp index 79e2b422f..b26bdc866 100644 --- a/common/src/dm_anonymous.cpp +++ b/common/src/dm_anonymous.cpp @@ -300,6 +300,7 @@ std::string GetCallerPkgName(const std::string &pkgName) uint16_t GetSubscribeId(const std::string &pkgName) { std::vector strVec; + size_t subIdIndex = 1; size_t start = 0; size_t end = pkgName.find("#"); @@ -309,8 +310,8 @@ uint16_t GetSubscribeId(const std::string &pkgName) { end = pkgName.find("#", start); } strVec.push_back(pkgName.substr(start)); - if (strVec.size() >= 2) { - return std::atoi(strVec.at(1).c_str()); + if (strVec.size() >= subIdIndex + 1) { + return std::atoi(strVec.at(subIdIndex).c_str()); } return 0; } diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index e58ed0540..8966578c7 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -374,6 +374,7 @@ std::vector DeviceProfileConnector::GetP OHOS::DistributedHardware::ProcessInfo processInfo; processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); processInfo.userId = item.GetAccesser().GetAccesserUserId(); + processInfoVec.push_back(processInfo); } return processInfoVec; } @@ -899,11 +900,11 @@ int32_t DeviceProfileConnector::HandleAccountLogoutEvent(int32_t remoteUserId, c if (item.GetTrustDeviceId() != remoteUdid) { continue; } - if (item.GetAccesser().GetAccesserDeviceId() == remoteUdid + if (item.GetAccesser().GetAccesserDeviceId() == remoteUdid && item.GetAccesser().GetAccesserUserId() != remoteUserId) { continue; } - if (item.GetAccessee().GetAccesseeDeviceId() == remoteUdid + if (item.GetAccessee().GetAccesseeDeviceId() == remoteUdid && item.GetAccessee().GetAccesseeUserId() != remoteUserId) { continue; } @@ -1015,7 +1016,7 @@ int32_t DeviceProfileConnector::HandleUserSwitched(const std::string &localUdid, } std::vector DeviceProfileConnector::GetCurrentUserAclProfile(const std::string &localUdid, - int32_t localUserId, const std::string &remoteUdid) + int32_t localUserId, const std::string &remoteUdid) { LOGI("localUdid %{public}s, localUserId %{public}d, remoteUdid %{public}s.", GetAnonyString(localUdid).c_str(), localUserId, GetAnonyString(remoteUdid).c_str()); diff --git a/commondependency/src/multiple_user_connector.cpp b/commondependency/src/multiple_user_connector.cpp index 37eca6ddb..548991c30 100644 --- a/commondependency/src/multiple_user_connector.cpp +++ b/commondependency/src/multiple_user_connector.cpp @@ -115,7 +115,7 @@ void MultipleUserConnector::GetTokenIdAndForegroundUserId(uint32_t &tokenId, int } void MultipleUserConnector::GetCallerUserId(int32_t &userId) -{ +{ #if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) return; #elif OS_ACCOUNT_PART_EXISTS diff --git a/services/implementation/include/authentication/dm_auth_manager.h b/services/implementation/include/authentication/dm_auth_manager.h index 6c471abce..13ff40542 100644 --- a/services/implementation/include/authentication/dm_auth_manager.h +++ b/services/implementation/include/authentication/dm_auth_manager.h @@ -529,6 +529,7 @@ private: int32_t GetBindLevel(int32_t bindLevel); std::string GetBundleName(nlohmann::json &jsonObject); int32_t GetBinderInfo(); + void SetProcessInfo(); private: std::shared_ptr softbusConnector_; diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index d370f7aa5..5434a6eeb 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -153,7 +153,6 @@ private: void HandleRemoteUserRemoved(int32_t preUserId, const std::string &remoteUdid); DmAuthForm ConvertBindTypeToAuthForm(int32_t bindType); - private: std::shared_ptr authMgr_; std::shared_ptr deviceStateMgr_; diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index 8bab21877..d39197b62 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -144,7 +144,6 @@ public: const std::string &remoteUdid); std::map GetDeviceIdAndBindLevel(int32_t userId); - private: std::string GetUdidHashByNetworkId(const std::string &networkId); diff --git a/services/implementation/src/authentication/auth_message_processor.cpp b/services/implementation/src/authentication/auth_message_processor.cpp index eeb719b9b..26ab14c88 100644 --- a/services/implementation/src/authentication/auth_message_processor.cpp +++ b/services/implementation/src/authentication/auth_message_processor.cpp @@ -42,7 +42,7 @@ AuthMessageProcessor::~AuthMessageProcessor() void AuthMessageProcessor::GetJsonObj(nlohmann::json &jsonObj) { - if (authResponseContext_->bindType.size() > MAX_BINDTYPE_SIZE) { + if (authResponseContext_ == nullptr || authResponseContext_->bindType.size() > MAX_BINDTYPE_SIZE) { LOGE("GetJsonObj invalid bindType size."); return; } diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index cc4a026ea..1261f6137 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -1948,12 +1948,8 @@ void DmAuthManager::SrcAuthDeviceFinish() if (authResponseContext_->confirmOperation == USER_OPERATION_TYPE_ALLOW_AUTH || (authResponseContext_->confirmOperation == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS && authResponseContext_->haveCredential)) { - if ((authResponseContext_->bindLevel == APP || authResponseContext_->bindLevel == SERVICE) && - !authResponseContext_->isIdenticalAccount && !authResponseContext_->hostPkgName.empty()) { - ProcessInfo processInfo; - processInfo.pkgName = authResponseContext_->hostPkgName; - processInfo.userId = authResponseContext_->localUserId; - softbusConnector_->SetProcessInfo(processInfo); + if (!authResponseContext_->isIdenticalAccount && !authResponseContext_->hostPkgName.empty()) { + SetProcessInfo(); } softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK)); @@ -1965,12 +1961,8 @@ void DmAuthManager::SrcAuthDeviceFinish() if (authResponseContext_->confirmOperation == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS && !authResponseContext_->haveCredential) { authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT); - if ((authResponseContext_->bindLevel == APP || authResponseContext_->bindLevel == SERVICE) && - !authResponseContext_->isIdenticalAccount && !authResponseContext_->hostPkgName.empty()) { - ProcessInfo processInfo; - processInfo.pkgName = authResponseContext_->hostPkgName; - processInfo.userId = authResponseContext_->localUserId; - softbusConnector_->SetProcessInfo(processInfo); + if (!authResponseContext_->isIdenticalAccount && !authResponseContext_->hostPkgName.empty()) { + SetProcessInfo(); } softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); authRequestState_->TransitionTo(std::make_shared()); @@ -1999,10 +1991,7 @@ void DmAuthManager::SinkAuthDeviceFinish() } if (authResponseContext_->isOnline) { LOGI("The device is online."); - ProcessInfo processInfo; - processInfo.pkgName = authResponseContext_->hostPkgName; - processInfo.userId = authResponseContext_->localUserId; - softbusConnector_->SetProcessInfo(processInfo); + SetProcessInfo(); softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); } } @@ -2276,25 +2265,22 @@ void DmAuthManager::PutAccessControlList() aclInfo.deviceIdHash = localUdidHash; DmAccesser accesser; accesser.requestBundleName = authResponseContext_->hostPkgName; + DmAccessee accessee; + accessee.trustBundleName = authResponseContext_->hostPkgName; if (authRequestState_ != nullptr && authResponseState_ == nullptr) { accesser.requestTokenId = static_cast(authResponseContext_->tokenId); accesser.requestUserId = authRequestContext_->localUserId; accesser.requestAccountId = authRequestContext_->localAccountId; accesser.requestDeviceId = authRequestContext_->localDeviceId; - } else if (authRequestState_ == nullptr && authResponseState_ != nullptr) { - accesser.requestTokenId = static_cast(authResponseContext_->remoteTokenId); - accesser.requestUserId = authResponseContext_->remoteUserId; - accesser.requestAccountId = authResponseContext_->remoteAccountId; - accesser.requestDeviceId = authResponseContext_->localDeviceId; - } - DmAccessee accessee; - accessee.trustBundleName = authResponseContext_->hostPkgName; - if (authRequestState_ != nullptr && authResponseState_ == nullptr) { accessee.trustTokenId = static_cast(authResponseContext_->remoteTokenId); accessee.trustUserId = authRequestContext_->remoteUserId; accessee.trustAccountId = authRequestContext_->remoteAccountId; accessee.trustDeviceId = authResponseContext_->deviceId; } else if (authRequestState_ == nullptr && authResponseState_ != nullptr) { + accesser.requestTokenId = static_cast(authResponseContext_->remoteTokenId); + accesser.requestUserId = authResponseContext_->remoteUserId; + accesser.requestAccountId = authResponseContext_->remoteAccountId; + accesser.requestDeviceId = authResponseContext_->localDeviceId; accessee.trustTokenId = static_cast(authResponseContext_->tokenId); accessee.trustUserId = authResponseContext_->localUserId; accessee.trustAccountId = authResponseContext_->localAccountId; @@ -2552,5 +2538,19 @@ int32_t DmAuthManager::GetBinderInfo() } return ret; } + +void DmAuthManager::SetProcessInfo() +{ + CHECK_NULL_VOID(authResponseContext_); + ProcessInfo processInfo; + if (authResponseContext_->bindLevel == APP) { + processInfo.pkgName = authResponseContext_->hostPkgName; + processInfo.userId = authResponseContext_->localUserId; + } else if (authResponseContext_->bindLevel == DEVICE || authResponseContext_->bindLevel == INVALIED_TYPE) { + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = authResponseContext_->localUserId; + } + softbusConnector_->SetProcessInfo(processInfo); +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index e0523d1b8..df582817f 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -660,6 +660,10 @@ int32_t DeviceManagerServiceImpl::DpAclAdd(const std::string &udid) MultipleUserConnector::SetSwitchOldAccountId(MultipleUserConnector::GetOhosAccountId()); if (deviceStateMgr_->CheckIsOnline(udid)) { LOGI("DeviceManagerServiceImpl DpAclAdd identical account and online"); + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + processInfo.userId = MultipleUserConnector::GetForegroundUser(); + softbusConnector_->SetProcessInfo(processInfo); deviceStateMgr_->OnDeviceOnline(udid, DmAuthForm::IDENTICAL_ACCOUNT); } LOGI("DeviceManagerServiceImpl::DpAclAdd completed"); diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index e7d6cfeb8..d69ad0e04 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -94,6 +94,7 @@ private: #endif std::vector GetWhiteListSAProcessInfo(); std::vector GetNotifyProcessInfoByUserId(int32_t userId); + ProcessInfo DealBindProcessInfo(const ProcessInfo &processInfo); private: #if !defined(__LITEOS_M__) IpcServerListener ipcServerListener_; diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index 00d8fd798..9d4f63042 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -252,7 +252,8 @@ public: */ virtual int32_t UnRegisterUiStateCallback(const std::string &pkgName) = 0; - virtual std::unordered_map GetAppTrustDeviceIdList(std::string pkgname, int32_t userId) = 0; + virtual std::unordered_map + GetAppTrustDeviceIdList(std::string pkgname, int32_t userId) = 0; virtual int32_t DpAclAdd(const std::string &udid) = 0; virtual int32_t IsSameAccount(const std::string &udid) = 0; virtual void ScreenCommonEventCallback(std::string commonEventType) = 0; diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index fba0a4d9d..2c5b2bced 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -228,7 +228,7 @@ void DeviceManagerService::UnRegisterCallerAppId(const std::string &pkgName) AppManager::GetInstance().UnRegisterCallerAppId(pkgName); } -int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, const std::string &extra, +int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, const std::string &extra,//todo 56 std::vector &deviceList) { LOGI("Begin for pkgName = %{public}s.", pkgName.c_str()); @@ -1637,7 +1637,7 @@ void DeviceManagerService::HandleUserSwitched(int32_t curUserId, int32_t preUser curUserDeviceMap = dmServiceImpl_->GetDeviceIdAndBindLevel(curUserId); preUserDeviceMap = dmServiceImpl_->GetDeviceIdAndBindLevel(preUserId); for (const auto &item : curUserDeviceMap) { - peerUdids.push_back(item.first); + peerUdids.push_back(item.first); } for (const auto &item : preUserDeviceMap) { if (find(peerUdids.begin(), peerUdids.end(), item.first) == peerUdids.end()) { diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index 5f6e71a71..366b6f3c8 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -156,6 +156,8 @@ void DeviceManagerServiceListener::ProcessAppStateChange(const ProcessInfo &proc std::shared_ptr pReq = std::make_shared(); std::shared_ptr pRsp = std::make_shared(); std::vector processInfos = GetWhiteListSAProcessInfo(); + ProcessInfo bindProcessInfo = DealBindProcessInfo(processInfo); + processInfos.push_back(bindProcessInfo); if (state == DEVICE_STATE_ONLINE) { for (const auto &it : processInfos) { { @@ -611,5 +613,16 @@ std::vector DeviceManagerServiceListener::GetNotifyProcessInfoByUse } return processInfosTemp; } + +ProcessInfo DeviceManagerServiceListener::DealBindProcessInfo(const ProcessInfo &processInfo) +{ + std::set systemSA = ipcServerListener_.GetSystemSA(); + if (systemSA.find(processInfo.pkgName) == systemSA.end()) { + return processInfo; + } + ProcessInfo bindProcessInfo = processInfo; + bindProcessInfo.userId = 0; + return bindProcessInfo; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/service/src/discovery/discovery_manager.cpp b/services/service/src/discovery/discovery_manager.cpp index 82d5e012a..a015ea43f 100644 --- a/services/service/src/discovery/discovery_manager.cpp +++ b/services/service/src/discovery/discovery_manager.cpp @@ -614,7 +614,7 @@ void DiscoveryManager::ClearDiscoveryCache(const std::string &pkgName) uint16_t subscribeId = 0; { std::lock_guard autoLock(locks_); - if (pkgNameSet_.find(pkgName) != pkgNameSet_.end()) { //todo 发现待修改 + if (pkgNameSet_.find(pkgName) != pkgNameSet_.end()) { LOGI("Erase pkgname %{public}s from pkgNameSet.", pkgName.c_str()); pkgNameSet_.erase(pkgName); } diff --git a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp index 94e5a033a..41af96b9e 100644 --- a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp +++ b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp @@ -251,7 +251,7 @@ void RelationShipChangeMsg::ToSyncForegroundUserIdPayLoad(uint8_t *&msg, uint32_ for (uint32_t idx = 1; idx < len;) { msg[idx] |= foregroundUserIds[idx - 1] & 0xFF; msg[idx + 1] |= (foregroundUserIds[idx - 1] >> BITS_PER_BYTE) & 0xFF; - idx += 2; + idx += 2;//todo } } -- Gitee From 4ddc32ec13b05381d415608082cd455548feb915 Mon Sep 17 00:00:00 2001 From: hwzhangchuang Date: Fri, 8 Nov 2024 21:31:49 +0800 Subject: [PATCH 24/27] add checksum nofitfy Signed-off-by: hwzhangchuang --- .../service/include/device_manager_service.h | 1 + .../include/softbus/softbus_listener.h | 1 + .../service/src/device_manager_service.cpp | 68 +++++++++++++++++-- .../service/src/softbus/softbus_listener.cpp | 20 +++++- 4 files changed, 81 insertions(+), 9 deletions(-) diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index 25141ceb1..fe4fa3947 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -185,6 +185,7 @@ public: bool CheckIsSameAccount(const DmAccessCaller &caller, const DmAccessCallee &callee); void HandleDeviceNotTrust(const std::string &msg); void HandleDeviceTrustedChange(const std::string &msg); + void HandleUserIdCheckSumChange(const std::string &msg); int32_t SetDnPolicy(const std::string &pkgName, std::map &policy); void ClearDiscoveryCache(const ProcessInfo &processInfo); diff --git a/services/service/include/softbus/softbus_listener.h b/services/service/include/softbus/softbus_listener.h index 9cfe41426..d6dfaf6cf 100644 --- a/services/service/include/softbus/softbus_listener.h +++ b/services/service/include/softbus/softbus_listener.h @@ -56,6 +56,7 @@ public: static void OnDeviceTrustedChange(TrustChangeType type, const char *msg, uint32_t msgLen); static void DeviceNotTrust(const std::string &msg); static void DeviceTrustedChange(const std::string &msg); + static void DeviceUserIdCheckSumChange(const std::string &msg); static void OnDeviceScreenStatusChanged(NodeStatusType type, NodeStatus *status); static void DeviceScreenStatusChange(DmDeviceInfo deviceInfo); static void OnCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index b1454f904..34d983741 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -19,6 +19,7 @@ #include #include "app_manager.h" +#include "nlohmann/json.hpp" #include "dm_anonymous.h" #include "dm_constants.h" #include "dm_crypto.h" @@ -60,13 +61,18 @@ constexpr const char* LIB_DM_ADAPTER_NAME = "libdevicemanageradapter.z.so"; namespace OHOS { namespace DistributedHardware { DM_IMPLEMENT_SINGLE_INSTANCE(DeviceManagerService); -const int32_t NORMAL = 0; -const int32_t SYSTEM_BASIC = 1; -const int32_t SYSTEM_CORE = 2; -constexpr const char* ALL_PKGNAME = ""; -constexpr const char* NETWORKID = "NETWORK_ID"; -constexpr uint32_t INVALIED_BIND_LEVEL = 0; -constexpr uint32_t DM_IDENTICAL_ACCOUNT = 1; +namespace { + const int32_t NORMAL = 0; + const int32_t SYSTEM_BASIC = 1; + const int32_t SYSTEM_CORE = 2; + constexpr const char *ALL_PKGNAME = ""; + constexpr const char *NETWORKID = "NETWORK_ID"; + constexpr uint32_t INVALIED_BIND_LEVEL = 0; + constexpr uint32_t DM_IDENTICAL_ACCOUNT = 1; + const std::string USERID_CHECKSUM_NETWORKID_KEY = "networkId"; + const std::string USERID_CHECKSUM_DISCOVER_TYPE_KEY = "discoverType"; + constexpr uint32_t USERID_CHECKSUM_DISCOVERY_TYPE_WIFI_MASK = 0b0010; +} DeviceManagerService::~DeviceManagerService() { LOGI("DeviceManagerService destructor"); @@ -1964,6 +1970,54 @@ void DeviceManagerService::HandleDeviceTrustedChange(const std::string &msg) return; } +void DeviceManagerService::HandleUserIdCheckSumChange(const std::string &msg) +{ + if (msg.empty()) { + LOGE("Msg is empty."); + return; + } + LOGI("handle user trust change, msg: %{public}s", msg.c_str()); + + nlohmann::json msgJsonObj = nlohmann::json::parse(msg, nullptr, false); + if (msgJsonObj.is_discarded()) { + LOGE("msg prase error."); + return; + } + if (!IsString(msgJsonObj, USERID_CHECKSUM_NETWORKID_KEY)) { + LOGE("msg not contain networkId."); + return; + } + if (!IsUint32(msgJsonObj, USERID_CHECKSUM_DISCOVER_TYPE_KEY)) { + LOGE("msg not contain discoveryType."); + return; + } + std::string peerNetworkId = msgJsonObj[USERID_CHECKSUM_NETWORKID_KEY].get(); + uint32_t discoveryType = msgJsonObj[USERID_CHECKSUM_DISCOVER_TYPE_KEY].get(); + + if ((discoveryType & USERID_CHECKSUM_DISCOVERY_TYPE_WIFI_MASK) != 0x0) { + // TODO: use connection to exchange foreground userid + LOGI("Try open softbus session to exchange foreground userid"); + } else { + LOGI("Try send brodcast to exchange foreground userid"); + std::string udid = ""; + SoftbusCache::GetInstance().GetUdidFromCache(peerNetworkId.c_str(), udid); + if (udid.empty()) { + LOGE("Can not get udid for networkid: %{public}s", GetAnonyString(peerNetworkId).c_str()); + return; + } + + std::vector peerUdids = { udid }; + std::vector userVec; + int32_t ret = MultipleUserConnector::GetForegroundUsers(userVec); + if (ret != DM_OK || userVec.empty()) { + LOGE("Get foreground userids failed, ret: %{public}d", ret); + } else { + LOGE("Send local forground userids"); + SendForegroundUserIdsBroadCast(peerUdids, userVec); + } + } +} + void DeviceManagerService::ClearDiscoveryCache(const ProcessInfo &processInfo) { LOGI("PkgName %{public}s.", processInfo.pkgName.c_str()); diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index b06255e35..76d207a87 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -62,6 +62,7 @@ static std::mutex g_lnnCbkMapMutex; static std::mutex g_radarLoadLock; static std::mutex g_onlineDeviceNumLock; static std::mutex g_lockDeviceTrustedChange; +static std::mutex g_lockUserIdCheckSumChange; static std::mutex g_lockDeviceOnLine; static std::mutex g_lockDeviceOffLine; static std::mutex g_lockDevInfoChange; @@ -159,6 +160,12 @@ void SoftbusListener::DeviceTrustedChange(const std::string &msg) DeviceManagerService::GetInstance().HandleDeviceTrustedChange(msg); } +void SoftbusListener::DeviceUserIdCheckSumChange(const std::string &msg) +{ + std::lock_guard lock(g_lockUserIdCheckSumChange); + DeviceManagerService::GetInstance().HandleUserIdCheckSumChange(msg); +} + void SoftbusListener::DeviceScreenStatusChange(DmDeviceInfo deviceInfo) { std::lock_guard lock(g_lockDevScreenStatusChange); @@ -349,16 +356,18 @@ void SoftbusListener::OnLocalDevInfoChange() void SoftbusListener::OnDeviceTrustedChange(TrustChangeType type, const char *msg, uint32_t msgLen) { LOGI("OnDeviceTrustedChange."); - if (msg == nullptr || msgLen > MAX_SOFTBUS_MSG_LEN) { + if (msg == nullptr || msgLen > MAX_SOFTBUS_MSG_LEN || strlen(msg) != msgLen) { LOGE("OnDeviceTrustedChange msg invalied."); return; } - std::string softbusMsg = std::string(msg); + std::string softbusMsg = std::string(msg, msgLen); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) if (type == TrustChangeType::DEVICE_NOT_TRUSTED) { ffrt::submit([=]() { DeviceNotTrust(softbusMsg); }); } else if (type == TrustChangeType::DEVICE_TRUST_RELATIONSHIP_CHANGE) { ffrt::submit([=]() { DeviceTrustedChange(softbusMsg); }); + } else if (type == TrustChangeType::DEVICE_USERIDCHECKSUM_CHANGE) { // DEVICE_USERIDCHECKSUM_CHANGE + ffrt::submit([=]() { DeviceUserIdCheckSumChange(softbusMsg); }); } else { LOGE("Invalied trust change type."); } @@ -377,6 +386,13 @@ void SoftbusListener::OnDeviceTrustedChange(TrustChangeType type, const char *ms LOGE("deviceTrustedChange setname failed."); } deviceTrustedChange.detach(); + } else if (type == TrustChangeType::DEVICE_USERIDCHECKSUM_CHANGE) { // DEVICE_USERIDCHECKSUM_CHANGE + std::thread deviceUserIdCheckSumChange([=]() { DeviceUserIdCheckSumChange(softbusMsg); }); + int32_t ret = pthread_setname_np(deviceUserIdCheckSumChange.native_handle(), DEVICE_NOT_TRUST); + if (ret != DM_OK) { + LOGE("deviceUserIdCheckSumChange setname failed."); + } + deviceUserIdCheckSumChange.detach(); } else { LOGE("Invalied trust change type."); } -- Gitee From 26eee666b68f110bbd694e2622dcf52dd94751cd Mon Sep 17 00:00:00 2001 From: yangwei_814916 Date: Sat, 9 Nov 2024 10:23:46 +0800 Subject: [PATCH 25/27] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=8F=91=E7=8E=B0?= =?UTF-8?q?=E5=9B=9E=E8=B0=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yangwei_814916 --- .../include/device_manager_service_listener.h | 14 +- .../src/device_manager_service_listener.cpp | 222 ++++++++++++------ 2 files changed, 161 insertions(+), 75 deletions(-) diff --git a/services/service/include/device_manager_service_listener.h b/services/service/include/device_manager_service_listener.h index d69ad0e04..2f0dee87b 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -95,11 +95,21 @@ private: std::vector GetWhiteListSAProcessInfo(); std::vector GetNotifyProcessInfoByUserId(int32_t userId); ProcessInfo DealBindProcessInfo(const ProcessInfo &processInfo); + void ProcessDeviceOnline(const std::vector procInfoVec, const ProcessInfo &processInfo, + const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); + void ProcessDeviceOffline(const std::vector procInfoVec, const ProcessInfo &processInfo, + const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); + void ProcessDeviceInfoChange(const std::vector procInfoVec, const ProcessInfo &processInfo, + const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); + void ProcessAppOnline(const std::vector procInfoVec, const ProcessInfo &processInfo, + const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); + void ProcessAppOffline(const std::vector procInfoVec, const ProcessInfo &processInfo, + const DmDeviceState &state, const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo); private: #if !defined(__LITEOS_M__) IpcServerListener ipcServerListener_; - static std::mutex alreadyOnlinePkgNameLock_; - static std::map alreadyOnlinePkgName_; + static std::mutex alreadyNotifyPkgNameLock_; + static std::map alreadyOnlinePkgName_; #endif }; } // namespace DistributedHardware diff --git a/services/service/src/device_manager_service_listener.cpp b/services/service/src/device_manager_service_listener.cpp index 366b6f3c8..ae4d67783 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -46,8 +46,8 @@ namespace OHOS { namespace DistributedHardware { -std::mutex DeviceManagerServiceListener::alreadyOnlinePkgNameLock_; -std::map DeviceManagerServiceListener::alreadyOnlinePkgName_ = {}; +std::mutex DeviceManagerServiceListener::alreadyNotifyPkgNameLock_; +std::map DeviceManagerServiceListener::alreadyOnlinePkgName_ = {}; void DeviceManagerServiceListener::ConvertDeviceInfoToDeviceBasicInfo(const std::string &pkgName, const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo) { @@ -116,36 +116,20 @@ void DeviceManagerServiceListener::ProcessDeviceStateChange(const ProcessInfo &p const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo) { LOGI("In"); - std::shared_ptr pReq = std::make_shared(); - std::shared_ptr pRsp = std::make_shared(); std::vector processInfoVec = GetNotifyProcessInfoByUserId(processInfo.userId); - if (state == DEVICE_STATE_OFFLINE) { - RemoveOnlinePkgName(info); - for (const auto &it : processInfoVec) { - SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); - ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); - } - } - if (state == DEVICE_STATE_ONLINE) { - for (const auto &it : processInfoVec) { - DmDeviceState notifyState = state; - { - std::lock_guard autoLock(alreadyOnlinePkgNameLock_); - if (alreadyOnlinePkgName_.find(it) != alreadyOnlinePkgName_.end()) { - notifyState = DmDeviceState::DEVICE_INFO_CHANGED; - } else { - alreadyOnlinePkgName_[it] = info; - } - } - SetDeviceInfo(pReq, it, notifyState, info, deviceBasicInfo); - ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); - } - } - if (state == DEVICE_INFO_READY || state == DEVICE_INFO_CHANGED) { - for (const auto &it : processInfoVec) { - SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); - ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); - } + switch (static_cast(state)) { + case static_cast(DmDeviceState::DEVICE_STATE_ONLINE): + ProcessDeviceOnline(processInfoVec, processInfo, state, info, deviceBasicInfo); + break; + case static_cast(DmDeviceState::DEVICE_STATE_OFFLINE): + ProcessDeviceOffline(processInfoVec, processInfo, state, info, deviceBasicInfo); + break; + case static_cast(DmDeviceState::DEVICE_INFO_READY): + case static_cast(DmDeviceState::DEVICE_INFO_CHANGED): + ProcessDeviceInfoChange(processInfoVec, processInfo, state, info, deviceBasicInfo); + break; + default: + break; } } @@ -153,45 +137,20 @@ void DeviceManagerServiceListener::ProcessAppStateChange(const ProcessInfo &proc const DmDeviceInfo &info, const DmDeviceBasicInfo &deviceBasicInfo) { LOGI("In"); - std::shared_ptr pReq = std::make_shared(); - std::shared_ptr pRsp = std::make_shared(); - std::vector processInfos = GetWhiteListSAProcessInfo(); - ProcessInfo bindProcessInfo = DealBindProcessInfo(processInfo); - processInfos.push_back(bindProcessInfo); - if (state == DEVICE_STATE_ONLINE) { - for (const auto &it : processInfos) { - { - std::lock_guard autoLock(alreadyOnlinePkgNameLock_); - if (alreadyOnlinePkgName_.find(it) != alreadyOnlinePkgName_.end()) { - continue; - } - alreadyOnlinePkgName_[it] = info; - } - SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); - ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); - } - } - if (state == DEVICE_STATE_OFFLINE) { - if (!SoftbusCache::GetInstance().CheckIsOnline(std::string(info.deviceId))) { - RemoveOnlinePkgName(info); - for (const auto &it : processInfos) { - SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); - ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); - } - } else { - { - std::lock_guard autoLock(alreadyOnlinePkgNameLock_); - if (alreadyOnlinePkgName_.find(processInfo) != alreadyOnlinePkgName_.end()) { - alreadyOnlinePkgName_.erase(processInfo); - } - } - SetDeviceInfo(pReq, processInfo, state, info, deviceBasicInfo); - ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); - } - } - if (state == DEVICE_INFO_READY || state == DEVICE_INFO_CHANGED) { - SetDeviceInfo(pReq, processInfo, state, info, deviceBasicInfo); - ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); + std::vector processInfoVec = GetWhiteListSAProcessInfo(); + switch (static_cast(state)) { + case static_cast(DmDeviceState::DEVICE_STATE_ONLINE): + ProcessAppOnline(processInfoVec, processInfo, state, info, deviceBasicInfo); + break; + case static_cast(DmDeviceState::DEVICE_STATE_OFFLINE): + ProcessAppOffline(processInfoVec, processInfo, state, info, deviceBasicInfo); + break; + case static_cast(DmDeviceState::DEVICE_INFO_READY): + case static_cast(DmDeviceState::DEVICE_INFO_CHANGED): + ProcessDeviceInfoChange(processInfoVec, processInfo, state, info, deviceBasicInfo); + break; + default: + break; } } @@ -548,7 +507,7 @@ void DeviceManagerServiceListener::RemoveOnlinePkgName(const DmDeviceInfo &info) { LOGI("udidHash: %{public}s.", GetAnonyString(info.deviceId).c_str()); { - std::lock_guard autoLock(alreadyOnlinePkgNameLock_); + std::lock_guard autoLock(alreadyNotifyPkgNameLock_); for (auto item = alreadyOnlinePkgName_.begin(); item != alreadyOnlinePkgName_.end();) { if (std::string(item->second.deviceId) == std::string(info.deviceId)) { item = alreadyOnlinePkgName_.erase(item); @@ -575,9 +534,9 @@ void DeviceManagerServiceListener::OnCredentialAuthStatus(const ProcessInfo &pro void DeviceManagerServiceListener::OnAppUnintall(const std::string &pkgName) { - std::lock_guard autoLock(alreadyOnlinePkgNameLock_); + std::lock_guard autoLock(alreadyNotifyPkgNameLock_); for (auto it = alreadyOnlinePkgName_.begin(); it != alreadyOnlinePkgName_.end();) { - if (it->first.pkgName.find(pkgName) == 0) { + if (it->first.find(pkgName) == 0) { it = alreadyOnlinePkgName_.erase(it); } else { ++it; @@ -624,5 +583,122 @@ ProcessInfo DeviceManagerServiceListener::DealBindProcessInfo(const ProcessInfo bindProcessInfo.userId = 0; return bindProcessInfo; } + +void DeviceManagerServiceListener::ProcessDeviceOnline(const std::vector procInfoVec, + const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, + const DmDeviceBasicInfo &deviceBasicInfo) +{ + LOGI("userId %{public}d, state %{public}d, udidhash %{public}s.", processInfo.userId, static_cast(state), + GetAnonyString(info.deviceId).c_str()); + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + for (const auto &it : procInfoVec) { + std::string notifyPkgname = processInfo.pkgName + "#" + + std::to_string(processInfo.userId) + "#" + std::string(info.deviceId); + DmDeviceState notifyState = state; + { + std::lock_guard autoLock(alreadyNotifyPkgNameLock_); + if (alreadyOnlinePkgName_.find(notifyPkgname) != alreadyOnlinePkgName_.end()) { + notifyState = DmDeviceState::DEVICE_INFO_CHANGED; + } else { + alreadyOnlinePkgName_[notifyPkgname] = info; + } + } + SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); + ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); + } +} + +void DeviceManagerServiceListener::ProcessDeviceOffline(const std::vector procInfoVec, + const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, + const DmDeviceBasicInfo &deviceBasicInfo) +{ + LOGI("userId %{public}d, state %{public}d, udidhash %{public}s.", processInfo.userId, static_cast(state), + GetAnonyString(info.deviceId).c_str()); + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + if (!SoftbusCache::GetInstance().CheckIsOnline(std::string(info.deviceId))) { + RemoveOnlinePkgName(info); + } + for (const auto &it : procInfoVec) { + std::string notifyPkgname = processInfo.pkgName + "#" + + std::to_string(processInfo.userId) + "#" + std::string(info.deviceId); + { + std::lock_guard autoLock(alreadyNotifyPkgNameLock_); + if (alreadyOnlinePkgName_.find(notifyPkgname) != alreadyOnlinePkgName_.end()) { + alreadyOnlinePkgName_.erase(notifyPkgname); + } + } + SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); + ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); + } +} + +void DeviceManagerServiceListener::ProcessDeviceInfoChange(const std::vector procInfoVec, + const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, + const DmDeviceBasicInfo &deviceBasicInfo) +{ + LOGI("userId %{public}d, state %{public}d, udidhash %{public}s.", processInfo.userId, static_cast(state), + GetAnonyString(info.deviceId).c_str()); + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + for (const auto &it : procInfoVec) { + SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); + ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); + } +} + +void DeviceManagerServiceListener::ProcessAppOnline(const std::vector procInfoVec, + const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, + const DmDeviceBasicInfo &deviceBasicInfo) +{ + LOGI("userId %{public}d, state %{public}d, udidhash %{public}s.", processInfo.userId, static_cast(state), + GetAnonyString(info.deviceId).c_str()); + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + for (const auto &it : procInfoVec) { + std::string notifyPkgname = processInfo.pkgName + "#" + + std::to_string(processInfo.userId) + "#" + std::string(info.deviceId); + DmDeviceState notifyState = state; + { + std::lock_guard autoLock(alreadyNotifyPkgNameLock_); + if (alreadyOnlinePkgName_.find(notifyPkgname) != alreadyOnlinePkgName_.end()) { + notifyState = DmDeviceState::DEVICE_INFO_CHANGED; + } else { + alreadyOnlinePkgName_[notifyPkgname] = info; + } + } + SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); + ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); + } +} + +void DeviceManagerServiceListener::ProcessAppOffline(const std::vector procInfoVec, + const ProcessInfo &processInfo, const DmDeviceState &state, const DmDeviceInfo &info, + const DmDeviceBasicInfo &deviceBasicInfo) +{ + LOGI("userId %{public}d, state %{public}d, udidhash %{public}s.", processInfo.userId, static_cast(state), + GetAnonyString(info.deviceId).c_str()); + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + if (!SoftbusCache::GetInstance().CheckIsOnline(std::string(info.deviceId))) { + RemoveOnlinePkgName(info); + for (const auto &it : procInfoVec) { + SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); + ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); + } + } else { + std::string notifyPkgname = processInfo.pkgName + "#" + + std::to_string(processInfo.userId) + "#" + std::string(info.deviceId); + { + std::lock_guard autoLock(alreadyNotifyPkgNameLock_); + if (alreadyOnlinePkgName_.find(notifyPkgname) != alreadyOnlinePkgName_.end()) { + alreadyOnlinePkgName_.erase(notifyPkgname); + } + } + SetDeviceInfo(pReq, processInfo, state, info, deviceBasicInfo); + ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); + } +} } // namespace DistributedHardware } // namespace OHOS -- Gitee From ccb63565cff9069b347ca6671904ed927416b775 Mon Sep 17 00:00:00 2001 From: hwzhangchuang Date: Sat, 9 Nov 2024 22:20:59 +0800 Subject: [PATCH 26/27] add exchange userid by open session Signed-off-by: hwzhangchuang --- common/include/dm_anonymous.h | 2 + common/include/dm_constants.h | 1 + common/src/dm_anonymous.cpp | 20 + services/service/BUILD.gn | 6 + .../service/include/device_manager_service.h | 2 + .../relationshipsyncmgr/dm_comm_tool.h | 67 +++ .../relationshipsyncmgr/dm_transport.h | 67 +++ .../relationshipsyncmgr/dm_transport_msg.h | 59 +++ .../service/src/device_manager_service.cpp | 39 +- .../src/relationshipsyncmgr/dm_comm_tool.cpp | 246 ++++++++++ .../src/relationshipsyncmgr/dm_transport.cpp | 454 ++++++++++++++++++ .../relationshipsyncmgr/dm_transport_msg.cpp | 113 +++++ 12 files changed, 1068 insertions(+), 8 deletions(-) create mode 100644 services/service/include/relationshipsyncmgr/dm_comm_tool.h create mode 100644 services/service/include/relationshipsyncmgr/dm_transport.h create mode 100644 services/service/include/relationshipsyncmgr/dm_transport_msg.h create mode 100644 services/service/src/relationshipsyncmgr/dm_comm_tool.cpp create mode 100644 services/service/src/relationshipsyncmgr/dm_transport.cpp create mode 100644 services/service/src/relationshipsyncmgr/dm_transport_msg.cpp diff --git a/common/include/dm_anonymous.h b/common/include/dm_anonymous.h index 69efd3c68..90328b628 100644 --- a/common/include/dm_anonymous.h +++ b/common/include/dm_anonymous.h @@ -72,6 +72,8 @@ std::string GetAnonyIntegerList(const std::vector &values) } return temp; } +bool IsIdLengthValid(const std::string &inputID); +bool IsMessageLengthValid(const std::string &inputMessage); } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_ANONYMOUS_H diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index 026659bb4..eba3ce7d4 100755 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -131,6 +131,7 @@ constexpr const char* DM_ITF_VER = "1.1"; constexpr const char* DM_PKG_NAME = "ohos.distributedhardware.devicemanager"; constexpr const char* DM_SESSION_NAME = "ohos.distributedhardware.devicemanager.resident"; constexpr const char* DM_PIN_HOLDER_SESSION_NAME = "ohos.distributedhardware.devicemanager.pinholder"; +constexpr const char* DM_SYNC_USERID_SESSION_NAME = "ohos.distributedhardware.devicemanager.syncuserid"; constexpr const char* DM_CAPABILITY_OSD = "osdCapability"; constexpr const char* DM_CAPABILITY_APPROACH = "approach"; constexpr const char* DM_CAPABILITY_TOUCH = "touch"; diff --git a/common/src/dm_anonymous.cpp b/common/src/dm_anonymous.cpp index 79e2b422f..e502e7d3a 100644 --- a/common/src/dm_anonymous.cpp +++ b/common/src/dm_anonymous.cpp @@ -22,6 +22,7 @@ namespace { constexpr uint32_t MAX_MESSAGE_LEN = 40 * 1024 * 1024; constexpr uint32_t MAX_MAP_LEN = 1000; constexpr uint32_t MAX_INT_LEN = 20; +constexpr uint32_t MAX_ID_LEN = 256; } std::string GetAnonyString(const std::string &value) @@ -314,5 +315,24 @@ uint16_t GetSubscribeId(const std::string &pkgName) { } return 0; } + +bool IsIdLengthValid(const std::string &inputID) +{ + if (inputID.empty() || inputID.length() > MAX_ID_LEN) { + LOGE("On parameter length error, maybe empty or beyond MAX_ID_LEN!"); + return false; + } + return true; +} + +bool IsMessageLengthValid(const std::string &inputMessage) +{ + if (inputMessage.empty() || inputMessage.length() > MAX_MESSAGE_LEN) { + LOGE("On parameter error, maybe empty or beyond MAX_MESSAGE_LEN!"); + return false; + } + return true; +} + } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/service/BUILD.gn b/services/service/BUILD.gn index ee1da5e34..571a17bcd 100644 --- a/services/service/BUILD.gn +++ b/services/service/BUILD.gn @@ -72,6 +72,9 @@ if (defined(ohos_lite)) { "src/permission/lite/permission_manager.cpp", "src/pinholder/pin_holder.cpp", "src/pinholder/pin_holder_session.cpp", + "src/relationshipsyncmgr/dm_comm_tool.cpp", + "src/relationshipsyncmgr/dm_transport_msg.cpp", + "src/relationshipsyncmgr/dm_transport.cpp", "src/relationshipsyncmgr/relationship_sync_mgr.cpp", "src/softbus/mine_softbus_listener.cpp", "src/softbus/softbus_listener.cpp", @@ -180,6 +183,9 @@ if (defined(ohos_lite)) { "src/publishcommonevent/dm_data_share_common_event.cpp", "src/publishcommonevent/dm_package_common_event.cpp", "src/publishcommonevent/dm_screen_common_event.cpp", + "src/relationshipsyncmgr/dm_comm_tool.cpp", + "src/relationshipsyncmgr/dm_transport_msg.cpp", + "src/relationshipsyncmgr/dm_transport.cpp", "src/relationshipsyncmgr/relationship_sync_mgr.cpp", "src/softbus/mine_softbus_listener.cpp", "src/softbus/softbus_listener.cpp", diff --git a/services/service/include/device_manager_service.h b/services/service/include/device_manager_service.h index fe4fa3947..31c07bb2d 100644 --- a/services/service/include/device_manager_service.h +++ b/services/service/include/device_manager_service.h @@ -195,6 +195,8 @@ public: void SubscribePackageCommonEvent(); int32_t GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid, std::string &networkId); void HandleCredentialAuthStatus(uint16_t deviceTypeId, int32_t errcode); + void ProcessForegroundUserIds(const std::vector &remoteUserIds, const std::string &remoteUdid); + private: bool IsDMServiceImplReady(); bool IsDMServiceAdapterLoad(); diff --git a/services/service/include/relationshipsyncmgr/dm_comm_tool.h b/services/service/include/relationshipsyncmgr/dm_comm_tool.h new file mode 100644 index 000000000..1b89e6062 --- /dev/null +++ b/services/service/include/relationshipsyncmgr/dm_comm_tool.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_COMM_TOOL_H +#define OHOS_DM_COMM_TOOL_H + +#include +#include +#include +#include + +#include "dm_transport.h" +#include "dm_transport_msg.h" +#include "event_handler.h" + +namespace OHOS { +namespace DistributedHardware { +// send local foreground userids msg +constexpr int32_t DM_COMM_SEND_LOCAL_FOREGROUND_USERIDS = 1; +// if receive remote device send foreground userids, response local foreground uerids +// This msg no need response +constexpr int32_t DM_COMM_RSP_LOCAL_FOREGROUND_USERIDS = 2; + +class DMCommTool : public std::enable_shared_from_this { +public: + DMCommTool(); + virtual ~DMCommTool() = default; + static std::shared_ptr GetInstance(); + void Init(); + void UnInit(); + + void SendLocalForegroundUserIds(const std::string rmtNetworkId, const std::vector &userids); + void RspLocalForegroundUserIds(const std::string rmtNetworkId, const std::vector &userids); + + class DMCommToolEventHandler : public AppExecFwk::EventHandler { + public: + DMCommToolEventHandler(const std::shared_ptr runner, + std::shared_ptr dmCommToolPtr); + ~DMCommToolEventHandler() override = default; + void ProcessEvent(const AppExecFwk::InnerEvent::Pointer &event) override; + private: + std::weak_ptr dmCommToolWPtr_; + }; + std::shared_ptr GetEventHandler(); + const std::shared_ptr GetDMTransportPtr(); + + void ProcessReceiveUserIdsEvent(const std::shared_ptr commMsg); + void ProcessResponseUserIdsEvent(const std::shared_ptr commMsg); +private: + std::shared_ptr dmTransportPtr_; + std::shared_ptr eventHandler_; +}; +} // DistributedHardware +} // OHOS +#endif \ No newline at end of file diff --git a/services/service/include/relationshipsyncmgr/dm_transport.h b/services/service/include/relationshipsyncmgr/dm_transport.h new file mode 100644 index 000000000..cf8eb0890 --- /dev/null +++ b/services/service/include/relationshipsyncmgr/dm_transport.h @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_TRANSPORT_H +#define OHOS_DM_TRANSPORT_H + +#include +#include +#include +#include +#include +#include + +#include "event_handler.h" +#include "socket.h" +#include "softbus_bus_center.h" + +namespace OHOS { +namespace DistributedHardware { +class DMCommTool; +class DMTransport { +public: + explicit DMTransport(std::shared_ptr dmCommToolPtr); + int32_t Init(); + int32_t UnInit(); + virtual ~DMTransport() = default; + // open softbus channel with remote device by networkid. + int32_t StartSocket(const std::string &rmtNetworkId); + // stop softbus channel with remote device by networkid. + int32_t StopSocket(const std::string &rmtNetworkId); + int32_t Send(const std::string &rmtNetworkId, const std::string &payload); + int32_t OnSocketOpened(int32_t socketId, const PeerSocketInfo &info); + void OnSocketClosed(int32_t socketId, ShutdownReason reason); + void OnBytesReceived(int32_t socketId, const void *data, uint32_t dataLen); + +private: + int32_t CreateServerSocket(); + int32_t CreateClientSocket(const std::string &remoteDevId); + bool IsDeviceSessionOpened(const std::string &remoteDevId, int32_t &socketId); + std::string GetRemoteNetworkIdBySocketId(int32_t socketId); + void ClearDeviceSocketOpened(const std::string &remoteDevId); + void HandleReceiveMessage(const int32_t socketId, const std::string &payload); + +private: + std::mutex rmtSocketIdMtx_; + // record the socket id for the connection with remote devices, + std::map remoteDevSocketIds_; + std::atomic localServerSocket_; + std::string localSocketName_; + std::atomic isSocketSvrCreateFlag_; + std::weak_ptr dmCommToolWPtr_; +}; +} // DistributedHardware +} // OHOS +#endif \ No newline at end of file diff --git a/services/service/include/relationshipsyncmgr/dm_transport_msg.h b/services/service/include/relationshipsyncmgr/dm_transport_msg.h new file mode 100644 index 000000000..620ea648d --- /dev/null +++ b/services/service/include/relationshipsyncmgr/dm_transport_msg.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_DM_TRANSPORT_MSG_H +#define OHOS_DM_TRANSPORT_MSG_H + +#include +#include +#include + +namespace OHOS { +namespace DistributedHardware { +const char* const USERIDS_MSG_USERIDS_KEY = "userIds"; +const char* const COMM_MSG_CODE_KEY = "code"; +const char* const COMM_MSG_MSG_KEY = "msg"; + +struct UserIdsMsg { + std::vector userIds; + UserIdsMsg() : userIds({}) {} + UserIdsMsg(std::vector userIds) : userIds(userIds) {} +}; + +void ToJson(cJSON *jsonObject, const UserIdsMsg &userIds); +void FromJson(const cJSON *jsonObject, UserIdsMsg &userIds); + +struct CommMsg { + int32_t code; + std::string msg; + CommMsg() : code(-1), msg("") {} + CommMsg(int32_t code, std::string msg) : code(code), msg(msg) {} +}; + +void ToJson(cJSON *jsonObject, const CommMsg &commMsg); +void FromJson(const cJSON *jsonObject, CommMsg &commMsg); + +std::string GetCommMsgString(const CommMsg &commMsg); + +struct InnerCommMsg { + std::string remoteNetworkId; + std::shared_ptr commMsg; + InnerCommMsg(std::string remoteNetworkId, std::shared_ptr commMsg) + : remoteNetworkId(remoteNetworkId), commMsg(commMsg) {} +}; + +} // DistributedHardware +} // OHOS +#endif \ No newline at end of file diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 34d983741..92aa87e47 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -21,6 +21,7 @@ #include "app_manager.h" #include "nlohmann/json.hpp" #include "dm_anonymous.h" +#include "dm_comm_tool.h" #include "dm_constants.h" #include "dm_crypto.h" #include "dm_hidumper.h" @@ -209,6 +210,8 @@ int32_t DeviceManagerService::InitDMServiceListener() if (pinHolder_ == nullptr) { pinHolder_ = std::make_shared(listener_); } + + DMCommTool::GetInstance()->Init(); LOGI("Init success."); return DM_OK; } @@ -1747,6 +1750,20 @@ void DeviceManagerService::HandleForegroundUserIdsBroadCast(const std::vector &remoteUserIds, + const std::string &remoteUdid) +{ + LOGI("process foreground userids: %{public}s, remote udid: %{public}s", + GetAnonyIntegerList(remoteUserIds).c_str(), GetAnonyString(remoteUdid).c_str()); + if (IsDMServiceImplReady()) { + std::vector remoteUserIdsU16; + for (auto const &u : remoteUserIds) { + remoteUserIdsU16.push_back(static_cast(u)); + } + dmServiceImpl_->HandleSyncForegroundUserIdEvent(remoteUserIdsU16, remoteUdid); + } +} + void DeviceManagerService::ScreenCommonEventCallback(std::string commonEventType) { if (!IsDMImplSoLoaded()) { @@ -1994,9 +2011,21 @@ void DeviceManagerService::HandleUserIdCheckSumChange(const std::string &msg) std::string peerNetworkId = msgJsonObj[USERID_CHECKSUM_NETWORKID_KEY].get(); uint32_t discoveryType = msgJsonObj[USERID_CHECKSUM_DISCOVER_TYPE_KEY].get(); + std::vector userVec; + int32_t ret = MultipleUserConnector::GetForegroundUsers(userVec); + if (ret != DM_OK || userVec.empty()) { + LOGE("Get foreground userids failed, ret: %{public}d", ret); + return; + } + if ((discoveryType & USERID_CHECKSUM_DISCOVERY_TYPE_WIFI_MASK) != 0x0) { // TODO: use connection to exchange foreground userid LOGI("Try open softbus session to exchange foreground userid"); + std::vector userVecUInt; + for (auto const &u : userVec) { + userVecUInt.push_back(static_cast(u)); + } + DMCommTool::GetInstance()->SendLocalForegroundUserIds(peerNetworkId, userVecUInt); } else { LOGI("Try send brodcast to exchange foreground userid"); std::string udid = ""; @@ -2007,14 +2036,8 @@ void DeviceManagerService::HandleUserIdCheckSumChange(const std::string &msg) } std::vector peerUdids = { udid }; - std::vector userVec; - int32_t ret = MultipleUserConnector::GetForegroundUsers(userVec); - if (ret != DM_OK || userVec.empty()) { - LOGE("Get foreground userids failed, ret: %{public}d", ret); - } else { - LOGE("Send local forground userids"); - SendForegroundUserIdsBroadCast(peerUdids, userVec); - } + LOGE("Send local forground userids"); + SendForegroundUserIdsBroadCast(peerUdids, userVec); } } diff --git a/services/service/src/relationshipsyncmgr/dm_comm_tool.cpp b/services/service/src/relationshipsyncmgr/dm_comm_tool.cpp new file mode 100644 index 000000000..de589b6a3 --- /dev/null +++ b/services/service/src/relationshipsyncmgr/dm_comm_tool.cpp @@ -0,0 +1,246 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_comm_tool.h" + +#include "cJSON.h" + +#include "device_manager_service.h" +#include "dm_anonymous.h" +#include "dm_constants.h" +#include "dm_transport.h" +#include "dm_transport_msg.h" +#include "dm_log.h" +#include "dm_softbus_cache.h" +#include "multiple_user_connector.h" + +namespace OHOS { +namespace DistributedHardware { +DMCommTool::DMCommTool() : dmTransportPtr_(nullptr) +{ + LOGI("Ctor DMCommTool"); +} + +void DMCommTool::Init() +{ + LOGI("Init DMCommTool"); + dmTransportPtr_ = std::make_shared(shared_from_this()); + std::shared_ptr runner = AppExecFwk::EventRunner::Create(true); + eventHandler_ = std::make_shared(runner, shared_from_this()); + dmTransportPtr_->Init(); +} + +void DMCommTool::UnInit() +{ + LOGI("UnInit DMCommTool"); + if (dmTransportPtr_ == nullptr) { + LOGI("dmTransportPtr_ is null"); + return; + } + dmTransportPtr_->UnInit(); +} + +std::shared_ptr DMCommTool::GetInstance() +{ + static std::shared_ptr instance = std::make_shared(); + return instance; +} + +void DMCommTool::SendLocalForegroundUserIds(const std::string rmtNetworkId, const std::vector &userids) +{ + if (!IsIdLengthValid(rmtNetworkId) || userids.empty() || dmTransportPtr_ == nullptr) { + LOGE("param invalid, networkId: %{public}s, userids size: %{public}d", + GetAnonyString(rmtNetworkId).c_str(), static_cast(userids.size())); + return; + } + + if (dmTransportPtr_->StartSocket(rmtNetworkId) != DM_OK) { + LOGE("Start socket error"); + return; + } + + UserIdsMsg userIdsMsg(userids); + cJSON *root = cJSON_CreateObject(); + if (root == nullptr) { + LOGE("Create cJSON object failed."); + return; + } + ToJson(root, userIdsMsg); + char *msg = cJSON_PrintUnformatted(root); + if (msg == nullptr) { + cJSON_Delete(root); + return; + } + std::string msgStr(msg); + cJSON_Delete(root); + CommMsg commMsg(DM_COMM_SEND_LOCAL_FOREGROUND_USERIDS, msgStr); + std::string payload = GetCommMsgString(commMsg); + + int32_t ret = dmTransportPtr_->Send(rmtNetworkId, payload); + if (ret != DM_OK) { + LOGE("Send local foreground userids failed, ret: %{public}d", ret); + return; + } + LOGI("Send local foreground userids success"); +} + +void DMCommTool::RspLocalForegroundUserIds(const std::string rmtNetworkId, const std::vector &userids) +{ + UserIdsMsg userIdsMsg(userids); + cJSON *root = cJSON_CreateObject(); + if (root == nullptr) { + LOGE("Create cJSON object failed."); + return; + } + ToJson(root, userIdsMsg); + char *msg = cJSON_PrintUnformatted(root); + if (msg == nullptr) { + cJSON_Delete(root); + return; + } + std::string msgStr(msg); + cJSON_Delete(root); + CommMsg commMsg(DM_COMM_RSP_LOCAL_FOREGROUND_USERIDS, msgStr); + std::string payload = GetCommMsgString(commMsg); + + int32_t ret = dmTransportPtr_->Send(rmtNetworkId, payload); + if (ret != DM_OK) { + LOGE("Response local foreground userids failed, ret: %{public}d", ret); + return; + } + LOGI("Response local foreground userids success"); +} + +DMCommTool::DMCommToolEventHandler::DMCommToolEventHandler(const std::shared_ptr runner, + std::shared_ptr dmCommToolPtr) : AppExecFwk::EventHandler(runner), dmCommToolWPtr_(dmCommToolPtr) +{ + LOGI("Ctor DMCommToolEventHandler"); +} + +void DMCommTool::DMCommToolEventHandler::ProcessEvent( + const AppExecFwk::InnerEvent::Pointer &event) +{ + uint32_t eventId = event->GetInnerEventId(); + std::shared_ptr commMsg = event->GetSharedObject(); + if (commMsg == nullptr) { + LOGE("ProcessEvent commMsg is null"); + return; + } + if (dmCommToolWPtr_.expired()) { + LOGE("dmCommToolWPtr_ is expired"); + return; + } + std::shared_ptr dmCommToolPtr = dmCommToolWPtr_.lock(); + if (dmCommToolPtr == nullptr) { + LOGE("dmCommToolPtr is null"); + return; + } + switch (eventId) { + case DM_COMM_SEND_LOCAL_FOREGROUND_USERIDS: { + // Process remote foreground userids and send back local user ids + dmCommToolPtr->ProcessReceiveUserIdsEvent(commMsg); + break; + } + case DM_COMM_RSP_LOCAL_FOREGROUND_USERIDS: { + // Process remote foreground userids and close session + dmCommToolPtr->ProcessResponseUserIdsEvent(commMsg); + break; + } + default: + LOGE("event is undefined, id is %{public}d", eventId); + break; + } +} + +void DMCommTool::ProcessReceiveUserIdsEvent(const std::shared_ptr commMsg) +{ + LOGI("Receive remote userids, process and rsp local userid"); + std::string rmtUdid = ""; + SoftbusCache::GetInstance().GetUdidFromCache(commMsg->remoteNetworkId.c_str(), rmtUdid); + if (rmtUdid.empty()) { + LOGE("Can not find remote udid by networkid: %{public}s", commMsg->remoteNetworkId.c_str()); + return; + } + + std::string payload = commMsg->commMsg->msg; + //TODO: analyze + cJSON *root = cJSON_Parse(payload.c_str()); + if (root == NULL) { + LOGE("the msg is not json format"); + return; + } + UserIdsMsg userIdsMsg; + FromJson(root, userIdsMsg); + cJSON_Delete(root); + if (userIdsMsg.userIds.empty()) { + LOGE("Parse but get none remote userids"); + } else { + // step1: process remote userids + DeviceManagerService::GetInstance().ProcessForegroundUserIds(userIdsMsg.userIds, rmtUdid); + } + + // step2: send back local userids + std::vector userVec; + MultipleUserConnector::GetForegroundUsers(userVec); + std::vector userVecUInt; + for (auto const &u : userVec) { + userVecUInt.push_back(static_cast(u)); + } + RspLocalForegroundUserIds(commMsg->remoteNetworkId, userVecUInt); +} + +void DMCommTool::ProcessResponseUserIdsEvent(const std::shared_ptr commMsg) +{ + LOGI("process receive remote userids response"); + // step1: close socket + this->dmTransportPtr_->StopSocket(commMsg->remoteNetworkId); + + std::string rmtUdid = ""; + SoftbusCache::GetInstance().GetUdidFromCache(commMsg->remoteNetworkId.c_str(), rmtUdid); + if (rmtUdid.empty()) { + LOGE("Can not find remote udid by networkid: %{public}s", commMsg->remoteNetworkId.c_str()); + return; + } + + std::string payload = commMsg->commMsg->msg; + //TODO: analyze + cJSON *root = cJSON_Parse(payload.c_str()); + if (root == NULL) { + LOGE("the msg is not json format"); + return; + } + UserIdsMsg userIdsMsg; + FromJson(root, userIdsMsg); + cJSON_Delete(root); + if (userIdsMsg.userIds.empty()) { + LOGE("Parse but get none remote userids"); + return; + } + // step2: process remote userids + DeviceManagerService::GetInstance().ProcessForegroundUserIds(userIdsMsg.userIds, rmtUdid); +} + +std::shared_ptr DMCommTool::GetEventHandler() +{ + return this->eventHandler_; +} + +const std::shared_ptr DMCommTool::GetDMTransportPtr() +{ + return this->dmTransportPtr_; +} + +} // DistributedHardware +} // OHOS \ No newline at end of file diff --git a/services/service/src/relationshipsyncmgr/dm_transport.cpp b/services/service/src/relationshipsyncmgr/dm_transport.cpp new file mode 100644 index 000000000..6b5110380 --- /dev/null +++ b/services/service/src/relationshipsyncmgr/dm_transport.cpp @@ -0,0 +1,454 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_transport.h" + +#include + +#include "cJSON.h" +#include +#include "dm_anonymous.h" +#include "dm_comm_tool.h" +#include "dm_constants.h" +#include "dm_log.h" +#include "dm_softbus_cache.h" +#include "dm_transport_msg.h" + +namespace OHOS { +namespace DistributedHardware { +namespace { +// Dsoftbus sendBytes max message length: 4MB +constexpr uint32_t MAX_SEND_MSG_LENGTH = 4 * 1024 * 1024; +constexpr uint32_t INTERCEPT_STRING_LENGTH = 20; +constexpr uint32_t MAX_ROUND_SIZE = 1000; +static QosTV g_qosInfo[] = { + { .qos = QOS_TYPE_MIN_BW, .value = 256 * 1024}, + { .qos = QOS_TYPE_MAX_LATENCY, .value = 8000 }, + { .qos = QOS_TYPE_MIN_LATENCY, .value = 2000 } +}; +static uint32_t g_qosTvParamIndex = static_cast(sizeof(g_qosInfo) / sizeof(g_qosInfo[0])); +static std::weak_ptr g_dmCommToolWPtr_; +} + +DMTransport::DMTransport(std::shared_ptr dmCommToolPtr) : remoteDevSocketIds_({}), localServerSocket_(-1), + localSocketName_(""), isSocketSvrCreateFlag_(false), dmCommToolWPtr_(dmCommToolPtr) +{ + LOGI("Ctor DMTransport"); + g_dmCommToolWPtr_ = dmCommToolPtr; +} + +int32_t DMTransport::OnSocketOpened(int32_t socketId, const PeerSocketInfo &info) +{ + LOGI("OnSocketOpened, socket: %{public}d, peerSocketName: %{public}s, peerNetworkId: %{public}s, " + "peerPkgName: %{public}s", socketId, info.name, GetAnonyString(info.networkId).c_str(), info.pkgName); + std::lock_guard lock(rmtSocketIdMtx_); + remoteDevSocketIds_[info.networkId] = socketId; + return DM_OK; +} + +void DMTransport::OnSocketClosed(int32_t socketId, ShutdownReason reason) +{ + LOGI("OnSocketClosed, socket: %{public}d, reason: %{public}d", socketId, (int32_t)reason); + std::lock_guard lock(rmtSocketIdMtx_); + for (auto iter = remoteDevSocketIds_.begin(); iter != remoteDevSocketIds_.end(); ++iter) { + if (iter->second == socketId) { + remoteDevSocketIds_.erase(iter); + break; + } + } +} + +void DMTransport::OnBytesReceived(int32_t socketId, const void *data, uint32_t dataLen) +{ + if (socketId < 0 || data == nullptr || dataLen == 0 || dataLen > MAX_SEND_MSG_LENGTH) { + LOGE("OnBytesReceived param check failed"); + return; + } + + std::string remoteNeworkId = GetRemoteNetworkIdBySocketId(socketId); + if (remoteNeworkId.empty()) { + LOGE("Can not find the remote network id by socketId: %{public}d", socketId); + return; + } + + uint8_t *buf = reinterpret_cast(calloc(dataLen + 1, sizeof(uint8_t))); + if (buf == nullptr) { + LOGE("OnBytesReceived: malloc memory failed"); + return; + } + + if (memcpy_s(buf, dataLen + 1, reinterpret_cast(data), dataLen) != EOK) { + LOGE("OnBytesReceived: memcpy memory failed"); + free(buf); + return; + } + + std::string message(buf, buf + dataLen); + LOGI("Receive message size: %{public}" PRIu32, dataLen); + HandleReceiveMessage(socketId, message); + free(buf); + return; +} + +void DMTransport::HandleReceiveMessage(const int32_t socketId, const std::string &payload) +{ + std::string rmtNetworkId = GetRemoteNetworkIdBySocketId(socketId); + if (rmtNetworkId.empty()) { + LOGE("Can not find networkId by socketId: %{public}d", socketId); + return; + } + if (payload.empty() || payload.size() > MAX_SEND_MSG_LENGTH) { + LOGE("payload invalid"); + return; + } + LOGI("Receive msg: %{public}s", payload.c_str()); + cJSON *root = cJSON_Parse(payload.c_str()); + if (root == NULL) { + LOGE("the msg is not json format"); + return; + } + std::shared_ptr commMsg = std::make_shared(); + FromJson(root, *commMsg); + cJSON_Delete(root); + + std::shared_ptr innerMsg = std::make_shared(rmtNetworkId, commMsg); + + LOGI("Receive DM msg, code: %{public}d, msg: %{public}s", commMsg->code, GetAnonyString(commMsg->msg).c_str()); + AppExecFwk::InnerEvent::Pointer msgEvent = AppExecFwk::InnerEvent::Get(commMsg->code, innerMsg); + std::shared_ptr dmCommToolSPtr = dmCommToolWPtr_.lock(); + if (dmCommToolSPtr == nullptr) { + LOGE("Can not get DMCommTool ptr"); + return; + } + if (dmCommToolSPtr->GetEventHandler() == nullptr) { + LOGE("Can not get eventHandler"); + return; + } + dmCommToolSPtr->GetEventHandler()->SendEvent(msgEvent, 0, AppExecFwk::EventQueue::Priority::IMMEDIATE); +} + +std::shared_ptr GetDMCommToolPtr() +{ + if (g_dmCommToolWPtr_.expired()) { + LOGE("DMCommTool Weak ptr expired"); + return nullptr; + } + + std::shared_ptr dmCommToolSPtr = g_dmCommToolWPtr_.lock(); + if (dmCommToolSPtr == nullptr) { + LOGE("Can not get DMCommTool ptr"); + return nullptr; + } + + return dmCommToolSPtr; +} + +void OnBind(int32_t socket, PeerSocketInfo info) +{ + std::shared_ptr dmCommToolSPtr = GetDMCommToolPtr(); + if (dmCommToolSPtr == nullptr) { + LOGE("Can not get DMCommTool ptr"); + return; + } + dmCommToolSPtr->GetDMTransportPtr()->OnSocketOpened(socket, info); +} + +void OnShutdown(int32_t socket, ShutdownReason reason) +{ + std::shared_ptr dmCommToolSPtr = GetDMCommToolPtr(); + if (dmCommToolSPtr == nullptr) { + LOGE("Can not get DMCommTool ptr"); + return; + } + dmCommToolSPtr->GetDMTransportPtr()->OnSocketClosed(socket, reason); +} + +void OnBytes(int32_t socket, const void *data, uint32_t dataLen) +{ + std::shared_ptr dmCommToolSPtr = GetDMCommToolPtr(); + if (dmCommToolSPtr == nullptr) { + LOGE("Can not get DMCommTool ptr"); + return; + } + dmCommToolSPtr->GetDMTransportPtr()->OnBytesReceived(socket, data, dataLen); +} + +void OnMessage(int32_t socket, const void *data, uint32_t dataLen) +{ + (void)socket; + (void)data; + (void)dataLen; + LOGI("socket: %{public}d, dataLen:%{public}" PRIu32, socket, dataLen); +} + +void OnStream(int32_t socket, const StreamData *data, const StreamData *ext, + const StreamFrameInfo *param) +{ + (void)socket; + (void)data; + (void)ext; + (void)param; + LOGI("socket: %{public}d", socket); +} + +void OnFile(int32_t socket, FileEvent *event) +{ + (void)event; + LOGI("socket: %{public}d", socket); +} + +void OnQos(int32_t socket, QoSEvent eventId, const QosTV *qos, uint32_t qosCount) +{ + if (qosCount == 0 || qosCount > MAX_ROUND_SIZE) { + LOGE("qosCount is invalid!"); + return; + } + LOGI("OnQos, socket: %{public}d, QoSEvent: %{public}d, qosCount: %{public}" PRIu32, + socket, (int32_t)eventId, qosCount); + for (uint32_t idx = 0; idx < qosCount; idx++) { + LOGI("QosTV: type: %{public}d, value: %{public}d", (int32_t)qos[idx].qos, qos[idx].value); + } +} + +ISocketListener iSocketListener = { + .OnBind = OnBind, + .OnShutdown = OnShutdown, + .OnBytes = OnBytes, + .OnMessage = OnMessage, + .OnStream = OnStream, + .OnFile = OnFile, + .OnQos = OnQos +}; + +int32_t DMTransport::CreateServerSocket() +{ + LOGI("CreateServerSocket start"); + localSocketName_ = DM_SYNC_USERID_SESSION_NAME; + LOGI("CreateServerSocket , local socketName: %{public}s", localSocketName_.c_str()); + std::string dmPkgName(DM_PKG_NAME); + SocketInfo info = { + .name = const_cast(localSocketName_.c_str()), + .pkgName = const_cast(dmPkgName.c_str()), + .dataType = DATA_TYPE_BYTES + }; + int32_t socket = Socket(info); + LOGI("CreateServerSocket Finish, socket: %{public}d", socket); + return socket; +} + +int32_t DMTransport::CreateClientSocket(const std::string &rmtNetworkId) +{ + if (!IsIdLengthValid(rmtNetworkId)) { + return ERR_DM_INPUT_PARA_INVALID; + } + LOGI("CreateClientSocket start, peerNetworkId: %{public}s", GetAnonyString(rmtNetworkId).c_str()); + std::string peerSocketName = DM_SYNC_USERID_SESSION_NAME; + std::string dmPkgName(DM_PKG_NAME); + SocketInfo info = { + .name = const_cast(localSocketName_.c_str()), + .peerName = const_cast(peerSocketName.c_str()), + .peerNetworkId = const_cast(rmtNetworkId.c_str()), + .pkgName = const_cast(dmPkgName.c_str()), + .dataType = DATA_TYPE_BYTES + }; + int32_t socket = Socket(info); + LOGI("Bind Socket server, socket: %{public}d, localSocketName: %{public}s, peerSocketName: %{public}s", + socket, localSocketName_.c_str(), peerSocketName.c_str()); + return socket; +} + +int32_t DMTransport::Init() +{ + LOGI("Init DMTransport"); + if (isSocketSvrCreateFlag_.load()) { + LOGI("SocketServer already create success."); + return DM_OK; + } + int32_t socket = CreateServerSocket(); + if (socket < DM_OK) { + LOGE("CreateSocketServer failed, ret: %{public}d", socket); + return ERR_DM_FAILED; + } + + int32_t ret = Listen(socket, g_qosInfo, g_qosTvParamIndex, &iSocketListener); + if (ret != DM_OK) { + LOGE("Socket Listen failed, error code %{public}d.", ret); + return ERR_DM_FAILED; + } + isSocketSvrCreateFlag_.store(true); + localServerSocket_ = socket; + LOGI("Finish Init DSoftBus Server Socket, socket: %{public}d", socket); + return DM_OK; +} + +int32_t DMTransport::UnInit() +{ + { + std::lock_guard lock(rmtSocketIdMtx_); + for (auto iter = remoteDevSocketIds_.begin(); iter != remoteDevSocketIds_.end(); ++iter) { + LOGI("Shutdown client socket: %{public}d to remote dev: %{public}s", iter->second, + GetAnonyString(iter->first).c_str()); + Shutdown(iter->second); + } + remoteDevSocketIds_.clear(); + } + + if (!isSocketSvrCreateFlag_.load()) { + LOGI("DSoftBus Server Socket already remove success."); + } else { + LOGI("Shutdown DSoftBus Server Socket, socket: %{public}d", localServerSocket_.load()); + Shutdown(localServerSocket_.load()); + localServerSocket_ = -1; + isSocketSvrCreateFlag_.store(false); + } + return DM_OK; +} + +bool DMTransport::IsDeviceSessionOpened(const std::string &rmtNetworkId, int32_t &socketId) +{ + if (!IsIdLengthValid(rmtNetworkId)) { + return false; + } + std::lock_guard lock(rmtSocketIdMtx_); + if (remoteDevSocketIds_.find(rmtNetworkId) == remoteDevSocketIds_.end()) { + return false; + } + socketId = remoteDevSocketIds_.at(rmtNetworkId); + LOGI("DeviceSession has opened, rmtNetworkId: %{public}s, socketId: %{public}d", + GetAnonyString(rmtNetworkId).c_str(), socketId); + return true; +} + +std::string DMTransport::GetRemoteNetworkIdBySocketId(int32_t socketId) +{ + std::lock_guard lock(rmtSocketIdMtx_); + std::string networkId = ""; + for (auto const &item : remoteDevSocketIds_) { + if (item.second == socketId) { + networkId = item.first; + break; + } + } + return networkId; +} + +void DMTransport::ClearDeviceSocketOpened(const std::string &remoteDevId) +{ + if (!IsIdLengthValid(remoteDevId)) { + return; + } + std::lock_guard lock(rmtSocketIdMtx_); + remoteDevSocketIds_.erase(remoteDevId); +} + +int32_t DMTransport::StartSocket(const std::string &rmtNetworkId) +{ + if (!IsIdLengthValid(rmtNetworkId)) { + return ERR_DM_INPUT_PARA_INVALID; + } + int32_t socketId = -1; + if (IsDeviceSessionOpened(rmtNetworkId, socketId)) { + LOGE("Softbus session has already opened, deviceId: %{public}s", GetAnonyString(rmtNetworkId).c_str()); + return DM_OK; + } + + int32_t socket = CreateClientSocket(rmtNetworkId); + if (socket < DM_OK) { + LOGE("StartSocket failed, ret: %{public}d", socket); + return ERR_DM_FAILED; + } + + int32_t ret = Bind(socket, g_qosInfo, g_qosTvParamIndex, &iSocketListener); + if (ret < DM_OK) { + LOGE("OpenSession fail, rmtNetworkId: %{public}s, socket: %{public}d, ret: %{public}d", + GetAnonyString(rmtNetworkId).c_str(), socket, ret); + Shutdown(socket); + return ERR_DM_FAILED; + } + + LOGI("Bind Socket success, rmtNetworkId:%{public}s, socketId: %{public}d", + GetAnonyString(rmtNetworkId).c_str(), socket); + std::string peerSocketName = DM_SYNC_USERID_SESSION_NAME; + std::string dmPkgName(DM_PKG_NAME); + PeerSocketInfo peerSocketInfo = { + .name = const_cast(peerSocketName.c_str()), + .networkId = const_cast(rmtNetworkId.c_str()), + .pkgName = const_cast(dmPkgName.c_str()), + .dataType = DATA_TYPE_BYTES + }; + OnSocketOpened(socket, peerSocketInfo); + return DM_OK; +} + +int32_t DMTransport::StopSocket(const std::string &rmtNetworkId) +{ + if (!IsIdLengthValid(rmtNetworkId)) { + return ERR_DM_INPUT_PARA_INVALID; + } + int32_t socketId = -1; + if (!IsDeviceSessionOpened(rmtNetworkId, socketId)) { + LOGI("remote dev may be not opened, rmtNetworkId: %{public}s", GetAnonyString(rmtNetworkId).c_str()); + return ERR_DM_FAILED; + } + + LOGI("StopSocket rmtNetworkId: %{public}s, socketId: %{public}d", + GetAnonyString(rmtNetworkId).c_str(), socketId); + Shutdown(socketId); + ClearDeviceSocketOpened(rmtNetworkId); + return DM_OK; +} + +int32_t DMTransport::Send(const std::string &rmtNetworkId, const std::string &payload) +{ + if (!IsIdLengthValid(rmtNetworkId) || !IsMessageLengthValid(payload)) { + return ERR_DM_INPUT_PARA_INVALID; + } + int32_t socketId = -1; + if (!IsDeviceSessionOpened(rmtNetworkId, socketId)) { + LOGI("The session is not open, target networkId: %{public}s", GetAnonyString(rmtNetworkId).c_str()); + return ERR_DM_FAILED; + } + uint32_t payLoadSize = payload.size(); + LOGI("Send payload size: %{public}" PRIu32 ", target networkId: %{public}s, socketId: %{public}d", + static_cast(payload.size()), GetAnonyString(rmtNetworkId).c_str(), socketId); + + if (payLoadSize > MAX_SEND_MSG_LENGTH) { + LOGE("Send error: msg size: %{public}" PRIu32 " too long", payLoadSize); + return ERR_DM_FAILED; + } + uint8_t *buf = reinterpret_cast(calloc((payLoadSize), sizeof(uint8_t))); + if (buf == nullptr) { + LOGE("Send: malloc memory failed"); + return ERR_DM_FAILED; + } + + if (memcpy_s(buf, payLoadSize, reinterpret_cast(payload.c_str()), + payLoadSize) != EOK) { + LOGE("Send: memcpy memory failed"); + free(buf); + return ERR_DM_FAILED; + } + + int32_t ret = SendBytes(socketId, buf, payLoadSize); + free(buf); + if (ret != DM_OK) { + LOGE("dsoftbus send error, ret: %{public}d", ret); + return ERR_DM_FAILED; + } + LOGI("Send payload success"); + return DM_OK; +} +} // DistributedHardware +} // OHOS \ No newline at end of file diff --git a/services/service/src/relationshipsyncmgr/dm_transport_msg.cpp b/services/service/src/relationshipsyncmgr/dm_transport_msg.cpp new file mode 100644 index 000000000..bb8a1779b --- /dev/null +++ b/services/service/src/relationshipsyncmgr/dm_transport_msg.cpp @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "dm_transport_msg.h" + +#include "dm_anonymous.h" +#include "dm_log.h" + +namespace OHOS { +namespace DistributedHardware { +namespace { + const int32_t MAX_FOREGROUND_USER_ID_NUM = 5; +} +void ToJson(cJSON *jsonObject, const UserIdsMsg &userIdsMsg) +{ + if (jsonObject == nullptr) { + LOGE("Json pointer is nullptr!"); + return; + } + cJSON *userIdArr = cJSON_CreateArray(); + if (userIdArr == nullptr) { + return; + } + for (auto const &userId : userIdsMsg.userIds) { + cJSON_AddItemToArray(userIdArr, cJSON_CreateNumber(userId)); + } + cJSON_AddItemToObject(jsonObject, USERIDS_MSG_USERIDS_KEY, userIdArr); +} + +void FromJson(const cJSON *jsonObject, UserIdsMsg &userIdsMsg) +{ + if (jsonObject == nullptr) { + LOGE("Json pointer is nullptr!"); + return; + } + cJSON *userIdsArr = cJSON_GetObjectItem(jsonObject, USERIDS_MSG_USERIDS_KEY); + if (cJSON_IsArray(userIdsArr)) { + int32_t arrSize = cJSON_GetArraySize(userIdsArr); + if (arrSize > MAX_FOREGROUND_USER_ID_NUM) { + LOGE("Receive too many userids, %{public}d", arrSize); + return; + } + for (int32_t i = 0; i < arrSize; i++) { + cJSON *userIdItem = cJSON_GetArrayItem(userIdsArr, i); + if (cJSON_IsNumber(userIdItem)) { + uint32_t userId = static_cast(userIdItem->valueint); + userIdsMsg.userIds.push_back(userId); + } + } + } +} + +void ToJson(cJSON *jsonObject, const CommMsg &commMsg) +{ + if (jsonObject == nullptr) { + LOGE("Json pointer is nullptr!"); + return; + } + cJSON_AddNumberToObject(jsonObject, COMM_MSG_CODE_KEY, commMsg.code); + const char *msg = commMsg.msg.c_str(); + cJSON_AddStringToObject(jsonObject, COMM_MSG_MSG_KEY, msg); +} + +void FromJson(const cJSON *jsonObject, CommMsg &commMsg) +{ + if (jsonObject == nullptr) { + LOGE("Json pointer is nullptr!"); + return; + } + cJSON *codeObj = cJSON_GetObjectItem(jsonObject, COMM_MSG_CODE_KEY); + if (cJSON_IsNumber(codeObj)) { + commMsg.code = codeObj->valueint; + } + std::string keyMsg(COMM_MSG_MSG_KEY); + cJSON *msgObj = cJSON_GetObjectItem(jsonObject, COMM_MSG_MSG_KEY); + if (cJSON_IsString(msgObj)) { + commMsg.msg = msgObj->valuestring; + } +} + +std::string GetCommMsgString(const CommMsg &commMsg) +{ + cJSON *rootMsg = cJSON_CreateObject(); + if (rootMsg == nullptr) { + LOGE("Create cJSON object failed."); + return ""; + } + ToJson(rootMsg, commMsg); + char *msg = cJSON_PrintUnformatted(rootMsg); + if (msg == nullptr) { + cJSON_Delete(rootMsg); + return ""; + } + std::string msgStr = std::string(msg); + cJSON_free(msg); + cJSON_Delete(rootMsg); + + return msgStr; +} +} // DistributedHardware +} // OHOS \ No newline at end of file -- Gitee From 9959245f588d64e9ee7c471333f918508fff767b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=B7=8D?= Date: Sun, 10 Nov 2024 10:29:29 +0800 Subject: [PATCH 27/27] =?UTF-8?q?=E5=A2=9E=E5=8A=A0userId?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- commondependency/src/deviceprofile_connector.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index 8966578c7..5ddc90494 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -730,7 +730,7 @@ int32_t DeviceProfileConnector::CheckAccessControl(const DmAccessCaller &caller, { LOGI("PkgName %{public}s, srcUdid %{public}s, sinkUdid %{public}s", caller.pkgName.c_str(), GetAnonyString(srcUdid).c_str(), GetAnonyString(sinkUdid).c_str()); - std::vector profiles = GetAccessControlProfile(); + std::vector profiles = GetAccessControlProfileByUserId(caller.userId); for (auto &item : profiles) { if (item.GetStatus() != ACTIVE || (item.GetTrustDeviceId() != sinkUdid && item.GetTrustDeviceId() != srcUdid)) { @@ -782,7 +782,7 @@ int32_t DeviceProfileConnector::CheckIsSameAccount(const DmAccessCaller &caller, { LOGI("DeviceProfileConnector::CheckIsSameAccount pkgName %{public}s, srcUdid %{public}s, sinkUdid %{public}s", caller.pkgName.c_str(), GetAnonyString(srcUdid).c_str(), GetAnonyString(sinkUdid).c_str()); - std::vector profiles = GetAccessControlProfile(); + std::vector profiles = GetAccessControlProfileByUserId(caller.userId); for (auto &item : profiles) { if (item.GetStatus() != ACTIVE || (item.GetTrustDeviceId() != sinkUdid && item.GetTrustDeviceId() != srcUdid)) { -- Gitee