diff --git a/common/include/device_manager_ipc_interface_code.h b/common/include/device_manager_ipc_interface_code.h index cd6dee5cd4e9ce1f712173880300f8c256e7e605..b0b7f485b6e39401d351d05c804ccbf087fee9ab 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 292a3049c2287935501dfc32c2124013496893ef..90328b628db53aa7c99f9fe20039dff239fb9ed6 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,35 @@ 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); +uint16_t GetSubscribeId(const std::string &pkgName); +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; +} +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 932dc05623ec86b2733052b2b5814fbef868b60f..856920cd63f4866f36c9b5172a585d65f34bec41 100755 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -133,6 +133,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/include/ipc/model/ipc_req.h b/common/include/ipc/model/ipc_req.h index fd0d0c7855f30f8847666a5e5ca2665356e1d157..f16984c71256738b4ae1e97238c2dba9e2394d1c 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/common/include/ipc/model/ipc_start_discover_req.h b/common/include/ipc/model/ipc_start_discover_req.h deleted file mode 100644 index 863951ceae69342d6ddeef4f999c3f407753eeeb..0000000000000000000000000000000000000000 --- 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 421402c8549e6c18485c33db75fc04364d40d16f..0000000000000000000000000000000000000000 --- 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 d5d2ae5ec5de0877bbc322c72e8db5a7765b35ab..0000000000000000000000000000000000000000 --- 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 6bfd220042231c968c74f4f239b68c1996d4f433..7e485418f02b513c1fade4059bbdee6da87d3845 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) @@ -50,6 +51,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 +74,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"); @@ -265,5 +284,57 @@ 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; +} + +uint16_t GetSubscribeId(const std::string &pkgName) +{ + std::vector strVec; + size_t subIdIndex = 1; + 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() >= subIdIndex + 1) { + return std::atoi(strVec.at(subIdIndex).c_str()); + } + 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/common/src/dm_error_message.cpp b/common/src/dm_error_message.cpp index 8cf81bdfa3cbf9e7917dbdcdc2eaeae6e43de07c..18d2cbe110a0b8adb82f8574ad5a0c9088081b90 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."}, diff --git a/commondependency/include/deviceprofile_connector.h b/commondependency/include/deviceprofile_connector.h index fb95f058bf83f0e09b71596509d6651da9a42474..d336aa2d8d3c5160c3a2fc175c2b9f0187dbe10c 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; @@ -78,7 +79,7 @@ typedef struct DmAccessee { typedef struct DmOfflineParam { uint32_t bindType; - std::vector pkgNameVec; + std::vector processVec; int32_t leftAclNumber; } DmOfflineParam; @@ -95,12 +96,11 @@ 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, - const std::string &deviceId); - DmOfflineParam GetOfflineParamFromAcl(std::string trustDeviceId, std::string requestDeviceId); + const std::string &deviceId, int32_t userId); std::vector GetBindTypeByPkgName(std::string pkgName, std::string requestDeviceId, std::string trustUdid); std::vector SyncAclByBindType(std::string pkgName, std::vector bindTypeVec, @@ -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 GetPkgNameFromAcl(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); @@ -127,15 +128,23 @@ 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 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, 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); + 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); @@ -158,7 +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); + 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 6cdbc214b62c72d0b2a27c413e7ab6602a4c4209..5733f02dac27085110f157ff0842a955ce5e9e04 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 @@ -19,6 +19,7 @@ #include #include #include +#include namespace OHOS { namespace DistributedHardware { class MultipleUserConnector { @@ -46,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 @@ -85,6 +94,12 @@ public: * @tc.type: FUNC */ static std::string GetSwitchOldAccountName(void); + static void GetTokenIdAndForegroundUserId(uint32_t &tokenId, int32_t &userId); + 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_; static std::string accountId_; diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index c581a822413842fcdfd34624961da520a4ffacde..955d7a80496b0d99b290e3b3c1f343e3538443d1 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(); @@ -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,17 +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 = GetAccessControlProfile(); - LOGI("AccessControlProfile size is %{public}zu", profiles.size()); + std::vector filterProfiles = GetCurrentUserAclProfile(localUdid, + MultipleUserConnector::GetForegroundUser(), peerUdid); + 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; } @@ -194,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; @@ -224,7 +221,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) { @@ -339,7 +337,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; @@ -361,61 +360,23 @@ std::vector DeviceProfileConnector::SyncAclByBindType(std::string pkgNa return bindType; } -std::vector DeviceProfileConnector::GetPkgNameFromAcl(std::string &localDeviceId, - std::string &targetDeviceId) +std::vector DeviceProfileConnector::GetProcessInfoFromAclByUserId( + const std::string &localDeviceId, const std::string &targetDeviceId, int32_t userId) { - LOGI("Start."); - std::vector profiles = GetAccessControlProfile(); - LOGI("AccessControlProfile size is %{public}zu", profiles.size()); - std::vector pkgNameVec; - for (auto &item : profiles) { + std::vector filterProfiles = GetCurrentUserAclProfile(localDeviceId, + MultipleUserConnector::GetForegroundUser(), targetDeviceId); + LOGI("filterProfiles size is %{public}zu", filterProfiles.size()); + std::vector processInfoVec; + 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)) { - pkgNameVec.push_back(item.GetAccesser().GetAccesserBundleName()); - } - } - return pkgNameVec; -} - -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(); - 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; - offlineParam.pkgNameVec.push_back(item.GetAccesser().GetAccesserBundleName()); - } 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()); - } - if (priority > offlineParam.bindType) { - offlineParam.bindType = priority; - } + OHOS::DistributedHardware::ProcessInfo processInfo; + processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.userId = item.GetAccesser().GetAccesserUserId(); + processInfoVec.push_back(processInfo); } - return offlineParam; + return processInfoVec; } int32_t DeviceProfileConnector::PutAccessControlList(DmAclInfo aclInfo, DmAccesser dmAccesser, DmAccessee dmAccessee) @@ -539,6 +500,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()); @@ -550,6 +515,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()); @@ -858,6 +827,31 @@ int32_t DeviceProfileConnector::GetBindLevel(const std::string &pkgName, const s return bindLevel; } +std::map DeviceProfileConnector::GetDeviceIdAndBindLevel(std::vector userIds, + const std::string &localUdid) +{ + std::vector profiles = GetAllAccessControlProfile(); + std::map deviceIdMap; + for (const auto &item : profiles) { + 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.GetBindLevel(), deviceIdMap); + continue; + } + 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.GetBindLevel(), deviceIdMap); + continue; + } + } + return deviceIdMap; +} + std::map DeviceProfileConnector::GetDeviceIdAndBindType(int32_t userId, const std::string &accountId, const std::string &localUdid) { @@ -883,14 +877,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); } } @@ -900,12 +894,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; 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; } @@ -945,13 +947,13 @@ 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) { @@ -963,7 +965,8 @@ 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(); continue; } if (item.GetAccessee().GetAccesseeUserId() == remoteUserId && @@ -972,11 +975,12 @@ 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(); continue; } } - return pkgName; + return processInfo; } std::vector DeviceProfileConnector::GetAllAccessControlProfile() @@ -993,6 +997,180 @@ 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); + } + } + return DM_OK; +} + +std::vector DeviceProfileConnector::GetCurrentUserAclProfile(const std::string &localUdid, + 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()); + std::vector profiles = GetAllAccessControlProfile(); + std::vector profilesTemp; + for (const auto &item : profiles) { + if (item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccesser().GetAccesserUserId() == localUserId && + item.GetAccessee().GetAccesseeDeviceId() == remoteUdid) { + profilesTemp.push_back(item); + } else if (item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccessee().GetAccesseeUserId() == localUserId && + item.GetAccesser().GetAccesserDeviceId() == remoteUdid) { + profilesTemp.push_back(item); + } + } + 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 c284da7b88257e18e09a7cebe0e0aa4715348d01..e6b8b1e32cc1a4f3e2b12a305f368f2b5c217024 100644 --- a/commondependency/src/multiple_user_connector.cpp +++ b/commondependency/src/multiple_user_connector.cpp @@ -15,10 +15,11 @@ #include "multiple_user_connector.h" +#include "dm_constants.h" #include "dm_log.h" - #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) #include "account_info.h" +#include "ipc_skeleton.h" #include "ohos_account_kits.h" #ifdef OS_ACCOUNT_PART_EXISTS #include "os_account_manager.h" @@ -70,6 +71,25 @@ std::string MultipleUserConnector::GetOhosAccountId(void) #endif } +std::string MultipleUserConnector::GetOhosAccountIdByUserId(int32_t userId) +{ +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) + (void)userId; + 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 + (void)userId; + return ""; +#endif +} + std::string MultipleUserConnector::GetOhosAccountName(void) { #if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) @@ -90,6 +110,34 @@ std::string MultipleUserConnector::GetOhosAccountName(void) #endif } +void MultipleUserConnector::GetTokenIdAndForegroundUserId(uint32_t &tokenId, int32_t &userId) +{ +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); +#else + (void)tokenId; +#endif + userId = GetForegroundUser(); +} + +void MultipleUserConnector::GetCallerUserId(int32_t &userId) +{ +#if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) + (void)userId; + 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); + } + return; +#else // OS_ACCOUNT_PART_EXISTS + (void)userId; + return; +#endif +} + void MultipleUserConnector::SetSwitchOldUserId(int32_t userId) { std::lock_guard lock(lock_); @@ -125,5 +173,54 @@ std::string MultipleUserConnector::GetSwitchOldAccountName(void) std::lock_guard lock(lock_); return accountName_; } + +int32_t MultipleUserConnector::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 +} + +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]; +} + +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/interfaces/inner_kits/native_cpp/include/device_manager_impl.h b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h index f701b55403c6a7694840d340fb5e086a886c704d..f887ff9d6af7e5e50aaffc185cfe32b3c03b8d5e 100644 --- a/interfaces/inner_kits/native_cpp/include/device_manager_impl.h +++ b/interfaces/inner_kits/native_cpp/include/device_manager_impl.h @@ -412,21 +412,20 @@ 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); 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__) 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 4354ee3ead61a00f6559916ca40b86b3ad208853..73646703eab2bde8de9e8a9e70b48aaac4210300 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,22 @@ typedef struct DmAccessCallee { int32_t userId; std::string extra; } DmAccessCallee; + +typedef struct ProcessInfo { + int32_t userId; + std::string pkgName; + + bool operator==(const ProcessInfo &other) const + { + return (userId == other.userId) && (pkgName == other.pkgName); + } + + bool operator<(const ProcessInfo &other) const + { + return (userId < other.userId) || + (userId == other.userId && pkgName < other.pkgName); + } +} ProcessInfo; } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_DEVICE_INFO_H \ No newline at end of file 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 10ffd05cd363e10d5b6a33cfc56cf97d1d1e7a74..3f68a9ee0d97d79fe2820f931260b2f61621c513 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 @@ -125,6 +125,7 @@ public: uint16_t deviceTypeId, int32_t errcode); void OnSinkBindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, int32_t status, std::string content); + 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 42e3e6086fcdb935f0d092a9421f807b53105ef7..4afabf43886eaf2669e10d428407046b6cec6ede 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,112 @@ 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; - { - std::lock_guard autoLock(subscribIdLock); - if (subscribIdMap_.find(tokenId) == subscribIdMap_.end()) { - return ERR_DM_STOP_DISCOVERY; - } - subscribeId = subscribIdMap_[tokenId]; - subscribIdMap_.erase(tokenId); + 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()); + } + if (subscribeId == DM_INVALID_FLAG_ID) { + subscribeId = GetSubscribeIdFromMap(pkgName); } - 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; + } + std::string discoveryFlag = ComposeStr(pkgName, subscribeId); + 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 +1630,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 +1639,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 +1672,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 +1686,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 +1883,32 @@ 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()); + } + 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); - 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(discoveryFlag); + if (iter == pkgName2SubIdMap_.end()) { + pkgName2SubIdMap_[discoveryFlag] = subscribeId; } } - 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; } @@ -2488,5 +2401,18 @@ int32_t DeviceManagerImpl::UnRegisterSinkBindCallback(const std::string &pkgName 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/ipc/lite/ipc_cmd_parser.cpp b/interfaces/inner_kits/native_cpp/src/ipc/lite/ipc_cmd_parser.cpp index 248628c0da2f24a76587fdaaf931949f2b2a9b74..18b494a3ded83f20a43950fb84418848d882b4eb 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 { @@ -163,44 +161,6 @@ ON_IPC_READ_RESPONSE(GET_TRUST_DEVICE_LIST, 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(); - std::string extra = pReq->GetFilterOption(); - uint16_t subscribeId = pReq->GetSubscribeId(); - - IpcIoInit(&request, buffer, buffLen, 0); - WriteString(&request, pkgName.c_str()); - WriteString(&request, extra.c_str()); - WriteUint16(&request, subscribeId); - return DM_OK; -} - -ON_IPC_READ_RESPONSE(START_DEVICE_DISCOVERY, IpcIo &reply, std::shared_ptr pBaseRsp) -{ - return SetRspErrCode(reply, pBaseRsp); -} - -ON_IPC_SET_REQUEST(STOP_DEVICE_DISCOVER, 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 a18aa832729d791bd31e32d284395a4c9d18875a..a69f4a51352289b4134aab467f01796262b34fb4 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 046090539cbecb85ef947fb13abfcf5fff7c32a8..8cf07b354cfcf4d4005cc634f95ac9556a023664 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,34 @@ 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::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; - } - tempCbk = iter->second; - } + std::shared_ptr tempCbk = GetDiscoveryCallback(pkgName, subscribeId); 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::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; - } - tempCbk = iter->second; - } + std::shared_ptr tempCbk = GetDiscoveryCallback(pkgName, subscribeId); 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,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::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; - } - tempCbk = iter->second; - } + std::shared_ptr tempCbk = GetDiscoveryCallback(pkgName, subscribeId); if (tempCbk == nullptr) { LOGE("OnDiscoveryFailed error, registered device discovery callback is nullptr."); return; @@ -624,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::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; - } - tempCbk = iter->second; - } + std::shared_ptr tempCbk = GetDiscoveryCallback(pkgName, subscribeId); if (tempCbk == nullptr) { LOGE("OnDiscoverySuccess error, registered device discovery callback is nullptr."); return; @@ -1237,5 +1171,29 @@ void DeviceManagerNotify::OnSinkBindResult(const std::string &pkgName, const Pee } tempCbk->OnBindResult(targetId, result, status, content); } + +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/include/authentication/auth_message_processor.h b/services/implementation/include/authentication/auth_message_processor.h index 959d3a87ab17b218bb0022be85424d552ccb9f71..e5eb58829b8e7c28cbcdfc9a3ea5493db6d99ab2 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/auth_ui_state_manager.h b/services/implementation/include/authentication/auth_ui_state_manager.h index badf235d6e846e96dae919f76d1fe800a7d4aa30..2a7bdbc6d762a9ed90aece6608c5c9013c8a7f19 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 85982bc1240b003dd9a6425a7c66b4f651a5585f..bd7394a0a026fbac7c6856c4e76f44242d8e24bc 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; @@ -368,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 @@ -532,6 +528,9 @@ private: void DeleteOffLineTimer(int32_t sessionId); bool IsAllowDeviceBind(); int32_t GetBindLevel(int32_t bindLevel); + std::string GetBundleName(nlohmann::json &jsonObject); + int32_t GetBinderInfo(); + void SetProcessInfo(); private: std::shared_ptr softbusConnector_; @@ -567,6 +566,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 b20c09bfbde9bff567b4a7051c0e54742e273efe..f9216f3f6b0f76afdac85d365ef28b7b01b4024a 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 */ @@ -110,7 +110,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/dependency/softbus/softbus_connector.h b/services/implementation/include/dependency/softbus/softbus_connector.h index 674002a710119d9b861cda53879192b3bfffa478..49b417ce1911884303289e6e8b23127f4619926e 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 SetProcessInfoVec(std::vector processInfoVec); + std::vector GetProcessInfo(); + void ClearProcessInfo(); DmDeviceInfo GetDeviceInfoByDeviceId(const std::string &deviceId); void DeleteOffLineTimer(std::string &udidHash); @@ -177,11 +177,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/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 551f915189a3ae630aebb616b2dad18cbbf2fc42..0a986f2f1ca6ba0861126860ba3667096e382986 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); @@ -133,22 +133,26 @@ public: int32_t StopAuthenticateDevice(const std::string &pkgName); void HandleCredentialAuthStatus(const std::string &deviceList, 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); + 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 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); 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 switchUserId); - + 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 67c30b86348081d04a1ac21c9e31575b35484e30..b9b536eecfe83adb6a400b80abdff747c7c08d46 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); @@ -135,10 +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 switchUserId); + void HandleUserSwitched(const std::map &deviceMap, int32_t currentUserId, + int32_t beforeUserId); int32_t StopAuthenticateDevice(const std::string &pkgName); void HandleCredentialAuthStatus(const std::string &deviceList, 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); + void HandleRemoteUserRemoved(int32_t preUserId, 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 de6028f18c02a23f4ff01d81dd1d8853e97c1ffc..26ab14c8804418bb95943126ff1d73702e6e400e 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; } @@ -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/auth_ui_state_manager.cpp b/services/implementation/src/authentication/auth_ui_state_manager.cpp index ab4d5e415eadf376eb60fb4bb5d2765c0408aa14..d338980d721493ec475e1b803fc11729cefe2cab 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 aa1973ff71528a59f002c54f02364210ff2a695c..71fc5685fa413838f66534174dc092e3bd932a82 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 { @@ -90,6 +93,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"; @@ -136,9 +140,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; } @@ -149,15 +153,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; @@ -198,9 +204,12 @@ 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(); + uint32_t tokenId; + MultipleUserConnector::GetTokenIdAndForegroundUserId(tokenId, authRequestContext_->localUserId); + authRequestContext_->tokenId = static_cast(tokenId); + 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(); @@ -219,14 +228,12 @@ 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(); } authRequestContext_->bindLevel = GetBindLevel(authRequestContext_->bindLevel); } + authRequestContext_->bundleName = GetBundleName(jsonObject); authRequestContext_->token = std::to_string(GenRandInt(MIN_PIN_TOKEN, MAX_PIN_TOKEN)); } @@ -261,6 +268,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."); @@ -275,8 +286,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); @@ -336,17 +347,22 @@ 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_->SetPkgName(pkgName); - 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); - hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); - return DM_OK; + 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); + 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."); @@ -742,6 +758,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; @@ -899,9 +916,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); @@ -963,9 +980,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); @@ -975,7 +992,7 @@ void DmAuthManager::ProcessAuthRequestExt(const int32_t &sessionId) bool DmAuthManager::IsAuthFinish() { if (authResponseContext_->reply == ERR_DM_UNSUPPORTED_AUTH_TYPE) { - listener_->OnAuthResult(authResponseContext_->hostPkgName, peerTargetId_.deviceId, + listener_->OnAuthResult(processInfo_, peerTargetId_.deviceId, authRequestContext_->token, AuthState::AUTH_REQUEST_NEGOTIATE_DONE, ERR_DM_UNSUPPORTED_AUTH_TYPE); authRequestState_->TransitionTo(std::make_shared()); return true; @@ -1108,10 +1125,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"); @@ -1211,7 +1227,8 @@ int32_t DmAuthManager::JoinNetwork() void DmAuthManager::SinkAuthenticateFinish() { LOGI("DmAuthManager::SinkAuthenticateFinish, isFinishOfLocal: %{public}d", isFinishOfLocal_); - listener_->OnSinkBindResult(authResponseContext_->hostPkgName, peerTargetId_, authResponseContext_->reply, + processInfo_.pkgName = authResponseContext_->hostPkgName; + listener_->OnSinkBindResult(processInfo_, peerTargetId_, authResponseContext_->reply, authResponseContext_->state, GenerateBindResultContent()); if (authResponseState_->GetStateType() == AuthState::AUTH_RESPONSE_FINISH && authPtr_ != nullptr) { authUiStateMgr_->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_SHOW); @@ -1240,9 +1257,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; @@ -1285,16 +1302,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"); @@ -1957,9 +1964,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()) { - softbusConnector_->SetPkgName(authResponseContext_->hostPkgName); + if (!authResponseContext_->isIdenticalAccount && !authResponseContext_->hostPkgName.empty()) { + SetProcessInfo(); } softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); timer_->DeleteTimer(std::string(AUTHENTICATE_TIMEOUT_TASK)); @@ -1972,9 +1978,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()) { - softbusConnector_->SetPkgName(authResponseContext_->hostPkgName); + if (!authResponseContext_->isIdenticalAccount && !authResponseContext_->hostPkgName.empty()) { + SetProcessInfo(); } softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); authRequestState_->TransitionTo(std::make_shared()); @@ -2004,7 +2009,7 @@ void DmAuthManager::SinkAuthDeviceFinish() } if (authResponseContext_->isOnline) { LOGI("The device is online."); - softbusConnector_->SetPkgName(authResponseContext_->hostPkgName); + SetProcessInfo(); softbusConnector_->HandleDeviceOnline(remoteDeviceId_, authForm_); } } @@ -2125,18 +2130,16 @@ 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); + authResponseContext_->remoteAccountId = authResponseContext_->localAccountId; + authResponseContext_->remoteUserId = authResponseContext_->localUserId; + GetBinderInfo(); + MultipleUserConnector::SetSwitchOldAccountId(authResponseContext_->localAccountId); + MultipleUserConnector::SetSwitchOldUserId(authResponseContext_->localUserId); authResponseContext_->isIdenticalAccount = false; - if (authResponseContext_->localAccountId == accountId && accountId != "ohosAnonymousUid") { + if (authResponseContext_->localAccountId == authResponseContext_->remoteAccountId && + authResponseContext_->localAccountId != "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; @@ -2285,25 +2288,24 @@ void DmAuthManager::PutAccessControlList() } aclInfo.deviceIdHash = localUdidHash; DmAccesser accesser; - accesser.requestTokenId = static_cast(authResponseContext_->tokenId); 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.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) { + 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; accessee.trustDeviceId = localUdid; @@ -2526,5 +2528,58 @@ 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 = false; + std::string bundleName; + AppManager::GetInstance().GetCallerName(isSystemSA, bundleName); + return bundleName; +} + +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; + return DM_OK; + } + authResponseContext_->localUserId = MultipleUserConnector::GetForegroundUser(); + authResponseContext_->localAccountId = + MultipleUserConnector::GetOhosAccountIdByUserId(authResponseContext_->localUserId); + 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; +} + +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/credential/dm_credential_manager.cpp b/services/implementation/src/credential/dm_credential_manager.cpp index 043d2dd322ae530417d730ebed4101d95c186e6b..97cb2d577bad8ff4098760d72850e35f66c37739 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,12 @@ 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; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + MultipleUserConnector::GetCallerUserId(callerUserId); +#endif + 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 +253,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 +264,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 +274,15 @@ int32_t DmCredentialManager::RegisterCredentialCallback(const std::string &pkgNa LOGE("DmCredentialManager::RegisterCredentialCallback input param is empty"); return ERR_DM_FAILED; } + int32_t userId = -1; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + MultipleUserConnector::GetCallerUserId(userId); +#endif 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())); diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index e524c67d00c46a44fc43dd6c8aa043af1188eadf..2f1124e400bd29ea9f8a5da88db07da5408f280e 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -49,11 +49,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, @@ -675,32 +675,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 f24af10f611ac67fa4fcaa7b5254fe541a9f8e51..37a142f82caafb5914eee5d1cb116d763e50a5ba 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) { + 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."); - 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_->SetPkgNameVec(offlineParam.pkgNameVec); - deviceStateMgr_->HandleDeviceStatusChange(devState, devInfo); - } - if (offlineParam.leftAclNumber == 0) { - LOGI("Delete credential in HandleDeviceOffline."); - hiChainAuthConnector_->DeleteCredential(trustDeviceId, MultipleUserConnector::GetCurrentAccountUserID()); + 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); @@ -252,32 +265,34 @@ 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 pkgNameVec = - DeviceProfileConnector::GetInstance().GetPkgNameFromAcl(requestDeviceId, trustDeviceId); - if (pkgNameVec.size() == 0) { - LOGI("The online device not need report pkgname"); - return; - } - softbusConnector_->SetPkgNameVec(pkgNameVec); + std::vector processInfoVec = + 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 pkgNameVec = - DeviceProfileConnector::GetInstance().GetPkgNameFromAcl(requestDeviceId, trustDeviceId); - if (pkgNameVec.size() == 0) { - LOGI("The online device not need report pkgname"); - return; - } - softbusConnector_->SetPkgNameVec(pkgNameVec); + std::vector processInfoVec = + DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(requestDeviceId, trustDeviceId, + MultipleUserConnector::GetForegroundUser()); + softbusConnector_->SetProcessInfoVec(processInfoVec); devInfo.authForm = DmAuthForm::ACROSS_ACCOUNT; } LOGI("DeviceManagerServiceImpl::HandleOnline success devInfo auform %{public}d.", devInfo.authForm); @@ -300,6 +315,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 +507,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) { @@ -624,8 +643,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::GetForegroundUser(); + accesser.requestAccountId = MultipleUserConnector::GetOhosAccountIdByUserId(accesser.requestUserId); MultipleUserConnector::SetSwitchOldUserId(accesser.requestUserId); MultipleUserConnector::SetSwitchOldAccountId(accesser.requestAccountId); accesser.requestDeviceId = requestDeviceId; @@ -641,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"); @@ -658,12 +681,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() @@ -692,12 +715,35 @@ void DeviceManagerServiceImpl::HandleUserRemoved(int32_t preUserId) hiChainConnector_->DeleteAllGroup(preUserId); } -void DeviceManagerServiceImpl::HandleUserSwitched(int32_t switchUserId) +void DeviceManagerServiceImpl::HandleRemoteUserRemoved(int32_t userId, const std::string &remoteUdid) { - LOGI("switchUserId: %{public}d.", switchUserId); - DeviceProfileConnector::GetInstance().DeleteAclForUserRemoved(switchUserId); - CHECK_NULL_VOID(hiChainConnector_); - hiChainConnector_->DeleteP2PGroup(switchUserId); + LOGI("remoteUdid %{public}s, userId %{public}d", GetAnonyString(remoteUdid).c_str(), userId); + //TOOD: process remote device delete user +} + +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); } void DeviceManagerServiceImpl::ScreenCommonEventCallback(std::string commonEventType) @@ -739,6 +785,16 @@ int32_t DeviceManagerServiceImpl::GetBindLevel(const std::string &pkgName, const return DeviceProfileConnector::GetInstance().GetBindLevel(pkgName, localUdid, udid, tokenId); } +std::map DeviceManagerServiceImpl::GetDeviceIdAndBindLevel(int32_t userId) +{ + char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localUdidTemp); + std::vector userIds; + userIds.push_back(userId); + return DeviceProfileConnector::GetInstance().GetDeviceIdAndBindLevel(userIds, localUdid); +} + std::map DeviceManagerServiceImpl::GetDeviceIdAndBindType(int32_t userId, const std::string &accountId) { @@ -761,11 +817,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) @@ -804,17 +862,50 @@ 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_->SetPkgName(pkgName); + softbusConnector_->SetProcessInfo(processInfo); 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()); + 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) { LOGI("In"); @@ -839,16 +930,15 @@ 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(); - 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 pkgNameVec = - DeviceProfileConnector::GetInstance().GetPkgNameFromAcl(requestDeviceId, trustDeviceId); - if (pkgNameVec.size() == 0) { - LOGI("not need report pkgname"); - return; - } - softbusConnector_->SetPkgNameVec(pkgNameVec); + std::vector processInfoVec = + 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 d8b73f8566076b62075aab4d4c7439bf29d7fc67..6d5ee5be4bf0a89a638f29c0946cd98828d77181 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; } @@ -512,9 +513,12 @@ void DeviceManagerServiceImpl::HandleDeviceScreenStatusChange(DmDeviceInfo &devI return; } -void DeviceManagerServiceImpl::HandleUserSwitched(int32_t switchUserId) +void DeviceManagerServiceImpl::HandleUserSwitched(const std::map &deviceMap, + int32_t currentUserId, int32_t beforeUserId) { - (void)switchUserId; + (void)deviceMap; + (void)currentUserId; + (void)beforeUserId; return; } @@ -533,13 +537,31 @@ void DeviceManagerServiceImpl::HandleCredentialAuthStatus(const std::string &dev 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; +} + +void HandleRemoteUserRemoved(int32_t preUserId, const std::string &remoteUdid) +{ + (void)preUserId; + (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 1848fc3b1dc4c291cab73b4c9c2fdb8849d61f0f..9039e7b4dabe00f0f200bfead73ddcf864e97226 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)) @@ -110,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) @@ -126,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) @@ -139,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); @@ -150,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); @@ -165,17 +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; - } - std::vector pkgName = softbusConnector_->GetPkgName(); - if (pkgName.size() == 0) { - listener_->OnDeviceStateChange(std::string(DM_PKG_NAME), devState, devInfo); - } else { - for (auto item : pkgName) { - listener_->OnDeviceStateChange(item, devState, devInfo); - } + CHECK_NULL_VOID(softbusConnector_); + CHECK_NULL_VOID(listener_); + std::vector processInfoVec = softbusConnector_->GetProcessInfo(); + for (const auto &item : processInfoVec) { + listener_->OnDeviceStateChange(item, devState, devInfo); } } @@ -201,7 +196,10 @@ 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; + processInfo.userId = MultipleUserConnector::GetForegroundUser(); + listener_->OnDeviceStateChange(processInfo, state, saveInfo); } } @@ -511,20 +509,11 @@ bool DmDeviceStateManager::CheckIsOnline(const std::string &udid) void DmDeviceStateManager::HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) { - if (softbusConnector_ == nullptr || listener_ == nullptr) { - LOGE("failed, ptr is null."); - return; - } - std::vector pkgName = softbusConnector_->GetPkgName(); - LOGI("pkgName size: %{public}zu", pkgName.size()); - if (pkgName.size() == 0) { - listener_->OnDeviceScreenStateChange(std::string(DM_PKG_NAME), devInfo); - } else { - for (auto item : pkgName) { - listener_->OnDeviceScreenStateChange(item, devInfo); - } - } - softbusConnector_->ClearPkgName(); + CHECK_NULL_VOID(softbusConnector_); + CHECK_NULL_VOID(listener_); + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + listener_->OnDeviceScreenStateChange(processInfo, devInfo); } void DmDeviceStateManager::HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, @@ -534,7 +523,9 @@ void DmDeviceStateManager::HandleCredentialAuthStatus(const std::string &deviceL LOGE("Failed, listener_ is null."); return; } - listener_->OnCredentialAuthStatus(std::string(DM_PKG_NAME), deviceList, deviceTypeId, errcode); + ProcessInfo processInfo; + processInfo.pkgName = std::string(DM_PKG_NAME); + listener_->OnCredentialAuthStatus(processInfo, deviceList, 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 594b949f1f0f8dc8a50fdf9ea753bf279a57f613..a9ccaee3a3a19ec9997feb80e8117f1922a5a60d 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/BUILD.gn b/services/service/BUILD.gn index b1e2abbc9cb4d9fc2a4272ff33b52037898acfa1..52412fe3d25afa2efd284ff8f2c0294f1fb1e716 100644 --- a/services/service/BUILD.gn +++ b/services/service/BUILD.gn @@ -30,7 +30,6 @@ if (defined(ohos_lite)) { "include/ipc/lite", "include/permission/lite", "include/pinholder", - "include/relationshipsyncmgr", "${common_path}/include", "${common_path}/include/ipc", "${common_path}/include/ipc/lite", @@ -72,7 +71,6 @@ if (defined(ohos_lite)) { "src/permission/lite/permission_manager.cpp", "src/pinholder/pin_holder.cpp", "src/pinholder/pin_holder_session.cpp", - "src/relationshipsyncmgr/relationship_sync_mgr.cpp", "src/softbus/mine_softbus_listener.cpp", "src/softbus/softbus_listener.cpp", ] @@ -180,6 +178,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.cpp", + "src/relationshipsyncmgr/dm_transport_msg.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 a8bd812087b0d6e008841ecb4f4bd81d53e7d283..b6ca204106361b313091d6fa4774b54b2872fcd7 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); @@ -192,17 +184,20 @@ public: bool CheckAccessControl(const DmAccessCaller &caller, const DmAccessCallee &callee); bool CheckIsSameAccount(const DmAccessCaller &caller, const DmAccessCallee &callee); void HandleDeviceNotTrust(const std::string &msg); +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) void HandleDeviceTrustedChange(const std::string &msg); - + void HandleUserIdCheckSumChange(const std::string &msg); +#endif 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); void SubscribePackageCommonEvent(); int32_t GetNetworkIdByUdid(const std::string &pkgName, const std::string &udid, std::string &networkId); void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode); - int32_t SetLocalDeviceName(const std::string &localDeviceName, const std::string &localDisplayName); + void ProcessForegroundUserIds(const std::vector &remoteUserIds, const std::string &remoteUdid); + int32_t SetLocalDeviceName(const std::string &localDeviceName); private: bool IsDMServiceImplReady(); bool IsDMServiceAdapterLoad(); @@ -216,18 +211,36 @@ 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); + /** + * @brief send local foreground userids by broadcast + * + * @param peerUdids the broadcast target device udid list + * @param userIds local foreground userids + * @param isNeedResponse true for need remote send back remote foreground userids, false for NO NEED send back + */ + void SendForegroundUserIdsBroadCast(const std::vector &peerUdids, + const std::vector &userIds, bool isNeedResponse); + 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(); - 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); 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 HandleUserSwitched(int32_t switchUserId); + void HandleUserRemoved(int32_t removedUserId); + /** + * @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 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 a175c85252cbe4cbadbecd08eaeb7e9b4e632219..8b4b90f6004159e3e2fb3208e2bab482f1e6533f 100644 --- a/services/service/include/device_manager_service_listener.h +++ b/services/service/include/device_manager_service_listener.h @@ -39,57 +39,55 @@ 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; + 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 std::string &pkgName, DmDeviceInfo &devInfo) override; - void OnCredentialAuthStatus(const std::string &pkgName, const std::string &deviceList, uint16_t deviceTypeId, + void OnDeviceScreenStateChange(const ProcessInfo &processInfo, DmDeviceInfo &devInfo) override; + void OnCredentialAuthStatus(const ProcessInfo &processInfo, const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode) override; void OnAppUnintall(const std::string &pkgName) override; - void OnSinkBindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, + void OnSinkBindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, int32_t status, std::string content) override; 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, + void ProcessDeviceStateChange(const ProcessInfo &processInfo, 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, + void SetDeviceScreenInfo(std::shared_ptr pReq, const ProcessInfo &processInfo, const DmDeviceInfo &deviceInfo); void RemoveOnlinePkgName(const DmDeviceInfo &info); #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) @@ -97,11 +95,24 @@ private: int32_t ConvertUdidHashToAnoyDeviceId(const std::string &pkgName, const std::string &udidHash, std::string &anoyDeviceId); #endif + 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::unordered_map alreadyOnlinePkgName_; + static std::mutex alreadyNotifyPkgNameLock_; + 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 04c5deef3d1676541d48e30ec4d3ce2677d79da3..ddb542ab239bf474634fae20dbf913924c8a48eb 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_impl.h b/services/service/include/idevice_manager_service_impl.h index f447e2ebca4811ff3be5db62dd0212c6cb7ac8fa..841bde7c72fa79048ba811e038354217d3c8188d 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) = 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; @@ -271,11 +272,16 @@ 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(const std::map &deviceMap, int32_t currentUserId, + int32_t beforeUserId) = 0; virtual int32_t StopAuthenticateDevice(const std::string &pkgName) = 0; virtual void HandleCredentialAuthStatus(const std::string &deviceList, 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/include/idevice_manager_service_listener.h b/services/service/include/idevice_manager_service_listener.h index 9e39d244002de9a800c823ec117412198edebd96..8d617c9f73f51d4b5295ea49a2b8fcf0bedae5c0 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; /** @@ -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; /** @@ -157,17 +150,17 @@ 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 * @tc.desc: Candidate Restrict Status Change of the DeviceManager Service Listener * @tc.type: FUNC */ - virtual void OnCredentialAuthStatus(const std::string &pkgName, const std::string &deviceList, + virtual void OnCredentialAuthStatus(const ProcessInfo &processInfo, const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode) = 0; virtual void OnAppUnintall(const std::string &pkgName) = 0; - virtual void OnSinkBindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, + virtual void OnSinkBindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, int32_t status, std::string content) = 0; }; } // namespace DistributedHardware diff --git a/services/service/include/ipc/lite/ipc_server_listener.h b/services/service/include/ipc/lite/ipc_server_listener.h index f6dfcb6af53d1c6df0583ef85c6885cac9faedeb..294cbe2265b002277c7e345c6e904fa49df9600a 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 @@ -17,7 +17,9 @@ #define OHOS_DM_IPC_SERVER_LISTENER_H #include +#include +#include "dm_device_info.h" #include "ipc_req.h" #include "ipc_rsp.h" #include "ipc_server_listenermgr.h" @@ -38,18 +40,12 @@ 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(); + std::set GetSystemSA(); 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 4a19b1e57ed5fc5d3abdcdd5f53205345607bd4d..af97616104ad978621bcf9c40865e4708af5aa28 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 @@ -17,7 +17,8 @@ #define OHOS_DM_IPC_SERVER_LISTENER_H #include - +#include +#include "dm_device_info.h" #include "ipc_req.h" #include "ipc_rsp.h" @@ -37,18 +38,12 @@ 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(); + 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 6c3f819f284cb0084c2ec1cf6b21ad6f54b32dc4..ff6055c45a34e54977043a66324bdfc5d797d936 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 @@ -30,6 +31,7 @@ #include "system_ability.h" #include "account_boot_listener.h" +#include "dm_device_info.h" #include "dm_single_instance.h" namespace OHOS { @@ -86,14 +88,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 +105,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 @@ -150,19 +145,23 @@ 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_; ServiceRunningState state_; mutable std::mutex listenerLock_; - std::map> appRecipient_; - std::map> dmListener_; + 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 4d41f71dbdf46bb3baae1f4d816cd970f67873a2..85b6bd48e40f8c8be777da026549473ac672e97c 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(); bool CheckProcessNameValidOnSetDnPolicy(const std::string &processName); }; } // namespace DistributedHardware diff --git a/services/service/include/permission/standard/permission_manager.h b/services/service/include/permission/standard/permission_manager.h index 6b3716507fa8858a782f4e70a089d393b0c9b1bd..ddf790bf0ac202bd41b355de7ac7ccdc27f3c4b8 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(); bool CheckProcessNameValidOnSetDnPolicy(const std::string &processName); }; } // namespace DistributedHardware diff --git a/services/service/include/pinholder/pin_holder.h b/services/service/include/pinholder/pin_holder.h index 75d999cd99f55d002a71923e26162f0040086379..c31157cbdc02a393d156b8d8a8eab247f8372f53 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/include/publishcommonevent/dm_account_common_event.h b/services/service/include/publishcommonevent/dm_account_common_event.h index b0a9e68785b3d242173f433f02b663eb1a88a874..640bf206fbfe1a46397b40662700966244747b77 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/include/relationshipsyncmgr/dm_comm_tool.h b/services/service/include/relationshipsyncmgr/dm_comm_tool.h new file mode 100644 index 0000000000000000000000000000000000000000..1b89e60625c446aa0a98bef6eea84f757f8b73d9 --- /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 0000000000000000000000000000000000000000..cf8eb0890673f1c8b612f3a1b323facb1fd16564 --- /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 0000000000000000000000000000000000000000..ebfe1a84991174d4e4c4f3fc252e917284d08b02 --- /dev/null +++ b/services/service/include/relationshipsyncmgr/dm_transport_msg.h @@ -0,0 +1,74 @@ +/* + * 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"; + +const char* const DSOFTBUS_NOTIFY_USERIDS_UDIDKEY = "remoteUdid"; +const char* const DSOFTBUS_NOTIFY_USERIDS_USERIDKEY = "foregroundUserIds"; + +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) {} +}; + +struct NotifyUserIds { + std::string remoteUdid; + std::vector userIds; + NotifyUserIds() : remoteUdid(""), userIds({}) {} + NotifyUserIds(std::string remoteUdid, std::vector userIds) + : remoteUdid(remoteUdid), userIds(userIds) {} + + std::string ToString(); +}; + +void ToJson(cJSON *jsonObject, const NotifyUserIds &userIds); +void FromJson(const cJSON *jsonObject, NotifyUserIds &userIds); +} // DistributedHardware +} // OHOS +#endif \ No newline at end of file diff --git a/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h b/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h index 10156b19d5694b268a53def4d90b045aa034aa73..fb8b3b3cff89582df472dd25069e7d0617e8f84f 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,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; - 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 FromSyncForegroundUserIdPayLoad(const cJSON *payloadJson); + bool FromDelUserPayLoad(const cJSON *payloadJson); std::string ToJson() const; bool FromJson(const std::string &msgJson); diff --git a/services/service/include/softbus/softbus_listener.h b/services/service/include/softbus/softbus_listener.h index 9220f2e139b9cb4addef3895e9c1d117f1c92224..1ccbaa02ef29f88f4da6f919714feb37bb34cf28 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(const char *deviceList, uint32_t deviceListLen, uint16_t deviceTypeId, @@ -103,6 +104,7 @@ public: int32_t GetDeviceScreenStatus(const char *networkId, int32_t &screenStatus); static int32_t GetNetworkIdByUdid(const std::string &udid, std::string &networkId); int32_t SetLocalDeviceName(const std::string &localDeviceName, const std::string &localDisplayName); + int32_t SetForegroundUserIdsToDSoftBus(const std::string &remoteUserId, const std::vector &userIds); private: static int32_t FillDeviceInfo(const DeviceInfo &device, DmDeviceInfo &dmDevice); int32_t InitSoftPublishLNN(); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index db144ccbe5b07e915b4e2854a187867c1c6dce8e..2704909fbff2b7be523d8cabd890911d4a26a474 100755 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -19,21 +19,24 @@ #include #include "app_manager.h" +#include "nlohmann/json.hpp" #include "dm_anonymous.h" #include "dm_constants.h" #include "dm_crypto.h" #include "dm_hidumper.h" #include "dm_log.h" #include "dm_softbus_cache.h" +#include "dm_transport_msg.h" #include "parameter.h" #include "permission_manager.h" -#include "relationship_sync_mgr.h" #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) #include "common_event_support.h" #include "datetime_ex.h" +#include "dm_comm_tool.h" #include "iservice_registry.h" #include "kv_adapter_manager.h" #include "multiple_user_connector.h" +#include "relationship_sync_mgr.h" #if defined(SUPPORT_POWER_MANAGER) #include "power_mgr_client.h" #endif // SUPPORT_POWER_MANAGER @@ -60,13 +63,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"); @@ -203,6 +211,9 @@ int32_t DeviceManagerService::InitDMServiceListener() if (pinHolder_ == nullptr) { pinHolder_ = std::make_shared(listener_); } +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + DMCommTool::GetInstance()->Init(); +#endif LOGI("Init success."); return DM_OK; } @@ -228,7 +239,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()); @@ -258,12 +269,19 @@ int32_t DeviceManagerService::GetTrustedDeviceList(const std::string &pkgName, c } return DM_OK; } - if (onlineDeviceList.size() > 0 && IsDMServiceImplReady()) { + uint32_t tokenId = 0; + int32_t userId = -1; + MultipleUserConnector::GetTokenIdAndForegroundUserId(tokenId, userId); + if (userId == -1 || tokenId == 0) { + 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)); + if (PermissionManager::GetInstance().CheckWhiteListSystemSA(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)) @@ -404,72 +422,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()) { @@ -1593,8 +1545,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); @@ -1622,19 +1574,22 @@ 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())) { - HandleUserSwitched(MultipleUserConnector::GetSwitchOldUserId()); - } - MultipleUserConnector::SetSwitchOldUserId(userId); + 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(userId, MultipleUserConnector::GetOhosAccountId()); + dmServiceImplExt_->AccountUserSwitched(currentUserId, MultipleUserConnector::GetOhosAccountId()); } } else if (commonEventType == CommonEventSupport::COMMON_EVENT_HWID_LOGIN) { MultipleUserConnector::SetSwitchOldAccountId(MultipleUserConnector::GetOhosAccountId()); @@ -1643,7 +1598,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."); } @@ -1680,22 +1635,71 @@ void DeviceManagerService::HandleAccountLogout(int32_t userId, const std::string } } -void DeviceManagerService::HandleUserSwitched(int32_t switchUserId) +void DeviceManagerService::HandleUserSwitched(int32_t curUserId, int32_t preUserId) { - LOGI("switchUserId: %{public}d.", switchUserId); + 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; + 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; + 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, false); + } + } if (IsDMServiceImplReady()) { - dmServiceImpl_->HandleUserSwitched(switchUserId); + dmServiceImpl_->HandleUserSwitched(preUserDeviceMap, curUserId, preUserId); } } -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, MultipleUserConnector::GetSwitchOldAccountId()); + 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) { @@ -1712,6 +1716,80 @@ void DeviceManagerService::SendAccountLogoutBroadCast(const std::vectorSendAclChangedBroadcast(broadCastMsg); } +void DeviceManagerService::SendForegroundUserIdsBroadCast(const std::vector &peerUdids, + const std::vector &userIds, bool isNeedResponse) +{ + 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 = isNeedResponse; + 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); + } + } + + // Notify received remote foreground userids to dsoftbus + std::vector userIds; + for (const auto &u : remoteUserIds) { + userIds.push_back(static_cast(u)); + } + + if (softbusListener_ != nullptr) { + softbusListener_->SetForegroundUserIdsToDSoftBus(remoteUdid, userIds); + } + + if (IsDMServiceImplReady()) { + dmServiceImpl_->HandleSyncForegroundUserIdEvent(remoteUserIds, remoteUdid); + } +} + +void DeviceManagerService::ProcessForegroundUserIds(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 (softbusListener_ != nullptr) { + softbusListener_->SetForegroundUserIdsToDSoftBus(remoteUdid, remoteUserIds); + } + + 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()) { @@ -1899,7 +1977,6 @@ void DeviceManagerService::SendServiceUnBindBroadCast(const std::vectorSendAclChangedBroadcast(broadCastMsg); } -#endif void DeviceManagerService::HandleDeviceTrustedChange(const std::string &msg) { @@ -1930,6 +2007,13 @@ void DeviceManagerService::HandleDeviceTrustedChange(const std::string &msg) dmServiceImpl_->HandleAppUnBindEvent(relationShipMsg.userId, relationShipMsg.peerUdid, static_cast(relationShipMsg.tokenId)); break; + case RelationShipChangeType::SYNC_FOREGROUND_USERID: + 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; @@ -1937,11 +2021,66 @@ void DeviceManagerService::HandleDeviceTrustedChange(const std::string &msg) return; } -void DeviceManagerService::ClearDiscoveryCache(const std::string &pkgName) +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(); + + 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 = ""; + 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 }; + LOGE("Send local forground userids"); + SendForegroundUserIdsBroadCast(peerUdids, userVec, true); + } +} +#endif + +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.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 84d08e8c2daf946d2b6ce305c7fdf185022c3453..2150b78246288663bd2201c0be3dc4490269bf94 100644 --- a/services/service/src/device_manager_service_listener.cpp +++ b/services/service/src/device_manager_service_listener.cpp @@ -13,6 +13,8 @@ * limitations under the License. */ +#include + #include "device_manager_service_listener.h" #include "app_manager.h" @@ -39,17 +41,19 @@ #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" namespace OHOS { namespace DistributedHardware { -std::mutex DeviceManagerServiceListener::alreadyOnlinePkgNameLock_; -std::unordered_map DeviceManagerServiceListener::alreadyOnlinePkgName_ = {}; +std::mutex DeviceManagerServiceListener::alreadyNotifyPkgNameLock_; +std::map DeviceManagerServiceListener::alreadyOnlinePkgName_ = {}; void DeviceManagerServiceListener::ConvertDeviceInfoToDeviceBasicInfo(const std::string &pkgName, const DmDeviceInfo &info, DmDeviceBasicInfo &deviceBasicInfo) { + (void)pkgName; if (memset_s(&deviceBasicInfo, sizeof(DmDeviceBasicInfo), 0, sizeof(DmDeviceBasicInfo)) != DM_OK) { LOGE("ConvertDeviceInfoToDeviceBasicInfo memset_s failed."); return; @@ -77,21 +81,22 @@ 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 = ""; - if (AppManager::GetInstance().GetAppIdByPkgName(pkgName, appId) != DM_OK) { + 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."); @@ -110,160 +115,109 @@ 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) +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 PkgNameVec = ipcServerListener_.GetAllPkgName(); - if (state == DEVICE_STATE_OFFLINE) { - 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)); - DmDeviceState notifyState = state; - { - std::lock_guard autoLock(alreadyOnlinePkgNameLock_); - if (alreadyOnlinePkgName_.find(notifyKey) != alreadyOnlinePkgName_.end()) { - notifyState = DmDeviceState::DEVICE_INFO_CHANGED; - } else { - alreadyOnlinePkgName_[notifyKey] = 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 : PkgNameVec) { - SetDeviceInfo(pReq, it, state, info, deviceBasicInfo); - ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); - } + std::vector processInfoVec = GetNotifyProcessInfoByUserId(processInfo.userId); + 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; } } -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"); - std::shared_ptr pReq = std::make_shared(); - std::shared_ptr pRsp = std::make_shared(); - std::unordered_set notifyPkgnames = PermissionManager::GetInstance().GetSystemSA(); - notifyPkgnames.insert(pkgName); - if (state == DEVICE_STATE_ONLINE) { - for (const auto &it : notifyPkgnames) { - std::string notifyKey = it + "_" + info.deviceId; - { - std::lock_guard autoLock(alreadyOnlinePkgNameLock_); - if (alreadyOnlinePkgName_.find(notifyKey) != alreadyOnlinePkgName_.end()) { - continue; - } - alreadyOnlinePkgName_[notifyKey] = 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 : notifyPkgnames) { - 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); - } - } - SetDeviceInfo(pReq, pkgName, 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); - ipcServerListener_.SendRequest(SERVER_DEVICE_STATE_NOTIFY, pReq, pRsp); + std::vector processInfoVec = GetWhiteListSAProcessInfo(); + ProcessInfo bindProcessInfo = DealBindProcessInfo(processInfo); + processInfoVec.push_back(bindProcessInfo); + 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; } } -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)) { - ProcessDeviceStateChange(state, info, deviceBasicInfo); + ConvertDeviceInfoToDeviceBasicInfo(processInfo.pkgName, info, deviceBasicInfo); + if (processInfo.pkgName == std::string(DM_PKG_NAME)) { + ProcessDeviceStateChange(processInfo, state, info, deviceBasicInfo); } else { - ProcessAppStateChange(pkgName, state, info, deviceBasicInfo); + ProcessAppStateChange(processInfo, state, info, deviceBasicInfo); } #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) KVAdapterManager::GetInstance().DeleteAgedEntry(); #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); } @@ -279,7 +233,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(); @@ -290,42 +244,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(); @@ -337,20 +294,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(); @@ -359,79 +317,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)) @@ -485,55 +449,70 @@ 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(); - for (const auto &it : PkgNameVec) { - pReq->SetPkgName(it); + int32_t userId = -1; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + userId = MultipleUserConnector::GetForegroundUser(); +#endif + std::vector processInfoVec = GetNotifyProcessInfoByUserId(userId); + 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); } } 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) { + if (AppManager::GetInstance().GetAppIdByPkgName(processInfo.pkgName, appId) != DM_OK) { pReq->SetDeviceInfo(deviceInfo); return; } DmDeviceInfo dmDeviceInfo = deviceInfo; - ConvertUdidHashToAnoyAndSave(pkgName, dmDeviceInfo); + ConvertUdidHashToAnoyAndSave(processInfo.pkgName, dmDeviceInfo); pReq->SetDeviceInfo(dmDeviceInfo); return; #endif pReq->SetDeviceInfo(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_.GetAllPkgName(); - for (const auto &it : PkgNameVec) { - SetDeviceScreenInfo(pReq, it, devInfo); + int32_t userId = -1; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + userId = MultipleUserConnector::GetForegroundUser(); +#endif + std::vector processInfoVec = + GetNotifyProcessInfoByUserId(userId); + 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::unordered_set notifyPkgnames = PermissionManager::GetInstance().GetSystemSA(); - notifyPkgnames.insert(pkgName); - for (const auto &it : notifyPkgnames) { - 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); } } @@ -541,7 +520,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); @@ -552,31 +531,31 @@ void DeviceManagerServiceListener::RemoveOnlinePkgName(const DmDeviceInfo &info) } } -void DeviceManagerServiceListener::OnCredentialAuthStatus(const std::string &pkgName, +void DeviceManagerServiceListener::OnCredentialAuthStatus(const ProcessInfo &processInfo, const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode) { - LOGI("In, pkgName = %{public}s", pkgName.c_str()); - std::shared_ptr pReq = - std::make_shared(); - std::shared_ptr pRsp = std::make_shared(); - pReq->SetDeviceList(deviceList); - pReq->SetDeviceTypeId(deviceTypeId); - pReq->SetErrCode(errcode); - if (pkgName == std::string(DM_PKG_NAME)) { - std::vector PkgNameVec = ipcServerListener_.GetAllPkgName(); - for (const auto &it : PkgNameVec) { - pReq->SetPkgName(it); - ipcServerListener_.SendRequest(SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY, pReq, pRsp); - } - } else { - pReq->SetPkgName(pkgName); + LOGI("In, pkgName = %{public}s", processInfo.pkgName.c_str()); + int32_t userId = -1; +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + userId = MultipleUserConnector::GetForegroundUser(); +#endif + std::vector processInfoVec = + GetNotifyProcessInfoByUserId(userId); + for (const auto &item : processInfoVec) { + std::shared_ptr pReq = std::make_shared(); + std::shared_ptr pRsp = std::make_shared(); + pReq->SetDeviceList(deviceList); + pReq->SetDeviceTypeId(deviceTypeId); + pReq->SetErrCode(errcode); + pReq->SetPkgName(item.pkgName); + pReq->SetProcessInfo(item); ipcServerListener_.SendRequest(SERVICE_CREDENTIAL_AUTH_STATUS_NOTIFY, pReq, pRsp); } } 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.find(pkgName) == 0) { it = alreadyOnlinePkgName_.erase(it); @@ -586,7 +565,7 @@ void DeviceManagerServiceListener::OnAppUnintall(const std::string &pkgName) } } -void DeviceManagerServiceListener::OnSinkBindResult(const std::string &pkgName, const PeerTargetId &targetId, +void DeviceManagerServiceListener::OnSinkBindResult(const ProcessInfo &processInfo, const PeerTargetId &targetId, int32_t result, int32_t status, std::string content) { std::shared_ptr pReq = std::make_shared(); @@ -598,17 +577,186 @@ void DeviceManagerServiceListener::OnSinkBindResult(const std::string &pkgName, #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); + std::vector processInfos = ipcServerListener_.GetAllProcessInfo(); + ProcessInfo processInfoTemp;; + for (auto item : processInfos) { + if (item.pkgName == processInfo.pkgName) { + processInfoTemp = item; + } + } + if (processInfoTemp.pkgName.empty()) { + LOGI("not register listener"); + return; + } + pReq->SetProcessInfo(processInfoTemp); pReq->SetPeerTargetId(returnTargetId); pReq->SetResult(result); pReq->SetStatus(status); pReq->SetContent(content); ipcServerListener_.SendRequest(SINK_BIND_TARGET_RESULT, pReq, pRsp); } + +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; + processInfos.push_back(processInfo); + } + return processInfos; +} + +std::vector DeviceManagerServiceListener::GetNotifyProcessInfoByUserId(int32_t userId) +{ + 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); + } else if (item.userId == userId) { + processInfosTemp.push_back(item); + } + } + 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; +} + +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, notifyState, 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, notifyState, 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 diff --git a/services/service/src/discovery/discovery_manager.cpp b/services/service/src/discovery/discovery_manager.cpp index 285337a8f18495f8033a44e09f96b97355e51443..a015ea43f582f7308f23e14044dc4c1a0f337be7 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 9154339c21937856cf2166444359cd4bf3c919ee..e6f3bd310875eaab82ea9303f337181d7a43f277 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 9543725599ad1ac3d3656fa3be74fe9d52c43b3a..912b538aecc506aada4825f6df96135c4cc1e32f 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,21 @@ 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); - } + ProcessInfo processInfo; + processInfo.pkgName = kv.first; + processInfoVec.push_back(processInfo); } - return DM_OK; + return processInfoVec; } -std::vector IpcServerListener::GetAllPkgName() +std::set IpcServerListener::GetSystemSA() { - std::vector pkgNameList; - const std::map &listenerMap = IpcServerListenermgr::GetInstance().GetAllListeners(); - for (const auto &kv : listenerMap) { - pkgNameList.push_back(kv.first); - } - return pkgNameList; + 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 2bb2369b37e7e8697b284df01125b46113899b5f..dd83b850d02e5c18b00cfa376eb5fa2a466c6ffc 100644 --- a/services/service/src/ipc/standard/ipc_cmd_parser.cpp +++ b/services/service/src/ipc/standard/ipc_cmd_parser.cpp @@ -43,9 +43,12 @@ #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" - +#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; @@ -419,8 +422,11 @@ ON_IPC_CMD(REGISTER_DEVICE_MANAGER_LISTENER, MessageParcel &data, MessageParcel OHOS::HiviewDFX::XCollie::GetInstance().CancelTimer(id); return ERR_DM_POINT_NULL; } + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + MultipleUserConnector::GetCallerUserId(processInfo.userId); 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,39 +439,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; + processInfo.pkgName = pkgName; + MultipleUserConnector::GetCallerUserId(processInfo.userId); DeviceManagerService::GetInstance().UnRegisterCallerAppId(pkgName); - int32_t result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); - if (!reply.WriteInt32(result)) { - LOGE("write result failed"); - return ERR_DM_IPC_WRITE_FAILED; - } - 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); + int32_t result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); if (!reply.WriteInt32(result)) { LOGE("write result failed"); return ERR_DM_IPC_WRITE_FAILED; @@ -473,17 +451,6 @@ ON_IPC_CMD(START_DEVICE_DISCOVERY, MessageParcel &data, MessageParcel &reply) 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 a9dc4c9f4cad5e8df52c98e5b0d547da249983b5..9c9cec34aef265ddc24420dd78d9ef7b2d03fd57 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,36 +31,27 @@ 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()); + LOGI("cannot get listener for package:%{public}s.", processInfo.pkgName.c_str()); return ERR_DM_POINT_NULL; } return listener->SendCmd(cmdCode, req, rsp); } -std::vector IpcServerListener::GetAllPkgName() +std::vector IpcServerListener::GetAllProcessInfo() { - return IpcServerStub::GetInstance().GetAllPkgName(); + return IpcServerStub::GetInstance().GetAllProcessInfo(); } -int32_t IpcServerListener::SendAll(int32_t cmdCode, std::shared_ptr req, std::shared_ptr rsp) +std::set IpcServerListener::GetSystemSA() { - 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().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 c5dd20a76991810261c25d48f2ddaba789799e9d..224c5a3c75eed0a2c8ed0f0c2f241ce889cd0f0f 100644 --- a/services/service/src/ipc/standard/ipc_server_stub.cpp +++ b/services/service/src/ipc/standard/ipc_server_stub.cpp @@ -33,8 +33,10 @@ #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" +#include "permission_manager.h" namespace OHOS { namespace DistributedHardware { @@ -211,119 +213,104 @@ 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", processInfo.pkgName.c_str()); 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); } } - sptr appRecipient = sptr(new AppDeathRecipient()); if (!listener->AsObject()->AddDeathRecipient(appRecipient)) { LOGE("AddDeathRecipient Failed"); } - dmListener_[pkgName] = listener; - appRecipient_[pkgName] = appRecipient; - LOGD("Register listener complete."); + dmListener_[processInfo] = listener; + appRecipient_[processInfo] = appRecipient; + AddSystemSA(processInfo.pkgName); + 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); + RemoveSystemSA(processInfo.pkgName); 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); + processInfoVec.push_back(iter.first); } - return DM_OK; + return processInfoVec; } -std::vector IpcServerStub::GetAllPkgName() +const sptr IpcServerStub::GetDmListener(ProcessInfo processInfo) const { - std::vector PkgNameVec; - std::lock_guard autoLock(listenerLock_); - for (const auto &iter : dmListener_) { - PkgNameVec.push_back(iter.first); - } - return PkgNameVec; -} - -const sptr IpcServerStub::GetDmListener(std::string pkgName) 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) @@ -350,10 +337,34 @@ 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); +} + +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 407455c0a522501c829d4fa88e252f3b8c94a28c..3b479ef978a13a14966d3eedd2ad02f6a96cc4fe 100644 --- a/services/service/src/permission/lite/permission_manager.cpp +++ b/services/service/src/permission/lite/permission_manager.cpp @@ -54,17 +54,23 @@ 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; +} + bool PermissionManager::CheckProcessNameValidOnSetDnPolicy(const std::string &processName) { (void)processName; diff --git a/services/service/src/permission/standard/permission_manager.cpp b/services/service/src/permission/standard/permission_manager.cpp index f49d5fcf7cdfc30ae5426436372aa8d0d30a339c..59a1fe23756eafed0238da903eff4053b4991187 100644 --- a/services/service/src/permission/standard/permission_manager.cpp +++ b/services/service/src/permission/standard/permission_manager.cpp @@ -197,7 +197,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]); @@ -208,7 +208,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) { @@ -218,6 +218,20 @@ 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; +} + bool PermissionManager::CheckProcessNameValidOnSetDnPolicy(const std::string &processName) { if (processName.empty()) { diff --git a/services/service/src/pinholder/pin_holder.cpp b/services/service/src/pinholder/pin_holder.cpp index 8b86a63d28c93ef606664e90d6db8be4f3026e06..400d9ddf20a59d16cb02c4f941a95620e1d54ed1 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/services/service/src/publishcommonevent/dm_account_common_event.cpp b/services/service/src/publishcommonevent/dm_account_common_event.cpp index 50ca53d73f3998854651c89ef1899c3a401c46d0..cdbc822d20631e47f7aa5fee339d34598dd2c638 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."); 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 0000000000000000000000000000000000000000..23e7958a5d1011ccc5a2ab1f82bda1ccf05200cc --- /dev/null +++ b/services/service/src/relationshipsyncmgr/dm_comm_tool.cpp @@ -0,0 +1,245 @@ +/* + * 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 0000000000000000000000000000000000000000..6b51103803f7fc9bc9afc9251b92b88f6f93b7b2 --- /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 0000000000000000000000000000000000000000..651f7ad6ab24a46fb7b35bc3b50311368b24cf10 --- /dev/null +++ b/services/service/src/relationshipsyncmgr/dm_transport_msg.cpp @@ -0,0 +1,182 @@ +/* + * 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; + } + + 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; +} + +void ToJson(cJSON *jsonObject, const NotifyUserIds ¬ifyUserIds) +{ + if (jsonObject == nullptr) { + LOGE("Json pointer is nullptr!"); + return; + } + + cJSON_AddStringToObject(jsonObject, DSOFTBUS_NOTIFY_USERIDS_UDIDKEY, notifyUserIds.remoteUdid.c_str()); + + cJSON *userIdArr = cJSON_CreateArray(); + if (userIdArr == nullptr) { + return; + } + for (auto const &userId : notifyUserIds.userIds) { + cJSON_AddItemToArray(userIdArr, cJSON_CreateNumber(userId)); + } + cJSON_AddItemToObject(jsonObject, DSOFTBUS_NOTIFY_USERIDS_USERIDKEY, userIdArr); +} + +void FromJson(const cJSON *jsonObject, NotifyUserIds ¬ifyUserIds) +{ + if (jsonObject == nullptr) { + LOGE("Json pointer is nullptr!"); + return; + } + + cJSON *msgObj = cJSON_GetObjectItem(jsonObject, DSOFTBUS_NOTIFY_USERIDS_UDIDKEY); + if (cJSON_IsString(msgObj)) { + notifyUserIds.remoteUdid = msgObj->valuestring; + } + + cJSON *userIdsArr = cJSON_GetObjectItem(jsonObject, DSOFTBUS_NOTIFY_USERIDS_USERIDKEY); + 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); + notifyUserIds.userIds.push_back(userId); + } + } + } +} + +std::string NotifyUserIds::ToString() +{ + cJSON *msg = cJSON_CreateObject(); + if (msg == NULL) { + LOGE("failed to create cjson object"); + return ""; + } + + ToJson(msg, *this); + char *retStr = cJSON_PrintUnformatted(msg); + if (retStr == nullptr) { + LOGE("to json is nullptr."); + cJSON_Delete(msg); + return ""; + } + std::string ret = std::string(retStr); + cJSON_Delete(msg); + cJSON_free(retStr); + return ret; +} +} // DistributedHardware +} // OHOS \ No newline at end of file diff --git a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp index 494e959a82cc6d0f29c8dcd28e1b23d23ffbd773..252e90797f7d62a44cc8acacb050685d3b310b38 100644 --- a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp +++ b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp @@ -25,36 +25,55 @@ 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 BIT_PER_BYTES = 8; + 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 BITS_PER_BYTE = 8; const int32_t INVALIED_PAYLOAD_SIZE = 12; const char * const MSG_TYPE = "TYPE"; 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_MASK = 0b01111111; + const uint32_t MAX_MEM_MALLOC_SIZE = 4 * 1024; } 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 +98,14 @@ bool RelationShipChangeMsg::ToBroadcastPayLoad(uint8_t *&msg, uint32_t &len) con ToAppUnbindPayLoad(msg, len); ret = true; break; + case RelationShipChangeType::SYNC_FOREGROUND_USERID: + ToSyncForegroundUserIdPayLoad(msg, len); + ret = true; + break; + case RelationShipChangeType::DEL_USER: + ToDelUserPayLoad(msg, len); + ret = true; + break; default: LOGE("RelationShipChange type invalid"); break; @@ -104,6 +131,12 @@ bool RelationShipChangeMsg::FromBroadcastPayLoad(const cJSON *payloadJson, Relat case RelationShipChangeType::APP_UNBIND: ret = FromAppUnbindPayLoad(payloadJson); break; + case RelationShipChangeType::SYNC_FOREGROUND_USERID: + ret = FromSyncForegroundUserIdPayLoad(payloadJson); + break; + case RelationShipChangeType::DEL_USER: + ret = FromDelUserPayLoad(payloadJson); + break; default: LOGE("RelationShipChange type invalid"); break; @@ -124,12 +157,18 @@ 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; 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,21 +182,24 @@ 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) || + (type == RelationShipChangeType::DEL_USER); } 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) || + (type == (uint32_t)RelationShipChangeType::DEL_USER); } void RelationShipChangeMsg::ToAccountLogoutPayLoad(uint8_t *&msg, uint32_t &len) const { 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++) { @@ -170,7 +212,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; } @@ -179,16 +221,55 @@ 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; } +void RelationShipChangeMsg::ToSyncForegroundUserIdPayLoad(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; + + if (len > MAX_MEM_MALLOC_SIZE) { + LOGE("len too long"); + return; + } + 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 (uint32_t idx = 1; idx < len;) { + msg[idx] |= foregroundUserIds[idx - 1] & 0xFF; + msg[idx + 1] |= (foregroundUserIds[idx - 1] >> BITS_PER_BYTE) & 0xFF; + idx += USERID_BYTES; + } +} + +void RelationShipChangeMsg::ToDelUserPayLoad(uint8_t *&msg, uint32_t &len) const +{ + len = DEL_USER_PAYLOAD_LEN; + msg = new uint8_t[DEL_USER_PAYLOAD_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) { @@ -196,7 +277,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; } @@ -205,7 +286,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 = ""; @@ -226,7 +307,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; } @@ -235,7 +316,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; @@ -248,7 +329,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; } @@ -257,7 +338,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; @@ -265,13 +346,83 @@ 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; +} + +bool RelationShipChangeMsg::FromSyncForegroundUserIdPayLoad(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 invalid, 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_MASK); + } + + 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)) << BITS_PER_BYTE; + this->foregroundUserIds.push_back(tempUserId); + tempUserId = 0; + } + } + return true; +} + +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)) { + this->userId |= (static_cast(payloadItem->valueint)) << (i * BITS_PER_BYTE); } } return true; } -cJSON *RelationShipChangeMsg::ToArrayJson() const +cJSON *RelationShipChangeMsg::ToPayLoadJson() const { uint8_t *payload = nullptr; uint32_t len = 0; @@ -304,7 +455,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); diff --git a/services/service/src/softbus/softbus_listener.cpp b/services/service/src/softbus/softbus_listener.cpp index f04bb4a0f4c6ae97210456c84854d4f28b691f29..71818abe42adf03d59686d2880a5527cc2328751 100644 --- a/services/service/src/softbus/softbus_listener.cpp +++ b/services/service/src/softbus/softbus_listener.cpp @@ -29,6 +29,7 @@ #include "dm_device_info.h" #include "dm_log.h" #include "dm_softbus_cache.h" +#include "dm_transport_msg.h" #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) #include "ffrt.h" #endif @@ -62,6 +63,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; @@ -155,8 +157,22 @@ void SoftbusListener::DeviceNotTrust(const std::string &msg) void SoftbusListener::DeviceTrustedChange(const std::string &msg) { +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) std::lock_guard lock(g_lockDeviceTrustedChange); DeviceManagerService::GetInstance().HandleDeviceTrustedChange(msg); +#else + void(msg); +#endif +} + +void SoftbusListener::DeviceUserIdCheckSumChange(const std::string &msg) +{ +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + std::lock_guard lock(g_lockUserIdCheckSumChange); + DeviceManagerService::GetInstance().HandleUserIdCheckSumChange(msg); +#else + void(msg); +#endif } void SoftbusListener::DeviceScreenStatusChange(DmDeviceInfo deviceInfo) @@ -358,17 +374,21 @@ 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 { + } + // else if (type == TrustChangeType::DEVICE_USERIDCHECKSUM_CHANGE) { // DEVICE_USERIDCHECKSUM_CHANGE todo + // ffrt::submit([=]() { DeviceUserIdCheckSumChange(softbusMsg); }); + // } + else { LOGE("Invalied trust change type."); } #else @@ -386,7 +406,16 @@ void SoftbusListener::OnDeviceTrustedChange(TrustChangeType type, const char *ms LOGE("deviceTrustedChange setname failed."); } deviceTrustedChange.detach(); - } else { + } + // else if (type == TrustChangeType::DEVICE_USERIDCHECKSUM_CHANGE) { // DEVICE_USERIDCHECKSUM_CHANGE todo + // 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."); } #endif @@ -1139,5 +1168,14 @@ int32_t SoftbusListener::GetDeviceScreenStatus(const char *networkId, int32_t &s LOGI("GetDeviceScreenStatus screenStatus: %{public}d.", devScreenStatus); return DM_OK; } + +int32_t SoftbusListener::SetForegroundUserIdsToDSoftBus(const std::string &remoteUdid, + const std::vector &userIds) +{ + NotifyUserIds notifyUserIds(remoteUdid, userIds); + std::string msg = notifyUserIds.ToString(); + LOGI("Notify remote userid to dsoftbus, msg: %{public}s", GetAnonyString(msg).c_str()); + return SetDLUserId(DM_PKG_NAME, msg.c_str(), static_cast(msg.size())); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp b/test/commonfuzztest/authenticatedevice_fuzzer/authenticate_device_fuzzer.cpp index 54241e5b2fbd6f5a0eed00c8f61b754b579d4292..3f1ee3fc8363572519ed79d4341fa4ff04a58dc1 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 65d8cbd12972ce06f6aca1d79041d0a24118ac57..9a2d26d009f61dfdfb20620b6b67c6d705e25cd0 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 57f0ca81bfb37db9d7c062e236744df682de3a3a..2943deaf9914fb8c6357c40fb6610bbb411acc93 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); } @@ -777,40 +776,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_credential_manager.h b/test/commonunittest/UTTest_dm_credential_manager.h index 1347ebfdb52c747526d447e944cdc6b6dbde8e6c..50ac9b4500495c084c267a55f66e531d9bd7ec94 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_deviceprofile_connector.cpp b/test/commonunittest/UTTest_dm_deviceprofile_connector.cpp index 3e2038dc205705656ab8abec39c6fb5338d30a36..6665ccc34db446bbe243bb8f49a74d9744f4f247 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 { @@ -46,7 +47,7 @@ HWTEST_F(DeviceProfileConnectorTest, GetAppTrustDeviceList_001, testing::ext::Te { std::string pkgName; std::string deviceId = "deviceId"; - auto ret = DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgName, deviceId); + auto ret = DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgName, deviceId, 100); EXPECT_EQ(ret.empty(), true); } @@ -54,7 +55,7 @@ HWTEST_F(DeviceProfileConnectorTest, GetAppTrustDeviceList_002, testing::ext::Te { std::string pkgName = "bundleName"; std::string deviceId = "deviceId"; - auto ret = DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgName, deviceId); + auto ret = DeviceProfileConnector::GetInstance().GetAppTrustDeviceList(pkgName, deviceId, 100); EXPECT_EQ(ret.empty(), true); } @@ -451,54 +452,30 @@ 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, GetProcessInfoFromAclByUserId_001, testing::ext::TestSize.Level0) { std::string localDeviceId = "localDeviceId"; std::string targetDeviceId = "targetDeviceId"; - auto ret = DeviceProfileConnector::GetInstance().GetPkgNameFromAcl(localDeviceId, targetDeviceId); + auto ret = DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(localDeviceId, targetDeviceId, 100); EXPECT_EQ(ret.empty(), true); } -HWTEST_F(DeviceProfileConnectorTest, GetPkgNameFromAcl_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().GetPkgNameFromAcl(localDeviceId, targetDeviceId); + auto ret = DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(localDeviceId, targetDeviceId, 100); EXPECT_EQ(ret.empty(), true); } -HWTEST_F(DeviceProfileConnectorTest, GetPkgNameFromAcl_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().GetPkgNameFromAcl(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; @@ -791,10 +768,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/commonunittest/UTTest_permission_manager.cpp b/test/commonunittest/UTTest_permission_manager.cpp index 8c8ef0f395c35313204fc953bc24e90e57a53d78..12ad9a7f9e387357e50ea487bf197ddbed0b6ea5 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 dfa125cbc8a9e8b36590a18730d59dfd1f3baee7..51e187c50c56a1ecd380d87920ea11b7e01c79bf 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/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp b/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp index 1d9b2bb50f0568db529f95e4801604fa2d7e4737..68743c29d022a91d770d4adcd3df87aa3fec64b6 100644 --- a/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp +++ b/test/servicesfuzztest/deviceprofileconnector_fuzzer/device_profile_connector_fuzzer.cpp @@ -54,11 +54,9 @@ void DeviceProfileConnectorFuzzTest(const uint8_t* data, size_t size) int32_t userId = *(reinterpret_cast(data)); std::string accountId(reinterpret_cast(data), size); int32_t bindLevel = *(reinterpret_cast(data)); - DeviceProfileConnector::GetInstance().CheckBindType(trustDeviceId, requestDeviceId); DeviceProfileConnector::GetInstance().GetBindTypeByPkgName(pkgName, requestDeviceId, trustUdid); - DeviceProfileConnector::GetInstance().GetPkgNameFromAcl(localDeviceId, targetDeviceId); - DeviceProfileConnector::GetInstance().GetOfflineParamFromAcl(trustDeviceId, requestDeviceId); + DeviceProfileConnector::GetInstance().GetProcessInfoFromAclByUserId(localDeviceId, targetDeviceId, userId); DeviceProfileConnector::GetInstance().PutAccessControlList(aclInfo, dmAccesser, dmAccessee); DeviceProfileConnector::GetInstance().DeleteAccessControlList(pkgName, localDeviceId, requestDeviceId, bindLevel); DeviceProfileConnector::GetInstance().UpdateAccessControlList(userId, accountId, accountId); diff --git a/test/servicesfuzztest/ipccmdregister_fuzzer/ipc_cmd_register_fuzzer.cpp b/test/servicesfuzztest/ipccmdregister_fuzzer/ipc_cmd_register_fuzzer.cpp index f8e05ec0a2ed1e21310d2b3b2601d8b122a809e7..99d41ffae0cdcf91b6dad6cb90f3b1251d171651 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/ipcserverlistener_fuzzer/ipc_server_listener_fuzzer.cpp b/test/servicesfuzztest/ipcserverlistener_fuzzer/ipc_server_listener_fuzzer.cpp index 6e531a28748022915e91f824c5c1e232a9caad9a..b7c8de713697f2bd0b20b2e1482f938b5bec6c05 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 3f134f4d013e06aa1c2090fd5df25abd1a625b7f..1a75d5056d5d3646ec456a6daa445b3059a94823 100644 --- a/test/servicesfuzztest/ipcserverstub_fuzzer/ipc_server_stub_fuzzer.cpp +++ b/test/servicesfuzztest/ipcserverstub_fuzzer/ipc_server_stub_fuzzer.cpp @@ -44,18 +44,20 @@ 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(); IpcServerStub::GetInstance().Init(); IpcServerStub::GetInstance().OnRemoteRequest(code, data1, reply, option); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); - IpcServerStub::GetInstance().GetDmListener(pkgName); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); + IpcServerStub::GetInstance().GetDmListener(processInfo); IpcServerStub::GetInstance().SendCmd(code, req, rsp); - IpcServerStub::GetInstance().GetAllPkgName(); - IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + IpcServerStub::GetInstance().GetAllProcessInfo(); + 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 2d666504d4b34437e399a04994046a935ab7d429..58ec428205d6bb4fbac75df841da8ee850cf018c 100644 --- a/test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.cpp +++ b/test/softbusfuzztest/softbusconnectorcommon_fuzzer/softbus_connector_common_fuzzer.cpp @@ -38,7 +38,6 @@ void SoftBusConnectorCommonFuzzTest(const uint8_t* data, size_t size) softbusConnector->GetDeviceUdidHashByUdid(str); softbusConnector->EraseUdidFromMap(str); softbusConnector->GetNetworkIdByDeviceId(str); - softbusConnector->SetPkgName(str); softbusConnector->CheckIsOnline(str); softbusConnector->GetDeviceInfoByDeviceId(str); } diff --git a/test/softbusunittest/UTTest_softbus_connector.cpp b/test/softbusunittest/UTTest_softbus_connector.cpp index ebd24ea1a0e1051eb12b14de5303f8ad8101d73e..57dbcc5e2c8934e86f91585f8e2fc2eed07acd17 100644 --- a/test/softbusunittest/UTTest_softbus_connector.cpp +++ b/test/softbusunittest/UTTest_softbus_connector.cpp @@ -813,14 +813,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) { + ProcessInfo processInfo; + std::vector processInfoVec; std::string pkgName = "pkgName"; std::vector pkgNameVec; 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); } /** @@ -871,25 +873,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); } @@ -897,11 +899,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); } /** @@ -915,7 +917,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); } /** @@ -929,7 +931,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); } /** @@ -941,7 +943,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); } /** @@ -969,7 +971,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_impl.cpp b/test/unittest/UTTest_device_manager_impl.cpp index 8e236a8145fa98e141384c84f58d4fd890cecca9..d7bd61aa0ec2ca0b56858cecc27cf67065b28cc0 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 f2fe2485c8889541893bfdaa96879f21dae73e68..89cab06b2d6536633d0de599811f465e0c91a2e5 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); @@ -1221,9 +1218,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 7cd7c5d1461b72ff25aa471d6fc8534b5e6ebc82..b979e8e45d07721598f5787957df6496efd7f8a2 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 7ced282820176034b76b127834e4910a870996e3..fbd06cce915297263792e8a82ac13eada69413fd 100644 --- a/test/unittest/UTTest_device_manager_service.cpp +++ b/test/unittest/UTTest_device_manager_service.cpp @@ -117,100 +117,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_EQ(ret, SOFTBUS_DISCOVER_COAP_STOP_DISCOVER_FAIL); - 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 @@ -343,15 +249,15 @@ HWTEST_F(DeviceManagerServiceTest, UnPublishDeviceDiscovery_004, testing::ext::T 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, preUserId); commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGIN; - DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, preUserId); commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_HWID_LOGOUT; - DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, preUserId); commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED; - DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, preUserId); commonEventType = EventFwk::CommonEventSupport::COMMON_EVENT_BOOT_COMPLETED; - DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, preUserId); DeviceManagerService::GetInstance().HandleAccountLogout(userId, accountId); DeviceManagerService::GetInstance().HandleUserRemoved(preUserId); DeviceManagerService::GetInstance().softbusListener_ = std::make_shared(); @@ -1243,34 +1149,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; @@ -2253,24 +2131,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 = ""; @@ -2305,9 +2165,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_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index bdf8cfd33bbb3edec6550cd9cca0ca113d675665..365f6e5b17eecc9bcbc8ff72ca92bc50c8ec1d42 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -1397,7 +1397,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, 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 77a8944df02a9490362899881d9d5bf60cf3b171..392e34b7b1b1d54d6b7cc138ba735159ad76936a 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,16 @@ 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; 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 +79,16 @@ 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; 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); } @@ -96,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); } @@ -114,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); } @@ -132,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); } @@ -152,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); } @@ -173,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); } @@ -190,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); } @@ -236,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); } @@ -251,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); } @@ -265,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); } @@ -282,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); } @@ -299,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); } @@ -316,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); } @@ -343,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 @@ -366,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); } @@ -382,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); } @@ -397,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); } @@ -411,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); } @@ -425,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 d181708dbe25fa61b8e5a5abfca82a895e9297f4..8574fd19155a0d3e970e1f23511b427bbe99584f 100644 --- a/test/unittest/UTTest_device_manager_service_two.cpp +++ b/test/unittest/UTTest_device_manager_service_two.cpp @@ -105,19 +105,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 @@ -273,9 +260,9 @@ HWTEST_F(DeviceManagerServiceTest, InitAccountInfo_201, testing::ext::TestSize.L { int32_t userId = 100; std::string commonEventType = "usual.event.USER_SWITCHED"; - DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); + DeviceManagerService::GetInstance().AccountCommonEventCallback(commonEventType, userId, 101); commonEventType = "common.event.HWID_LOGIN"; - DeviceManagerService::GetInstance().AccountCommonEventCallback(userId, commonEventType); + 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 f66bfbe80d67b07b2d4c5e8ad8b200e6780cae41..fa302b097b2b54471c02275e3906ff4f9a66ccad 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 d8acbce6fec9087c7a417cd40ed942f82f18b013..f0e906e95ac360f83c8931fb9446c2fa8b859e8c 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,37 +61,31 @@ 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; } - void OnDeviceFound(const std::string &pkgName, 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 OnDeviceFound(const ProcessInfo &processInfo, uint16_t subscribeId, const DmDeviceInfo &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; } @@ -101,80 +96,80 @@ public: (void)publishResult; } - 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)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; @@ -187,16 +182,16 @@ 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; } - void OnCredentialAuthStatus(const std::string &pkgName, const std::string &deviceList, uint16_t deviceTypeId, + void OnCredentialAuthStatus(const ProcessInfo &processInfo, const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode) override { - (void)pkgName; + (void)processInfo; (void)deviceList; (void)deviceTypeId; (void)errcode; @@ -207,10 +202,10 @@ public: (void)pkgName; } - void OnSinkBindResult(const std::string &pkgName, const PeerTargetId &targetId, int32_t result, + void OnSinkBindResult(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; diff --git a/test/unittest/UTTest_ipc_client_server_proxy.cpp b/test/unittest/UTTest_ipc_client_server_proxy.cpp index ac258affd51421dc9720f49ae786d7b8bee688b0..5aed918cd222502c20d206d1700ece10a4e24565 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 e4bb689199df58b0727b0738ae17b4e0d40cb4b6..f8ed9f05362822dd24e6accf3fe46bcea6ee3c6b 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 71e2f2b7d688507d18c5ef981cc3994658fb80ed..00ba99d82601e85f63531bf0cf88f0a204eb879c 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 6e20ac4c5a00a5a8f581f049e6e44eda74761a18..912b90eeb69a50eed0aa11fa9725b5864299a7e9 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 d987321e3e64fdda68b780e5ee70a38d23e6799f..f37d754c0a3594112360fc20e97847d5dc44dee6 100644 --- a/test/unittest/UTTest_ipc_server_client_proxy.cpp +++ b/test/unittest/UTTest_ipc_server_client_proxy.cpp @@ -95,12 +95,15 @@ 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()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); // set req not null @@ -135,12 +138,15 @@ 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()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); // set req not null @@ -175,12 +181,15 @@ 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()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); std::shared_ptr req = std::make_shared(); std::shared_ptr rsp = std::make_shared(); // set req not null @@ -215,12 +224,15 @@ 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()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + 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 60d60f42fcf12bedcc019fd4f40637c8e6e74ba8..e73bf2e5da4ca3fed11872c5f1278e168fa9b472 100644 --- a/test/unittest/UTTest_ipc_server_listener.cpp +++ b/test/unittest/UTTest_ipc_server_listener.cpp @@ -129,9 +129,12 @@ HWTEST_F(IpcServerListenerTest, SendRequest_003, testing::ext::TestSize.Level0) int32_t cmdCode = 9999; // set pkgName not null std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; // 2. set remoteObject not nullptr sptr remoteObject = sptr(new IpcClientStub()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); // set req not null std::shared_ptr req = std::make_shared(); // set rsp not null @@ -162,10 +165,13 @@ 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; - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); // set req not null std::shared_ptr req = std::make_shared(); // set rsp not null @@ -176,7 +182,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); } /** @@ -197,9 +203,12 @@ HWTEST_F(IpcServerListenerTest, SendRequest_005, testing::ext::TestSize.Level0) int32_t cmdCode = 9999; // 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()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); // set req not null std::shared_ptr req = std::make_shared(); // set rsp not null @@ -230,9 +239,12 @@ HWTEST_F(IpcServerListenerTest, SendRequest_006, testing::ext::TestSize.Level0) int32_t cmdCode = 0; // 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()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); // set req not null std::shared_ptr req = std::make_shared(); // set rsp null @@ -263,9 +275,12 @@ HWTEST_F(IpcServerListenerTest, SendRequest_007, testing::ext::TestSize.Level0) int32_t cmdCode = -1; // 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()); - IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, remoteObject); + IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, remoteObject); // set req not null std::shared_ptr req = std::make_shared(); // set rsp null @@ -279,87 +294,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 2bbbecb96cb35139a4cf45e336b73927a4059188..83bbb6c7683b92c40513d277e6fd1f17b3e901fa 100644 --- a/test/unittest/UTTest_ipc_server_stub.cpp +++ b/test/unittest/UTTest_ipc_server_stub.cpp @@ -227,9 +227,12 @@ HWTEST_F(IpcServerStubTest, QueryServiceState_001, testing::ext::TestSize.Level0 HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_001, testing::ext::TestSize.Level0) { std::string pkgName = ""; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; int ret = 0; sptr listener = nullptr; - ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); ASSERT_EQ(ret, ERR_DM_POINT_NULL); } @@ -243,9 +246,12 @@ HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_001, testing::ext::Tes HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_002, testing::ext::TestSize.Level0) { std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; int ret = 0; sptr listener = sptr(new IpcClientStub()); - ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); ASSERT_EQ(ret, DM_OK); } @@ -259,9 +265,12 @@ HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_002, testing::ext::Tes HWTEST_F(IpcServerStubTest, RegisterDeviceManagerListener_003, testing::ext::TestSize.Level0) { std::string pkgName = ""; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; int ret = 0; sptr listener = sptr(new IpcClientStub()); - ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); ASSERT_EQ(ret, ERR_DM_POINT_NULL); } @@ -277,10 +286,13 @@ 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 - ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(processInfo, listener); // 3. check ret is DM_OK ASSERT_EQ(ret, DM_OK); } @@ -301,22 +313,25 @@ 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 - ret = IpcServerStub::GetInstance().RegisterDeviceManagerListener(pkgName, listener); + 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 +345,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); } @@ -350,15 +365,18 @@ HWTEST_F(IpcServerStubTest, UnRegisterDeviceManagerListener_002, testing::ext::T { // 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 - 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); } @@ -375,9 +393,12 @@ HWTEST_F(IpcServerStubTest, UnRegisterDeviceManagerListener_003, testing::ext::T { // 1. Set pkgName is com.ohos.test std::string pkgName = "com.ohos.test"; + ProcessInfo processInfo; + processInfo.pkgName = pkgName; + processInfo.userId = 100; int ret = 0; // 2. Call IpcServerStub UnRegisterDeviceManagerListener - ret = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(pkgName); + ret = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); // 3. check ret is DM_OK ASSERT_EQ(ret, DM_OK); } @@ -396,18 +417,21 @@ 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; + processInfo.userId = 100; 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); } @@ -427,52 +451,28 @@ 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 - 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 std::string testPkgName = "com.test"; - result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(testPkgName); + result = IpcServerStub::GetInstance().UnRegisterDeviceManagerListener(processInfo); // 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 @@ -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 == 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,15 +527,17 @@ 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 - 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; // 2. Call IpcServerStub UnRegisterDeviceManagerListener - ret = IpcServerStub::GetInstance().GetDmListener(pkgName); + ret = IpcServerStub::GetInstance().GetDmListener(processInfo); // 3. check ret is DM_OK ASSERT_NE(ret, nullptr); } @@ -549,16 +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 - 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; // 2. Call IpcServerStub UnRegisterDeviceManagerListener - std::string testPkgName = "test"; - ret = IpcServerStub::GetInstance().GetDmListener(testPkgName); + ret = IpcServerStub::GetInstance().GetDmListener(processInfo); // 3. check ret is DM_OK ASSERT_EQ(ret, nullptr); } @@ -575,15 +581,17 @@ 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 - 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 - ret = IpcServerStub::GetInstance().GetDmListener(pkgName); + ret = IpcServerStub::GetInstance().GetDmListener(processInfo); // 3. check ret is nullptr ASSERT_EQ(ret, nullptr); } @@ -600,15 +608,17 @@ 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 - ret = IpcServerStub::GetInstance().GetDmListener(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 0c70d88ae3fc91240cf0d0bdfc622a50a0ff2f4d..4db0579fd045df0da1efd4e3da1164e02ff80d58 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 b3c8e04b948610e1336fd8ef9442628a8aa1a283..74d538f59202a640203cf91336f442f4dbddcf1a 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,8 @@ #include #include +#include +#include "dm_device_info.h" #include "ipc_req.h" #include "ipc_rsp.h" @@ -35,18 +37,14 @@ 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::set GetSystemSA(); std::shared_ptr req_; }; } // namespace DistributedHardware diff --git a/utils/include/appInfo/lite/app_manager.h b/utils/include/appInfo/lite/app_manager.h index 33927be8e12c8be97d5339d12d44a2b5d7835f67..52dc07f81f46dc4b1dd31c525d688e92d1aed12b 100644 --- a/utils/include/appInfo/lite/app_manager.h +++ b/utils/include/appInfo/lite/app_manager.h @@ -30,6 +30,9 @@ 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); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/utils/include/appInfo/standard/app_manager.h b/utils/include/appInfo/standard/app_manager.h index 6843378672392deba429720c56e0b80d5680ff46..8f19166a6ac0814eae9da3f72b8a39000933d4d5 100644 --- a/utils/include/appInfo/standard/app_manager.h +++ b/utils/include/appInfo/standard/app_manager.h @@ -36,6 +36,9 @@ 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: 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 ea3ab90ccebed693a414b9eb0ff0487e420558c6..fd2aeb7680224d250e52d968ad1a809f712d3a05 100644 --- a/utils/src/appInfo/lite/app_manager.cpp +++ b/utils/src/appInfo/lite/app_manager.cpp @@ -46,5 +46,27 @@ bool AppManager::IsSystemSA() { return true; } + +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 AppManager::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 cb2c61ec9c3db74c74268ec3219d485ca62b95e3..b1d173f537c7413c5245db95d3e2954249afa4dd 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) +{ + auto hapTokenId = AccessTokenKit::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